Skip to content

refactor(gateway): schedule idle work and prewarm - #158666

Merged
steipete merged 1 commit into
mainfrom
hostneutral/scheduler-idle-tasks-0925
Sep 26, 2026
Merged

steipete merged 1 commit into
mainfrom
hostneutral/scheduler-idle-tasks-0925

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Idle maintenance and startup prewarm own timeouts outside the Gateway scheduler.

User Impact

Idle work keeps its existing foreground-priority, admission, retry and shutdown behavior. Existing installs need no migration or operator action; stores, configuration, ports, RPC and public SDK contracts are unchanged.

Why This Change Was Made

Require the kernel scheduler and stable IDs for idle jobs; thread it through the surviving handler-prewarm and post-attach startup owners. Delete the private timeout/clearTimeout path. Preserve main's consolidated prewarm sequence, current-config reads, startup-relative delays and outgoing-handler joins. The context-cache prewarm module retired by #158555 stays deleted.

One scheduler instance per Gateway process, enforced by types. No private constructor or standalone entry point is introduced. This slice adds no database access, schema or transaction changes. Independent worker liveness timers and per-operation timeouts remain outside this migration.

Production +50/-35/net +15; tests/support +175/-55/net +120; docs +0/-0/net 0. Required dependency/registration plumbing accounts for growth.

Evidence

The prior head 622edd22febed3fbcdc99c1886c15c2ecfa5c550 had an unrelated teardown failure in src/infra/outbound/delivery-completion.test.ts (ENOTEMPTY removing its temporary SQLite root), originating job. Other red shards were fail-fast cancellations. On the same Testbox lease, the complete recorded job groups passed on clean main 837fad120fbab0c0df0dd7bc7009dd90decfbd38 in 538.101s, and the failing file passed alone in 15.525s. The fixture removes its directory without retiring its SQLite/maintenance resources; the exact competing writer remains unproven. Twelve relevant test/storage/cleanup source files are identical between this head and clean main, and the failing test does not boot Gateway. This remains an unreproduced failure; the later green run does not establish a fix. No unrelated fixture change or blind CI rerun has been added.

Current head f293bd28576e8e5a30b79e23c5718a040a4669a9 is rebased onto main 2d5c68187a38db0c3bbe4cc18be77c12b0f54727 because main advanced, with an identical reviewed patch. Exact-head CI run 36230141296 and the enforced CI gate are green.

The refreshed focused Testbox attempt did not reach test execution: source-capsule preparation on the overloaded local host outlasted lease tbx_01m3edhed3b3gy7qhr2ke2rkxp (run 36230115499); it was interrupted after the lease completed. No new focused pass is claimed. The following focused proof belongs to the prior head 622edd22febed3fbcdc99c1886c15c2ecfa5c550. All 276 cases in 6 focused suites passed on blacksmith-testbox lease tbx_01m3e2nta4ngefyyk0dsf55cr4, run 36220641511. Commands: pnpm install --frozen-lockfile, then pnpm test <file> --maxWorkers=1; exact commit and clean source verified before and after.

File Prior-head command wall
src/gateway/server-idle-task.test.ts 3.531s
src/gateway/server-idle-task.lifecycle.test.ts 2.480s
src/gateway/server-startup-handler-prewarm.test.ts 2.314s
src/gateway/server-runtime-services.test.ts 25.187s
src/gateway/server-startup-post-attach.test.ts 11.323s
src/gateway/server-plugin-reload.recovery.test.ts 23.097s

The earlier CI failure came from an unrelated chained assertion in server-chat-progress-snapshot.ts. The exact lint command reproduced on clean old main (exit1,22.357s) and passed on clean current main (exit0,24.004s), which contains the owning fix 66b812f26e725cd709e08860d2cb46ba496cd308. No unrelated fix was added here. The accepted auto-merge request was retired through native recovery before replacing the head; replacement admission must use the retained native outcome and refreshed preparation. Exact-head CI is now complete; no new merge request has been submitted.

Earlier focused and review evidence

Head bb1dd3bd690f1c585c69ac37ad85a2a8a059b2d1 has the exact reviewed and Testbox-proven tree 2fd43c92f8fffd1c743dada364fcc5b11c7c3e83, based on main bed7385166380136b880e21f58232416d5375ebf. On blacksmith-testbox lease tbx_01m3e2nta4ngefyyk0dsf55cr4, run 36220641511, frozen install and all six focused files / 276 cases passed. Baseline SHA, patch bytes, full tree and unchanged source after tests were verified.

Commands: pnpm install --frozen-lockfile, then pnpm test <file> --maxWorkers=1.

File Command wall
src/gateway/server-idle-task.test.ts 1.997s
src/gateway/server-idle-task.lifecycle.test.ts 2.081s
src/gateway/server-startup-handler-prewarm.test.ts 2.092s
src/gateway/server-runtime-services.test.ts 22.981s
src/gateway/server-startup-post-attach.test.ts 10.749s
src/gateway/server-plugin-reload.recovery.test.ts 23.103s

The new manual-clock regression advances six seconds in earlier startup work and verifies a later five-second deadline adds no extra delay. The negative control with the old Date clock reads failed for the intended reason (5000ms instead of zero); the corrected owner passed. Existing lifecycle coverage exercises busy admission, restart/suspend fences, stop-before-start and shutdown initiated by a warning callback. No new per-test Gateway boot, sleep or polling was added.

Deslop, full cross-shard caller census and whitespace checks passed. Fresh Codex review of the upstream-adapted slice is clean through P2, following the original clean review. The full-source tree matches the isolated review candidate exactly. Earlier baseline costs remain in PR history; no performance improvement is claimed. GitHub's enforced CI gate supplies changed-file validation. Final merged-main maintenance/cron/suspend/restart/shutdown live proof follows the last stack slice.

Stack

  1. #157517 — diagnostic liveness preparation; merged.
  2. #158275 — internal auth factory naming; merged.
  3. #158423 — kernel scheduler and companion sweep; merged.
  4. #158531 — event-loop health; merged.
  5. #158537 — channel health; merged.
  6. #158614 — mention expiry; merged.
  7. #158617 — upstream monitoring; merged.
  8. #158662 — worker-placement maintenance; merged.
  9. Idle work and prewarm — this slice.
  10. #158690 — Incognito expiry; merged.
  11. #158717 — OAuth maintenance; merged.
  12. #158727 — initial lifetime maintenance; pending.
  13. Remaining reviewed owner migrations and final documentation/live proof — pending.

@clawsweeper

clawsweeper Bot commented Sep 26, 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 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 26, 2026, 5:20 AM ET / 09:20 UTC (Revision 6).

ClawSweeper review

What this changes

Routes Gateway idle cleanup and post-ready handler prewarming through the process scheduler and updates clock-driven lifecycle tests.

Merge readiness

⛔ Blocked before merge - 2 items remain

Current main still uses private timers for this work, so the PR remains useful. I found no definite introduced code defect, but the required installed-update lifecycle proof remains outstanding.

Priority: P3
Reviewed head: f293bd28576e8e5a30b79e23c5718a040a4669a9

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch and focused lifecycle coverage are sound, while the repository-required installed-upgrade result remains missing.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: 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.

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 Introduced scheduler cutover: The pinned merge-base-to-head patch replaces the idle task's private timeout with a named scheduler job while retaining work admission, retry, warning, and stop paths.
Current-main necessity: Fetched current main still arms the idle task with setTimeout; its handler prewarm also calculates the startup delay from Date.now(). The requested cutover is therefore absent there.
Scheduler lifecycle: The existing scheduler fences new jobs in beginClose and joins pending jobs in stop; the Gateway close prelude calls beginClose before closing runtime dependencies.
Findings None None.
Security None None.

How this fits together

After Gateway startup, optional prewarming prepares common request paths and idle maintenance cleans up retained resources. The process scheduler controls their wakeups; work admission prioritizes requests, and shutdown joins accepted work.

flowchart LR
A[Gateway startup] --> B[Process scheduler]
B --> C{Idle and open?}
C -->|yes| D[Handler prewarm]
C -->|yes| E[Maintenance cleanup]
C -->|busy| B
D --> F[First requests]
D --> G[Shutdown joins work]
E --> G
Loading

Before merge

  • Resolve merge risk (P1) - An existing installation has not been shown passing through the published updater to this candidate and then reaching Gateway readiness, scheduled idle work, and clean shutdown; lifecycle availability after upgrade remains unverified.
  • Complete next step (P2) - Record a published-updater run from an existing installation to this candidate showing Gateway readiness, scheduled idle work or prewarm, and clean shutdown.
Agent review details

Security

None.

PR surface

Source +15, Tests +120. Total +135 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 50 35 +15
Tests 6 175 55 +120
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 225 90 +135

Review metrics

Metric Value Why it matters
Production versus test delta production +15 net; tests/support +120 net Required scheduler wiring accounts for the small production increase; most growth exercises clock and lifecycle behavior.

Merge-risk options

Maintainer options:

  1. Prove the installed upgrade (recommended)
    Capture a redacted published-updater-to-candidate run that reaches readiness, executes scheduled idle work or prewarm, and shuts down cleanly before merge.

Technical review

Best possible solution:

Keep one process-owned scheduler for idle maintenance and prewarming while preserving foreground priority, startup deadlines, and shutdown joins on upgraded installations.

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

Not applicable: this is a scheduling refactor. Focused tests and a prior-head controlled-clock probe exercise its lifecycle behavior, but no installed-update run is supplied.

Is this the best way to solve the issue?

Yes: the existing process scheduler is the appropriate wakeup owner, and the patch keeps request admission and request-time loaders in their established owners. The required upgrade proof remains.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is a bounded internal Gateway scheduling refactor without a demonstrated current user-facing regression.
  • merge-risk: 🚨 availability: Moving startup and maintenance wakeups to the shared scheduler changes Gateway lifecycle timing, whose installed-upgrade path remains unproven.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

  • Introduced scheduler cutover: The pinned merge-base-to-head patch replaces the idle task's private timeout with a named scheduler job while retaining work admission, retry, warning, and stop paths. (src/gateway/server-idle-task.ts:48, f293bd28576e)
  • Current-main necessity: Fetched current main still arms the idle task with setTimeout; its handler prewarm also calculates the startup delay from Date.now(). The requested cutover is therefore absent there. (src/gateway/server-idle-task.ts:44, 5f3781df412c)
  • Scheduler lifecycle: The existing scheduler fences new jobs in beginClose and joins pending jobs in stop; the Gateway close prelude calls beginClose before closing runtime dependencies. (src/infra/gateway-scheduler.ts:136, f293bd28576e)
  • Focused lifecycle coverage: Changed tests exercise idle admission, restart and suspension fences, sidecar joins, and a later prewarm deadline after earlier work advances the clock. (src/gateway/server-idle-task.lifecycle.test.ts:30, f293bd28576e)
  • Required upgrade proof: Repository policy requires a published updater handing an existing installation to a lifecycle-changing candidate. The PR body and prior completed review report focused Testbox and controlled-clock evidence, but no such updater-to-candidate result. (AGENTS.md:83, f293bd28576e)
  • Prior production-path observation: The maintainer discussion reports a prior-head controlled-clock probe of the real prewarm owner: closing the scheduler prevented an unwanted callback while an open-scheduler control still ran. It also explicitly distinguishes that observation from installed-update proof. See refactor(gateway): schedule idle work and prewarm #158666 (comment).

Likely related people:

  • Peter Steinberger: Raw commit 362cee1 adds src/infra/gateway-scheduler.ts:43 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 362cee12114d; files: src/infra/gateway-scheduler.ts)
  • Galin Iliev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Show the published updater handing an existing install to this head, including Gateway readiness, scheduled idle work or prewarm, and clean shutdown.

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.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-26T05:20:19.893Z sha 7ffc68a :: blocked before merge. :: none
  • reviewed 2026-09-26T05:46:06.136Z sha 7ffc68a :: blocked before merge. :: none
  • reviewed 2026-09-26T06:12:27.120Z sha bb1dd3b :: blocked before merge. :: none
  • reviewed 2026-09-26T06:57:16.284Z sha 622edd22febed3fbcdc99c1886c15c2ecfa5c550 :: blocked before merge. :: none
  • reviewed 2026-09-26T08:40:24.158Z sha f293bd2 :: blocked before merge. :: none

@steipete steipete closed this Sep 26, 2026
@steipete steipete reopened this Sep 26, 2026
@steipete
steipete force-pushed the hostneutral/scheduler-idle-tasks-0925 branch from 7ffc68a to bb1dd3b Compare September 26, 2026 06:05
@steipete
steipete enabled auto-merge (squash) September 26, 2026 06:12
@steipete
steipete disabled auto-merge September 26, 2026 06:17
@steipete
steipete force-pushed the hostneutral/scheduler-idle-tasks-0925 branch from bb1dd3b to 622edd2 Compare September 26, 2026 06:19
@fuller-stack-dev

Copy link
Copy Markdown
Member

Additional shutdown regression proof for this existing PR, @steipete. Please continue its current native recovery and landing workflow; I have not changed this branch or submitted another merge request.

The unchanged server-close.model-acquisition.test.ts final-Gateway case failed in CI run 36221717993, job 108348547488. Its log reports post-ready gateway data prewarm failed for chat.send after model-reload cancellation, then a forbidden model-runtime chunk import.

I reproduced that failure on fresh main 65e3eecabd84876e6e32ac858aa8ce83e9d25674 using the job's decoded 95-file agentic-control-plane-runtime-server-hosted-2 group, its Gateway-server config, two workers, and plan concurrency one. The group finished with 1,661 passing tests and the same one failure in 402.176s. On published head 622edd22febed3fbcdc99c1886c15c2ecfa5c550, the identical saved group passed all 1,662 tests in 433.244s. Both ran on Node 24.20.0, macOS arm64, with private test state and unchanged test assertions.

The standalone file also passed on main, and Vitest scheduled the candidate's file earlier in the group. To separate the repair from test-order luck, I ran an identical controlled-clock probe against the real scheduleGatewayHandlerPrewarm on both commits:

Transition Main PR head
Hold post-ready gate, call scheduler.beginClose(), release gate, advance timer 1 unwanted callback 0 callbacks
Same sequence with an open scheduler 1 callback 1 callback

Both controls ended with zero admitted root work and no warnings. This confirms that the scheduler cutover also fixes optional prewarming starting while shutdown is joining a canceled model reload. The real Gateway cases retain coverage for an active sibling and a closing sibling. This is Gateway/owner-boundary proof, not an installed-update test.

Independent review raised a possible descendant-work join gap in the idle handle. A native probe using the actual Gateway sidecar owner falsified the proposed teardown race: the idle handle settled first, but the lifetime owner stayed pending until the scheduler-tracked child settled. The kernel already registers scheduler.stop() in that owner. No speculative patch was added.

The current required CI blocker is separate: run 36223414976, job 108353386257 failed delivery-completion.test.ts > pending-final delivery completion > invalidates an earlier recovery decision and wakes the exact session with ENOTEMPTY removing its private fixture directory. That group had 1,177 passing tests and one failure. This report does not clear that failed gate.

@fuller-stack-dev

fuller-stack-dev commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

@steipete The separate fixture cleanup repair landed in #158730 as 4ec3b0cd4d08d3d3071b88fcefce4969cbd5b5b4 at 09:11 UTC. Canonical ancestry and the exact changed-file blob were verified on main 14e4028809f54c1f382013abe30c0055ce67a22d. Your #158666 branch and retained native recovery/landing remain with you.

The two-line repair awaits the existing cleanupSessionStateForTest({ stateDir: tmpDir }) owner before fixture removal. It settles writers and reconciles and closes the owned database resources. Production behavior, assertions, retries, and timeouts are unchanged.

The unchanged canonical lifecycle probe deterministically found an open native SQLite handle at removal; the identical candidate probe found it closed. The intermittent ENOTEMPTY did not recur, so this proves missing resource closure, not the exact filesystem collision. The earlier 1,178-test replay alone does not clear #158666's failed CI gate.

All ten completion cases and three cleanup-helper cases passed, the entire touched test file and cleanup helper were audited, and configured API review found no actionable issues. Exact published-head CI passed, and authenticated ClawSweeper review completed. Raw red/green evidence, commands, audit, and limitations remain linked in #158730. Native landing reused completed proof; no tests or builds were repeated for publisher recovery.

No branch change or merge request was made against #158666.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 Sep 26, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member

@steipete Please resume the existing scheduler worker for this PR's remaining installed-update proof and landing. I checked the current head, 622edd22febed3fbcdc99c1886c15c2ecfa5c550; the branch and retained native recovery/merge workflow remain yours.

The two remaining items can progress separately:

Please first recheck the live head and existing evidence, then use your existing isolated environment where valid to complete that lifecycle proof. Our unchanged 95-file Gateway group and controlled-clock close comparison are already documented above; no repeat is needed unless a relevant source or environment assumption changes. Keep fixture state private, settle owned resources, and preserve meaningful failure assertions without sleeps, retries, or broader timeouts to hide a failure.

Once the fixture repair is available, assess canonical movement, refresh the candidate as needed, and continue your existing native recovery/landing workflow only with the required exact-head checks passing. Remove consumed generated environments and proof staging through their owning tools, retaining one compact record with verified published evidence links.

Please acknowledge which existing worker has accepted this continuation, or identify the exact owner/session availability blocker. I have not created another scheduler owner, changed this branch, or submitted another merge intent.

@steipete
steipete force-pushed the hostneutral/scheduler-idle-tasks-0925 branch from 622edd2 to f293bd2 Compare September 26, 2026 08:33
@steipete
steipete merged commit 2919fa6 into main Sep 26, 2026
199 checks passed
@steipete
steipete deleted the hostneutral/scheduler-idle-tasks-0925 branch September 26, 2026 09:36
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants