Repository navigation
perf(gateway): avoid repeated idle database reads - #172964
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 92a03de7c5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| publishSqliteDatabaseAdmission( | ||
| db, | ||
| emptyWatchedSessionUpstreamLinksAdmission, | ||
| rows.length === 0 ? true : undefined, | ||
| ); |
There was a problem hiding this comment.
Fence empty-cache publication against intervening writes
When a legacy synchronous link writer adds a link after this query has returned no rows but before the worker's admission reaches the host, its undefined invalidation can be overwritten by this later stale true publication. listWatchedSessionUpstreamLinks then permanently skips the worker scan and misses the newly watched upstream until another link or cursor write occurs; publish the empty fact only if the database/write revision captured before the query is still current.
AGENTS.md reference: AGENTS.md:L68-L70
Useful? React with 👍 / 👎.
| const health = rows.map(({ oldestFailedAt, ...row }) => | ||
| oldestFailedAt == null ? row : Object.assign(row, { oldestFailedAt }), | ||
| ); | ||
| publishSqliteDatabaseAdmission(database.db, failedDeliveryQueueHealthAdmission, health); |
There was a problem hiding this comment.
Reject stale health snapshots after concurrent queue writes
If an in-process queue writer changes a failed row while this worker read is in flight, the writer's undefined invalidation can be followed by this stale health publication and therefore overwritten. Subsequent health requests reuse the stale array indefinitely—potentially hiding a new dead letter or reporting a completed one—until an unrelated queue mutation invalidates it again; condition publication on the pre-read write revision, as the removed cache logic did.
AGENTS.md reference: AGENTS.md:L68-L70
Useful? React with 👍 / 👎.
|
Codex review: needs changes before merge. What this changesThis PR reuses owner-published delivery health, empty upstream-watch membership, and plugin inventory to reduce idle database reads. Example: A Gateway has no watched upstream links and repeatedly polls for them.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep this maintainer-authored optimization open; it follows the existing ownership design but leaves a Gateway test failing because its assertions still require the removed wrapper cache. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherGateway health collection, upstream monitoring, and skills discovery consume shared-state and plugin-owner facts; committed mutations invalidate those facts before later consumers reuse them. flowchart TD
A[Gateway background work] --> B[Delivery queue owner]
A --> C[Upstream link owner]
A --> D[Skills discovery]
B --> E[Shared database admission facts]
C --> E
D --> F[Published plugin inventory]
E --> G[Shared state workers]
Technical reviewBest possible solution: Keep the owner-published caches and update the Gateway regression to verify results and actual database work rather than obsolete wrapper call counts. Do we have a high-confidence way to reproduce the issue? Current-main source shows repeated upstream worker scans and database-wide delivery-health invalidation; CI independently demonstrates the obsolete Gateway assertion failing on the reviewed head. Is this the best way to solve the issue? Reusing existing owners and their publication lifecycle fits the repository design; completing the test cutover is preferable to restoring the redundant Gateway cache. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 731fcf98396a. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +49, Tests +246. Total +295 across 12 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 15, 2026, 5:12 AM ET / 09:12 UTC. |
|
Reviewed the two P2 cache-publication comments. Both describe an overlapping legacy synchronous writer and an in-flight worker read. The accepted edge is that diagnostics or newly watched upstream discovery can lag until the next relevant owner write or reload. Queue custody, actual delivery execution, and final authority checks before destructive session operations are unchanged. This change deliberately does not add revision fencing or another cross-thread handshake for those internal bookkeeping races. The accepted cases are recorded in the PR body. If an observed incident warrants changing the deprecated synchronous writer path, that should be addressed at that owner boundary. |
|
Post-merge measurement is complete: all three alternating baseline/candidate pairs include the full five-minute connected-idle window. The PR body now contains the per-run counts, owner savings, warm/shared-read checks, MAIN exposure and limitations.
Changed owners directly save 24/9, 25/10 and 26/11 SQL/requests per five-minute window. All deferred work remains in headline idle totals. Idle and causal warm MAIN stay zero; raw warm windows still contain 4–13 startup lease assertions. The under-10 SQL/min target is not reached. All six runs pass the 13-turn, child-spawn, compaction, idle and shutdown checks, with zero native SQL failures and no surviving fixture children. They remain partial workloads: cron execution is unmeasured because the fixture lacks the required stored inference account. One initial C3 attempt failed before any measured turn with startup Merged as |
Reuse delivery-owner failed-health facts and raw-empty upstream-watch membership until their owners invalidate them. Supply passive skills discovery with the Gateway's published plugin inventory. Remove the database-wide delivery-health token cache and redundant polling reads while retaining skill-file discovery and destructive-operation authority checks. Add owner-invalidation regressions and count actual health worker reads in Gateway tests.
What Problem This Solves
A connected, idle Gateway repeatedly reloads unchanged delivery diagnostics, upstream-watch membership, and installed-plugin metadata.
User Impact
Reduces background database work while keeping delivery health, upstream notifications, and skill-file discovery current through their existing owners. No schema, configuration, retention, or security-policy changes.
Why This Change Was Made
The delivery-queue owner now publishes its failed-health projection and invalidates it on queue writes, replacing the Gateway's database-wide write-token cache. The upstream-link owner remembers a raw empty watched-link result; the three membership-creating writers invalidate that fact. Skills discovery consumes the Gateway's published plugin inventory while continuing to scan admitted skill roots.
Removed checks and accepted edges:
Evidence
Three alternating baseline/candidate pairs (M1, C1, M2, C2, M3, C3), each with the complete 300-second connected-idle interval. Baseline
281fe9ffda60881138a090b12a105dd431bf2447; final candidatecc82889fb48a6921fcf5976db2d2e630c7a12cba. The shared harness remained unchanged; a frozen copy added the five-minute interval, external scratch and phase markers. Builds were pinned and reused. Counts only; the loaded host does not support latency claims.All six are partial workloads: 13 turns, child spawn, compaction, idle and shutdown pass, with zero native SQL execution/prepare failures and no surviving fixture children; cron execution is unmeasured because its fixture lacks the required stored inference account. Deferred work and zero-SQL worker requests remain counted in the full idle totals.
Median [min–max] across three runs. Warm metrics use each run's median of ten turns.
The full idle median falls 26.6% in SQL and 47.5% in requests, but the under-10 SQL/min target is not reached. These whole-window differences also reflect placement of unchanged deferred work. Direct changed-owner savings are separated below.
Five filesystem-only skills tasks remain in every idle window. Residual work includes memory and usage publication after a 30-second quiet debounce, demand-triggered activity/experience review, real placement settlement, write-triggered WAL maintenance, and one delayed lifecycle cleanup. The source/owner ledger accounts for every idle statement and request; some generic queued session reads/patches lose their high-level trigger at the queue boundary, so those trigger gaps remain explicit.
Shared causal warm reads per turn: exact-entry facts, actor hydration, entry-cache snapshot loads and watermark reads all stay 0; primary row-facts SELECTs are 1.2 [1.2–1.2] on baseline and 1.2 [1.0–1.2] on candidate. Whole-workload SQL and requests fall in all three pairs. Boot+connect+first-turn SQL is 2063/2009, 2076/2061 and 2069/2103 (baseline/candidate), median 2069→2061; requests 257/249, 259/257 and 259/266, median 259→257. This preserves the deferred-startup work that moves between phases.
Each run still observes 477 MAIN statements: 455 boot admission, 13 startup lifecycle lease assertions, and 9 shutdown. M2/C3 place nine lease assertions in first-turn and four in raw warm windows; other runs place all thirteen in raw warm windows. None fires during connected idle. Raw warm windows therefore must not be described as MAIN-free.
Raw warm totals change by +12/+3, +3/−1 and −36/−11 SQL/requests in the three pairs, while raw and causal warm medians do not rise. Pair 1 moves the same 12-SQL/four-request cron maintenance pass into warm windows; session-entry reads and WAL placement reconcile the remainder. Pair 2 redistributes unchanged plugin startup, lease, catalog, admission, memory and checkpoint work. C3 also has one fewer
session.entry.patch.commitper warm turn (BEGIN + session_nodes upsert + COMMIT), explaining its causal −3 SQL/−1 request per turn. All 30 session_windows upserts and transcript-rewrite SQL remain. The queue stack does not preserve that patch's semantic caller or values, so this variation is not credited to the idle optimization. Whole-workload totals are lower in every pair.One initial C3 attempt failed before any measured turn:
sessions.createreturnedschema-missingduring agent-store startup/admission; later readers succeeded and the closed fixture had schema 27 with 69 tables. It is excluded. The involved startup/admission files are unchanged between baseline and candidate. Exact commit ordering is unproven; this remains an unresolved startup-owner follow-up. One unchanged replacement passed. That is measurement recovery, not a demonstrated fix.The retained T1 exact-row read is the final guard before destructive session rewind/fork; it protects user data from mutation after external adoption. Four deprecated synchronous SDK compatibility sites also remain unchanged. Final-candidate PR CI passed executable T1/dialect ratchets, production/test types, type-aware lint, Madge, export collisions, source contracts, and all non-UI test shards. Numeric ratchet evidence at production commit
92a03de7c5is T1 223→223 and T1-compat 12→12 (run 38709025963, job 116336247174); the final test-only candidate independently passes the ratchet in run 38711848397, job 116345611942. All three dialect categories stay at zero in the changed production scope. Knip was not selected by PR CI, so the native three-scan export check ran separately on the final candidate. Its nonzero exit contains only exact scan/file/symbol findings already present in scheduled main run 38707273563, job 116330111359: production 6 versus 7 on main, full tree 7 versus 10, scripts 10 versus 10; zero new findings. No ignore or baseline changes.The delivery-queue suite passed 36 tests, including the new owner-invalidation cases before they were moved into a focused health file. The skills regression failed against old production exactly on the redundant installed-index read. Candidate focused health passed 6/6 cases; skills discovery passed 4/4. The focused upstream suite passed 11/11. PR CI caught an obsolete facade-call-count assertion in Gateway health diagnostics; the test-only repair now counts actual worker operations, and all 4 focused cases pass. Two isolated Codex autoreview rounds are complete: one production round and one test-repair round. The diagnostic/watch overlap observations are accepted recoverable edges described above; no actionable finding remains. Changed-file formatting, oxlint, and
git diff --checkpass.No SDK surface, schema/migration, plugin-loading lifecycle, update, or service-lifecycle changes; the corresponding API diff and published-driver update cell do not apply.
LOC: production +107/-58 (net +49); tests +340/-91 (net +249).
CI inheritance: the two
session-management.sidebar.e2e.test.tsspawned-session nesting cases fail with the identical expected-0/received-4 assertion on scheduled main and this PR. UI source is untouched; recorded in the campaign red-main inbox.