test(pipeline): coordinate stale writers within the live lease window

This commit is contained in:
2026-11-15 23:03:53 +03:00
parent 2fa1b45da2
commit 972cef8f7f
7 changed files with 3024 additions and 241 deletions
-1
View File
@@ -23,7 +23,6 @@ PUBLIC_PORT=8085
API_CPUS=0.5 API_CPUS=0.5
API_MEMORY=768m API_MEMORY=768m
DB_POOL_SIZE=10 DB_POOL_SIZE=10
RECONCILE_GRACE_SECONDS=300
BROKER_URL_FILE=/run/secrets/broker_url BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2 WORKER_CONCURRENCY=2
+11
View File
@@ -232,3 +232,14 @@ slots/COUNT сдерживает конкуренцию. Возможен лиш
долгой эксплуатации. Нет global admission quota: при долгой недоступности долгой эксплуатации. Нет global admission quota: при долгой недоступности
worker/broker PG outbox может расти; исследование перегрузки — другой трек. worker/broker PG outbox может расти; исследование перегрузки — другой трек.
Short synthetic fixtures и повторы ограничивают обобщение на большие файлы. Short synthetic fixtures и повторы ограничивают обобщение на большие файлы.
Успешно завершившиеся child samples не включают RSS убитых процессов.
## Настройки
Compose использует PUBLIC_PORT, API_REPLICAS/CPUS/MEMORY, DB_POOL_SIZE,
SESSION_TTL_SECONDS, WORKER_CONCURRENCY, JOB_MAX_ATTEMPTS/TIMEOUT/LEASE и
STAGING_RETENTION_SECONDS. Значения .env.example для S3 endpoint/region/bucket,
MAX_UPLOAD_BYTES/MAX_IMAGE_PIXELS и idempotency TTL документируют фиксированный
контракт реализации: s3:9000/us-east-1/messenger,10MiB/40M/24h. Их нельзя изменить
одним редактированием env: соответствующие constants/SQL надо менять согласованно.
Secret *_FILE paths заданы в compose; значения создаёт bootstrap.
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
PASS: staging_before_handoff_crash
PASS: commit_before_publish_and_worker_stopped
PASS: confirmed_broker_entry_survives_sigkill
PASS: relay_crash_after_xadd_before_pg_marker
PASS: before_effect_sigkill_repeat_1
PASS: after_effect_sigkill_repeat_1
PASS: after_commit_sigkill_repeat_1
PASS: before_effect_sigkill_repeat_2
PASS: after_effect_sigkill_repeat_2
PASS: after_commit_sigkill_repeat_2
PASS: transient_retry_with_jitter
PASS: hung_child_killed_and_retried
PASS: permanent_failed_registry_and_audited_replay
PASS: finite_retry_exhaustion_then_explicit_replay
PASS: reordered_and_duplicate_notifications
Traceback (most recent call last):
File "<frozen runpy>", line 203, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "<repository>/scripts/verify_pipeline.py", line 604, in <module>
report["worker_metrics"] = inside(
File "<repository>/scripts/verify_pipeline.py", line 481, in main
"reordered_and_duplicate_notifications",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...<4 lines>...
},
^
File "<repository>/scripts/verify_pipeline.py", line 48, in wait
raise TimeoutError("Fault scenario condition not reached")
TimeoutError: Fault scenario condition not reached
+126
View File
@@ -0,0 +1,126 @@
"""Summarize measured fault invariants and child resource samples."""
import argparse
import csv
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def effects(case):
for key in ["effect", "v1", "v2"]:
if key in case:
yield key, case[key]
for i, item in enumerate(case.get("effects", [])):
yield str(i + 1), item
def main():
p = argparse.ArgumentParser()
p.add_argument("input", type=Path)
p.add_argument("--output", required=True, type=Path)
a = p.parse_args()
d = json.loads(a.input.read_text())
assert d["complete"] and d.get("scope", "all") == "all"
rows = []
for case in d["cases"]:
for role, e in effects(case):
j = e["job"]
rows.append(
dict(
case=case["case"],
role=role,
job_id=j["id"],
version=j["pipeline_version"],
attempt=j["attempt"],
cycle=j["cycle"],
fence=j["fence"],
state=j["state"],
publications=e["publications"],
variant_rows=len(e["variants"]),
physical_keys=len(e["physical_keys"]),
)
)
a.output.mkdir(parents=True, exist_ok=True)
with (a.output / "effects.csv").open("w") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
ready = [r for r in rows if r["state"] == "ready"]
assert all(
r["publications"] == 1
and r["variant_rows"] == 4
and r["physical_keys"] == 4
for r in ready
)
stale = [r for r in rows if r["state"] == "obsolete"]
assert all(r["publications"] == 0 for r in stale)
samples = [
x["detail"]
for x in d["worker_metrics"]
if x["detail"].get("result") == "ready"
and "rss_peak_mib" in x["detail"]
]
stats = {
"source_commit": d["source_commit"],
"cases": len(d["cases"]),
"observed_ready_effects": len(ready),
"observed_obsolete_effects": len(stale),
"all_ready_have_one_publication_and_four_variants": True,
"all_obsolete_have_zero_publications": True,
"successful_child_samples": len(samples),
"child_elapsed_range_seconds": [
min(x["seconds"] for x in samples),
max(x["seconds"] for x in samples),
],
"child_cpu_range_seconds": [
min(x["cpu_seconds"] for x in samples),
max(x["cpu_seconds"] for x in samples),
],
"child_peak_rss_range_mib": [
min(x["rss_peak_mib"] for x in samples),
max(x["rss_peak_mib"] for x in samples),
],
"scope": "process self metrics, no queue lag or throughput claim; fault-free and retry children only where a result was returned",
}
(a.output / "summary.json").write_text(json.dumps(stats, indent=2) + "\n")
fig, axes = plt.subplots(1, 2, figsize=(13, 5), layout="constrained")
axes[0].bar(
range(1, len(rows) + 1),
[r["publications"] for r in rows],
color=[
"#246b8e" if r["state"] == "ready" else "#d17d20" for r in rows
],
)
axes[0].axhline(1, color="#5b6870", linestyle="--", linewidth=1)
axes[0].set(
xlabel="Effect observation (CSV row)",
ylabel="Committed publications",
title="One publication per ready version; stale v1 = 0",
yticks=[0, 1],
)
axes[1].scatter(
[x["seconds"] for x in samples],
[x["rss_peak_mib"] for x in samples],
color="#246b8e",
s=35,
alpha=0.8,
)
axes[1].set(
xlabel="Child elapsed, seconds",
ylabel="Child peak RSS, MiB",
title=f"{len(samples)} completed child samples (synthetic320×200)",
)
for ax in axes:
ax.grid(axis="y", alpha=0.2)
fig.savefig(a.output / "pipeline-results.png", dpi=150)
plt.close(fig)
print(json.dumps(stats, indent=2))
if __name__ == "__main__":
main()
+95 -17
View File
@@ -100,6 +100,9 @@ def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("--output", default="evidence/pipeline-repeat.json") parser.add_argument("--output", default="evidence/pipeline-repeat.json")
parser.add_argument("--repeats", type=int, default=2) parser.add_argument("--repeats", type=int, default=2)
parser.add_argument(
"--start-at", choices=["all", "versions"], default="all"
)
args = parser.parse_args() args = parser.parse_args()
output = ROOT / args.output output = ROOT / args.output
if output.exists(): if output.exists():
@@ -108,6 +111,7 @@ def main():
"source_commit": command(["git", "rev-parse", "HEAD"]), "source_commit": command(["git", "rev-parse", "HEAD"]),
"date": datetime.now(timezone.utc).isoformat(), "date": datetime.now(timezone.utc).isoformat(),
"track": 2, "track": 2,
"scope": args.start_at,
"complete": False, "complete": False,
"cases": [], "cases": [],
} }
@@ -234,6 +238,7 @@ def main():
) )
return effect return effect
if args.start_at == "all":
# Source-only crash before the DB handoff must never be reported as accepted. # Source-only crash before the DB handoff must never be reported as accepted.
stop("worker") stop("worker")
stop("relay") stop("relay")
@@ -273,6 +278,7 @@ def main():
}, },
) )
# API durable commit/outbox survives restart without a broker or worker. # API durable commit/outbox survives restart without a broker or worker.
stop("broker")
a, j = upload() a, j = upload()
linked = client.post( linked = client.post(
f"/api/v1/chats/{chat}/messages", f"/api/v1/chats/{chat}/messages",
@@ -288,7 +294,6 @@ def main():
) )
compose("restart", "api") compose("restart", "api")
ready() ready()
compose("kill", "-s", "SIGKILL", "broker")
start("broker") start("broker")
start("relay") start("relay")
start("worker") start("worker")
@@ -300,6 +305,7 @@ def main():
"effect": effect, "effect": effect,
"queued_link_allowed": True, "queued_link_allowed": True,
"api_and_broker_restarted": True, "api_and_broker_restarted": True,
"broker_stopped_during_upload": True,
}, },
) )
# Broker-volume survival with a confirmed, still-unconsumed stream entry. # Broker-volume survival with a confirmed, still-unconsumed stream entry.
@@ -350,13 +356,22 @@ def main():
) )
# Repeated before/after effect and commit/ack windows. # Repeated before/after effect and commit/ack windows.
for repeat in range(args.repeats): for repeat in range(args.repeats):
for phase in ["before_effect", "after_effect", "after_commit"]: for phase in [
"before_effect",
"after_effect",
"after_commit",
]:
stop("worker") stop("worker")
a, j = upload() a, j = upload()
marker = inject(j, phase, "wait") marker = inject(j, phase, "wait")
start("worker") start("worker")
wait(lambda marker=marker: hit(marker)) wait(lambda marker=marker: hit(marker))
at_crash = inspect_effect(j) at_crash = inspect_effect(j)
assert at_crash["job"]["state"] == (
"ready"
if phase == "after_commit"
else "processing"
)
assert at_crash["publications"] == ( assert at_crash["publications"] == (
1 if phase == "after_commit" else 0 1 if phase == "after_commit" else 0
) )
@@ -366,6 +381,22 @@ def main():
compose("kill", "-s", "SIGKILL", "worker") compose("kill", "-s", "SIGKILL", "worker")
start("worker") start("worker")
effect = confirm(a, j) effect = confirm(a, j)
if phase == "after_commit":
wait(
lambda j=j: any(
e["event"] == "duplicate_decision"
and e["detail"]["state"] == "ready"
for e in inspect_effect(j)["events"]
)
)
wait(
lambda j=j: inside(
f"print(json.dumps(not any(json.loads(fields.get('job','{{}}')).get('job_id')=={j!r} for _,fields in queue.xrange(STREAM))))"
)
)
effect = inspect_effect(j)
else:
assert effect["job"]["attempt"] >= 2
save( save(
f"{phase}_sigkill_repeat_{repeat + 1}", f"{phase}_sigkill_repeat_{repeat + 1}",
{"at_crash": at_crash, "effect": effect}, {"at_crash": at_crash, "effect": effect},
@@ -379,15 +410,35 @@ def main():
save("transient_retry_with_jitter", {"effect": effect}) save("transient_retry_with_jitter", {"effect": effect})
stop("worker") stop("worker")
a, j = upload() a, j = upload()
inject(j, "before_effect", "hang") marker = inject(j, "before_effect", "hang")
start("worker") start("worker")
wait(lambda: hit(marker))
cid = compose("ps", "-q", "worker").split()[0]
code = """import json,pathlib,re
limits=[]
for p in pathlib.Path('/proc').glob('[0-9]*/limits'):
try:
line=next(x for x in p.read_text().splitlines() if x.startswith('Max address space'))
if re.search(r'805306368\\s+805306368',line): limits.append({'pid':p.parent.name,'limit':line})
except (FileNotFoundError,PermissionError,StopIteration,ProcessLookupError): pass
root=pathlib.Path('/sys/fs/cgroup')
print(json.dumps({'bounded_children':limits,'cgroup':{n:(root/n).read_text().strip() for n in ['memory.max','memory.current','memory.peak','cpu.max','pids.current']}}))
"""
limits = json.loads(
command(["docker", "exec", cid, "python", "-c", code])
)
assert 1 <= len(limits["bounded_children"]) <= 2
assert limits["cgroup"]["memory.max"] == "1610612736"
effect = confirm(a, j) effect = confirm(a, j)
assert any( assert any(
e["event"] == "retry" e["event"] == "retry"
and e["detail"]["code"] == "worker_timeout" and e["detail"]["code"] == "worker_timeout"
for e in effect["events"] for e in effect["events"]
) )
save("hung_child_killed_and_retried", {"effect": effect}) save(
"hung_child_killed_and_retried",
{"effect": effect, "observed_limits": limits},
)
stop("worker") stop("worker")
a, j = upload() a, j = upload()
inject(j, "before_effect", "permanent") inject(j, "before_effect", "permanent")
@@ -456,7 +507,9 @@ def main():
for e in inspect_effect(j)["events"] for e in inspect_effect(j)["events"]
) )
) )
assert inspect_effect(j)["job"]["attempt"] == ea["job"]["attempt"] assert (
inspect_effect(j)["job"]["attempt"] == ea["job"]["attempt"]
)
save( save(
"reordered_and_duplicate_notifications", "reordered_and_duplicate_notifications",
{ {
@@ -470,20 +523,45 @@ def main():
stop("worker") stop("worker")
a, j = upload() a, j = upload()
marker = inject(j, "after_effect", "wait") marker = inject(j, "after_effect", "wait")
start("worker") # Keep one controller process hot throughout the narrow stale-writer window.
wait(lambda marker=marker: hit(marker)) code = f"""from src.pipeline import event
k = operator(j, version=2) with db.connection() as c: event(c,UUID({j!r}),'version_controller_waiting')
v2 = confirm(a, k) end=time.monotonic()+45
hashes = {v["name"]: v["sha256"] for v in v2["variants"]} while True:
inside( with db.connection() as c: hit=c.execute('SELECT hit_at FROM pipeline_faults WHERE id=%s',({marker},)).fetchone()['hit_at']
f"with db.connection() as c: c.execute('UPDATE pipeline_faults SET released_at=clock_timestamp() WHERE id=%s',({marker},))\nprint('true')" if hit: break
) if time.monotonic()>end: raise TimeoutError('v1 hook never hit')
time.sleep(.05)
k=change(db,store,job_id=UUID({j!r}),operator='synthetic-verifier',reason='Held stale writer race',version=2)
end=time.monotonic()+10
while True:
with db.connection() as c: ready=c.execute('SELECT state FROM jobs WHERE id=%s',(k,)).fetchone()['state']=='ready'
if ready: break
if time.monotonic()>end: raise TimeoutError('v2 did not finish inside live v1 budget')
time.sleep(.05)
with db.connection() as c:
hashes=c.execute('SELECT name,sha256 FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=2 ORDER BY name',({a["id"]!r},)).fetchall()
c.execute('UPDATE pipeline_faults SET released_at=clock_timestamp() WHERE id=%s',({marker},))
end=time.monotonic()+10
while True:
with db.connection() as c: stale=c.execute("SELECT count(*) n FROM pipeline_events WHERE job_id=%s AND event='stale_completion_rejected'",({j!r},)).fetchone()['n']
if stale: break
if time.monotonic()>end: raise TimeoutError('Old completion was not rejected')
time.sleep(.05)
print(json.dumps({{'job_id':k,'hashes':{{r['name']:r['sha256'] for r in hashes}}}}))
"""
with ThreadPoolExecutor(max_workers=1) as hot:
future = hot.submit(inside, code)
wait( wait(
lambda j=j: any( lambda j=j: inside(
e["event"] == "stale_completion_rejected" f"with db.connection() as c: n=c.execute(\"SELECT count(*) n FROM pipeline_events WHERE job_id=%s AND event='version_controller_waiting'\",({j!r},)).fetchone()['n']\nprint(json.dumps(n>0))"
for e in inspect_effect(j)["events"]
) )
) )
start("worker")
race = future.result(timeout=45)
k = race["job_id"]
hashes = race["hashes"]
confirm(a, k)
duplicate(j, 12) duplicate(j, 12)
wait( wait(
lambda j=j: any( lambda j=j: any(
@@ -597,7 +675,7 @@ print(json.dumps({{'anonymous':anonymous,'iam':denials}}))""")
output.write_text( output.write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n" json.dumps(report, ensure_ascii=False, indent=2) + "\n"
) )
print("PASS: complete versioned pipeline fault matrix", flush=True) print("PASS: versioned pipeline scope=" + args.start_at, flush=True)
if __name__ == "__main__": if __name__ == "__main__":
+51
View File
@@ -66,3 +66,54 @@ def test_invalid_notification_is_rejected(field, value):
data[field] = value data[field] = value
with pytest.raises((ValueError, TypeError)): with pytest.raises((ValueError, TypeError)):
validate_job(data) validate_job(data)
def test_worker_rejects_oversized_pixels_before_decode():
import hashlib
import io
from PIL import Image
from src.pipeline import PermanentFailure
from src.worker import make_variants
stream = io.BytesIO()
Image.new("1", (8000, 5001)).save(stream, format="PNG")
raw = stream.getvalue()
row = dict(
size_bytes=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
content_type="image/png",
pipeline_version=1,
)
with (
pytest.warns(Image.DecompressionBombWarning),
pytest.raises(PermanentFailure, match="pixel_limit"),
):
list(make_variants(raw, row))
def test_worker_rejects_changed_source_checksum():
from src.pipeline import PermanentFailure
from src.worker import make_variants
with pytest.raises(PermanentFailure, match="source_checksum_mismatch"):
list(make_variants(b"changed", dict(size_bytes=7, sha256="0" * 64)))
def test_worker_rejects_invalid_image_as_permanent():
import hashlib
from src.pipeline import PermanentFailure
from src.worker import make_variants
raw = b"not an image"
with pytest.raises(PermanentFailure, match="invalid_image"):
list(
make_variants(
raw,
dict(
size_bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest()
),
)
)