Skip to content

perf(gateway): skip unchanged idle maintenance reads - #169894

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

steipete merged 12 commits into
mainfrom
dbasync/idlesql2-maintenance

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Idle Gateway timers repeatedly scan empty recovery/OAuth inventories, retained secret/device expiry state, and unchanged failed-delivery counts. Cron history maintenance also opens a write transaction when nothing changes, invalidating shared-state readers every minute.

User Impact

Idle Gateways issue fewer database requests while preserving active placement recovery, OAuth refresh, retention deadlines, delivery-pressure expiry, and cross-process liveness. No configuration or schema changes are required.

Why This Change Was Made

Keep the existing Gateway owners authoritative. Reuse their write receipts for empty placement recovery and personal OAuth inventories; use admitted physical-database write tokens for secret/device deadlines, hidden OAuth inventories, and failed-delivery counts. Actual queued work stays live. Cron computes its recovery/pruning plan in the existing serialized writer command and opens a transaction only when rows change.

Removed checks and accepted edges:

  • Device setup expiry no longer rechecks the read-operation revision after its synchronous query. The host uses the existing committed write token and next expiry; unsupported outside writers must hold exclusive database ownership.
  • A no-op device expiry purge no longer revalidates credential authority after returning zero. It has no credential or external effect; real pairing mutations keep their live authority checks.
  • Empty recovery inventories sleep until the placement owner publishes a change. Local-only bookkeeping that cannot create recovery work does not wake them; nonempty recovery keeps direct reads.

Secret deletion keeps the conditional creation-time predicate so a refreshed transient handoff is not deleted. Cron still checks retained active receipts and process liveness, preserves newly-lost retention, and prunes transactionally. Delivery pressure remains a live read because lease expiry can change without a write. Active OAuth records keep the existing refresh/expiry/recovery and effect checks.

Evidence

The isolated shared harness completed the workload, five-minute no-user-turn window, and clean shutdown. One baseline/candidate pair is used under the approved reduced-testing workflow; the first batch is shown separately for attribution.

Metric Baseline First batch Combined candidate
Idle statements/min, raw 82.0 58.6 70.0
Idle requests/min, raw 39.2 24.4 26.6
Idle MAIN statements/min, raw 1.4 0 12.6
Warm SQL, median [min–max] 463.5 [446–625] 470 [413–585] 404 [388–545]
Warm requests, median [min–max] 113 [103–158] 117 [101–140] 95 [88–115]
Warm MAIN SQL 0 0 0

Raw idle SQL falls 14.6% and requests 32.1% versus baseline; the ≤30 SQL/min and ≤15 requests/min aims are not met. The raw second-candidate window includes unchanged Workshop work that earlier runs completed before idle. All three runs execute exactly 134 synchronous Workshop transcript-anchor authority checks; 63 shifted into a 0.761-second burst at the start of this idle window. The experience-review owner, scheduler, and agent-end trigger sources are byte-identical across all measured revisions. This is phase drift, not added SQL. Subtracting only those 63 proven shifted statements would give 57.4 SQL/min; requests are not adjusted because their parent attribution is incomplete. These checks guard the review's current source/lifecycle/permission authority before effects and remain a separate async-owner follow-up. They are not silently removed from the raw table. No warmed MAIN increase occurs.

Touched idle owner SQL/min first→combined Requests/min first→combined
Placement recovery / empty inventory 6.0→1.2 1.0→0.2
Cron history / minute maintenance 4.0→1.0 1.0→1.0
Secret expiry / deadline with write-token invalidation 4.0→2.0 1.0→1.0
Device expiry / deadline with write-token invalidation 1.0→1.0 1.0→1.0
Hidden OAuth / retained active records 2.0→2.0 2.0→2.0
Personal OAuth / empty inventory 1.0→0 1.0→0
Failed-delivery count / write-token invalidation 1.0→1.2 1.0→1.2

Health-related reads each ran six rather than five times in the last idle window; the placement inventory also includes one cleanup/retirement. These raw increases are disclosed as window-boundary/due-work differences, not claimed as removed polling. The shifted background review also performs writes and therefore legitimately invalidates caches. Active OAuth refresh, expiry/retention due work, cross-process liveness, pressure expiry, and WAL checkpoints remain. The final owner counts are observed rates, not promises that every idle cache stays empty.

Touched warmed operations (SQL/requests per turn, baseline→combined): placement recovery 1.8/0.3→0.6/0.1; cron history 1.2/0.3→0.1/0.1; secret expiry 0.8/0.2→0.2/0.1; hidden OAuth 0.5/0.4→0.2/0.2; device expiry 0.3/0.3→0.1/0.1; placement reads 0.3/0.3→0.1/0.1. Failed-delivery and the two ingress-health reads each fall from 0.3/0.3 to zero during warmed turns. No touched warm operation increases.

Shared read families per warm turn (baseline→combined): exact-entry facts 11.5→8.7; actor hydration 7.4→7.2; entry-cache snapshots 1.8→0.5; row-facts SQL 25.0→24.5; shared row-facts SQL 2.5→2.8; watermarks 6.0→5.9. The +0.3 shared-row-facts difference is disclosed and outweighed by −59.5 net SQL / −18 requests per warmed turn. It is recorded for follow-up.

Provenance: baseline 3e3a9a87e58b; first batch 457339912ac0; combined 44efea52e883 plus the saved OAuth import and aggregate-null/fallback corrections. The private harness retained the shared observer and workload, adding a five-minute idle phase. Later integration, type/export/test corrections are not represented as an exact measured final head. Both earlier runs completed their runtime workloads but failed the wrapper's final all-RPC assertion on unavailable mentions.dismiss; the combined run completed all RPCs successfully.

Validation:

  • Two completed Codex autoreviews, clean in the requested scope. Changed-file oxfmt, type-aware oxlint, and diff check passed.
  • Direct T1 primitives in changed production files remain 0→0, with no synchronous fallback. Tests cover owner-receipt invalidation, stale-read prevention after in-process writes, expiry, and cron no-op versus pruning behavior.
  • Final-head CI 38261850645 at 557c5893b51b: production types, all test-type stripes, lint, source/architecture guards including Madge, T1/worker and dialect ratchets, and all test shards passed.
  • The earlier CI run 38256733527 exposed two inherited failures: the duplicate wrapper inventory is reproduced from exact main parent 08005517; the unchanged node-reapproval test fails with the same 4001 device-pairing-changed on main 38237812441 / job 114773019169. The shared startup-GC fixture is corrected in the first batch; its selected regression passed in 5.834s (350.68s wall time including the fresh worker build).
  • Knip's inherited transcript/UI exports are removed by upstream f13b3cd209cd; no new lane-owned unused export remains. All three serial canonical Knip scans completed: production and full-tree reported only those inherited transcript/UI exports; the script scan passed with no findings. No lane-owned export finding remains.

No schema, SDK, update, Doctor, plugin-loading, or service-lifecycle contract changes; no SDK diff or published-driver update cell applies. Release-note context: reduce unchanged idle-maintenance database work without configuration changes.

Integration head 557c5893b51b: merged the landed first batch (d43b88eb1bbd) into this branch with no production-code conflicts. The two test conflicts preserve the landed startup-recovery regression and the existing recovery-cache regression. Own diff against that main parent: 30 files, +786/−332 lines.

The conflict-only integration passed changed-test formatting and type-aware lint; final-head CI confirms the integrated types, static checks and tests.

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.
Cache empty recovery and OAuth inventories under their existing owners,
retain secret and device expiry deadlines under committed write tokens,
and reuse failed-delivery health counts until the database changes.

Plan cron history maintenance inside its serialized worker and skip the
write transaction when there is no recovery or pruning work. Keep active
recovery, retention deadlines, credential effects, and lease-sensitive
health reads live.
@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 in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes size: XL labels Oct 12, 2026
…dlesql2-maintenance

# Conflicts:
#	src/gateway/worker-environments/placement-turn-authority.ts
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 caches unchanged maintenance inventories and expiry deadlines and skips Cron write transactions when no rows need changing.

Example: An idle Gateway runs Cron history maintenance with no history requiring recovery or pruning.

  • Before: Maintenance opens a write transaction and invalidates shared-state readers.
  • After: Maintenance returns zero reconciled and pruned rows without opening the write transaction.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Static patch review is positive, but required runtime readiness remains unproven.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Idle Gateways spend database and worker capacity repeatedly inspecting unchanged maintenance state.
Reason: The maintainer-authored direction has clear resource value and preserves existing ownership, settings, and retention contracts.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it contains useful, maintainer-directed performance work absent from fetched main, and no new discrete introduced defect was established.

Priority: P2
Reviewed head: 903202980660c03f4cd64146b6ace6d3ebf145f4

Before merge

  • Complete next step - Classify the node-reapproval failure in checks-node-changed-compact-large-19-2 against the pinned base before landing; fix it only if this PR caused it.

Findings

None.

Tests

  • Missing end-to-end proof: The required candidate idle comparison remains pending, and supplied evidence does not document base-fail/head-pass execution of the new regressions.
Agent review details

How this fits together

Gateway timers call placement, OAuth, secret, device, health, and Cron owners, which consume committed-write publications and return recovery, cleanup, or diagnostic results.

flowchart TD
A[Gateway timers] --> B[Maintenance owners]
C[Committed writes] --> D[Cache invalidation]
D --> B
E[Expiry deadlines] --> B
B --> F[Shared state workers]
F --> G[Recovery cleanup and health results]
Loading

Technical review

Best possible solution:

Land the existing-owner optimization after its declared validation is complete.

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

Current-main source establishes repeated maintenance reads and unconditional Cron maintenance transactions; this read-only review ran no target code.

Is this the best way to solve the issue?

Receipt-based invalidation and explicit deadlines address redundant work at the existing owners while retaining active recovery and lease-sensitive pressure reads.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • System and agent OAuth inventories keeps the original intent (0a86702: Settings authorization requires Gateway-owned polling, refresh records, and restart recovery; only empty inventories are cached.)
  • Personal OAuth inventory keeps the original intent (bc1d2b9: Connection authority moved through workers with committed publications; the new empty-inventory cache consumes those publications.)
  • Placement recovery discovery keeps the original intent (b81e04f: Recovery discovery moved to the read worker while retaining recovery ordering and live effect checks; nonempty inventories still read directly.)
  • Secret expiry keeps the original intent (fffbda3: Secret cleanup moved off the Gateway thread to avoid stalls while retaining expiry rules; the worker boundary and deadlines remain.)
  • Device setup expiry changes intended behavior with a stated reason (20cfa13: Earlier maintenance retained worker-side expiry observations and no-effect revalidation; the body explains replacing those with host-held committed-write tokens and deadlines.)
  • Cron history maintenance keeps the original intent (3a69600: Row-dependent maintenance belongs in the serialized worker without host waits while holding the writer.)
  • Delivery health keeps the original intent (c6b7810: Failed-delivery counts moved to the shared worker while preserving diagnostics; lease-sensitive ingress pressure remains live.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 0a86702 adds src/gateway/github-oauth-lifecycle.ts:446 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0a86702241ce; files: src/gateway/github-oauth-lifecycle.ts)
  • Dallin Romney: Raw commit 3e5f7d4 adds src/gateway/worker-environments/placement-store.ts:39 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 3e5f7d43aaa1; files: src/gateway/worker-environments/placement-store.ts)
  • Vincent Koc: Raw commit 0211407 adds src/gateway/health/delivery-queue.ts:8 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 +250, Tests +204. Total +454 across 30 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 18 443 193 +250
Tests 12 343 139 +204
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 30 786 332 +454

Review metrics

Metric Value Why it matters
Production versus test growth Production +443/−193; tests and test routing +343/−139 Production growth implements receipt-bound caches and separates Cron planning from transactional application; tests cover invalidation, expiry, and no-op maintenance.

Labels

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded idle-resource improvement without an established outage caused by the redundant maintenance work.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-12T12:52:33.844Z sha 44efea5 :: needs changes before merge. :: [P1] Restore the device inventory import used by authorization start
  • reviewed 2026-10-12T13:04:20.155Z sha 181dba0 :: needs changes before merge. :: [P1] Restore the device inventory import used by authorization start | [P2] Place the health test in the manifest's canonical order
  • reviewed 2026-10-12T13:32:01.992Z sha 6e09cb4 :: needs changes before merge. :: none

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

Reuse the generation-3 environment for the seeded startup placement's retry, preserving the orphan-cleanup admission assertion.
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 12, 2026
Base automatically changed from dbasync/idlesql2 to main October 12, 2026 14:04
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 557c5893b51b0204d1f025e08e7bb8b1c514e0d5
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/github-oauth-lifecycle-helpers.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/github-oauth-lifecycle.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/github-personal-oauth.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/placement-authority-owner.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/placement-read-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/placement-turn-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/placement-turn-authority.types.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/infra/device-bootstrap.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/infra/device-bootstrap.worker-kernel.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/infra/device-pairing-store.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/infra/device-pairing-worker.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/secrets/store/secret-store-expiry.kernel.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/secrets/store/secret-store.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Oct 12, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the docs Improvements or additions to documentation label Oct 12, 2026
@steipete
steipete merged commit 70ba239 into main Oct 12, 2026
148 checks passed
@steipete
steipete deleted the dbasync/idlesql2-maintenance branch October 12, 2026 14:31
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Reuse owner write receipts and expiry deadlines for maintenance caches. Keep active recovery, OAuth refresh, retention and live security checks. Skip no-op cron write transactions.

Release-note context: reduce idle Gateway database work without configuration or schema changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. security-sensitive-changed size: XL 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