Skip to content

fix(gateway): batch worker placement session evidence - #124372

Merged
steipete merged 7 commits into
mainfrom
steipete/fix-gateway-session-store-identity-churn
Aug 16, 2026
Merged

steipete merged 7 commits into
mainfrom
steipete/fix-gateway-session-store-identity-churn

Conversation

@steipete

@steipete steipete commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

After #124453 removed repeated target identity discovery, Molty still ran near 148% CPU and timed out WebSocket/RPC handshakes. Its 60-second worker-placement retirement sweep resolves evidence for 537 durable placements; the pre-fix live signature was 1,065 statx calls over 2 seconds, including repeated configured and retired/manual agent store probes.

Why This Change Was Made

PR #123785 (3c5e2ff2964f, authored and merged by @steipete) correctly added fail-closed orphan placement retirement, but the sweep called complete target resolution and synchronous SQLite evidence lookup once per placement. This change snapshots the placement list; canonicalizes persisted placement keys and owners; resolves ordinary target availability once per distinct agent; routes incognito keys independently to their process-held key-selected store; batches exact session-key/current-session-id evidence per physical SQLite store in bounded 400-value queries; validates each relevant serialized row once with the scalar path's canonical parser; then reuses prepared current / absent / unknown results throughout reconciliation.

The owner repair keeps configured-agent existing-target lookup on its bounded canonical/default-root paths instead of launching full-roster discovery once per placement owner. It preserves both upgrade contracts from the scalar path: canonical replacement-owner keys are probed before batching, while an exact row still owned by a deleted legacy agent is probed alongside the canonical owner with current > unknown > absent precedence. This also preserves the safety contract that an unreadable default-root candidate must keep media history from being reaped even when the configured canonical store is healthy. Genuine missing stores remain absent; unreadable, ambiguous, invalid, stale-projection, schema-incompatible, or indeterminate stores remain unknown. The old per-placement evidence path is removed.

User Impact

Gateways with large worker-placement histories no longer spend each reconciliation interval rediscovering and reopening the same stores. Orphan cleanup stays intact across ordinary, incognito, canonicalized, and legacy-owner sessions; inaccessible/corrupt stores fail closed; and RPC/channel work remains responsive during the sweep.

Evidence

  • Final owner proof: node scripts/run-vitest.mjs src/gateway/server-worker-placement-session-evidence.test.ts src/gateway/worker-environments/placement-session-retirement.test.ts src/config/sessions/session-accessor.readonly.test.ts src/config/sessions/targets.test.ts src/gateway/managed-image-attachments.test.ts — 5 files, 153 tests passed.
  • Canonical-key siblings: node scripts/run-vitest.mjs src/gateway/server-worker-placement-startup.test.ts src/gateway/session-utils.test.ts — 2 files, 163 tests passed.
  • Resolver siblings: node scripts/run-vitest.mjs src/gateway/managed-image-attachments.test.ts src/gateway/server-methods/sessions-search.test.ts src/gateway/server.sessions.list-store-materialization.test.ts src/gateway/session-sharing-store-cache.test.ts src/cron/session-reaper.test.ts — 5 files, 143 tests passed.
  • Regression provenance: configured existing-target resolution calls the agent-root enumerator twice on the previous head; the bounded owner test now performs zero broad enumerations.
  • Canonical migration regressions: the previous batch sends raw agent:main:main instead of canonical agent:ops:main, and returns absent for a listed deleted-main placement whose exact row is still current. The final tests prove both the canonical probe and deleted-owner fallback.
  • Full changed gate: trusted-source local fallback OPENCLAW_CHECK_CHANGED_REMOTE_CHILD=1 node scripts/check-changed.mjs -- src/config/sessions/targets.ts src/config/sessions/targets.test.ts src/gateway/server-worker-placement-session-evidence.ts src/gateway/server-worker-placement-session-evidence.test.ts passed format, deadcode, core/test tsgo, changed-file lint, native schema/database guards, and import cycles. An earlier Daytona run passed every lane before its script-export Knip process was SIGKILLed; the local fallback completed that lane successfully.
  • Autoreview: final canonical/legacy-owner repair clean at 0.97; configured-target repair clean at 0.99; direct incognito routing clean at 0.98; serialized-row repair clean at 0.96; discovery fail-closed repair clean at 0.99.
  • Raw LOC: production +316/-78 (net +238); tests +359/-46 (net +313). Growth is confined to the bounded batch evidence owner, canonical and legacy-owner identity preparation, target-availability/incognito routing, scalar parser reuse, reconciliation-scoped resolver, and configured-owner target bound; the scalar per-placement path is deleted.
  • Discovery P1: ordinary target { available:false, reason:"read-failed" } returns unknown; genuine missing ordinary DB returns absent.
  • Serialized-row P1: forced entry_valid=1 with mismatched serialized identity returns unknown for exact/fallback while unrelated same-store valid evidence remains current.
  • Incognito P1: with ordinary discovery read-failed, a current incognito placement remains current and a deleted incognito placement is absent; ordinary discovery receives no incognito probe.
  • Configured-target safety: canonical and default-root candidates remain visible, so an unreadable same-owner candidate prevents destructive media-history cleanup without requiring all-agent discovery.
  • Exact-final-head Molty proof at 73bd4f2cc7af5d7a26437bda2c2d04574e417177: 30-second CPU 23.7% (pre-fix 148.3%), RSS 997 MiB (pre-fix 2.77 GiB), and 120 readlinks over a full 70-second reconciliation window (pre-owner-fix head 22,310/70s; original pre-fix 19,620/8s). HTTP across 20 samples was p50 3.4 ms, p95 19.8 ms, max 45.4 ms. Deep RPC returned the exact 73bd4f2cc7af build, health was non-degraded, Discord/Reef/Slack were connected with no errors, and no placement/evidence/serialized/canonical errors appeared after restart.
  • Scheduler proof: SQLite cron enabled with 11 jobs; Daily maintainer report remains enabled, lastStatus: ok, lastDeliveryStatus: delivered, consecutiveErrors: 0, next run 2026-08-16T17:30:00Z.
  • CI follow-up: unrelated exact-millisecond workspace timeout assertion now checks its actual <= 777 ms deadline invariant.
  • Backend-only change; no screenshots.
  • AI-assisted: yes. No transcript included.

@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 16, 2026 03:01
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Aug 16, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 16, 2026, 7:18 AM ET / 11:18 UTC.

ClawSweeper review

What this changes

This PR batches Gateway worker-placement session evidence during each retirement sweep, avoiding repeated session-store discovery and SQLite reads while retaining fail-closed orphan cleanup.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for maintainer review: current main still invokes the scalar resolver once per placement, while this branch creates one snapshot-scoped batch resolver and preserves the current/absent/unknown retirement contract. No discrete patch defect was found, but the session-state and availability-sensitive refactor is behind main and merits an exact-merge-head refresh before landing.

Priority: P1
Reviewed head: 73bd4f2cc7af5d7a26437bda2c2d04574e417177
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong exact-head behavior evidence and focused failure-preserving tests support a good patch, pending the normal current-main refresh for this lifecycle path.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body supplies exact-head live Gateway measurements over a full reconciliation interval, including responsive RPC and observed recovery without session-evidence errors.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body supplies exact-head live Gateway measurements over a full reconciliation interval, including responsive RPC and observed recovery without session-evidence errors.
Evidence reviewed 7 items Current-main performance path: Current main resolves a session-store target and identity evidence separately for each placement; the retirement loop invokes that resolver per listed placement.
Snapshot-scoped owner boundary: The PR builds identities and target results once for the placement snapshot, batches probes, and returns a stable resolver for the reconciliation pass.
Tri-state parsing and batched reads: The batch reader validates serialized rows before returning current evidence, groups probes by physical SQLite store, and preserves unreadable state as unknown.
Findings None None.
Security None None.

How this fits together

Gateway worker-placement retirement compares durable worker placements with authoritative session-store evidence before retiring orphaned environments. Placement records enter the reconciliation sweep; tri-state session evidence determines whether the worker environment is retained or safely retired.

flowchart LR
A[Durable worker placements] --> B[Retirement reconciliation snapshot]
B --> C[Session-store target resolution]
C --> D[Batch SQLite session evidence]
D --> E{Evidence outcome}
E -->|Absent| F[Retire orphan placement]
E -->|Current or unknown| G[Retain placement]
F --> H[Worker environment cleanup]
Loading

Decision needed

Question Recommendation
Should this session-retirement refactor be landed after a current-main rebase and exact-head validation refresh? Rebase and land: Refresh the branch against current main and land if the focused session-evidence and retirement checks remain green.

Why: The remaining choice is acceptance of a substantial but evidence-backed change on a destructive worker/session lifecycle path, which is intentionally marked for maintainer handling.

Before merge

  • Resolve merge risk (P1) - This bug fix adds net +238 production lines in the fail-closed session/placement retirement path; rebase on current main and refresh exact-head evidence/lifecycle validation so merge resolution cannot weaken unknown-versus-absent handling.
  • Complete next step (P2) - No bounded repair is identified; the protected maintainer path needs a current-main rebase and maintainer acceptance of the session/availability risk.
Agent review details

Security

None.

PR surface

Source +238, Tests +313. Total +551 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 316 78 +238
Tests 6 359 46 +313
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 675 124 +551

Review metrics

Metric Value Why it matters
Production versus test delta production +316/-78 (net +238); tests +359/-46 (net +313) The added batch owner and validation logic replace scalar per-placement evidence work, but the retirement-path growth deserves exact-head validation.

Stored data model

Persistent data-model change detected: durable storage schema: src/gateway/worker-environments/placement-session-retirement.test.ts, durable storage schema: src/gateway/worker-environments/placement-session-retirement.ts, migration/backfill/repair: src/config/sessions/session-accessor.readonly.test.ts, serialized state: src/config/sessions/session-accessor.readonly.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-entry-availability.ts, serialized state: src/config/sessions/targets.test.ts, and 4 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh the exact merge head (recommended)
    Rebase onto current main and rerun the focused evidence, target-resolution, and retirement checks before accepting this lifecycle-sensitive refactor.

Technical review

Best possible solution:

Rebase and land the single snapshot-scoped resolver once exact-head checks reconfirm tri-state retirement behavior; its added owner-boundary code replaces the scalar per-placement work, and no smaller net-neutral absorption is evident.

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

Yes — current main visibly performs target resolution and identity lookup for every placement, and the PR provides exact-head live measurements of that sweep under a large durable-placement history.

Is this the best way to solve the issue?

Yes — preparing one resolver per reconciliation snapshot keeps the authoritative tri-state decision at the session-store owner rather than adding a downstream cache or changing retirement policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0c546979b2ac.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies exact-head live Gateway measurements over a full reconciliation interval, including responsive RPC and observed recovery without session-evidence errors.

Label justifications:

  • P1: Large placement histories can make Gateway RPC and channel work unresponsive during the periodic retirement sweep.
  • merge-risk: 🚨 session-state: The PR changes how durable placement records are matched to canonical, legacy, and incognito session evidence before retirement.
  • merge-risk: 🚨 availability: A mistaken evidence outcome can either retain orphaned workers or trigger cleanup on a live environment, and the path runs periodically in Gateway.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body supplies exact-head live Gateway measurements over a full reconciliation interval, including responsive RPC and observed recovery without session-evidence errors.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies exact-head live Gateway measurements over a full reconciliation interval, including responsive RPC and observed recovery without session-evidence errors.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the merged retirement feature commit and the subsequent session-evidence optimization branch. (role: introduced and recently maintained the worker-placement retirement behavior; confidence: high; commits: 3c5e2ff2964f, 73bd4f2cc7af; files: src/gateway/server-worker-placement-session-evidence.ts, src/gateway/worker-environments/placement-session-retirement.ts)

Rank-up moves

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

  • Rebase onto current main and refresh the exact-head focused Gateway/session validation before merge.

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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-16T05:30:06.766Z sha 69a33388d47947b5734cd3d469c70a44d5378501 :: found issues before merge. :: [P1] Preserve unknown evidence when target discovery fails
  • reviewed 2026-08-16T07:31:23.683Z sha 080f491c0748eaeaf3455d2033ef74b0a97d811d :: found issues before merge. :: [P1] Preserve unknown evidence when target discovery skips a store
  • reviewed 2026-08-16T07:42:08.834Z sha 7d398b9dc0179dad2192e6abe59fe835dac1102c :: found issues before merge. :: [P1] Preserve unknown evidence when discovery skips a store
  • reviewed 2026-08-16T08:04:17.868Z sha 7742842 :: needs changes before merge. :: [P1] Validate serialized rows before returning current
  • reviewed 2026-08-16T08:34:16.786Z sha 0fa79cc :: found issues before merge. :: [P1] Preserve direct incognito session evidence
  • reviewed 2026-08-16T09:18:05.922Z sha 6e319b1 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-16T10:30:46.885Z sha b624a04 :: found issues before merge. :: [P1] Canonicalize placement keys before batch probing
  • reviewed 2026-08-16T10:56:18.466Z sha 73bd4f2 :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M and removed size: S labels Aug 16, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 16, 2026
@steipete
steipete force-pushed the steipete/fix-gateway-session-store-identity-churn branch from 5f4b848 to 69a3338 Compare August 16, 2026 05:24
@steipete steipete changed the title fix(gateway): stop repeated session store identity scans fix(gateway): batch worker placement session evidence Aug 16, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 16, 2026
@steipete
steipete force-pushed the steipete/fix-gateway-session-store-identity-churn branch from 69a3338 to 080f491 Compare August 16, 2026 07:25
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Aug 16, 2026
@steipete
steipete force-pushed the steipete/fix-gateway-session-store-identity-churn branch from 080f491 to 7d398b9 Compare August 16, 2026 07:35
@steipete
steipete force-pushed the steipete/fix-gateway-session-store-identity-churn branch from 7d398b9 to 7742842 Compare August 16, 2026 07:58
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Aug 16, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Aug 16, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 16, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready verification

Exact head: 73bd4f2cc7af5d7a26437bda2c2d04574e417177

  • Required CI: green — https://github.com/openclaw/openclaw/actions/runs/31942722985
  • Focused owner tests: 153 passed across placement evidence, retirement, session accessor, target resolution, and media cleanup.
  • Canonical-key/startup siblings: 163 passed.
  • Resolver/reaper siblings: 143 passed.
  • Changed gate: passed locally through the trusted-source fallback, including format, deadcode, core/test type checks, lint, schema/database guards, and import cycles. The earlier Daytona attempt was infrastructure-only: its script-export Knip process was SIGKILLed after preceding lanes passed.
  • Fresh autoreview: clean, no accepted/actionable findings.
  • Exact-head Molty gate: CPU 23.7% over 30 seconds versus 148.3% pre-fix; RSS 997 MiB versus 2.77 GiB; 120 readlinks over 70 seconds versus 22,310 on the prior head and 19,620/8s pre-fix; HTTP p95 19.8 ms/max 45.4 ms; deep RPC reported build 73bd4f2cc7af; health non-degraded; Discord, Reef, and Slack connected; no placement/evidence/canonical errors after restart.
  • Scheduler: SQLite cron enabled; Daily maintainer report remains enabled, last run ok, delivered, zero consecutive errors.
  • Current-head ClawSweeper: no findings, proof sufficient — fix(gateway): batch worker placement session evidence #124372 (comment)

Known proof gaps: none. Backend-only change; no visual surface.

@steipete
steipete merged commit 96cacfd into main Aug 16, 2026
198 checks passed
@steipete
steipete deleted the steipete/fix-gateway-session-store-identity-churn branch August 16, 2026 11:28
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

SemonCat pushed a commit to SemonCat/openclaw that referenced this pull request Aug 16, 2026
* perf(gateway): batch worker placement session evidence

* test(gateway): tolerate elapsed workspace timeout

* fix(gateway): preserve unknown placement evidence

* fix(sessions): validate batched placement evidence

* fix(gateway): preserve incognito placement evidence

* fix(sessions): bound configured target discovery

* fix(gateway): canonicalize batched placement evidence
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 17, 2026
* perf(gateway): batch worker placement session evidence

* test(gateway): tolerate elapsed workspace timeout

* fix(gateway): preserve unknown placement evidence

* fix(sessions): validate batched placement evidence

* fix(gateway): preserve incognito placement evidence

* fix(sessions): bound configured target discovery

* fix(gateway): canonicalize batched placement evidence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

1 participant