refactoring

This commit is contained in:
Матвей
2026-10-22 16:38:54 +03:00
parent 483d7eecb3
commit c84d112f0d
34 changed files with 791 additions and 84 deletions
+6 -1
View File
@@ -106,9 +106,14 @@ print("PASS: S3 outage gives 503 for readiness, download and upload; liveness st
input=json.dumps(payload)).strip())
finally:
compose('start', 's3')
# HeadBucket/read recovery alone does not prove the write path is ready.
# Use the same write-probing bootstrap as the documented restart hook.
compose('run', '--rm', '--no-deps', 's3-init')
wait_ready(c)
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
print('PASS: original available again after S3 restart')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after-recovery.png',
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
print('PASS: original available and new upload accepted after S3 restart/bootstrap')
if __name__ == '__main__':
+22 -13
View File
@@ -72,17 +72,18 @@ def main():
# A reference object must survive an apply sweep, even with zero grace.
protected = upload("protected.png")["json"]
message = client.message(alice, chat, "protected", attachments=[protected["id"]])["json"]
orphan = "originals/test-orphan-" + uuid.uuid4().hex
s3_code("put", orphan)
report = reconcile("--grace-seconds", "3600")
check(orphan in report["fresh_unreferenced"], "fresh orphan missing from dry-run")
check(not report["deleted"], "dry-run deleted an object")
report = reconcile("--apply", "--grace-seconds", "3600")
report = reconcile("--apply", "--grace-seconds", "3600", "--object-key", orphan)
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
report = reconcile("--apply", "--grace-seconds", "0")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
report = reconcile("--apply", "--grace-seconds", "0")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
check(orphan not in report["deleted"] and orphan not in report["orphan_candidates"],
"second repair run was not idempotent")
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
@@ -92,11 +93,14 @@ def main():
missing = upload("missing.png")["json"]
missing_key = "originals/" + missing["id"]
s3_code("delete", missing_key)
report = reconcile("--grace-seconds", "0")
expected = {"attachment_id": missing["id"], "object_key": missing_key}
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
s3_code("put", missing_key, image)
try:
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", missing_key)
expected = {"attachment_id": missing["id"], "object_key": missing_key}
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
finally:
s3_code("put", missing_key, image)
check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image,
"test object was not restored")
report = reconcile("--grace-seconds", "0")
@@ -107,6 +111,7 @@ def main():
# replica. The public load balancer may correctly select the healthy peer,
# which would not exercise this boundary.
environment = dict(__import__("os").environ, UPLOAD_FAULT_AFTER_S3_PUT="1")
before_fault = set(reconcile("--grace-seconds", "0")["orphan_candidates"])
try:
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
@@ -128,14 +133,18 @@ else:
input=json.dumps({"chat_id": chat["id"], "token": alice["token"],
"image": base64.b64encode(image).decode()}))
report = reconcile("--grace-seconds", "0")
injected = [key for key in report["orphan_candidates"] if key.startswith("originals/")]
check(injected, "injected post-PUT failure did not create a detectable orphan")
report = reconcile("--apply", "--grace-seconds", "0")
injected = sorted(set(report["orphan_candidates"]) - before_fault)
check(len(injected) == 1, "fault must create exactly one new orphan; run without other writers")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", injected[0])
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
print("PASS: PostgreSQL-side post-PUT/pre-DB failure is repaired without deleting references", flush=True)
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]
check(message in history["items"], "message reference was lost")
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
"used original was lost")
print("PASS: injected pre-INSERT failure repaired; message and used original survive", flush=True)
finally:
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""Real database rejection, concurrent commit, interrupted upload and pagination."""
import base64
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, run
PROBE = r'''
import asyncio, base64, hashlib, http.client, json, sys, urllib.request, urllib.error
from types import SimpleNamespace
from uuid import UUID, uuid4
from src.config import load_settings
from src.storage.postgres import PostgresStore
from src.storage.s3 import S3Store, S3Settings
from src.reconcile import run as reconcile, scan
payload = json.load(sys.stdin)
image = base64.b64decode(payload['image'])
chat_id, user_id = UUID(payload['chat_id']), UUID(payload['user_id'])
def upload(filename):
req = urllib.request.Request('http://api-a:8080/api/v1/chats/' + str(chat_id) +
'/attachments?filename=' + filename, data=image, method='POST',
headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
try:
with urllib.request.urlopen(req, timeout=30) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
return error.code, json.load(error)
async def main():
db = PostgresStore(load_settings().database_url)
s3 = S3Store(S3Settings.load())
await db.connect()
def args(key):
return SimpleNamespace(apply=True, grace_seconds=0, object_key=[key])
try:
# A failed metadata inventory must not authorize any S3 deletion.
key = 'originals/audit-inventory-' + uuid4().hex
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
class BrokenInventory:
async def attachment_keys(self):
# Real SQL failure, not an empty inventory on error.
return await db.pool.fetch('SELECT * FROM audit_missing_table_' + uuid4().hex)
try:
async with db.attachment_transaction(maintenance=True):
try:
await scan(args(key), BrokenInventory(), s3)
except Exception:
pass
else:
raise AssertionError('failed inventory did not abort')
assert key in await s3.list('originals/')
finally:
await s3.delete(key)
print('PASS: failed PostgreSQL inventory aborts apply without deleting the orphan', flush=True)
# An actual PostgreSQL trigger rejects only this test chat's INSERT.
suffix = uuid4().hex
name = 'audit_reject_' + suffix
before = await s3.list('originals/')
await db.pool.execute(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN IF NEW.chat_id = '{chat_id}'::uuid THEN
RAISE EXCEPTION 'synthetic audit rejection' USING ERRCODE = '23514';
END IF; RETURN NEW; END $$""")
try:
await db.pool.execute(f'CREATE TRIGGER {name} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {name}()')
status, body = await asyncio.to_thread(upload, 'db-failure.png')
assert status == 503 and body['error']['code'] == 'unavailable', (status, body)
assert await db.pool.fetchval('SELECT count(*) FROM attachments WHERE chat_id=$1', chat_id) == 0
finally:
await db.pool.execute(f'DROP TRIGGER IF EXISTS {name} ON attachments')
await db.pool.execute(f'DROP FUNCTION {name}()')
created = set(await s3.list('originals/')) - set(before)
assert len(created) == 1, created
key = created.pop()
report = await reconcile(SimpleNamespace(apply=False, grace_seconds=0, object_key=[key]))
assert key in report['orphan_candidates'] and not report['deleted']
assert (await reconcile(args(key)))['deleted'] == [key]
assert not (await reconcile(args(key)))['deleted']
print('PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op', flush=True)
# Writer holds a shared lock after PUT; cleanup must wait for COMMIT.
identifier = uuid4()
key = 'originals/' + str(identifier)
async with db.attachment_transaction() as connection:
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
sweep = asyncio.create_task(reconcile(args(key)))
for _ in range(40):
waiting = await db.pool.fetchval("SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=41004 AND objid=1 AND NOT granted")
if waiting:
break
await asyncio.sleep(.05)
assert waiting and not sweep.done(), 'maintenance failed to wait for active writer'
await db.create_attachment(identifier, chat_id, user_id, 'concurrent.png', 'image/png',
len(image), hashlib.sha256(image).hexdigest(), key, connection=connection)
report = await sweep
assert key not in report['deleted'] and key not in report['orphan_candidates']
row = await db.attachment_for_member(identifier, user_id)
assert await s3.download(row) == image
print('PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives', flush=True)
# Abrupt client close before all bytes arrive must not persist a file.
before = await s3.list('originals/')
rows = await db.attachment_keys()
def interrupt():
conn = http.client.HTTPConnection('api-a', 8080, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + str(chat_id) + '/attachments?filename=interrupted.png')
conn.putheader('Authorization', 'Bearer ' + payload['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(image) + 100000))
conn.endheaders()
conn.send(image[:32])
conn.close()
await asyncio.to_thread(interrupt)
await asyncio.sleep(1)
assert await db.attachment_keys() == rows
assert await s3.list('originals/') == before
status, body = await asyncio.to_thread(upload, 'after-disconnect.png')
assert status == 201, (status, body)
print('PASS: interrupted upload leaves no metadata/object and next upload succeeds', flush=True)
# Exercise pagination on real S3 without adding thousands of fixtures.
original_call = s3.call
async def small_pages(method, **kwargs):
if method == 'list_objects_v2':
kwargs['MaxKeys'] = 7
return await original_call(method, **kwargs)
expected = await s3.list('originals/')
s3.call = small_pages
actual, pages = await s3.list_with_pages('originals/')
assert actual == expected and pages > 1
print(f'PASS: S3 pagination: {len(actual)} keys across {pages} pages, no missing/duplicate keys', flush=True)
finally:
s3.client.close()
await db.close()
asyncio.run(main())
'''
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=30)
alice, _, _, chat = client.bootstrap()
payload = {"chat_id": chat["id"], "user_id": alice["id"], "token": alice["token"],
"image": base64.b64encode((ROOT / "tests/fixtures/sample.png").read_bytes()).decode()}
subprocess.run(["docker", "compose", "--profile", "maintenance", "run", "--rm", "--no-deps",
"--entrypoint", "/app/.venv/bin/python", "reconcile", "-c", PROBE],
cwd=ROOT, input=json.dumps(payload), text=True, check=True)
if __name__ == "__main__":
run(main)
+16 -2
View File
@@ -34,16 +34,27 @@ def main():
seed = (ROOT / "tests/fixtures/sample.png").read_bytes()
payload = seed + b"\0" * (args.size_mib * 1024 * 1024 - len(seed))
baseline, peak, samples, stop = api_memory(), {}, [], threading.Event()
check(len(baseline) == 2, "memory experiment requires two running APIs")
sampling_errors = []
timestamps = []
barrier = threading.Barrier(10)
def sampler():
while not stop.is_set():
values = api_memory()
try:
values = api_memory()
check(set(values) == set(baseline), "API containers changed during measurement")
except Exception as error:
sampling_errors.append(type(error).__name__)
return
timestamps.append(time.monotonic())
samples.append(values)
for name, value in values.items():
peak[name] = max(peak.get(name, 0), value)
time.sleep(.1)
def upload(index):
barrier.wait(timeout=15)
parsed = urlsplit(client.base)
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=60)
@@ -73,13 +84,16 @@ def main():
thread.join(timeout=5)
elapsed = time.monotonic() - started
check(len({item["id"] for item in attachments}) == 10, "uploads were not distinct")
check(not sampling_errors and len(samples) >= 2 and not thread.is_alive(),
"memory sampler failed or did not collect enough samples: " + repr(sampling_errors))
report = {
"uploads": 10, "file_bytes": len(payload), "concurrency": 10,
"api_upload_concurrency_limit": 1, "elapsed_seconds": round(elapsed, 3),
"baseline_memory_bytes": baseline, "peak_memory_bytes": peak,
"peak_growth_bytes": {name: peak.get(name, 0) - baseline.get(name, 0) for name in baseline},
"samples": len(samples),
"method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler.",
"sample_intervals_seconds": [round(b-a, 3) for a, b in zip(timestamps, timestamps[1:])],
"method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous.",
}
destination = ROOT / args.output
destination.parent.mkdir(parents=True, exist_ok=True)