fix(runtime): resolve PR #27/#26 post-merge review findings + tests #28
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #28"
general
weight: 0.35
Xander-Xai
Why
PR #27 (
feat/distributed-agent-runtime) was merged ate6b6588with all 5 of itsreview threads unresolved, and the branch was deleted. This PR is the post-merge
convergence those threads asked for: correctness fixes, the missing regression tests,
real-infrastructure evidence, and PR metadata. PR #26
(
feat/distributed-checkpoint-postgres) was closed with its 5 threads unresolved;its checkpoint commit
d615b8fis carried forward here and every #26 finding wasre-verified on this HEAD. Old-PR provenance is not a reason to ignore a finding.
Closes #25
Audit result — every unresolved thread re-verified on this HEAD
10 findings: 5 from #27, 5 from #26. Verdicts are from reading the code at
1d36a7a,not from the earlier round's claims.
| # | Finding | Source | Verdict | Fix + where |
|---|---|---|---|---|
| A | worker cannot boot with its own Compose env (
API_KEY/JWT_SECRET/SESSION_TOKEN_SECRET/CORS_ORIGINSmissing) | #27 | STILL_VALID |SERVICE_ROLE=workerskips API-only validation (core/config.py:212); Compose worker env forwards what it consumes; contract test asserts aruntime.celery_appimport succeeds with only the worker's env || B | retry-publication failure silently ACKed ->
RETRYINGforever | #27 | STILL_VALID, twice |RetryPublicationErrorescapes the task (runtime/executor.py:257) and the outer handler refuses to ACK a run parked inRETRYING/QUEUED(:278); durable backstopruntime.retry.reconcile_stuck_runs+scripts/reconcile_stuck_runs.py. Incomplete on first pass: escaping is not enough — Celery ACKs failed tasks by default, sotask_acks_on_failure_or_timeout=Falsewas also required (f5bdb51). Round-1 claim "acks_lateforces redelivery" was wrong || C |
PENDINGside-effect claim not mutually exclusive | #27 | STILL_VALID | atomicINSERT ... ON CONFLICT DO NOTHING+SELECT ... FOR UPDATE+ owner token (runtime/side_effects.py:184);mark_succeeded/mark_failedare owner-conditional so a stale executor cannot overwrite || D | lazy Redis session silently degrades to process memory | #27 | STILL_VALID |
ServiceContainer._assert_session_redis_readydoes a startup ping and refuses a degraded backend (core/container.py:148); production fail-fast || E |
Idempotency-Keyoverflowsvarchar(128); header unbounded | #27 | STILL_VALID | fixed-length canonical sha256 scope when it would overflow (runtime/run_service.py:61); oneIDEMPOTENCY_KEY_INPUT_MAXshared by header and body, 400 before the DB || F |
stream_callbackserialized into PostgreSQL checkpoint state | #26 | ALREADY_FIXED (before this round) | callback travels in a contextvar (core/streaming_context.py), never in state; re-verified against the realAsyncPostgresSaver|| G |
saver.setup()unbounded + cross-worker migration race | #26 | STILL_VALID |asyncio.wait_for(..., LANGGRAPH_CHECKPOINT_SETUP_TIMEOUT)(core/checkpointer.py:216);pg_try_advisory_lock+ backoff (core/checkpointer.py:55); timeout/failure closes the pool || H | session delete left conversation history in checkpoints | #26 | STILL_VALID | delete by thread_id string (
api/routes/sessions.py:136); idle-TTL retention defined explicitly viascripts/purge_orphan_checkpoints.pywith a min-age window || I |
checkpoint_idalwaysnullfor PostgreSQL | #26 | STILL_VALID | mapping-firstextract_checkpoint_id(api/routes/sessions.py:15),isinstance(Mapping)so a mock cannot fabricate an id |Note on H — a real regression the new test caught. The first attempt passed the
LangGraph
configdict toadelete_thread. The real signature isadelete_thread(thread_id: str), soDELETE ... WHERE thread_id = '{...}'matched norows and returned success while the conversation stayed in the checkpoint tables.
Fixed in
54e2b8d;test_session_delete_purges_checkpoint_and_recreate_is_cleanfailsbefore the fix and passes after.
No test expectation was weakened to get here. The only edit to a pre-existing test
(
test_gate11_pending_claim_lease_blocks_concurrent_execution) now backdatesclaim_expires_atas well asupdated_at: the authoritative expiry field became theclaim lease, so the old setup no longer actually simulated lease expiry.
Round 2 — four correctness gaps found in this PR's own new code
A follow-up review of this branch's new code raised 4 more findings (3 P1, 1 P2). All
were confirmed against real PostgreSQL 16 / Redis 7 and fixed in
f5bdb51. Each was asilent no-op rather than a loud failure, which is why they are listed explicitly:
| Finding | Symptom | Fix |
|---|---|---|
| Celery ACKs failed tasks |
task_acks_on_failure_or_timeoutdefaults True, so escaping the task did not redeliver — the finding-B mechanism was inert |task_acks_on_failure_or_timeout=False(runtime/celery_app.py) || retention query read
checkpoint_ts| no such column in the pinned saver schema ->UndefinedColumn, plan never produced |max(checkpoint->>'ts')(core/checkpoint_retention.py) || purge scanned
session:| keys arecsai:session:{id}:messages; scan matched nothing and hit the fail-closed abort | pattern derived fromREDIS_SESSION_PREFIX, both suffixes stripped ||
adelete_threadgot a config dict |WHERE thread_id = '{...}'matched 0 rows and "succeeded" ->--applynever deleted | passcandidate.thread_id(the same defect fixed in54e2b8d, missed at this duplicate call site) || reconciler filtered
next_retry_at IS NOT NULL| excluded exactly the QUEUED/NULL broker-loss case its own docstring claims to cover | match overdue backoff or old-enough QUEUED/NULL, with a 60s grace window |The Celery one matters most: it means round 1 shipped a fix whose stated mechanism did
not work, and only the reconciler backstop would have masked it.
Round 3 — the real-infra gate was not reproducible (this round)
A third review of the evidence rather than the code found that
make runtime-e2ewas a coin flip:test_gate11_side_effect_tool_executes_exactly_once_across_worker_killfailed inside a full suite run (
hits=0) while passing in isolation, and the suitescored 50/51 on some runs and 51/51 on others. The "51 passed" line in the previous
revision of this body was therefore not a reliable gate.
Mechanism (proven by injection, not inferred). Both tests that spawn real Celery
worker subprocesses stopped only
worker_binfinally;_stop_worker(worker_a)sat in the happy path. Any assertion failing before that line leaked a live
worker. Injecting one early failure:
| | orphan
celery_worker_runnerprocesses still alive afterwards ||---|---|
| before
7a41db7| 2 || after
7a41db7| 0 |This machine already had exactly such orphans, 2h04m old, from an earlier
session. They keep consuming queues and writing the shared
idem:/ckpt:keys,which is why a test that deletes those keys at setup still failed: the delete only
removes the values present at that instant.
| Finding | Fix |
|---|---|
|
finallyleakedworker_ain two tests | track every started worker in astartedlist and stop them all (test_tool_idempotency.py,test_worker_checkpoint_recovery.py) || provider Redis keys were global, not per-run | namespaced via
SIDE_EFFECT_KEY_PREFIX/CHECKPOINT_RESUME_KEY_PREFIX; default prefixes preserve standalone use ||
idem:ledger_hitswas a proxy, not a ledger observation | it incremented offphase, which only means "first pass or not" — so it could not demonstrate deduplication actually happened. It now increments only when the side-effect counter is observed unchanged acrossexecute_raw, i.e. the ledger returned a stored result and the handler did not run ||
scripts/test_worker_crash_recovery.pyshared the same global keys | same namespacing; report JSON keys deliberately left stable so artifacts stay schema-compatible |No test expectation was weakened or loosened. The assertions are unchanged; the
harness around them is now hermetic and the hit-counter asserts something real.
test_worker_checkpoint_recovery.pyalso failed on the first full-suite run afterthis branch's changes and then passed on 7 subsequent attempts (including 3/3 in
isolation and once against a deliberately emptied checkpoint schema). It carried the
identical leak + shared-namespace defects, both now fixed, but its exact failure
interleaving was never captured and is therefore not root-caused — it is
mitigated, not proven fixed. Stated plainly because rounds 1 and 2 each shipped a
"verified" fix whose stated mechanism did not hold.
Architecture
Unchanged from #27. PostgreSQL is canonical durable state (LangGraph checkpoint,
agent_runs,tool_side_effects,agent_dead_letters); Redis iscoordination/broker/TTL state (per-thread lock, session, L1 cache, Celery broker);
Celery is background transport (
acks_late,reject_on_worker_lost,visibility_timeout); asyncio is run-local only. Fast path (/api/chat) and asyncpath (
/api/runs) share theagent:thread-lock:{thread_id}namespace.SERVICE_ROLEmakes the config validation boundary explicit:api(the default) keepsthe original fail-closed behaviour,
workerskips theAPI_KEY/JWT_SECRET/SESSION_TOKEN_SECRET/CORS_ORIGINSvalidation it never reads.Failure semantics
| Scenario | Behaviour |
|---|---|
| worker crash | unacked task redelivered via
visibility_timeout; lease expiry lets another worker take over; nodes and side effects must be idempotent || retry publication fails | the task escapes -> no silent ACK;
reconcile_stuck_runsis the durable backstop for messages lost outside at-least-once || concurrent tool call | exactly one executor claims; others get
in_progress(transient) or the stored result; success/failure writes are owner-conditional || Redis unavailable | production session fail-fast; thread lock fails closed (503) |
| Postgres unavailable | checkpoint init fail-fast, no
MemorySaverfallback || session delete | checkpoint thread deleted; idle-TTL orphans reclaimed by
scripts/purge_orphan_checkpoints.pybehind a min-age window || duplicate run | terminal redelivery is a no-op |
Verification evidence
Re-run on this branch against real PostgreSQL 15.18 + Redis 7 (docker), not
mocked. Numbers below are from an independent re-run at
4b5d5b0; where they differfrom the previous revision of this body they were re-measured, not copied.
Earlier revisions of this body claimed
265 passedfor e2e,50 skippedforintegration,
ruff 0.4.0 -> 33 errors,mypy gradual -> 178 errors in 45 files, andPostgreSQL 16. Re-measured here: 260 / 58 skipped / 17 errors on ruff 0.16.9 / 175
errors in 44 files on both
mainand this branch (so no regression) /PostgreSQL 15.18. The absolute lint and mypy counts are toolchain- and
version-dependent; the meaningful comparison is the delta against
main, which iszero for all three.
Artifacts:
artifacts/distributed-runtime/20261002T113005Z/report.json(schemadistributed-runtime-evidence/v2,tested_code_sha=7a41db7, 4/4 PASS) andartifacts/runtime/chaos-20261002T113006Z.json. An earlier artifact generated at20261002T112731Zpredated the fix and was discarded rather than kept as evidence.Reading the lint line honestly
ruff check .is not green on this repository, on this branch or onmain. Withruff 0.16.9 it reports 17 errors, identical on
mainand on this branch — this PRcontributes zero new ones and fixes none of the pre-existing set.
ruff formatis likewise already red repo-wide (138 files at--check .
main); reformatting wasdeliberately not bundled here, and this round adds no new format hunks (verified
per-file against
0c563c0).CI runs no ruff step at all (
.github/workflows/ci.ymlhas zero ruff invocations),so
make lintbeing red is a pre-existing local-gate failure, not a CI failure.The type-checking gate is weaker than it looks, and that is worth stating. CI has
two mypy steps:
Type checking — strict(7 files, blocking, passing) andType checking — gradualwhich iscontinue-on-error: trueand names threepaths that do not exist in this repository (
session_manager.py,token_counter.py,drift_detector.py— the code lives undercore/session/). Thatstep therefore aborts on
Cannot read filebefore checking anything, and gatesnothing. Re-measured with those bogus paths removed: 175 errors in 44 files,
identical on
mainand on this branch. So type coverage outside the 7 strict filesis effectively unenforced and unmonitored. Repairing that gate is deliberately out of
scope for a correctness PR — flagging it rather than quietly claiming mypy coverage.
Known limitations (evidence boundary)
IMPLEMENTED+LOCALLY_VERIFIEDagainst real PostgreSQL and Redis in a localcontainer. Three review rounds have each found real defects in this branch (10 in
the merged #27/#26 threads, then 5 more in this PR's own new code, then a
non-reproducible evidence gate). A clean review is not evidence of correctness here,
and the merge recommendation below is deliberately conservative about that. Not claimed and not validated: real production traffic, a real
multi-replica cluster, long-running stability, real write-side ERP operations,
cross-process SSE replay, Kubernetes/HPA, multi-region. Deliberately not claimed:
exactly-once delivery, zero data loss, broker-native dead-letter routing — delivery is
at-least-once and idempotency is layered. The DLQ is an application-level
terminal-failure foundation, not a complete operational loop. Lock stale-worker fencing
(lease renewal / fencing tokens) is future work. The 649-query RAG metrics remain
NOT_VERIFIEDand are unrelated to this PR.Commits
b32628afix(runtime): resolve PR #27/#26 review findings (worker config, retry durability, atomic claims)7127394style(alembic): sort imports / terminate newline (migration 005)047e0dfstyle(runtime): explicit boolean for claim-lease mypy54e2b8dfix(runtime): delete checkpoint thread by thread_id, harden id extraction3d72287test(runtime): cover PR #27/#26 review findings end to endb27a3b6docs(runtime): converge review debt, evidence boundaries and PR metadata97212c5evidence(runtime): refresh verification + chaos artifacts at final commit3f3d2dbstyle(runtime): clear the two net-new ruff UP038 findings this branch introduced1d36a7aevidence(runtime): re-verify after the UP038 lint fix (real PostgreSQL + Redis)f5bdb51fix(runtime): close 4 correctness gaps the #28 follow-up review found in new code0c563c0evidence(runtime): re-verify at f5bdb51 after the round-2 correctness fixes7a41db7test(runtime): make the real-infra runtime gate hermetic; stop leaking workers4b5d5b0evidence(runtime): re-verify at 7a41db7 after making the runtime gate hermetic