Prove attachment reconciliation under storage faults

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 14:20:22 +03:00
parent 55bb55d639
commit 9c15fc3744
4 changed files with 242 additions and 0 deletions
@@ -0,0 +1,24 @@
# Reconciliation fault injection and inventory cost
## Hypothesis
The reconciler can identify an orphan left by a successful S3 PUT followed by a failed PostgreSQL write, and a missing S3 object referenced by committed metadata. Applying repairs should delete only an orphan older than the grace period, restore missing bytes only from a matching fixture, and leave fresh or linked objects untouched. A second pass should find no work for the repaired cases.
## Reproduce
On the local Compose stand with `.env` configured, run `sh scripts/fault-injection.sh`. The local build used `COMPOSE_FILE=compose.yaml:compose.local.yaml` because this host needed a temporary Docker DNS override; the override is ignored by Git. The script builds and runs the maintenance service and writes anonymized JSON under `evidence/reconciliation/`. It uses a synthetic user, chat, message, attachments, and object keys. Repeated runs append more synthetic inventory to persistent volumes, so compare measurements only within one run.
The PostgreSQL fault is an invalid foreign key insert after a successful S3 PUT. The transaction rolls back, leaving an object with no metadata. The S3 fault deletes an object after its metadata commits. A 5-second grace period lets the test age the first orphan, then create a fresh one. Production maintenance defaults to one hour. A message links another attachment throughout the test.
## Observed result
Raw result: [run-20261002T111817Z.json](run-20261002T111817Z.json). The initial dry-run saw 283 metadata rows and 285 S3 objects, including the injected old orphan, fresh orphan, and missing object. The dry-run left them unchanged. A deliberately wrong source was rejected before deletion. Apply without a source deleted the old orphan, retained the missing metadata as a manual incident, and preserved the fresh and linked objects. A second dry-run found the old orphan gone and the missing incident present; a repeated delete made no change to the injected orphan. Apply with the correct fixture restored the exact SHA-256 bytes. Repeated restore returned `already_present`, and the final dry-run found neither injected inconsistency.
Inventory scans used three sequential dry-run trials per size in the same maintenance process. CPU is user plus system time for that process; RSS is Linux `VmRSS`, and high-water RSS is `ru_maxrss`. Times are milliseconds, RSS is KiB.
| Inventory | Trial wall times | Trial CPU times | Median wall | Median CPU | RSS before → after across trials | Peak RSS |
| --- | --- | --- | ---: | ---: | --- | ---: |
| 333 metadata / 334 objects | 19.390, 21.143, 23.322 | 6.447, 7.420, 8.516 | 21.143 | 7.420 | 68152 → 68512 | 126608 |
| 533 metadata / 534 objects | 16.585, 24.219, 44.148 | 9.993, 9.997, 9.500 | 24.219 | 9.993 | 68512 → 68936 | 126608 |
The larger inventory used more CPU in this run; wall time varied widely, including one faster larger-inventory trial. These six samples on one local host do not establish a scaling law. The measurements exclude PostgreSQL and S3 server resources and include pre-existing data in persistent volumes. The process high-water RSS was reached before these scans, so it cannot isolate the scan's peak allocation; the before/after RSS readings show only retained process memory.
@@ -0,0 +1 @@
{"faults": {"apply_without_source": {"fresh_preserved": true, "linked_preserved": true, "missing_incident_retained": true, "old_deleted": true}, "post_delete_dry_run": {"missing_incident_retained": true, "old_absent": true}, "post_restore_dry_run": {"missing_absent": true, "old_absent": true}, "preview": {"fresh_detected": true, "inventory": {"metadata": 283, "objects": 285}, "linked_preserved": true, "missing_detected": true, "old_detected": true}, "repeat": "already_present", "repeat_delete_no_change": true, "restore": "restored", "wrong_fixture_rejected_without_delete": true}, "limits": "Single local host, 3 sequential dry-run scans per size; CPU/RSS are maintenance-process measurements only.", "measurements": [{"cpu_system_ms": 0.031, "cpu_user_ms": 6.416, "label": "plus_50", "metadata": 333, "objects": 334, "reconciler_ms": 19.349, "rss_after_kib": 68468, "rss_before_kib": 68152, "rss_hwm_kib": 126608, "trial": 1, "wall_ms": 19.39}, {"cpu_system_ms": 0.0, "cpu_user_ms": 7.42, "label": "plus_50", "metadata": 333, "objects": 334, "reconciler_ms": 21.098, "rss_after_kib": 68500, "rss_before_kib": 68468, "rss_hwm_kib": 126608, "trial": 2, "wall_ms": 21.143}, {"cpu_system_ms": 0.02, "cpu_user_ms": 8.496, "label": "plus_50", "metadata": 333, "objects": 334, "reconciler_ms": 23.282, "rss_after_kib": 68512, "rss_before_kib": 68500, "rss_hwm_kib": 126608, "trial": 3, "wall_ms": 23.322}, {"cpu_system_ms": 0.993, "cpu_user_ms": 9.0, "label": "plus_250", "metadata": 533, "objects": 534, "reconciler_ms": 16.523, "rss_after_kib": 68908, "rss_before_kib": 68512, "rss_hwm_kib": 126608, "trial": 1, "wall_ms": 16.585}, {"cpu_system_ms": 0.007, "cpu_user_ms": 9.99, "label": "plus_250", "metadata": 533, "objects": 534, "reconciler_ms": 24.163, "rss_after_kib": 68936, "rss_before_kib": 68908, "rss_hwm_kib": 126608, "trial": 2, "wall_ms": 24.219}, {"cpu_system_ms": 0.0, "cpu_user_ms": 9.5, "label": "plus_250", "metadata": 533, "objects": 534, "reconciler_ms": 44.084, "rss_after_kib": 68936, "rss_before_kib": 68936, "rss_hwm_kib": 126608, "trial": 3, "wall_ms": 44.148}], "summary": {"plus_250": {"median_cpu_ms": 9.993, "median_wall_ms": 24.219, "metadata": 533, "objects": 534}, "plus_50": {"median_cpu_ms": 7.42, "median_wall_ms": 21.143, "metadata": 333, "objects": 334}}}
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
# Run on an isolated synthetic-data Compose stand. COMPOSE_FILE may include a local override.
set -eu
cd "$(dirname "$0")/.."
mkdir -p evidence/reconciliation
stamp=$(date -u +%Y%m%dT%H%M%SZ)
temporary="evidence/reconciliation/.run-$stamp.tmp"
output="evidence/reconciliation/run-$stamp.json"
trap 'rm -f "$temporary"' EXIT HUP INT TERM
docker compose --env-file .env --profile maintenance build reconcile
docker compose --env-file .env --profile maintenance run --rm -T reconcile python - \
< student-tests/test_reconcile_research.py > "$temporary"
python3 -m json.tool "$temporary" >/dev/null
mv "$temporary" "$output"
trap - EXIT HUP INT TERM
printf 'Reconciliation evidence: %s\n' "$output"
+200
View File
@@ -0,0 +1,200 @@
"""Repeatable lab 4 consistency experiment; run inside the maintenance Compose service.
Writes one JSON result to stdout. It creates synthetic objects and metadata, but never
deletes the measured baseline or the fresh/linked objects after the experiment.
"""
import hashlib
import importlib.util
import io
import json
import resource
import statistics
import time
from pathlib import Path
from uuid import UUID, uuid4
import psycopg
from PIL import Image
from psycopg.rows import dict_row
from src.db import database_url
from src.store import store
spec = importlib.util.spec_from_file_location("reconciler", "scripts/reconcile-attachments.py")
reconciler = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reconciler)
def put(client, key: str, data: bytes) -> None:
client.put_object(reconciler.BUCKET, key, io.BytesIO(data), len(data), content_type="image/png")
def rss_kib() -> int:
for line in Path("/proc/self/status").read_text().splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1])
raise RuntimeError("VmRSS unavailable")
def scan(client, conn, label: str, trial: int) -> dict:
before = resource.getrusage(resource.RUSAGE_SELF)
rss_before = rss_kib()
start = time.perf_counter()
result = reconciler.reconcile(client, conn, False, 3600, None, None)
wall_ms = (time.perf_counter() - start) * 1000
after = resource.getrusage(resource.RUSAGE_SELF)
return {
"label": label, "trial": trial, "objects": result["inventory"]["objects"],
"metadata": result["inventory"]["metadata"],
"reconciler_ms": result["duration_ms"], "wall_ms": round(wall_ms, 3),
"cpu_user_ms": round((after.ru_utime - before.ru_utime) * 1000, 3),
"cpu_system_ms": round((after.ru_stime - before.ru_stime) * 1000, 3),
"rss_before_kib": rss_before, "rss_after_kib": rss_kib(), "rss_hwm_kib": after.ru_maxrss,
}
def main() -> None:
client = reconciler.storage()
fixture = Path("/fixtures/sample.png")
original = fixture.read_bytes()
digest = hashlib.sha256(original).hexdigest()
username = "research_" + uuid4().hex[:16]
owner = store.register(username, "Reconciliation research", "Test-password-123")
chat = store.create_chat(owner["id"], "Reconciliation research", [owner["id"]])
owner_id, chat_id = UUID(owner["id"]), UUID(chat["id"])
active_id, missing_id, old_id, fresh_id = (uuid4() for _ in range(4))
active_key, missing_key, old_key, fresh_key = (f"originals/{item}" for item in (active_id, missing_id, old_id, fresh_id))
put(client, active_key, original)
put(client, missing_key, original)
put(client, old_key, original)
try:
with psycopg.connect(database_url()) as failed:
failed.execute(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(old_id, uuid4(), owner_id, "orphan.png", old_key, "image/png", len(original), digest),
)
except psycopg.errors.ForeignKeyViolation:
pass
else:
raise AssertionError("PostgreSQL fault injection did not roll back")
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
for attachment_id, key in ((active_id, active_key), (missing_id, missing_key)):
conn.execute(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(attachment_id, chat_id, owner_id, "sample.png", key, "image/png", len(original), digest),
)
message_id = uuid4()
conn.execute("INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)",
(message_id, chat_id, owner_id, ""))
conn.execute("INSERT INTO message_attachments (message_id,chat_id,attachment_id,position) VALUES (%s,%s,%s,0)",
(message_id, chat_id, active_id))
client.remove_object(reconciler.BUCKET, missing_key)
time.sleep(6) # An explicit test-only 5-second grace; routine maintenance uses one hour.
put(client, fresh_key, original)
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
preview = reconciler.reconcile(client, conn, False, 5, None, None)
assert old_key in preview["old_orphans"] and fresh_key in preview["fresh_orphans"]
assert str(missing_id) in preview["manual_incidents"] and active_key not in preview["old_orphans"]
assert not reconciler.absent(client, old_key) # Dry-run did not delete.
wrong = Path("/tmp/research-wrong-source")
wrong.write_bytes(b"wrong fixture")
try:
reconciler.reconcile(client, conn, True, 5, missing_id, wrong)
except ValueError:
pass
else:
raise AssertionError("wrong fixture accepted")
assert not reconciler.absent(client, old_key)
apply_without_source = reconciler.reconcile(client, conn, True, 5, None, None)
assert old_key in apply_without_source["deleted"]
assert str(missing_id) in apply_without_source["manual_incidents"]
assert reconciler.absent(client, old_key) and reconciler.absent(client, missing_key)
assert not reconciler.absent(client, fresh_key) and not reconciler.absent(client, active_key)
assert conn.execute("SELECT 1 FROM message_attachments WHERE attachment_id=%s", (active_id,)).fetchone()
post_delete_preview = reconciler.reconcile(client, conn, False, 5, None, None)
assert old_key not in post_delete_preview["old_orphans"]
assert str(missing_id) in post_delete_preview["manual_incidents"]
assert fresh_key in post_delete_preview["fresh_orphans"]
repeat_delete = reconciler.reconcile(client, conn, True, 5, None, None)
assert old_key not in repeat_delete["deleted"]
restored = reconciler.reconcile(client, conn, True, 3600, missing_id, fixture)
assert restored["restore"] == "restored" and not reconciler.absent(client, missing_key)
repeat = reconciler.reconcile(client, conn, True, 3600, missing_id, fixture)
assert repeat["restore"] == "already_present" and not repeat["deleted"]
assert str(missing_id) not in repeat["manual_incidents"]
assert not reconciler.absent(client, fresh_key) and not reconciler.absent(client, active_key)
post_restore_preview = reconciler.reconcile(client, conn, False, 5, None, None)
assert old_key not in post_restore_preview["old_orphans"]
assert str(missing_id) not in post_restore_preview["manual_incidents"]
conn.commit()
tiny = io.BytesIO()
Image.new("RGB", (4, 4), (5, 30, 80)).save(tiny, format="PNG")
data = tiny.getvalue()
tiny_hash = hashlib.sha256(data).hexdigest()
def add_batch(count: int) -> None:
rows = []
for _ in range(count):
attachment_id = uuid4()
key = f"originals/{attachment_id}"
put(client, key, data)
rows.append((attachment_id, chat_id, owner_id, "inventory.png", key, "image/png", len(data), tiny_hash))
with conn.cursor() as cursor:
cursor.executemany(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", rows,
)
conn.commit()
measurements = []
for label, additional in (("plus_50", 50), ("plus_250", 200)):
add_batch(additional)
measurements.extend(scan(client, conn, label, trial) for trial in range(1, 4))
assert measurements[3]["objects"] >= measurements[0]["objects"] + 200
assert measurements[3]["metadata"] >= measurements[0]["metadata"] + 200
response = client.get_object(reconciler.BUCKET, missing_key)
try:
assert hashlib.sha256(response.read()).hexdigest() == digest
finally:
response.close()
response.release_conn()
summary = {label: {
"median_wall_ms": round(statistics.median(item["wall_ms"] for item in measurements if item["label"] == label), 3),
"median_cpu_ms": round(statistics.median(item["cpu_user_ms"] + item["cpu_system_ms"] for item in measurements if item["label"] == label), 3),
"objects": next(item["objects"] for item in measurements if item["label"] == label),
"metadata": next(item["metadata"] for item in measurements if item["label"] == label),
} for label in ("plus_50", "plus_250")}
print(json.dumps({
"faults": {
"preview": {"old_detected": old_key in preview["old_orphans"], "fresh_detected": fresh_key in preview["fresh_orphans"],
"missing_detected": str(missing_id) in preview["missing_attachment_ids"],
"linked_preserved": active_key not in preview["old_orphans"], "inventory": preview["inventory"]},
"wrong_fixture_rejected_without_delete": True,
"apply_without_source": {"old_deleted": old_key in apply_without_source["deleted"],
"missing_incident_retained": str(missing_id) in apply_without_source["manual_incidents"],
"fresh_preserved": True, "linked_preserved": True},
"post_delete_dry_run": {"old_absent": old_key not in post_delete_preview["old_orphans"],
"missing_incident_retained": str(missing_id) in post_delete_preview["manual_incidents"]},
"repeat_delete_no_change": old_key not in repeat_delete["deleted"],
"restore": restored["restore"], "repeat": repeat["restore"],
"post_restore_dry_run": {"old_absent": old_key not in post_restore_preview["old_orphans"],
"missing_absent": str(missing_id) not in post_restore_preview["manual_incidents"]},
}, "measurements": measurements, "summary": summary,
"limits": "Single local host, 3 sequential dry-run scans per size; CPU/RSS are maintenance-process measurements only."
}, sort_keys=True))
if __name__ == "__main__":
main()