forked from mtusi2026/mtusi2026lab5
test(pipeline): coordinate stale writers within the live lease window
This commit is contained in:
@@ -23,7 +23,6 @@ PUBLIC_PORT=8085
|
||||
API_CPUS=0.5
|
||||
API_MEMORY=768m
|
||||
DB_POOL_SIZE=10
|
||||
RECONCILE_GRACE_SECONDS=300
|
||||
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
|
||||
@@ -232,3 +232,14 @@ slots/COUNT сдерживает конкуренцию. Возможен лиш
|
||||
долгой эксплуатации. Нет global admission quota: при долгой недоступности
|
||||
worker/broker PG outbox может расти; исследование перегрузки — другой трек.
|
||||
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
@@ -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
|
||||
@@ -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()
|
||||
+318
-240
@@ -100,6 +100,9 @@ def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/pipeline-repeat.json")
|
||||
parser.add_argument("--repeats", type=int, default=2)
|
||||
parser.add_argument(
|
||||
"--start-at", choices=["all", "versions"], default="all"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
if output.exists():
|
||||
@@ -108,6 +111,7 @@ def main():
|
||||
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||
"date": datetime.now(timezone.utc).isoformat(),
|
||||
"track": 2,
|
||||
"scope": args.start_at,
|
||||
"complete": False,
|
||||
"cases": [],
|
||||
}
|
||||
@@ -234,256 +238,330 @@ def main():
|
||||
)
|
||||
return effect
|
||||
|
||||
# Source-only crash before the DB handoff must never be reported as accepted.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
marker = inject(chat, "api_after_staging", "wait")
|
||||
before = inside(
|
||||
f"with db.connection() as c: n=c.execute('SELECT count(*) n FROM attachments WHERE chat_id=%s',({chat!r},)).fetchone()['n']\nprint(json.dumps(n))"
|
||||
)
|
||||
pool = ThreadPoolExecutor(max_workers=1)
|
||||
future = pool.submit(
|
||||
lambda: client.post(
|
||||
f"/api/v1/chats/{chat}/attachments",
|
||||
headers={**h, "Content-Type": "image/png"},
|
||||
params={"filename": "unconfirmed.png"},
|
||||
content=raw,
|
||||
if args.start_at == "all":
|
||||
# Source-only crash before the DB handoff must never be reported as accepted.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
marker = inject(chat, "api_after_staging", "wait")
|
||||
before = inside(
|
||||
f"with db.connection() as c: n=c.execute('SELECT count(*) n FROM attachments WHERE chat_id=%s',({chat!r},)).fetchone()['n']\nprint(json.dumps(n))"
|
||||
)
|
||||
)
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
compose("kill", "-s", "SIGKILL", "api")
|
||||
try:
|
||||
response = future.result(15)
|
||||
assert response.status_code != 202
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
pool.shutdown()
|
||||
start("api")
|
||||
ready()
|
||||
after = inside(
|
||||
f"with db.connection() as c: n=c.execute('SELECT count(*) n FROM attachments WHERE chat_id=%s',({chat!r},)).fetchone()['n']\nprint(json.dumps(n))"
|
||||
)
|
||||
assert before == after
|
||||
save(
|
||||
"staging_before_handoff_crash",
|
||||
{
|
||||
"no_202": True,
|
||||
"no_attachment_or_job_created": True,
|
||||
"orphan_retained_for_cleanup": True,
|
||||
},
|
||||
)
|
||||
# API durable commit/outbox survives restart without a broker or worker.
|
||||
a, j = upload()
|
||||
linked = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
)
|
||||
assert linked.status_code == 201
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
compose("restart", "api")
|
||||
ready()
|
||||
compose("kill", "-s", "SIGKILL", "broker")
|
||||
start("broker")
|
||||
start("relay")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
save(
|
||||
"commit_before_publish_and_worker_stopped",
|
||||
{
|
||||
"attachment": a["id"],
|
||||
"effect": effect,
|
||||
"queued_link_allowed": True,
|
||||
"api_and_broker_restarted": True,
|
||||
},
|
||||
)
|
||||
# Broker-volume survival with a confirmed, still-unconsumed stream entry.
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
wait(
|
||||
lambda: inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM outbox WHERE job_id=%s AND published_at IS NOT NULL',({j!r},)).fetchone()\nprint(json.dumps(r['n']>0))"
|
||||
pool = ThreadPoolExecutor(max_workers=1)
|
||||
future = pool.submit(
|
||||
lambda: client.post(
|
||||
f"/api/v1/chats/{chat}/attachments",
|
||||
headers={**h, "Content-Type": "image/png"},
|
||||
params={"filename": "unconfirmed.png"},
|
||||
content=raw,
|
||||
)
|
||||
)
|
||||
)
|
||||
stop("relay")
|
||||
ids = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||
compose("kill", "-s", "SIGKILL", "broker")
|
||||
start("broker")
|
||||
wait(lambda: inside("print(json.dumps(queue.ping()))"))
|
||||
restored = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||
assert restored == ids, {"before": ids, "after": restored}
|
||||
start("relay")
|
||||
start("worker")
|
||||
save(
|
||||
"confirmed_broker_entry_survives_sigkill",
|
||||
{
|
||||
"effect": confirm(a, j),
|
||||
"same_stream_entries": True,
|
||||
"entry_count": len(ids),
|
||||
},
|
||||
)
|
||||
# Confirm succeeded, PG marker did not: relay recovery may publish a duplicate.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
a, j = upload()
|
||||
marker = inject(j, "relay_after_publish", "crash")
|
||||
start("relay")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
time.sleep(0.5)
|
||||
unpublished = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM outbox WHERE job_id=%s AND published_at IS NULL',({j!r},)).fetchone()\nprint(json.dumps(r['n']))"
|
||||
)
|
||||
assert unpublished >= 1
|
||||
start("relay")
|
||||
start("worker")
|
||||
save(
|
||||
"relay_crash_after_xadd_before_pg_marker",
|
||||
{
|
||||
"unpublished_after_crash": unpublished,
|
||||
"effect": confirm(a, j),
|
||||
},
|
||||
)
|
||||
# Repeated before/after effect and commit/ack windows.
|
||||
for repeat in range(args.repeats):
|
||||
for phase in ["before_effect", "after_effect", "after_commit"]:
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, phase, "wait")
|
||||
start("worker")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
at_crash = inspect_effect(j)
|
||||
assert at_crash["publications"] == (
|
||||
1 if phase == "after_commit" else 0
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
compose("kill", "-s", "SIGKILL", "api")
|
||||
try:
|
||||
response = future.result(15)
|
||||
assert response.status_code != 202
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
pool.shutdown()
|
||||
start("api")
|
||||
ready()
|
||||
after = inside(
|
||||
f"with db.connection() as c: n=c.execute('SELECT count(*) n FROM attachments WHERE chat_id=%s',({chat!r},)).fetchone()['n']\nprint(json.dumps(n))"
|
||||
)
|
||||
assert before == after
|
||||
save(
|
||||
"staging_before_handoff_crash",
|
||||
{
|
||||
"no_202": True,
|
||||
"no_attachment_or_job_created": True,
|
||||
"orphan_retained_for_cleanup": True,
|
||||
},
|
||||
)
|
||||
# API durable commit/outbox survives restart without a broker or worker.
|
||||
stop("broker")
|
||||
a, j = upload()
|
||||
linked = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
)
|
||||
assert linked.status_code == 201
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
compose("restart", "api")
|
||||
ready()
|
||||
start("broker")
|
||||
start("relay")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
save(
|
||||
"commit_before_publish_and_worker_stopped",
|
||||
{
|
||||
"attachment": a["id"],
|
||||
"effect": effect,
|
||||
"queued_link_allowed": True,
|
||||
"api_and_broker_restarted": True,
|
||||
"broker_stopped_during_upload": True,
|
||||
},
|
||||
)
|
||||
# Broker-volume survival with a confirmed, still-unconsumed stream entry.
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
wait(
|
||||
lambda: inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM outbox WHERE job_id=%s AND published_at IS NOT NULL',({j!r},)).fetchone()\nprint(json.dumps(r['n']>0))"
|
||||
)
|
||||
assert len(at_crash["physical_keys"]) == (
|
||||
0 if phase == "before_effect" else 4
|
||||
)
|
||||
compose("kill", "-s", "SIGKILL", "worker")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
save(
|
||||
f"{phase}_sigkill_repeat_{repeat + 1}",
|
||||
{"at_crash": at_crash, "effect": effect},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "transient")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
assert effect["job"]["attempt"] == 2
|
||||
save("transient_retry_with_jitter", {"effect": effect})
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "hang")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
assert any(
|
||||
e["event"] == "retry"
|
||||
and e["detail"]["code"] == "worker_timeout"
|
||||
for e in effect["events"]
|
||||
)
|
||||
save("hung_child_killed_and_retried", {"effect": effect})
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "permanent")
|
||||
start("worker")
|
||||
failed = until(a, "failed")
|
||||
assert failed["error_code"] == "invalid_image"
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
r = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
)
|
||||
assert r.status_code == 409
|
||||
assert operator(j) == j
|
||||
effect = confirm(a, j)
|
||||
assert effect["job"]["cycle"] == 2
|
||||
try:
|
||||
)
|
||||
stop("relay")
|
||||
ids = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||
compose("kill", "-s", "SIGKILL", "broker")
|
||||
start("broker")
|
||||
wait(lambda: inside("print(json.dumps(queue.ping()))"))
|
||||
restored = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||
assert restored == ids, {"before": ids, "after": restored}
|
||||
start("relay")
|
||||
start("worker")
|
||||
save(
|
||||
"confirmed_broker_entry_survives_sigkill",
|
||||
{
|
||||
"effect": confirm(a, j),
|
||||
"same_stream_entries": True,
|
||||
"entry_count": len(ids),
|
||||
},
|
||||
)
|
||||
# Confirm succeeded, PG marker did not: relay recovery may publish a duplicate.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
a, j = upload()
|
||||
marker = inject(j, "relay_after_publish", "crash")
|
||||
start("relay")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
time.sleep(0.5)
|
||||
unpublished = inside(
|
||||
f"with db.connection() as c: r=c.execute('SELECT count(*) n FROM outbox WHERE job_id=%s AND published_at IS NULL',({j!r},)).fetchone()\nprint(json.dumps(r['n']))"
|
||||
)
|
||||
assert unpublished >= 1
|
||||
start("relay")
|
||||
start("worker")
|
||||
save(
|
||||
"relay_crash_after_xadd_before_pg_marker",
|
||||
{
|
||||
"unpublished_after_crash": unpublished,
|
||||
"effect": confirm(a, j),
|
||||
},
|
||||
)
|
||||
# Repeated before/after effect and commit/ack windows.
|
||||
for repeat in range(args.repeats):
|
||||
for phase in [
|
||||
"before_effect",
|
||||
"after_effect",
|
||||
"after_commit",
|
||||
]:
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, phase, "wait")
|
||||
start("worker")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
at_crash = inspect_effect(j)
|
||||
assert at_crash["job"]["state"] == (
|
||||
"ready"
|
||||
if phase == "after_commit"
|
||||
else "processing"
|
||||
)
|
||||
assert at_crash["publications"] == (
|
||||
1 if phase == "after_commit" else 0
|
||||
)
|
||||
assert len(at_crash["physical_keys"]) == (
|
||||
0 if phase == "before_effect" else 4
|
||||
)
|
||||
compose("kill", "-s", "SIGKILL", "worker")
|
||||
start("worker")
|
||||
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(
|
||||
f"{phase}_sigkill_repeat_{repeat + 1}",
|
||||
{"at_crash": at_crash, "effect": effect},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "transient")
|
||||
start("worker")
|
||||
effect = confirm(a, j)
|
||||
assert effect["job"]["attempt"] == 2
|
||||
save("transient_retry_with_jitter", {"effect": effect})
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, "before_effect", "hang")
|
||||
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)
|
||||
assert any(
|
||||
e["event"] == "retry"
|
||||
and e["detail"]["code"] == "worker_timeout"
|
||||
for e in effect["events"]
|
||||
)
|
||||
save(
|
||||
"hung_child_killed_and_retried",
|
||||
{"effect": effect, "observed_limits": limits},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "permanent")
|
||||
start("worker")
|
||||
failed = until(a, "failed")
|
||||
assert failed["error_code"] == "invalid_image"
|
||||
assert (
|
||||
client.get(
|
||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
r = client.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
)
|
||||
assert r.status_code == 409
|
||||
assert operator(j) == j
|
||||
effect = confirm(a, j)
|
||||
assert effect["job"]["cycle"] == 2
|
||||
try:
|
||||
operator(j)
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Replay of ready must be rejected")
|
||||
save(
|
||||
"permanent_failed_registry_and_audited_replay",
|
||||
{
|
||||
"failed": failed,
|
||||
"effect": effect,
|
||||
"ready_replay_rejected": True,
|
||||
},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "transient", remaining=5)
|
||||
start("worker")
|
||||
failed = until(a, "failed", timeout=150)
|
||||
assert (
|
||||
failed["error_code"] == "retry_exhausted"
|
||||
and row(j)["attempt"] == 5
|
||||
)
|
||||
operator(j)
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Replay of ready must be rejected")
|
||||
save(
|
||||
"permanent_failed_registry_and_audited_replay",
|
||||
{
|
||||
"failed": failed,
|
||||
"effect": effect,
|
||||
"ready_replay_rejected": True,
|
||||
},
|
||||
)
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
inject(j, "before_effect", "transient", remaining=5)
|
||||
start("worker")
|
||||
failed = until(a, "failed", timeout=150)
|
||||
assert (
|
||||
failed["error_code"] == "retry_exhausted"
|
||||
and row(j)["attempt"] == 5
|
||||
)
|
||||
operator(j)
|
||||
save(
|
||||
"finite_retry_exhaustion_then_explicit_replay",
|
||||
{"failed": failed, "effect": confirm(a, j)},
|
||||
)
|
||||
# Reverse notification order and add concurrent copies: one publication/key.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
a, j = upload()
|
||||
b, k = upload()
|
||||
duplicate(k, 8)
|
||||
duplicate(j, 8)
|
||||
start("worker")
|
||||
start("relay")
|
||||
ea = confirm(a, j)
|
||||
confirm(b, k)
|
||||
duplicate(j, 10)
|
||||
duplicate(k, 10)
|
||||
wait(
|
||||
lambda: any(
|
||||
e["event"] == "duplicate_decision"
|
||||
for e in inspect_effect(j)["events"]
|
||||
save(
|
||||
"finite_retry_exhaustion_then_explicit_replay",
|
||||
{"failed": failed, "effect": confirm(a, j)},
|
||||
)
|
||||
# Reverse notification order and add concurrent copies: one publication/key.
|
||||
stop("worker")
|
||||
stop("relay")
|
||||
a, j = upload()
|
||||
b, k = upload()
|
||||
duplicate(k, 8)
|
||||
duplicate(j, 8)
|
||||
start("worker")
|
||||
start("relay")
|
||||
ea = confirm(a, j)
|
||||
confirm(b, k)
|
||||
duplicate(j, 10)
|
||||
duplicate(k, 10)
|
||||
wait(
|
||||
lambda: any(
|
||||
e["event"] == "duplicate_decision"
|
||||
for e in inspect_effect(j)["events"]
|
||||
)
|
||||
)
|
||||
assert (
|
||||
inspect_effect(j)["job"]["attempt"] == ea["job"]["attempt"]
|
||||
)
|
||||
save(
|
||||
"reordered_and_duplicate_notifications",
|
||||
{
|
||||
"effects": [inspect_effect(j), inspect_effect(k)],
|
||||
"added_duplicates": 36,
|
||||
"no_extra_attempt_after_ready": True,
|
||||
},
|
||||
)
|
||||
)
|
||||
assert inspect_effect(j)["job"]["attempt"] == ea["job"]["attempt"]
|
||||
save(
|
||||
"reordered_and_duplicate_notifications",
|
||||
{
|
||||
"effects": [inspect_effect(j), inspect_effect(k)],
|
||||
"added_duplicates": 36,
|
||||
"no_extra_attempt_after_ready": True,
|
||||
},
|
||||
)
|
||||
# Hold v1 after its PUTs, complete v2 on the other bounded slot, release old CAS.
|
||||
for repeat in range(args.repeats):
|
||||
stop("worker")
|
||||
a, j = upload()
|
||||
marker = inject(j, "after_effect", "wait")
|
||||
start("worker")
|
||||
wait(lambda marker=marker: hit(marker))
|
||||
k = operator(j, version=2)
|
||||
v2 = confirm(a, k)
|
||||
hashes = {v["name"]: v["sha256"] for v in v2["variants"]}
|
||||
inside(
|
||||
f"with db.connection() as c: c.execute('UPDATE pipeline_faults SET released_at=clock_timestamp() WHERE id=%s',({marker},))\nprint('true')"
|
||||
)
|
||||
wait(
|
||||
lambda j=j: any(
|
||||
e["event"] == "stale_completion_rejected"
|
||||
for e in inspect_effect(j)["events"]
|
||||
# Keep one controller process hot throughout the narrow stale-writer window.
|
||||
code = f"""from src.pipeline import event
|
||||
with db.connection() as c: event(c,UUID({j!r}),'version_controller_waiting')
|
||||
end=time.monotonic()+45
|
||||
while True:
|
||||
with db.connection() as c: hit=c.execute('SELECT hit_at FROM pipeline_faults WHERE id=%s',({marker},)).fetchone()['hit_at']
|
||||
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(
|
||||
lambda j=j: inside(
|
||||
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))"
|
||||
)
|
||||
)
|
||||
)
|
||||
start("worker")
|
||||
race = future.result(timeout=45)
|
||||
k = race["job_id"]
|
||||
hashes = race["hashes"]
|
||||
confirm(a, k)
|
||||
duplicate(j, 12)
|
||||
wait(
|
||||
lambda j=j: any(
|
||||
@@ -597,7 +675,7 @@ print(json.dumps({{'anonymous':anonymous,'iam':denials}}))""")
|
||||
output.write_text(
|
||||
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__":
|
||||
|
||||
@@ -66,3 +66,54 @@ def test_invalid_notification_is_rejected(field, value):
|
||||
data[field] = value
|
||||
with pytest.raises((ValueError, TypeError)):
|
||||
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()
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user