Forward the lab 5 foundation while preserving lab 6 telemetry

Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.

Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
This commit is contained in:
Artyom
2026-11-06 12:29:35 +03:00
parent dc9256baf9
commit 12db77133f
161 changed files with 11160 additions and 1467 deletions
+130 -25
View File
@@ -107,9 +107,11 @@ staging_left:
WHERE id = ANY(:'ids'::uuid[]) AND status = 'ready' AND staging_key IS NOT NULL
object_keys:
SELECT object_key AS key FROM attachment_variants
UNION ALL SELECT original_key FROM attachments WHERE original_key IS NOT NULL
UNION ALL SELECT staging_key FROM attachments WHERE staging_key IS NOT NULL
SELECT object_key AS key FROM attachment_variants WHERE attachment_id = ANY(:'ids'::uuid[])
UNION ALL SELECT original_key FROM attachments
WHERE id = ANY(:'ids'::uuid[]) AND original_key IS NOT NULL
UNION ALL SELECT staging_key FROM attachments
WHERE id = ANY(:'ids'::uuid[]) AND staging_key IS NOT NULL
columns:
SELECT table_name, column_name FROM information_schema.columns
@@ -252,6 +254,35 @@ class Stack:
out = self.rabbitmqadmin(*command, json.dumps(properties), stdin=json.dumps(payload))
check("routed successfully" in out, "broker did not route the injected job")
def s3_json(self, *argv, missing=False):
done = subprocess.run(
[*self.base, "run", "--rm", "--no-deps", "-T", "s3-cli", *argv, "--json"],
capture_output=True,
text=True,
timeout=60,
check=False,
)
body = json.loads(done.stdout or done.stderr)
if missing and done.returncode == 5 and body.get("details", {}).get("type") == "not_found":
return None
check(done.returncode == 0, "S3 inventory command failed: exit " + str(done.returncode))
return body
def objects(self, ids):
bucket = self.dc("exec", "-T", self.args.relay, "printenv", "S3_BUCKET").strip()
keys = set()
for ident in ids:
for prefix in ("staging", "originals"):
body = self.s3_json(
"object", "stat", f"root/{bucket}/{prefix}/{ident}", missing=True
)
if body is not None:
keys.add(body["name"])
body = self.s3_json("object", "list", "--recursive", f"root/{bucket}/variants/{ident}/")
check(not body["truncated"], "S3 variant inventory is truncated")
keys.update(item["key"] for item in body["items"])
return keys
def admin(self, *argv):
command = shlex.split(self.args.admin) + list(argv)
out = self.dc("run", "--rm", "--no-deps", "-T", self.args.worker, *command)
@@ -396,6 +427,9 @@ class Suite:
code = self.stack.wait_exit(service)
check(code == 137, f"{service} exited with {code}, expected 137 at {point}")
seen = observe(ident)
seen["containers"] = self.stack.dc(
"ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}", service
).splitlines()
self.stack.launch(service)
ready = self.api.wait(ident, timeout=self.args.recovery_timeout)
poll(lambda: all(r["published"] for r in self.stack.sql("outbox", id=ident)), 30, "outbox")
@@ -424,7 +458,12 @@ class Suite:
steps.append({"at": now(), "step": step, **extra})
self.stack.stop(self.args.worker)
mark("worker stopped")
mark(
"worker stopped",
containers=self.stack.dc(
"ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}", self.args.worker
).splitlines(),
)
att = self.api.fixture()
mark("upload 202 queued", attachment_id=att["id"])
self.api.content(att["id"], expected=409)
@@ -594,15 +633,39 @@ class Suite:
self.api.final[ident] = {"failed"}
kept = self.record(ident)["staging_key"]
check(kept is not None, "failed staging was removed before the retention period")
try:
self.stack.launch(self.args.relay, FAULT_STAGING_RETENTION_SECONDS="1")
poll(lambda: self.record(ident)["staging_key"] is None, 30, "failed staging cleanup")
finally:
self.stack.launch(self.args.relay)
retention = int(
self.stack.dc("exec", "-T", self.args.relay, "printenv", "STAGING_RETENTION_SECONDS")
)
aged = self.stack.dc(
"exec",
"-T",
self.args.postgres,
"sh",
"-c",
PSQL,
"sh",
"-v",
"id=" + ident,
"-v",
"chat=" + self.api.chat["id"],
"-v",
"age=" + str(retention + 1),
stdin="UPDATE attachments SET created_at = created_at - :age * interval '1 second', "
"updated_at = updated_at - :age * interval '1 second' "
"WHERE id = :'id' AND chat_id = :'chat' AND status = 'failed' RETURNING id;\n",
)
check(aged.strip() == ident, "did not age exactly the suite's failed attachment")
poll(lambda: self.record(ident)["staging_key"] is None, 30, "failed staging cleanup")
replay = self.stack.admin("replay", "--attachment-id", ident)
check(replay["result"] == "expired", f"replay after retention gave {replay}")
check(self.api.get(ident)["status"] == "failed", "expired replay changed the status")
return {"attachment_id": ident, "staging_before": "kept", "replay": replay}
return {
"attachment_id": ident,
"staging_before": "kept",
"retention_seconds": retention,
"aged_only": ident,
"replay": replay,
}
def image_matrix(self):
folder = Path(self.args.images)
@@ -696,11 +759,19 @@ class Suite:
poll(lambda: self.record(ident)["status"] == "processing", 30, "processing")
self.stack.kill(self.args.worker)
code = self.stack.wait_exit(self.args.worker)
containers = self.stack.dc(
"ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}", self.args.worker
).splitlines()
self.stack.launch(self.args.worker)
ready = self.api.wait(ident, timeout=self.args.recovery_timeout)
self.drained()
self.verify(ready)
return {"attachment_id": ident, "exit_code": code, "jobs": self.stack.sql("jobs", id=ident)}
return {
"attachment_id": ident,
"exit_code": code,
"containers": containers,
"jobs": self.stack.sql("jobs", id=ident),
}
def duplicate_in_flight(self):
self.stack.stop(self.args.worker)
@@ -743,36 +814,60 @@ class Suite:
def reorder_versions(self):
self.stack.stop(self.args.worker, self.args.relay)
ident = self.api.fixture()["id"]
self.reprocess(ident)
check(self.reprocess(ident)["result"] == "queued", "version 2 was not scheduled")
check(self.reprocess(ident)["result"] == "noop", "duplicate reprocess was not a noop")
self.stack.publish(self.payload(ident, 2))
self.queued(1)
self.stack.launch(self.args.relay)
self.queued(3)
self.stack.launch(self.args.worker)
self.published(ident, 2)
self.api.wait(ident)
before = self.snapshot(ident)
self.stack.launch(self.args.relay)
poll(
lambda: (
{j["pipeline_version"]: j["status"] for j in self.stack.sql("jobs", id=ident)}
== {1: "superseded", 2: "done"}
),
self.args.recovery_timeout,
"old version superseded",
)
poll(lambda: all(r["published"] for r in self.stack.sql("outbox", id=ident)), 30, "outbox")
self.drained()
final = self.snapshot(ident)
check(final["published"] == 2, f"published_version rolled back to {final['published']}")
check(before["public"] == final["public"], "late v1 changed the published v2 variants")
served = {v["name"]: v["sha256"] for v in final["public"]}
stored = {r["name"]: r["sha256"] for r in final["rows"] if r["pipeline_version"] == 2}
check(served == stored, "API serves variants of a version that is not published")
jobs = self.stack.sql("jobs", id=ident)
check(
{j["pipeline_version"]: j["status"] for j in jobs} == {1: "superseded", 2: "done"},
"v1 did not finish after v2",
)
self.verify(self.api.get(ident))
return {"attachment_id": ident, "jobs": self.stack.sql("jobs", id=ident)}
return {"attachment_id": ident, "jobs": jobs, "v2_before_v1": before, "after_v1": final}
def stale_after_new_version(self):
ident = self.api.fixture()["id"]
self.api.wait(ident)
self.reprocess(ident)
first = self.snapshot(ident)
check(self.reprocess(ident)["result"] == "queued", "version 2 was not scheduled")
check(self.api.get(ident)["status"] == "ready", "reprocess rolled back ready")
self.published(ident, 2)
self.drained()
before = self.snapshot(ident)
check(first["public"] != before["public"], "recipes did not produce distinct results")
self.stack.publish(self.payload(ident, 1))
self.drained()
time.sleep(1)
after = self.snapshot(ident)
check(before == after and after["published"] == 2, "stale v1 job changed the v2 result")
return {"attachment_id": ident, "published_version": after["published"]}
return {
"attachment_id": ident,
"published_version": after["published"],
"v1": first,
"v2_before_stale": before,
"v2_after_stale": after,
}
def invariants(self, dead_before):
ids = self.api.accepted
@@ -819,13 +914,21 @@ class Suite:
check(queues[QUEUE] == (0, 0), "messages left in " + QUEUE)
expected = dead_before + self.dead_letters
check(queues[DLQ][0] == expected, f"unexpected dead letters: {queues[DLQ]}")
if not self.args.s3_list:
return {"queues": queues, "s3": "SKIP: --s3-list is not set"}
keys = {r["key"] for r in self.stack.sql("object_keys")}
listing = run(shlex.split(self.args.s3_list)).splitlines()
stray = [k for k in (x.split()[-1] for x in listing if x.strip()) if k not in keys]
check(not stray, f"S3 objects without metadata: {stray[:5]}")
return {"queues": queues, "s3_objects": len(listing)}
keys = {r["key"] for r in self.stack.sql("object_keys", ids=array)}
if self.args.s3_list:
listing = {
x.split()[-1]
for x in run(shlex.split(self.args.s3_list)).splitlines()
if x.strip()
}
listing = {key for key in listing if any("/" + ident in key for ident in ids)}
else:
listing = self.stack.objects(ids)
check(
listing == keys,
f"S3 mismatch: extra={sorted(listing - keys)}, missing={sorted(keys - listing)}",
)
return {"queues": queues, "s3_objects": len(listing), "scoped_attachments": len(ids)}
def no_loss():
known = {r["id"] for r in self.stack.sql("known", ids=array)}
@@ -904,6 +1007,7 @@ class Suite:
report = {
"suite": "lab5-pipeline-idempotency",
"started_at": now(),
"source_sha": run(["git", "rev-parse", "HEAD"]).strip(),
"config": self.config(),
}
if self.args.preflight:
@@ -925,6 +1029,7 @@ class Suite:
finally:
self.stack.up(self.args.s3)
self.stack.restore()
report["accepted_ids"] = self.api.accepted if self.api else []
report["scenarios"] = results
return self.finish(report, results + report.get("invariants", []))