Skip to content

perf(gateway): avoid database polling in idle Gateways - #169871

Merged
steipete merged 6 commits into
mainfrom
dbasync/idlesql2
Oct 12, 2026
Merged

steipete merged 6 commits into
mainfrom
dbasync/idlesql2

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

An idle Gateway repeatedly queries unchanged placement, session-retention, and GitHub-publication state. These sweeps also inflate per-turn SQL counts when a turn overlaps a timer.

User Impact

Idle Gateways do less database work while preserving startup recovery, session retention, active placement maintenance, publication retries, and personal-publication confirmation. No configuration, schema, or migration changes are required.

Why This Change Was Made

Reuse the placement owner's receipt-invalidated maintenance inventory for disk checks, skip environment pruning when its resident inventory is empty, and finish orphan-ref cleanup against the startup inventory it already owns. Session registry maintenance now sleeps until the earliest expiry or a relevant committed session/topology change. GitHub publication recovery sleeps after an empty scan and resumes from its existing exact write receipts.

Removed checks and accepted edges:

  • Disk samples no longer synchronously reread a placement after a tunnel probe. A late old-binding sample may briefly emit an advisory refresh; the exact-binding reader hides it and the next sweep discards it. Command/tunnel authority checks remain.
  • Disk-cache cleanup uses one owner snapshot instead of individual synchronous lookups. A placement moved during a sweep is reconciled on the next pass.
  • Startup orphan cleanup no longer repeatedly discovers newly created placements. Their normal turn settlement owns cleanup; startup recovery retains its original unresolved roots. A root still held by session recovery may wait for an eligible later idle sweep or restart; these orphan refs are best-effort garbage collection and carry no live authority.

Cron run-history recovery keeps its minute cadence. Protected expired sessions, unreadable stores, failed sweeps, active environments, pending publications, unreported outcomes, and failed transcript reporting continue retrying. All real effect and retention guards remain.

Evidence

One isolated shared-harness live pair on baseline 3e3a9a87e58b and this batch's production commit 457339912ac0:

Metric Baseline This batch
Idle statements/min 82.0 58.6
Idle requests/min 39.2 24.4
Idle MAIN statements/min 1.4 0
Warm statements, median [min–max] 463.5 [446–625] 470 [413–585]
Warm requests, median [min–max] 113 [103–158] 117 [101–140]
Warm MAIN statements 0 0

Idle SQL falls 28.5%; requests fall 37.8%. The removed idle MAIN statements were startup orphan-cleanup workspace resolution.

Owner / trigger SQL/min before→after Requests/min before→after
Session registry / minute sweep→expiry deadline or receipt 10.0→0 2.0→0
Publication recovery / unchanged empty inventory 6.0→0 8.0→0
Environment pruning / empty resident inventory 2.0→0 2.0→0
Placement disk sweep / receipt-invalidated inventory 5.2→3.0 5.2→3.0
Startup orphan retry / live-worktree lookup 0.6→0 0.6→0

Shared read families per warm turn (baseline→this batch→combined follow-up #169894): exact-entry facts 11.5→11.7→8.7; actor hydration 7.4→7.1→7.2; entry-cache snapshots 1.8→1.6→0.5; row-facts SQL 25.0→23.5→24.5; shared row-facts SQL 2.5→2.2→2.8; watermarks 6.0→5.7→5.9. The first pair's four extra single-entry reads against two fewer broker reads did not recur in the combined run. The combined follow-up reduces warmed medians to 404 SQL / 95 requests, with zero warm MAIN. The small +0.3 shared-row-facts difference versus baseline is disclosed and outweighed by the net −59.5 SQL / −18 requests per warm turn.

All runs completed 13 turns, child completion, cron, compaction, five-minute idle, and clean shutdown. The first two wrappers failed only their final all-RPC assertion because mentions.dismiss returned UNAVAILABLE; their runtime workload and census completed. The combined run completed with all RPCs successful. That run used 44efea52e883 plus the saved required OAuth import and aggregate/fallback normalization corrections; later changes were type/export/test fixes and integrated upstream placement ownership. It is not represented as an exact final-head benchmark.

Validation:

  • Changed-file oxfmt, type-aware oxlint, and diff check passed. Direct T1 primitives in changed production files remain 0→0; three indirect synchronous placements.get sites are deleted, with no fallback.
  • Two completed Codex autoreviews, clean in the requested scope. No third round.
  • Regression coverage exercises placement receipt invalidation, empty→created environment pruning, startup orphan inventory, retention deadlines/receipt wakeups, and publication insertion/reporting retry.
  • CI 38256164777 validated 19cd255fa6b7 through merge 09044762a696 onto main 418aa6a54a07. Lint, source contracts, architecture/Madge, worker and dialect ratchets passed. Four type jobs fail at the unchanged updater's number/bigint snapshot identity mismatch (update-command-migrate.ts:211); the incompatible caller and type owner exist on that exact main.
  • All three serial canonical Knip scans completed. No finding is in this PR's files. Remaining type/script exports are byte-identical to exact main; old transcript/UI findings were removed by newer main and remain removed in the merge.
  • The CI startup-cleanup fixture incorrectly demanded GC while recovery still owned the placement. The final test uses normal reclamation, asserts the orphan ref still exists, and requires the next eligible sweep to remove it. Focused corrected regression passed (one selected test, 5.834s; 350.68s wall time including the fresh worker build). Remaining tests in that file are covered by CI; this diagnostic invocation deliberately selected the failing regression.

This changes scheduling, not update, Doctor, schema, plugin loading, SDK, or service lifecycle; no update cell or SDK diff applies. The public behavior/release-note context is reduced idle database work without configuration changes.

Follow-up: publication tests could assert observable retry/reporting outcomes in addition to their mock counts; this is advisory test-quality work, not a product regression.

Final test-only correction: 4deba4b49f77 (+4/−1). It uses normal reclamation before asserting GC; the failed prior assertion is not presented as passing. Required static proof above is unchanged by this fixture-only correction.

Final own-scope diff versus integrated main parent 08005517c47b: 19 files, +536/−88 lines (production8 files +229/−41; tests/support/manifest10 files +305/−47; docs1 file +2/−0).

Reuse owner-published placement and publication facts, and schedule session registry retention from known deadlines. Preserve active work, startup recovery, and effect authority while dropping redundant idle reads.
@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR replaces unchanged idle database scans with committed-write wakeups, retained placement inventories, and retention deadlines.

Example: A Gateway has no cron-run sessions or pending GitHub publications.

  • Before: Minute sweeps repeatedly read the unchanged inventories.
  • After: Registry retention and publication recovery sleep until relevant writes or deadlines require another scan.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful runtime measurements support the optimization, but the changed cleanup regression fails and four typecheck failures remain unattributed.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied isolated Gateway comparison exercises the changed maintenance owners through turns, child completion, cron, compaction, idle operation, and shutdown, reporting lower idle SQL and request rates; the production changes match the measured candidate.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: An idle Gateway repeatedly reads unchanged maintenance state and adds background database work during turns.
Reason: The maintainer-authored direction has measured idle savings and records the accepted advisory tradeoffs.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this PR open: the measured optimization is useful, but the changed startup-cleanup regression still fails after the previous fixture fix.

Priority: P2
Reviewed head: 19cd255fa6b774180898727d2731e3369d36ddb3

Before merge

  • Restore the startup orphan-cleanup retry regression (P2) - With REQUEST seeded before startup and redispatched using generation 3, provider completion now succeeds, but the following full sweep leaves refs/openclaw/worker-result-cleanup/orphan-claim behind. Exact-head CI reports the failure at line 573 in https://github.com/openclaw/openclaw/actions/runs/38256164777/job/114835226204. The previous generation fix is present, but this changed scenario still does not satisfy its eventual-cleanup contract. Repair the fixture or cleanup path while preserving both the busy-pass retention and eventual-deletion assertions; the annotation alone does not establish which owner causes the remaining failure.
  • Complete next step - Inspect diagnostics for check-prod-types and check-test-types-core-1, core-4, and core-5, distinguishing diff-caused errors from inherited failures.

Findings

  • [P2] Restore the startup orphan-cleanup retry regression — src/gateway/worker-environments/placement-dispatch-recovery-admission.test.ts:548-550

Tests

  • Low-value test src/gateway/github-publication-runtime.test.ts: The added cases mock recovery, resumption, and result listing, then assert invocation counts; replace or consolidate them with observable retry/reporting outcomes through the existing coordinator fixtures.
  • Missing end-to-end proof: Base-failing/head-passing regression proof is not established: exact-head CI still fails the busy-startup-placement cleanup case.
Agent review details

How this fits together

Gateway maintenance consumes SQLite owner snapshots and committed-write receipts to schedule retention, worker housekeeping, disk probes, and publication recovery.

flowchart TD
  A[Committed SQLite writes] --> B[Owner receipts]
  B --> C[Maintenance scheduling]
  D[Retention deadlines] --> C
  C --> E[Worker inventory and recovery]
  C --> F[Session retention]
  C --> G[Publication recovery]
Loading

Technical review

Best possible solution:

Retain the receipt-driven scheduling while restoring passing startup-cleanup coverage without weakening its eventual-deletion assertion.

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

Current-main source confirms repeated maintenance reads, and the supplied comparative Gateway results measure their cost; this read-only review executed no target code.

Is this the best way to solve the issue?

Reusing existing owner receipts and deadlines fits the problem and preserves the existing persistence owners, but the changed cleanup scenario must pass before merge.

Full review comments:

  • [P2] Restore the startup orphan-cleanup retry regression — src/gateway/worker-environments/placement-dispatch-recovery-admission.test.ts:548-550
    With REQUEST seeded before startup and redispatched using generation 3, provider completion now succeeds, but the following full sweep leaves refs/openclaw/worker-result-cleanup/orphan-claim behind. Exact-head CI reports the failure at line 573 in https://github.com/openclaw/openclaw/actions/runs/38256164777/job/114835226204. The previous generation fix is present, but this changed scenario still does not satisfy its eventual-cleanup contract. Repair the fixture or cleanup path while preserving both the busy-pass retention and eventual-deletion assertions; the annotation alone does not establish which owner causes the remaining failure.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 28df9fe159fc.

Provenance checked

  • Cron retention scheduling changes intended behavior with a stated reason (1b7dd0b: Defer retention until startup admission while retaining maintenance when scheduling is disabled; this PR preserves admission and explains replacing minute registry polling with deadlines.)
  • Disk-monitor discovery and sample acceptance changes intended behavior with a stated reason (21d59e1: Warn about cloud-worker disk exhaustion using exact-binding samples; this PR explicitly accepts advisory sample lag while retaining exact-binding presentation and tunnel checks.)
  • Startup orphan cleanup changes intended behavior with a stated reason (62a435d: Bound startup Git inventories across idle sweeps and retain result fences; this PR explains retaining only the startup placement inventory.)
  • GitHub publication recovery keeps the original intent (aec8993: Complete awaited worker-owned publication and lifecycle operations; the new receipt-driven wakeups retain those owners and failed-report retries.)
  • Terminal-environment pruning keeps the original intent (4ac9f4c: Prune terminal environments through the service owner; the new empty-inventory shortcut retains pruning whenever resident rows exist.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 7845182 adds src/config/sessions/session-registry-maintenance.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 784518241040; files: src/config/sessions/session-registry-maintenance.ts)

PR surface

Source +188, Tests +255, Docs +2. Total +445 across 19 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 229 41 +188
Tests 10 302 47 +255
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 533 88 +445

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P2: This is a measured idle-performance improvement with a blocking regression-test failure and no established urgent user-facing outage.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-12T11:47:40.563Z sha 4573399 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T12:19:28.306Z sha ec68d29 :: needs changes before merge. :: none
  • reviewed 2026-10-12T12:52:30.665Z sha 2b566a4 :: needs changes before merge. :: [P2] [P2] Align the restored cleanup fixture with startup-only discovery
  • reviewed 2026-10-12T13:16:11.162Z sha c1b14f5 :: needs changes before merge. :: [P2] Match the retry fixture’s environment to dispatch generation 3

Reviewed October 12, 2026, 9:46 AM ET / 13:46 UTC (Revision 5).

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@steipete steipete changed the title improve: avoid database polling in idle Gateways perf(gateway): avoid database polling in idle Gateways Oct 12, 2026
Reuse the generation-3 environment for the seeded startup placement's retry, preserving the orphan-cleanup admission assertion.
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@steipete
steipete merged commit d43b88e into main Oct 12, 2026
47 of 51 checks passed
@steipete
steipete deleted the dbasync/idlesql2 branch October 12, 2026 14:04
@steipete

Copy link
Copy Markdown
Contributor Author

Landed with the corrected startup-orphan regression passing. Follow-up from review: extend the publication retry tests to assert observable reporting outcomes alongside mock-call counts. This is separate test-quality work; the retained failure/retry paths are unchanged.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Reuse owner-held placement and publication inventories, and wake session retention from deadlines and committed receipts. Delete redundant synchronous placement reads while preserving recovery, active retention, and effect authority.

Idle live pair: 82.0 to 58.6 statements/min and 39.2 to 24.4 requests/min; idle MAIN SQL 1.4 to zero. Includes focused startup-orphan regression and recorded static/inherited CI evidence. Release-note context: reduce idle Gateway database work without configuration changes.
yozakura-ava pushed a commit to yozakura-ava/openclaw that referenced this pull request Oct 20, 2026
Upstream provenance: PR openclaw#169871, relevant upstream commit d43b88e; PR openclaw#171320, relevant upstream commit 17e87b0; adapted, not cherry-picked.

Adaptation: retain 10.5 startup discovery, recovery, expiry, lease, heartbeat, active-job protection, retry, and clock behavior while parking empty maintenance and waking from post-commit history/session invalidations. Added deadline calculation and fresh-facts retry handling; no schema or public API changes.

Regression coverage: maintenance lifecycle, retained session expiry, async invalidation, run-history, oxlint, oxfmt, and guarded tsgo:core. Direct tsc was separately resource-capped at 6G and could not complete.

Rollback: revert this commit only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant