← Back to Pull requests

fix(runtime): resolve PR #27/#26 post-merge review findings + tests #28

Closed
unknown closed this pull request without merging on Oct 02, 2026 13:17 UTC
View on GitHub
unknown unknown commented on Oct 02, 2026 08:24 UTC
Author

Why

PR #27 (feat/distributed-agent-runtime) was merged at e6b6588 with all 5 of its
review 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 d615b8f is carried forward here and every #26 finding was
re-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_ORIGINS missing) | #27 | STILL_VALID | SERVICE_ROLE=worker skips API-only validation (core/config.py:212); Compose worker env forwards what it consumes; contract test asserts a runtime.celery_app import succeeds with only the worker's env |
| B | retry-publication failure silently ACKed -> RETRYING forever | #27 | STILL_VALID, twice | RetryPublicationError escapes the task (runtime/executor.py:257) and the outer handler refuses to ACK a run parked in RETRYING/QUEUED (:278); durable backstop runtime.retry.reconcile_stuck_runs + scripts/reconcile_stuck_runs.py. Incomplete on first pass: escaping is not enough — Celery ACKs failed tasks by default, so task_acks_on_failure_or_timeout=False was also required (f5bdb51). Round-1 claim "acks_late forces redelivery" was wrong |
| C | PENDING side-effect claim not mutually exclusive | #27 | STILL_VALID | atomic INSERT ... ON CONFLICT DO NOTHING + SELECT ... FOR UPDATE + owner token (runtime/side_effects.py:184); mark_succeeded/mark_failed are owner-conditional so a stale executor cannot overwrite |
| D | lazy Redis session silently degrades to process memory | #27 | STILL_VALID | ServiceContainer._assert_session_redis_ready does a startup ping and refuses a degraded backend (core/container.py:148); production fail-fast |
| E | Idempotency-Key overflows varchar(128); header unbounded | #27 | STILL_VALID | fixed-length canonical sha256 scope when it would overflow (runtime/run_service.py:61); one IDEMPOTENCY_KEY_INPUT_MAX shared by header and body, 400 before the DB |
| F | stream_callback serialized 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 real AsyncPostgresSaver |
| 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 via scripts/purge_orphan_checkpoints.py with a min-age window |
| I | checkpoint_id always null for PostgreSQL | #26 | STILL_VALID | mapping-first extract_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 config dict to adelete_thread. The real signature is
adelete_thread(thread_id: str), so DELETE ... WHERE thread_id = '{...}' matched no
rows and returned success while the conversation stayed in the checkpoint tables.
Fixed in 54e2b8d; test_session_delete_purges_checkpoint_and_recreate_is_clean fails
before 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 backdates
claim_expires_at as well as updated_at: the authoritative expiry field became the
claim 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 a
silent 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_timeout defaults 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 are csai:session:{id}:messages; scan matched nothing and hit the fail-closed abort | pattern derived from REDIS_SESSION_PREFIX, both suffixes stripped |
| adelete_thread got a config dict | WHERE thread_id = '{...}' matched 0 rows and "succeeded" -> --apply never deleted | pass candidate.thread_id (the same defect fixed in 54e2b8d, 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-e2e was a coin flip: test_gate11_side_effect_tool_executes_exactly_once_across_worker_kill
failed inside a full suite run (hits=0) while passing in isolation, and the suite
scored 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_b in finally; _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_runner processes 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 |
|---|---|
| finally leaked worker_a in two tests | track every started worker in a started list 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_hits was a proxy, not a ledger observation | it incremented off phase, 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 across execute_raw, i.e. the ledger returned a stored result and the handler did not run |
| scripts/test_worker_crash_recovery.py shared 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.py also failed on the first full-suite run after
this 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 is
coordination/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 async
path (/api/runs) share the agent:thread-lock:{thread_id} namespace.

SERVICE_ROLE makes the config validation boundary explicit: api (the default) keeps
the original fail-closed behaviour, worker skips the API_KEY / JWT_SECRET /
SESSION_TOKEN_SECRET / CORS_ORIGINS validation 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_runs is 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 MemorySaver fallback |
| session delete | checkpoint thread deleted; idle-TTL orphans reclaimed by scripts/purge_orphan_checkpoints.py behind 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 differ
from the previous revision of this body they were re-measured, not copied.

mypy strict gate (the only blocking type gate)    -> Success: no issues found in 7 source files
ruff check . (ruff 0.16.9, NOT a CI gate)         -> 17 errors, byte-identical to main
ruff check <the 5 files this round changed>       -> All checks passed
ruff format --check <those 5 files>               -> no new debt (all hunks pre-existing at 0c563c0)
pytest tests/unit -q                              -> 1698 passed
pytest tests/integration -q -m "not real_llm"     -> 99 passed, 58 skipped
pytest tests/e2e -q -m "not real_llm"             -> 260 passed
make runtime-e2e (real PG + Redis)                -> 51 passed, x8 consecutive full-suite runs
                                                      (was 50/51 on some runs before this round)
orphan celery workers after each run              -> 0, every run
scripts/generate_openapi.py --check               -> OK (58 paths)
scripts/audit_doc_consistency.py                  -> OK (39 active documents)
scripts/project_facts.py --check current-state.md -> OK
scripts/verify_distributed_runtime.py (real PG+Redis) -> overall PASS (4/4 checks)
scripts/test_worker_crash_recovery.py             -> PASS (counter=1, invocations=2, ledger_hits=1)

Earlier revisions of this body claimed 265 passed for e2e, 50 skipped for
integration, ruff 0.4.0 -> 33 errors, mypy gradual -> 178 errors in 45 files, and
PostgreSQL 16. Re-measured here: 260 / 58 skipped / 17 errors on ruff 0.16.9 / 175
errors in 44 files on both main and 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 is
zero for all three.

Artifacts: artifacts/distributed-runtime/20261002T113005Z/report.json (schema
distributed-runtime-evidence/v2, tested_code_sha=7a41db7, 4/4 PASS) and
artifacts/runtime/chaos-20261002T113006Z.json. An earlier artifact generated at
20261002T112731Z predated 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 on main. With
ruff 0.16.9 it reports 17 errors, identical on main and on this branch — this PR
contributes zero new ones and fixes none of the pre-existing set. ruff format
--check .
is likewise already red repo-wide (138 files at main); reformatting was
deliberately 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.yml has zero ruff invocations),
so make lint being 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) and
Type checking — gradual which is continue-on-error: true and names three
paths that do not exist in this repository (session_manager.py,
token_counter.py, drift_detector.py — the code lives under core/session/). That
step therefore aborts on Cannot read file before checking anything, and gates
nothing. Re-measured with those bogus paths removed: 175 errors in 44 files,
identical on main and on this branch
. So type coverage outside the 7 strict files
is 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_VERIFIED against real PostgreSQL and Redis in a local
container. 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_VERIFIED and are unrelated to this PR.

Commits

  • b32628a fix(runtime): resolve PR #27/#26 review findings (worker config, retry durability, atomic claims)

  • 7127394 style(alembic): sort imports / terminate newline (migration 005)

  • 047e0df style(runtime): explicit boolean for claim-lease mypy

  • 54e2b8d fix(runtime): delete checkpoint thread by thread_id, harden id extraction

  • 3d72287 test(runtime): cover PR #27/#26 review findings end to end

  • b27a3b6 docs(runtime): converge review debt, evidence boundaries and PR metadata

  • 97212c5 evidence(runtime): refresh verification + chaos artifacts at final commit

  • 3f3d2db style(runtime): clear the two net-new ruff UP038 findings this branch introduced

  • 1d36a7a evidence(runtime): re-verify after the UP038 lint fix (real PostgreSQL + Redis)

  • f5bdb51 fix(runtime): close 4 correctness gaps the #28 follow-up review found in new code

  • 0c563c0 evidence(runtime): re-verify at f5bdb51 after the round-2 correctness fixes

  • 7a41db7 test(runtime): make the real-infra runtime gate hermetic; stop leaking workers

  • 4b5d5b0 evidence(runtime): re-verify at 7a41db7 after making the runtime gate hermetic
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: Xander-Xai Review duration: 292m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%