Skip to content

perf(gateway): avoid repeated idle database reads - #172964

Merged
steipete merged 2 commits into
mainfrom
dbasync/idlesql5
Oct 15, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/idlesql5

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Delivery health no longer rechecks a database-wide write token. Unrelated state writes cannot change queue health; queue mutations and database retirement invalidate the owner's fact. A legacy synchronous write overlapping an in-flight worker read can leave diagnostics stale until the next queue write or reload; this does not affect delivery custody or execution.
  • An empty upstream-watch result no longer causes a fresh worker request every poll. Membership becomes visible through successful owner writes; unsupported external live database writers are outside Gateway custody. A legacy synchronous write overlapping the empty worker read can delay watch discovery until the next link/cursor write or reload; final-effect authority checks remain unchanged.
  • Passive skill scans no longer reread installed-plugin metadata already published by the Gateway. Manifest/install-record changes appear through plugin lifecycle reload and its skills-source refresh; metadata publication alone does not refresh existing watcher inputs. SKILL.md edits inside admitted roots still appear on the next passive scan.

Evidence

Three alternating baseline/candidate pairs (M1, C1, M2, C2, M3, C3), each with the complete 300-second connected-idle interval. Baseline 281fe9ffda60881138a090b12a105dd431bf2447; final candidate cc82889fb48a6921fcf5976db2d2e630c7a12cba. 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.

Metric Baseline Candidate
Connected idle SQL/min 27.8 [27.0–35.4] 20.4 [19.2–34.0]
Connected idle requests/min 11.8 [8.2–13.6] 6.2 [5.8–8.4]
Five-minute idle SQL 139 [135–177] 102 [96–170]
Five-minute idle requests 59 [41–68] 31 [29–42]
Causal warm SQL/turn 84 [84–84] 84 [81–84]
Causal warm requests/turn 28 [28–28] 28 [27–28]
Raw warm-window SQL/turn 85 [85–85.5] 85 [82–86]
Raw warm-window requests/turn 29 [29–29] 29 [28–29]
Whole-workload SQL 3937 [3913–3946] 3887 [3883–3919]
Whole-workload requests 849 [848–854] 836 [829–841]
Observed idle / causal warm MAIN statements 0 / 0 0 / 0
T1 sites in changed idle operations (source audit) 0 0
T1 sites across touched files (source audit) 1 1

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.

Run Idle SQL / requests / MAIN Raw warm totals SQL / requests / MAIN Whole SQL / requests / MAIN
M1 135 / 41 / 0 896 / 298 / 13 3946 / 849 / 477
C1 170 / 42 / 0 908 / 301 / 13 3919 / 841 / 477
M2 177 / 68 / 0 914 / 307 / 4 3937 / 854 / 477
C2 102 / 31 / 0 917 / 306 / 13 3887 / 836 / 477
M3 139 / 59 / 0 904 / 303 / 13 3913 / 848 / 477
C3 96 / 29 / 0 868 / 292 / 4 3883 / 829 / 477
Changed owner: five-minute SQL / request reduction Pair 1 Pair 2 Pair 3
Delivery health 5 / 5 6 / 6 6 / 6
Empty upstream membership 4 / 4 4 / 4 5 / 5
Passive skills metadata 15 / 0 15 / 0 15 / 0
Total direct saving 24 / 9 25 / 10 26 / 11

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.commit per 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.create returned schema-missing during 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 92a03de7c5 is 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 --check pass.

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.ts spawned-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.

@clawsweeper

clawsweeper Bot commented Oct 15, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T09:21:16.374566Z cc82889 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L labels Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +110 to +114
publishSqliteDatabaseAdmission(
db,
emptyWatchedSessionUpstreamLinksAdmission,
rows.length === 0 ? true : undefined,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This 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.

  • Before: Each poll dispatches another database worker request.
  • After: Polls reuse the empty result until an owner write can create watched membership.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-based optimization with focused regression coverage, but the incomplete test cutover causes a confirmed CI failure; no persisted format or migration changes are introduced.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; supplied evidence covers production owners through tests, while connected-idle measurements remain pending.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: An idle connected Gateway repeatedly spends database and worker resources reloading unchanged background facts.
Reason: The maintainer-authored direction extends existing owner caches, preserves direct skill-file discovery, and introduces no user-facing option.

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
Reviewed head: 92a03de7c5d1012e2672abe275d51664e287cdae

Before merge

  • Update the Gateway test for queue-owned health caching (P2) - Removing readFailedQueueHealth makes every buildDeliveryQueueHealthSummary call invoke countFailedDeliveryQueueEntries, whose own admission cache now avoids database work. The existing test still expects only one invocation after two summaries, and the reviewed-head Node shard fails here with expected 1, received 2. Its later outbound call-count assertions also describe the removed implementation. Remove those obsolete assertions while preserving returned-health and ingress checks; the new owner-level health suite already verifies that warm reads issue no worker requests.

Findings

  • [P2] Update the Gateway test for queue-owned health caching — src/gateway/health/delivery-queue-cache.test.ts:27

Tests

  • Missing end-to-end proof: A completed connected-idle Gateway trace is not supplied, and only the skills regression is explicitly reported failing against the old production code.
Agent review details

How this fits together

Gateway 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]
Loading

Technical review

Best 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:

  • [P2] Update the Gateway test for queue-owned health caching — src/gateway/health/delivery-queue-cache.test.ts:27
    Removing readFailedQueueHealth makes every buildDeliveryQueueHealthSummary call invoke countFailedDeliveryQueueEntries, whose own admission cache now avoids database work. The existing test still expects only one invocation after two summaries, and the reviewed-head Node shard fails here with expected 1, received 2. Its later outbound call-count assertions also describe the removed implementation. Remove those obsolete assertions while preserving returned-health and ingress checks; the new owner-level health suite already verifies that warm reads issue no worker requests.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 731fcf98396a.

Provenance checked

  • Delivery-health caching changes intended behavior with a stated reason (70ba239: Avoid repeated failed-delivery scans using committed database write tokens; perf(gateway): park idle database maintenance behind owner receipts #171320 retained that token until compound queue writers supplied complete owner coverage.)
  • Watched upstream discovery keeps the original intent (3bedfb0: Move discovery into the shared worker while preserving ordering, deduplication, ambiguous-agent suppression, and best-effort failure behavior.)
  • Skills inventory freshness changes intended behavior with a stated reason (bd00389: Share installed-plugin inventory within a scan, then reread on the next scan; this PR explicitly transfers Gateway inventory freshness to plugin lifecycle publication and source refresh while retaining skill-file scans.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/health/delivery-queue-cache.test.ts src/infra/delivery-queue-health.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Vincent Koc: Raw commit 0211407 adds src/gateway/health/delivery-queue.ts:7 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0211407d8a2c; files: src/gateway/health/delivery-queue.ts)

PR surface

Source +49, Tests +246. Total +295 across 12 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 9 107 58 +49
Tests 3 332 86 +246
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 439 144 +295

Review metrics

Metric Value Why it matters
Production versus test LOC Production +107/-58; tests +332/-86. Production growth adds owner publications and invalidations; test growth covers mutation, rollback, replacement, membership creation, and discovery freshness.

Labels

Label changes:

  • add P2: This is a bounded background-performance improvement with a concrete test repair, without evidence of an urgent user-facing outage.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a bounded background-performance improvement with a concrete test repair, without evidence of an urgent user-facing outage.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 15, 2026, 5:12 AM ET / 09:12 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

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.

@steipete
steipete merged commit df12bc1 into main Oct 15, 2026
156 of 161 checks passed
@steipete
steipete deleted the dbasync/idlesql5 branch October 15, 2026 10:09
@steipete

Copy link
Copy Markdown
Contributor Author

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.

Median [min–max] Baseline Candidate
Idle SQL/min 27.8 [27.0–35.4] 20.4 [19.2–34.0]
Idle requests/min 11.8 [8.2–13.6] 6.2 [5.8–8.4]
Causal warm SQL/requests per turn 84/28 84/28
Raw warm SQL/requests per turn 85/29 85/29
Whole-workload SQL/requests 3937/849 3887/836

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 schema-missing; it is excluded and preserved as an unresolved startup/admission follow-up. The unchanged replacement passing is not a fix for that defect.

Merged as df12bc1d05a11a8eac12112ed19d98ac706b98af. No latency claim is made from this loaded host.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
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.
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