Skip to content

refactor(gateway): schedule durable session delivery retries - #159275

Merged
steipete merged 1 commit into
mainfrom
hostneutral/scheduler-session-delivery-0926
Sep 27, 2026
Merged

steipete merged 1 commit into
mainfrom
hostneutral/scheduler-session-delivery-0926

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-delivery retries currently own native timers separately from the Gateway scheduler. Move the pending-row retries, failed-scan retry, and delayed startup recovery onto the kernel scheduler, with a required dependency throughout the production constructor path.

The queue remains authoritative for claim deadlines, retry eligibility, settlement and persistence. A pending read uses the scheduler's approved earliest-deadline mode, keeping an earlier elapsed wake even if the wall clock moves backward or a stale claimed-row read finishes later. Active drains still coalesce duplicate requests, retry unchanged pending rows no faster than the existing retry floor, and join admitted reads and settlement writes on shutdown. There is one scheduler instance per Gateway process; required dependencies enforce injection through these paths.

Delete the native timer handles, their unref/clear plumbing and the leaf's duplicate earliest-deadline bookkeeping. Tests use the shared injected scheduler clock, including real-store backward-clock and delayed stale-read regressions.

User Impact and Update Behavior

Update behavior: existing rows, claim and retry timestamps, external delivery behavior, configuration and ports retain their contracts. Boot recovery reads the existing owning store; no new persisted schedule or migration is added. The deliberate timing change is that wall-clock forward jumps can shorten a retry wake, while a backward correction cannot postpone an earlier elapsed wake. Every wake reloads the owning row and checks current wall-time eligibility before delivery. No storage schema, config or SDK contract changes.

Scope and Stack

LOC: production +97/-86/net +11; tests +224/-111/net +113; docs +0/-0/net 0. The 518 changed lines include the complete typed constructor cutover and replacement of the original timer-driven tests; splitting these would leave dead code or two timing owners.

Stack: follows earliest-deadline contract #159260. The preceding media maintenance #159126 is merged; system-job retries #159129 are independent. Next: update watcher, update campaign, diagnostic/CLI/SDK, auth pruning, MCP preparation/cutover, then final docs and live proof. Earlier stack links are in the predecessor bodies.

Evidence

Proof: provider blacksmith-testbox, lease tbx_01m3fqja9r983kwbphpb3v3g5g, run 36270738491. After pnpm install --frozen-lockfile, each file ran with pnpm test <file> --maxWorkers=1:

  • src/infra/session-delivery-queue-runtime.test.ts: 21 cases passed, 31.429 s wall.
  • src/infra/session-delivery-queue.recovery.test.ts: 22 passed, 17.073 s.
  • src/gateway/server-runtime-services.test.ts: 37 passed, 10.370 s.

All 80 cases passed in 58.872 s. The two negative controls restored wall-only timing and replace semantics respectively: each failed its intended delivered-once assertion (zero deliveries), in 18.167 s and 18.293 s. Candidate source was restored and verified. Exact proof tree e08176b6a808af51bade9afedd893d2c49c20865; publication preserves all four reviewed/proved files byte-for-byte on fresh main, including the landed scheduler prerequisite. Required GitHub ci-gate replaces a separate check-changed invocation for this stack.

Review: deslop removed the redundant dueAt state and pre-schedule cancellation; Full-diff Codex P2 review and the subsequent one-line assertion delta review are both scoped-clean, with no accepted/actionable findings. Final stack proof will exercise an isolated Gateway, cron, SIGSTOP/SIGCONT, durable restart and budgeted SIGTERM against merged main.

Remote failure record: the first earliest-mode owner run passed 20 of 21 cases. The forward-clock test required nextWakeAtMs to equal now, while earliest mode correctly retained an already-overdue deadline. Only that assertion now checks due <= now; the zero host delay, delivered-once and empty-queue checks remain. Both new clock/stale-read regressions passed on that first run. The corrected 21-case suite and all 59 sibling cases passed in the proof above.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 26, 2026, 8:25 PM ET / September 27, 2026, 00:25 UTC.

ClawSweeper review

What this changes

Routes delayed session recovery and durable delivery retries through the shared Gateway scheduler, with tests for clock changes and stale reads.

Merge readiness

⛔ Blocked before merge - 3 items remain

Current main still uses private session-delivery timers, so this PR remains useful. The scheduler cutover has focused test coverage, but the required isolated Gateway restart-delivery proof is not yet shown.

Priority: P2
Reviewed head: 1c6b0b57f9337499a7a4c5ae6161b7d328641099

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🌊 off-meta tidepool Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 8 items Current main retains private timers: The current-main session runtime schedules retries with setTimeout and keeps its own elapsed deadline map; the delayed Gateway startup recovery also uses a native timer.
Introduced retry scheduling: The introduced hunk replaces each entry's native timer with an earliest-deadline Gateway scheduler job and passes the scheduler clock to the drain.
Scheduler prerequisite: The merged prerequisite adds the earliest-deadline mode used by this PR; that mode retains earlier wall and elapsed deadlines independently.
Findings None None.
Security None None.

How this fits together

The Gateway stores pending session deliveries in SQLite. Startup recovery and retry scheduling read those rows, then pass eligible entries to the existing delivery and settlement path.

flowchart LR
A[Pending SQLite rows] --> B[Startup recovery]
B --> C[Gateway scheduler]
C --> D[Reload current row]
D --> E{Retry eligible?}
E -->|Yes| F[Deliver and settle]
E -->|No| C
Loading

Before merge

  • Resolve merge risk (P1) - Moving delayed recovery and retry wakes to the shared scheduler changes restart-delivery custody, but the supplied tests do not show the scoped policy's isolated public sessions.create flow for a non-main session followed by a read or turn.
  • Resolve merge risk (P1) - The PR reports an after-change Gateway test time but does not provide the before-and-after benchmark required by the scoped Gateway policy.
  • Complete next step (P2) - Provide isolated Gateway proof of non-main sessions.create recovery with a subsequent read or turn, plus the scoped before-and-after Gateway test benchmark, before merge.
Agent review details

Security

None.

PR surface

Source +11, Tests +113. Total +124 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 97 86 +11
Tests 1 224 111 +113
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 321 197 +124

Review metrics

Metric Value Why it matters
Production and test growth production net +11 lines; tests net +113 lines The PR explains the production growth as the constructor cutover and adds clock and stale-read regression coverage.

Merge-risk options

Maintainer options:

  1. Prove Gateway recovery (recommended)
    Capture the required isolated non-main sessions.create recovery flow and record before-and-after timing for the affected Gateway test file.

Technical review

Best possible solution:

Use the shared Gateway scheduler for wake timing while SQLite retains claim, retry, and settlement authority, with restart recovery verified for the original non-main session.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this is an internal scheduling refactor, not a reported defect. Current main's private-timer path is visible in source.

Is this the best way to solve the issue?

Yes: the existing scheduler's merged earliest-deadline mode provides a narrow timing owner while the queue retains delivery decisions; the Gateway recovery composition still needs proof.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ea2a69fe6891.

Labels

Label changes:

  • add P2: This is a bounded reliability improvement to durable session delivery, with no demonstrated urgent regression.
  • add merge-risk: 🚨 message-delivery: A mistake in scheduler-owned restart recovery could leave persisted session deliveries waiting or route them at the wrong time.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🌊 off-meta tidepool and patch quality is 🦞 diamond lobster.

Label justifications:

  • P2: This is a bounded reliability improvement to durable session delivery, with no demonstrated urgent regression.
  • merge-risk: 🚨 message-delivery: A mistake in scheduler-owned restart recovery could leave persisted session deliveries waiting or route them at the wrong time.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🌊 off-meta tidepool and patch quality is 🦞 diamond lobster.

Evidence

What I checked:

  • Current main retains private timers: The current-main session runtime schedules retries with setTimeout and keeps its own elapsed deadline map; the delayed Gateway startup recovery also uses a native timer. (src/infra/session-delivery-queue-runtime.ts:37, ea2a69fe6891)
  • Introduced retry scheduling: The introduced hunk replaces each entry's native timer with an earliest-deadline Gateway scheduler job and passes the scheduler clock to the drain. (src/infra/session-delivery-queue-runtime.ts:86, 1c6b0b57f933)
  • Scheduler prerequisite: The merged prerequisite adds the earliest-deadline mode used by this PR; that mode retains earlier wall and elapsed deadlines independently. (src/infra/gateway-scheduler.ts:118, 52d1a0bb696e)
  • Prerequisite merge verified: The earliest-deadline prerequisite is a merged same-repository PR, while this branch's session-delivery cutover is still absent from current main. (52d1a0bb696e)
  • Queue authority remains at delivery: The drain checks current retry eligibility before delivery; the downstream delivery function checks its state-owner admission and resolves the queued session route. (src/infra/session-delivery-queue-recovery.ts:167, 1c6b0b57f933)
  • Scoped Gateway proof requirement: The Gateway policy requires an isolated public sessions.create flow with an explicit non-main session and a post-publication read or turn when restart-delivery custody changes. (src/gateway/AGENTS.md:86, 1c6b0b57f933)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Leon-SK668: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • joshavant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant