Skip to content

fix: skip idle chats when checking for stranded turns - #205835

Merged
vincentkoc merged 1 commit into
mainfrom
perf/idle-yield-selection
Nov 26, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
perf/idle-yield-selection

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

What Problem This Solves

Every minute, a gateway with many idle chats selected all their metadata to find turns that had yielded. In a 1,470-session fixture that returned 88,200 ordinary rows an hour after startup, even with zero new turns. This work came from the generic recovery sweep added in #202338.

User Impact

A quiet gateway still checks for stranded turns every minute. After the first scan it can skip ordinary sessions until a row changes. A parked turn with a live child, controller, exec, or retained continuation keeps waiting. A turn that loses its last wake source still receives its recorded failure.

Why This Change Was Made

The recovery sweep remembers the parked keys under the projection's existing row-publication revision. It still prepares metadata on each tick and checks live wake sources for every selected waiter. Clearing a pending final delivery invalidates the candidate set even when the ordinary session-list fields look the same. The cache retains keys only and uses the existing identity lookup.

Evidence

Five alternating before/after pairs on an exclusive Linux x64 AWS host with Node 24.19.0 and 1,470 synthetic sessions. Each arm ran 100 warm ticks per pair against the same hydrated projection. Wall and CPU times were recorded separately from allocation sampling. The acceptance rule was zero ordinary rows on an unchanged idle tick, while a newly eligible or stranded turn is still handled.

Per warm tick Before, median / p95 After, median / p95
Returned rows 1,470 / 1,470 0 / 0
Wall time (ms) 0.153 / 0.187 0.061 / 0.062
Process CPU (ms) 0.848 / 1.059 0.342 / 0.377
Sampled allocated bytes 170,385 / 238,572 2,634 / 2,960

Reproduce with the committed session-read fixture and yield benchmark. Run from the candidate checkout, using a new fixture directory and a new output path for each pass.

scratch=$(mktemp -d)
git show 31627710a8:src/gateway/session-yield-sweep.ts > "$scratch/baseline-sweep.ts"
node --import ./scripts/tsx.mjs scripts/perf/session-read-transactions-fixture.mjs \
  --root "$scratch/state" --database-only --sessions 1470 --events 6500 \
  --target-events 600 --body-bytes 64 --target-body-bytes 64 --snapshot-bytes 256
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/session-yield-measure.mjs \
  --root "$scratch/state" --baseline src/agents/tools/sessions-yield-tool.ts \
  --baseline-sweep "$scratch/baseline-sweep.ts" --operations 100 --output "$scratch/time.json"

Repeat the last command with --allocation and a fresh output filename to sample allocations. AWS comparison

The red regression selected both ineligible rows on the second tick. The patched sweep passed all seven focused cases, including recovery after final-delivery state clears and a held continuation releases. All eleven sibling restart cases passed. The gateway TypeScript check, scoped lint, formatting, and runtime build also passed. Focused tests and typecheck

The built gateway ran with 23 synthetic agents and 1,470 sessions, using one PID. Readiness returned HTTP 200 at 0, 65, 125, and 185 seconds. By 65 seconds, the broad selection had returned 1,470 rows once. Both its call count and row count stayed fixed through 125 and 185 seconds. The gateway exited with status 0. Restart tests, build, and gateway run

Independent autoreview of 31627710a8..395e5e444f found no actionable P0–P2 findings. The review covered the sweep, row-revision invalidation, candidate lookup, tests, and benchmark. Production changed by +15 net lines, tests by +59, and the benchmark by +12.

The September field report predates this sweep. It remains open for the offered same-PID, post-GC retainer evidence. Idle field investigation

@clawsweeper

clawsweeper Bot commented Nov 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.

@vincentkoc vincentkoc self-assigned this Nov 26, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts size: S labels Nov 26, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review November 26, 2026 07:52
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 26, 2026
@vincentkoc

vincentkoc commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

The hosted build-artifacts failure is inherited. The job checked out ce0fc4dd (the PR head merged into b7bd237d) and failed pnpm gateway:validators:check on packages/gateway-protocol/src/compiled/protocol.generated/predicates.js. The scheduled build on this branch’s unmodified parent 31627710 failed on the same file at 07:39 UTC. An unrelated compaction PR produced the same error 29 minutes before this PR opened. The two CI bases have identical gateway-protocol trees, generator, direct generator helpers, and lockfile. This job · Unmodified main parent · Earlier job · This merge-ref delta

On that base, the model logout schema accepts the optional literal revoke: true. The checked-in generated predicate omits revoke from its accepted properties. The current head of #205332 adds the missing property and literal check in the generated file. The yield change touches only the sweep, its regression test, and the benchmark. Schema on the failing base · Schema change · Contributor’s validator fix

@clawsweeper

clawsweeper Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses parked-session keys across unchanged projection revisions so periodic recovery skips ordinary idle chats.

Example: A quiet Gateway contains 1,470 ordinary sessions.

  • Before: Each warm recovery tick returns 1,470 session rows.
  • After: Unchanged warm ticks return zero rows after the initial scan.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, worthwhile optimization with relevant Gateway evidence and no identified patch defects; CI remains blocked by an inherited validator failure.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The public body records the changed selection behavior through a built Gateway on Linux x64 with Node 24.19.0: one initial 1,470-row broad selection, no additional broad selections across subsequent maintenance ticks, and healthy readiness; focused regression results cover delivery-state invalidation and released continuation recovery.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Quiet Gateways repeatedly allocate and traverse ordinary session metadata while checking for stranded turns.
Reason: The maintainer-authored direction removes measured recurring work with a small change inside the existing recovery owner.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it is a useful, maintainer-authored optimization that preserves stranded-turn recovery, with no actionable correctness findings.

Reviewed head: 395e5e444f47139085f22516171f7ae2f23d0ce5

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway maintenance supplies the session projection to the yield sweep, which checks live continuation sources and records failures for unreachable parked turns.

flowchart TD
  A[Gateway maintenance] --> B[Prepare session projection]
  B --> C[Projection revision and parked keys]
  C --> D[Select candidate sessions]
  D --> E[Check live wake sources]
  E --> F[Preserve valid waits]
  E --> G[Record unreachable turn failure]
Loading

Technical review

Best possible solution:

Retain this focused revision-keyed optimization and preserve the existing live wake checks and lifecycle failure owner.

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

Current main selects the full session roster before checking parked eligibility, matching the reported recurring idle work; this read-only review ran no target code.

Is this the best way to solve the issue?

The small cache reuses the projection's publication identity and indexed lookup, retains only keys, and continues checking mutable wake sources on every selected waiter.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Generic yielded-turn recovery keeps the original intent (51a07cc: Recover unreachable yielded follow-ups even when they have no current subagent registry record.)
  • Durable exec-result wake preservation keeps the original intent (463d774: Keep pending background-command results eligible for delivery before goal advancement and across restart.)
  • Yield measurement baseline keeps the original intent (51a07cc: The original benchmark used a no-op baseline because generic recovery did not yet exist; the added historical-source option enables comparison against that now-existing sweep.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Focused introduced change: The pinned introduced diff adds revision-keyed parked-session selection while retaining every existing wake-source check and the exact lifecycle failure writer. (src/gateway/session-yield-sweep.ts:29, 395e5e444f47)
  • Existing projection invalidation contract: Row replacement invalidates the sharing revision independently of selection-fact equality; candidate selection uses the existing identity indexes and returns immediately for an empty candidate set. (src/gateway/session-row-projection-revisions.ts:167, 395e5e444f47)
  • Distinct regression coverage: The added case checks idle-row exclusion, discovery after pending final delivery clears, repeated selection of retained waiters, and recorded failure after continuation release. (src/gateway/session-yield-sweep.test.ts:241, 395e5e444f47)
  • Current main still performs the broad selection: Fetched main retains the unconditional selectEntries call before filtering parked sessions; the PR's central optimization is absent. (src/gateway/session-yield-sweep.ts:24, a40778940382)
  • Public performance and Gateway evidence: The PR body reports five alternating benchmark pairs and a built Gateway with 23 synthetic agents and 1,470 sessions: broad selection stops after its initial scan while readiness remains healthy. The linked Crabbox portals were inaccessible to this reviewer; the scenario and results are self-contained in the public body. (395e5e444f47)
  • Inherited validator CI failure: Head build-artifacts fails at Check generated schema validators, and the exact merge-base build fails at the same step. The aggregate ci-gate reports that build failure. The separate repair fix(gateway): regenerate the shared preview validator #205332 documents stale shared-preview predicates on unchanged main; this is not evidence of a yield-sweep defect. (31627710a865)

Likely related people:

  • Peter Steinberger: Raw commit 51a07cc adds src/gateway/session-yield-sweep.ts:18 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 51a07cc9daa1; files: src/gateway/session-yield-sweep.ts)

PR surface

Source +15, Tests +59, Other +12. Total +86 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 16 1 +15
Tests 1 60 1 +59
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 20 8 +12
Total 3 96 10 +86

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • 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.

Reviewed November 26, 2026, 3:07 AM ET / 08:07 UTC.

@vincentkoc
vincentkoc merged commit f5545af into main Nov 26, 2026
195 of 198 checks passed
@vincentkoc
vincentkoc deleted the perf/idle-yield-selection branch November 26, 2026 08:35
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
obviyus added a commit that referenced this pull request Nov 29, 2026
…elded session (#204801)

## Problem

`src/gateway/session-yield-sweep.test.ts` > "settles only an unreachable parked lifecycle (exec-completion)" fails intermittently on scheduled `main` (run 45403387860): `expected undefined to be 'failed'` at the final status check.

Since #204265, the yield sweep keeps a yielded session waiting while it has a stored owed exec result (`shouldWake`, `session-yield-sweep.ts:45`). When the exec completion's wake settles as `cancelled`, `settleOwedExecWake` withholds the owed row asynchronously: `readPendingOwed` and then `withhold` on the database worker. The test resolved the wake and advanced the fake clock straight away. When the sweep tick ran before `withhold` committed, the sweep still saw the pending row and correctly left the session waiting, so the status stayed unset.

## Solution

Test-only change. After the wake settles, the test waits until `shouldWake` (the stored-row check the sweep itself uses) reports no owed result, then advances the clock. Product behavior is unchanged: the next sweep tick settles the session.

#204609 and #204621 do not touch this path. #204609 changes only `session-restart-resume-custody.ts`, which only the restart path imports. #204621 changes reply-operation backend readiness, which none of these modules use; the test's wake is mocked.

## Impact

No change to production code or user behavior.

## Evidence

- Before: intermittent red on scheduled `main` with the assertion above: run 45403387860, and again in run 45849028735 (2026-11-26, `checks-node-compact-large-14`, after #205835), `expected undefined to be 'failed'` in the exec-completion case. The race mechanism (`settleOwedExecWake` withholds the owed row after the wake settles) is unchanged on current `main`.
- Negative control (deterministic): with a 500 ms delay inserted before that `withhold` (local throwaway change), current `main` fails the exec-completion case 3/3 with the same assertion; with this change it passes 3/3.
- Without the delay, interleaved runs of `session-yield-sweep.test.ts` with this change applied to current `main`: 20/20 green (main alone was also 20/20 locally; the natural race is rare).

## Merge danger

Two-way door: test-only, a revert fully undoes it. Blast radius: one test file.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
…elded session (openclaw#204801)

## Problem

`src/gateway/session-yield-sweep.test.ts` > "settles only an unreachable parked lifecycle (exec-completion)" fails intermittently on scheduled `main` (run 45403387860): `expected undefined to be 'failed'` at the final status check.

Since openclaw#204265, the yield sweep keeps a yielded session waiting while it has a stored owed exec result (`shouldWake`, `session-yield-sweep.ts:45`). When the exec completion's wake settles as `cancelled`, `settleOwedExecWake` withholds the owed row asynchronously: `readPendingOwed` and then `withhold` on the database worker. The test resolved the wake and advanced the fake clock straight away. When the sweep tick ran before `withhold` committed, the sweep still saw the pending row and correctly left the session waiting, so the status stayed unset.

## Solution

Test-only change. After the wake settles, the test waits until `shouldWake` (the stored-row check the sweep itself uses) reports no owed result, then advances the clock. Product behavior is unchanged: the next sweep tick settles the session.

openclaw#204609 and openclaw#204621 do not touch this path. openclaw#204609 changes only `session-restart-resume-custody.ts`, which only the restart path imports. openclaw#204621 changes reply-operation backend readiness, which none of these modules use; the test's wake is mocked.

## Impact

No change to production code or user behavior.

## Evidence

- Before: intermittent red on scheduled `main` with the assertion above: run 45403387860, and again in run 45849028735 (2026-11-26, `checks-node-compact-large-14`, after openclaw#205835), `expected undefined to be 'failed'` in the exec-completion case. The race mechanism (`settleOwedExecWake` withholds the owed row after the wake settles) is unchanged on current `main`.
- Negative control (deterministic): with a 500 ms delay inserted before that `withhold` (local throwaway change), current `main` fails the exec-completion case 3/3 with the same assertion; with this change it passes 3/3.
- Without the delay, interleaved runs of `session-yield-sweep.test.ts` with this change applied to current `main`: 20/20 green (main alone was also 20/20 locally; the natural race is rare).

## Merge danger

Two-way door: test-only, a revert fully undoes it. Blast radius: one test file.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. gateway Gateway runtime P2 Normal backlog priority with limited blast radius. scripts Repository scripts size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant