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_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
|
||||||
|
|||||||
@@ -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
@@ -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 = 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,256 +238,330 @@ def main():
|
|||||||
)
|
)
|
||||||
return effect
|
return effect
|
||||||
|
|
||||||
# Source-only crash before the DB handoff must never be reported as accepted.
|
if args.start_at == "all":
|
||||||
stop("worker")
|
# Source-only crash before the DB handoff must never be reported as accepted.
|
||||||
stop("relay")
|
stop("worker")
|
||||||
marker = inject(chat, "api_after_staging", "wait")
|
stop("relay")
|
||||||
before = inside(
|
marker = inject(chat, "api_after_staging", "wait")
|
||||||
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))"
|
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,
|
|
||||||
)
|
)
|
||||||
)
|
pool = ThreadPoolExecutor(max_workers=1)
|
||||||
wait(lambda marker=marker: hit(marker))
|
future = pool.submit(
|
||||||
compose("kill", "-s", "SIGKILL", "api")
|
lambda: client.post(
|
||||||
try:
|
f"/api/v1/chats/{chat}/attachments",
|
||||||
response = future.result(15)
|
headers={**h, "Content-Type": "image/png"},
|
||||||
assert response.status_code != 202
|
params={"filename": "unconfirmed.png"},
|
||||||
except httpx.HTTPError:
|
content=raw,
|
||||||
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))"
|
|
||||||
)
|
)
|
||||||
)
|
wait(lambda marker=marker: hit(marker))
|
||||||
stop("relay")
|
compose("kill", "-s", "SIGKILL", "api")
|
||||||
ids = inside("print(json.dumps(queue.xrange(STREAM)))")
|
try:
|
||||||
compose("kill", "-s", "SIGKILL", "broker")
|
response = future.result(15)
|
||||||
start("broker")
|
assert response.status_code != 202
|
||||||
wait(lambda: inside("print(json.dumps(queue.ping()))"))
|
except httpx.HTTPError:
|
||||||
restored = inside("print(json.dumps(queue.xrange(STREAM)))")
|
pass
|
||||||
assert restored == ids, {"before": ids, "after": restored}
|
pool.shutdown()
|
||||||
start("relay")
|
start("api")
|
||||||
start("worker")
|
ready()
|
||||||
save(
|
after = inside(
|
||||||
"confirmed_broker_entry_survives_sigkill",
|
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))"
|
||||||
{
|
)
|
||||||
"effect": confirm(a, j),
|
assert before == after
|
||||||
"same_stream_entries": True,
|
save(
|
||||||
"entry_count": len(ids),
|
"staging_before_handoff_crash",
|
||||||
},
|
{
|
||||||
)
|
"no_202": True,
|
||||||
# Confirm succeeded, PG marker did not: relay recovery may publish a duplicate.
|
"no_attachment_or_job_created": True,
|
||||||
stop("worker")
|
"orphan_retained_for_cleanup": True,
|
||||||
stop("relay")
|
},
|
||||||
a, j = upload()
|
)
|
||||||
marker = inject(j, "relay_after_publish", "crash")
|
# API durable commit/outbox survives restart without a broker or worker.
|
||||||
start("relay")
|
stop("broker")
|
||||||
wait(lambda marker=marker: hit(marker))
|
a, j = upload()
|
||||||
time.sleep(0.5)
|
linked = client.post(
|
||||||
unpublished = inside(
|
f"/api/v1/chats/{chat}/messages",
|
||||||
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']))"
|
headers={**h, "Idempotency-Key": uuid4().hex},
|
||||||
)
|
json={"text": "", "attachment_ids": [a["id"]]},
|
||||||
assert unpublished >= 1
|
)
|
||||||
start("relay")
|
assert linked.status_code == 201
|
||||||
start("worker")
|
assert (
|
||||||
save(
|
client.get(
|
||||||
"relay_crash_after_xadd_before_pg_marker",
|
f"/api/v1/attachments/{a['id']}/content", headers=h
|
||||||
{
|
).status_code
|
||||||
"unpublished_after_crash": unpublished,
|
== 409
|
||||||
"effect": confirm(a, j),
|
)
|
||||||
},
|
compose("restart", "api")
|
||||||
)
|
ready()
|
||||||
# Repeated before/after effect and commit/ack windows.
|
start("broker")
|
||||||
for repeat in range(args.repeats):
|
start("relay")
|
||||||
for phase in ["before_effect", "after_effect", "after_commit"]:
|
start("worker")
|
||||||
stop("worker")
|
effect = confirm(a, j)
|
||||||
a, j = upload()
|
save(
|
||||||
marker = inject(j, phase, "wait")
|
"commit_before_publish_and_worker_stopped",
|
||||||
start("worker")
|
{
|
||||||
wait(lambda marker=marker: hit(marker))
|
"attachment": a["id"],
|
||||||
at_crash = inspect_effect(j)
|
"effect": effect,
|
||||||
assert at_crash["publications"] == (
|
"queued_link_allowed": True,
|
||||||
1 if phase == "after_commit" else 0
|
"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
|
stop("relay")
|
||||||
)
|
ids = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||||
compose("kill", "-s", "SIGKILL", "worker")
|
compose("kill", "-s", "SIGKILL", "broker")
|
||||||
start("worker")
|
start("broker")
|
||||||
effect = confirm(a, j)
|
wait(lambda: inside("print(json.dumps(queue.ping()))"))
|
||||||
save(
|
restored = inside("print(json.dumps(queue.xrange(STREAM)))")
|
||||||
f"{phase}_sigkill_repeat_{repeat + 1}",
|
assert restored == ids, {"before": ids, "after": restored}
|
||||||
{"at_crash": at_crash, "effect": effect},
|
start("relay")
|
||||||
)
|
start("worker")
|
||||||
stop("worker")
|
save(
|
||||||
a, j = upload()
|
"confirmed_broker_entry_survives_sigkill",
|
||||||
inject(j, "before_effect", "transient")
|
{
|
||||||
start("worker")
|
"effect": confirm(a, j),
|
||||||
effect = confirm(a, j)
|
"same_stream_entries": True,
|
||||||
assert effect["job"]["attempt"] == 2
|
"entry_count": len(ids),
|
||||||
save("transient_retry_with_jitter", {"effect": effect})
|
},
|
||||||
stop("worker")
|
)
|
||||||
a, j = upload()
|
# Confirm succeeded, PG marker did not: relay recovery may publish a duplicate.
|
||||||
inject(j, "before_effect", "hang")
|
stop("worker")
|
||||||
start("worker")
|
stop("relay")
|
||||||
effect = confirm(a, j)
|
a, j = upload()
|
||||||
assert any(
|
marker = inject(j, "relay_after_publish", "crash")
|
||||||
e["event"] == "retry"
|
start("relay")
|
||||||
and e["detail"]["code"] == "worker_timeout"
|
wait(lambda marker=marker: hit(marker))
|
||||||
for e in effect["events"]
|
time.sleep(0.5)
|
||||||
)
|
unpublished = inside(
|
||||||
save("hung_child_killed_and_retried", {"effect": effect})
|
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']))"
|
||||||
stop("worker")
|
)
|
||||||
a, j = upload()
|
assert unpublished >= 1
|
||||||
inject(j, "before_effect", "permanent")
|
start("relay")
|
||||||
start("worker")
|
start("worker")
|
||||||
failed = until(a, "failed")
|
save(
|
||||||
assert failed["error_code"] == "invalid_image"
|
"relay_crash_after_xadd_before_pg_marker",
|
||||||
assert (
|
{
|
||||||
client.get(
|
"unpublished_after_crash": unpublished,
|
||||||
f"/api/v1/attachments/{a['id']}/content", headers=h
|
"effect": confirm(a, j),
|
||||||
).status_code
|
},
|
||||||
== 409
|
)
|
||||||
)
|
# Repeated before/after effect and commit/ack windows.
|
||||||
r = client.post(
|
for repeat in range(args.repeats):
|
||||||
f"/api/v1/chats/{chat}/messages",
|
for phase in [
|
||||||
headers={**h, "Idempotency-Key": uuid4().hex},
|
"before_effect",
|
||||||
json={"text": "", "attachment_ids": [a["id"]]},
|
"after_effect",
|
||||||
)
|
"after_commit",
|
||||||
assert r.status_code == 409
|
]:
|
||||||
assert operator(j) == j
|
stop("worker")
|
||||||
effect = confirm(a, j)
|
a, j = upload()
|
||||||
assert effect["job"]["cycle"] == 2
|
marker = inject(j, phase, "wait")
|
||||||
try:
|
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)
|
operator(j)
|
||||||
except RuntimeError:
|
save(
|
||||||
pass
|
"finite_retry_exhaustion_then_explicit_replay",
|
||||||
else:
|
{"failed": failed, "effect": confirm(a, j)},
|
||||||
raise AssertionError("Replay of ready must be rejected")
|
)
|
||||||
save(
|
# Reverse notification order and add concurrent copies: one publication/key.
|
||||||
"permanent_failed_registry_and_audited_replay",
|
stop("worker")
|
||||||
{
|
stop("relay")
|
||||||
"failed": failed,
|
a, j = upload()
|
||||||
"effect": effect,
|
b, k = upload()
|
||||||
"ready_replay_rejected": True,
|
duplicate(k, 8)
|
||||||
},
|
duplicate(j, 8)
|
||||||
)
|
start("worker")
|
||||||
stop("worker")
|
start("relay")
|
||||||
a, j = upload()
|
ea = confirm(a, j)
|
||||||
inject(j, "before_effect", "transient", remaining=5)
|
confirm(b, k)
|
||||||
start("worker")
|
duplicate(j, 10)
|
||||||
failed = until(a, "failed", timeout=150)
|
duplicate(k, 10)
|
||||||
assert (
|
wait(
|
||||||
failed["error_code"] == "retry_exhausted"
|
lambda: any(
|
||||||
and row(j)["attempt"] == 5
|
e["event"] == "duplicate_decision"
|
||||||
)
|
for e in inspect_effect(j)["events"]
|
||||||
operator(j)
|
)
|
||||||
save(
|
)
|
||||||
"finite_retry_exhaustion_then_explicit_replay",
|
assert (
|
||||||
{"failed": failed, "effect": confirm(a, j)},
|
inspect_effect(j)["job"]["attempt"] == ea["job"]["attempt"]
|
||||||
)
|
)
|
||||||
# Reverse notification order and add concurrent copies: one publication/key.
|
save(
|
||||||
stop("worker")
|
"reordered_and_duplicate_notifications",
|
||||||
stop("relay")
|
{
|
||||||
a, j = upload()
|
"effects": [inspect_effect(j), inspect_effect(k)],
|
||||||
b, k = upload()
|
"added_duplicates": 36,
|
||||||
duplicate(k, 8)
|
"no_extra_attempt_after_ready": True,
|
||||||
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,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
# Hold v1 after its PUTs, complete v2 on the other bounded slot, release old CAS.
|
# Hold v1 after its PUTs, complete v2 on the other bounded slot, release old CAS.
|
||||||
for repeat in range(args.repeats):
|
for repeat in range(args.repeats):
|
||||||
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')
|
||||||
wait(
|
time.sleep(.05)
|
||||||
lambda j=j: any(
|
k=change(db,store,job_id=UUID({j!r}),operator='synthetic-verifier',reason='Held stale writer race',version=2)
|
||||||
e["event"] == "stale_completion_rejected"
|
end=time.monotonic()+10
|
||||||
for e in inspect_effect(j)["events"]
|
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)
|
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__":
|
||||||
|
|||||||
@@ -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()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user