Skip to content

perf(runtime): consume prepared session and placement facts - #169432

Merged
steipete merged 7 commits into
mainfrom
dbasync/sdkasync-remaining
Oct 12, 2026
Merged

steipete merged 7 commits into
mainfrom
dbasync/sdkasync-remaining

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem and change

Live progress callbacks still synchronously loaded session rows, and placement recovery synchronously listed placements during construction. Prepare the existing session owner once and read its committed facts from synchronous callbacks; prepare placement recovery's initial census with listAsync() before constructing the runtime. Remove the polling and duplicate follow-up read path.

Auth writes also loaded credentials they did not use. Static tokens, API keys, portable OAuth copies and fences now skip those observations; OAuth batches capture each requested source as a batch. The initial OAuth snapshot and atomic write/conditional rollback remain synchronous: existing stale-generation tests show that moving the initial capture past an await can accept a consumed credential. No public SDK contract, schema, retention or permission change.

Removed checks and accepted edges

  • Removed the 250 ms session polling and follow-up session ID/lifecycle/updatedAt comparisons. Committed owner facts determine verbosity; unavailable receipts retain the admitted preference until the next async preparation.
  • Removed the second ordered follow-up visibility read. Existing run/operator authority remains checked at progress delivery.
  • Removed unused pre-write observations for credentials that never enter generation validation. Their locked write still validates the current credential where required.
  • Placement's initial snapshot is captured before runtime construction; later live claims remain outside the interrupted-startup set. Execution and workspace authority checks remain intact.

T1 and SQL proof

Base 2665147fc1c2de4814606c7674e7014d1317ad8d; measured production head b235f4b5eaf923177573613c6e2d3fd1c068419f. Final head 5480c0b99d5a6 adds only a dispatch-fixture correction. Shared harness: three alternating M,C pairs on one remote host, 13 turns each; calibration, statement conservation, compaction, shutdown and child cleanup all pass. Warm duration ratio 1.014; maximum phase ratio 1.285.

Metric Base median [min–max] Candidate median [min–max]
Warmed all-thread statements/turn 322.5 [322.1–323.1] 322.5 [322.2–323.1]
Warmed requests/turn 92.1 [92.0–92.3] 92.2 [92.2–92.4]
Warmed MAIN statements/turn 0 [0–0] 0 [0–0]
First-turn all-thread statements 1271 [1240–1293] 1249 [1247–1256]
First-turn requests 227 [220–228] 223 [222–223]
Whole-workload all-thread statements 9531 [9518–9566] 9487 [9483–9509]
Whole-workload requests 1770 [1765–1774] 1760 [1757–1769]
Whole-workload MAIN statements 1987 [1986–1993] 1988 [1981–1988]

The +0.1 warmed requests (0.109%) is below the turn noise floor and traced by worker keys/timestamps/stacks to batching in unchanged session-list projection code (prepareSessionRowSharedFacts / withSessionRowDatabaseFacts). Its warmed SQL median remains 31 per ten turns; no warmed SQL-shape median grows. It is not a new request in the changed progress/placement/auth paths.

Phase Statements base → candidate Requests base → candidate MAIN statements base → candidate
Boot 2011 → 2011 66 → 67 1840 → 1839
Connect 829 → 820 27 → 28 13 → 13
First turn 1271 → 1249 227 → 223 43 → 43
Second session 1343 → 1332 337 → 335 33 → 29
Control 62 → 26 19 → 9 0 → 0
Cron 548 → 567 128 → 130 10 → 10
Compaction 170 → 170 32 → 32 2 → 2
Shutdown 86 → 89 14 → 14 52 → 52

Control+cron combined medians fall 610→603 statements and 147→142 requests; publication work shifts between those adjacent phases. Boot+connect statements fall 2840→2831; requests rise 93→95 from cold workerPlacements.read (+1, the moved census) and pageCache.step (+1), within the T1-move allowance. Compaction+shutdown rises three statements, within the absolute tolerance.

Subsystem operation medians over the workload: workerPlacements.read 2→3 statements/2→3 requests (the census moves off MAIN); auth-profile-rows 49→48 statements/requests. Control session-entry falls 10→5 statements and 2→1 requests; database.domain.execute falls 4→0 and 1→0. Other observed changes: first-turn pluginCatalog.read 50→32 statements/4→2 requests, catalog 8→5/1→0; second-session session-row-facts 77→71/16→15. These are measured operation deltas, not all attributed savings.

Lexical T1 remains 611 expressions/216 files; placement 11/6, auth 6/2, direct auto-reply 0. Ordinary placement constructor sync calls: 1→0. Three verbosity paths consume the prepared reader; native incognito stays with its owner. Released SDK implementations and real credential/effect primitives remain reachable, so this is not a zero-T1 inventory claim.

Review and validation

Two Codex autoreview rounds: no actionable P0/P1 findings. Remote owner/consumer tests: 43 files/542 tests (894s); final receipt/fixture owner set 10 files/122 tests (262s); placement cancellation (104s). The measurement caught an actual first-dispatch initialization-order error; moving preparation after coordinator construction fixed it, with actual gather/verbosity regressions passing (2 files/8 tests, 52s).

Changed-file static gates pass: type-aware lint, relevant config/messaging/root-tooling graphs, export collisions, Madge/import cycles, worker/T1 and dialect ratchets, native schema/database-first and sidecar guards. Knip is unchanged at 82 baseline findings with no candidate-only finding. Full check:changed was stopped after it expanded to 28 test-type graphs; affected graphs and all tail guards were run explicitly and passed. No SDK or extension runtime API surface changes in this PR.

Published driver 2026.10.1 × candidate update cell passed (667s), including readyz, running version, durable/incognito persistence and service stop. Evidence is reused: subsequent changes only reorder ordinary dispatch preparation and repair test fixtures; update/Doctor/schema/plugin-loading/lifecycle inputs are unchanged. The final dispatch suite passes 143 tests (74s wall). The final fixture fix replaces the removed reader in the dispatcher mock and deletes the obsolete test requiring polling; the real worker regression retains committed-write visibility coverage.

Native session writes also seal existing retained facts before observers, including explicit transactions; shedding optional facts discards the seal so they cannot be recertified. Existing owner regressions cover both paths. No new cache, subscription, schema, retention or permission contract.

LOC: 49 files, +476/−556. Accepted edge cases are listed above; initial OAuth capture and atomic write/conditional rollback stay because moving capture past an await demonstrably accepts a consumed credential generation.

@clawsweeper

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

@github-actions

github-actions Bot commented Oct 11, 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: 76ddff9152a7fdf5071249f729aa519f3d3e66dd
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/upsert-with-lock.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 gateway Gateway runtime agents Agent runtime and tooling size: L labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces repeated session and placement reads with prepared owner facts and skips unused credential observations.

Example: An active session changes verboseLevel from off to full.

  • Before: Tool-progress callbacks reload session state, with some gates polling every 250 ms.
  • After: Callbacks consume committed session facts immediately while explicit per-turn overrides remain fixed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused implementation with resolved prior findings; supporting harness results are stronger than the independently inspectable runtime evidence.
Proof confidence 🦐 gold shrimp (3/6) Maintainer-owned work is outside the ordinary contributor proof gate; supplied measurements and owner tests support the changed paths, but no raw runtime artifact was independently inspected.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated synchronous reads add Gateway work during progress callbacks and placement startup.
Reason: The existing area owner has chosen this direction, the cutover reduces duplicate work, and public configuration and stored formats remain unchanged.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-owned optimization remains distinct from main, and the latest commits resolve both prior findings without another concrete patch defect.

Priority: P2
Reviewed head: 76ddff9152a7fdf5071249f729aa519f3d3e66dd

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway reply dispatch consumes session preferences, placement startup consumes recovery records, and locked auth writers consume credential-generation facts before publishing their results.

flowchart TD
A[Gateway turn] --> B[Session preparation]
B --> C[Committed session facts]
C --> D[Progress callbacks]
E[Placement worker census] --> F[Startup recovery]
G[Credential observations] --> H[Locked auth writer]
Loading

Technical review

Best possible solution:

Consume existing committed owner facts while preserving live effect authority, OAuth generation fencing, and bounded receipt publication.

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

Source confirms the repeated reads and their replacement; no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

The change uses existing owners and explicitly records recoverable fallback behavior instead of adding another cache or authority layer.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Retained session facts and receipt certification keeps the original intent (ea4693e: Reuse bounded committed entry facts without bypassing writer ordering or live authority.)
  • Follow-up visibility reads and lifecycle comparisons changes intended behavior with a stated reason (c55f16f: Move observer reads off the Gateway thread while rejecting stale results.)
  • OAuth generation observations keeps the original intent (b824b72: Prevent queued writers and rollback from restoring consumed refresh generations.)
  • Startup interrupted-placement census keeps the original intent (20fb81f: Distinguish interrupted claims from live claims while retaining worker machines across updates.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -7, Tests -73. Total -80 across 49 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 16 245 252 -7
Tests 33 231 304 -73
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 49 476 556 -80

Review metrics

Metric Value Why it matters
Production versus test LOC Production +245/-252; tests and support +230/-304 The cutover removes polling and duplicate reads while adding focused publication and committed-preference coverage.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit. Replaced prior rating: 🧂 unranked krab.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.
  • remove proof: telegram-e2e: Current Telegram visible-proof status is not_needed.

Label justifications:

  • P2: A bounded runtime performance improvement with retained authority and no observed urgent user regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit. Replaced prior rating: 🧂 unranked krab.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 (6 earlier review cycles)
  • reviewed 2026-10-11T22:59:05.933Z sha e7f253d :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T23:24:41.212Z sha 29d4d1a :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T23:55:41.101Z sha 4002eba :: needs real behavior proof before merge. :: [P1] Initialize the reply coordinator before preparing verbosity
  • reviewed 2026-10-12T00:31:43.346Z sha e723e9a :: needs changes before merge. :: [P1] Initialize the reply coordinator before preparing verbosity
  • reviewed 2026-10-12T00:39:20.787Z sha e723e9a :: needs changes before merge. :: [P1] Initialize the reply coordinator before preparing verbosity
  • reviewed 2026-10-12T01:28:38.682Z sha b235f4b :: needs changes before merge. :: [P2] Migrate the dispatch fixtures to the prepared verbosity reader

Reviewed October 11, 2026, 10:11 PM ET / October 12, 2026, 02:11 UTC (Revision 7).

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Oct 11, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Oct 12, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Final head 76ddff9 adds only the required mock-isolation annotation; its mock-export ratchet passes. The 143-test dispatch result, scoped static checks, SQL measurements and update-cell evidence remain applicable. CI's eager-import-closure failure is inherited: main's wrapper-components inventory contains duplicate sender-identity, input-provenance and user-turn-transcript.metadata entries, and the exact test assertion fails against main's inventory; this PR does not change the inventory or test. Landing uses RELAXED LANDING v4 for that inherited failure.

@steipete
steipete merged commit 9cb62ee into main Oct 12, 2026
132 of 136 checks passed
@steipete
steipete deleted the dbasync/sdkasync-remaining branch October 12, 2026 02:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…#169432)

* perf(runtime): consume prepared session and placement facts

* fix(sessions): publish native entry receipt tokens after commit

* fix(runtime): exercise managed session write receipts

* test(sessions): run receipt proofs with managed database ownership

* fix(reply): prepare verbosity after dispatch ownership

* test(reply): update dispatch fixtures for prepared verbosity

* test(reply): document dispatch fixture isolation
steipete added a commit that referenced this pull request Oct 12, 2026
## What Problem This Solves

Node worker replies waited for workspace synchronization after the final assistant message was already durable, adding hundreds of milliseconds to the visible reply tail.

## User Impact

Worker-turn replies now finish before workspace reconciliation. A quick follow-up is accepted into durable custody and starts against the reconciled workspace. Conflicts and reconciliation failures appear as separate transcript notices and through existing placement/recovery state; they do not replace a delivered reply. No new RPC or stored state is added.

## Why This Change Was Made

Decision: **Peter, 2026-10-11** — deliver the reply when the worker is terminal and its transcript is durable; reconcile the workspace in the background.

The existing turn owner retains execution, the result claim, transcript scope, and recovery handling while delivering the reply separately. Context candidates are recorded before returning; workspace-dependent maintenance still follows acceptance. The old conflict suffix and assistant delta are removed.

A completed prior reply joins its existing settlement promise before a follow-up prepares placement state. This prevents a real placement-read invalidation during claim release while preserving live-turn collision and duplicate-run behavior. Production LOC: **+59**, within the approved +80 contract-change allowance.

## Evidence

Same-box Hetzner ccx33, OpenAI `gpt-4.1-mini`, two warmups and five measured turns per route and revision. Values are milliseconds:

| Path | Request → provider, before → after | TTFT, before → after | Provider terminal → chat final, before → after |
|---|---:|---:|---:|
| Local | 438 → 381 | 1720 → 1783 | 120 → 118 |
| Loopback node | 492 → 1045 | 1741 → 2321 | **412 → 236** |

The node reply tail improved **176 ms (42.7%)**, with a flat local control. Requests are sent immediately after the preceding final: the longer next-request admission deliberately includes the remaining prior reconciliation wait. TTFT includes that wait and provider variance; this is a reply-tail improvement, not a throughput or TTFT claim. All final replies and post-final `agent.wait` observations succeeded.

- Instrumented census confirms reconciliation finishes after chat final. Remaining node overhead is primarily terminal receipt/journal/transport handoff. Shorter reply-window counts do not imply that all background reconciliation work was deleted.
- Boundary proof covers durable early reply, retained result claim, immediate follow-up reading reconciled files, separate conflict notice, failure notice/recovery custody, and Stop/Move behavior. The accepted case fails on original production while reconciliation is held.
- New regression command: `pnpm test src/gateway/worker-environments/worker-turn-early-final.test.ts --maxWorkers=1`, 3/3 passed, **55.19 s** local wall time including setup; approximately **8.8 CI seconds** for the three cases in the initial hosted run. Remote runs also passed 111 sibling tests in 589.48 s and the final remaining 60 cases in 391.18 s; overlapping proof is not counted twice.
- Final-head [CI run](https://github.com/openclaw/openclaw/actions/runs/38206809322) is green, including required CI, source contracts, core lint, production types, all test type stripes, and runtime tests. Earlier CI caught obsolete settlement assertions, the quick-follow-up read race, and a detached callback receiver-type contract; all are fixed.
- Codex autoreview: no actionable P0/P1 findings. Formatting and `git diff --check` pass. No limits, timeouts, or baselines were raised.
- dbasync overlap checked: no shared production changes; the shared build-recovery test file has a separate fixture-initialization hunk in #169432.

The optional two-machine measurement could not complete worker installation through the relay, so no remote-node performance claim is made.

Release-note context: worker-turn final replies no longer wait for workspace synchronization; queued follow-ups still use the reconciled workspace, and workspace problems remain visible separately.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…aw#169484)

## What Problem This Solves

Node worker replies waited for workspace synchronization after the final assistant message was already durable, adding hundreds of milliseconds to the visible reply tail.

## User Impact

Worker-turn replies now finish before workspace reconciliation. A quick follow-up is accepted into durable custody and starts against the reconciled workspace. Conflicts and reconciliation failures appear as separate transcript notices and through existing placement/recovery state; they do not replace a delivered reply. No new RPC or stored state is added.

## Why This Change Was Made

Decision: **Peter, 2026-10-11** — deliver the reply when the worker is terminal and its transcript is durable; reconcile the workspace in the background.

The existing turn owner retains execution, the result claim, transcript scope, and recovery handling while delivering the reply separately. Context candidates are recorded before returning; workspace-dependent maintenance still follows acceptance. The old conflict suffix and assistant delta are removed.

A completed prior reply joins its existing settlement promise before a follow-up prepares placement state. This prevents a real placement-read invalidation during claim release while preserving live-turn collision and duplicate-run behavior. Production LOC: **+59**, within the approved +80 contract-change allowance.

## Evidence

Same-box Hetzner ccx33, OpenAI `gpt-4.1-mini`, two warmups and five measured turns per route and revision. Values are milliseconds:

| Path | Request → provider, before → after | TTFT, before → after | Provider terminal → chat final, before → after |
|---|---:|---:|---:|
| Local | 438 → 381 | 1720 → 1783 | 120 → 118 |
| Loopback node | 492 → 1045 | 1741 → 2321 | **412 → 236** |

The node reply tail improved **176 ms (42.7%)**, with a flat local control. Requests are sent immediately after the preceding final: the longer next-request admission deliberately includes the remaining prior reconciliation wait. TTFT includes that wait and provider variance; this is a reply-tail improvement, not a throughput or TTFT claim. All final replies and post-final `agent.wait` observations succeeded.

- Instrumented census confirms reconciliation finishes after chat final. Remaining node overhead is primarily terminal receipt/journal/transport handoff. Shorter reply-window counts do not imply that all background reconciliation work was deleted.
- Boundary proof covers durable early reply, retained result claim, immediate follow-up reading reconciled files, separate conflict notice, failure notice/recovery custody, and Stop/Move behavior. The accepted case fails on original production while reconciliation is held.
- New regression command: `pnpm test src/gateway/worker-environments/worker-turn-early-final.test.ts --maxWorkers=1`, 3/3 passed, **55.19 s** local wall time including setup; approximately **8.8 CI seconds** for the three cases in the initial hosted run. Remote runs also passed 111 sibling tests in 589.48 s and the final remaining 60 cases in 391.18 s; overlapping proof is not counted twice.
- Final-head [CI run](https://github.com/openclaw/openclaw/actions/runs/38206809322) is green, including required CI, source contracts, core lint, production types, all test type stripes, and runtime tests. Earlier CI caught obsolete settlement assertions, the quick-follow-up read race, and a detached callback receiver-type contract; all are fixed.
- Codex autoreview: no actionable P0/P1 findings. Formatting and `git diff --check` pass. No limits, timeouts, or baselines were raised.
- dbasync overlap checked: no shared production changes; the shared build-recovery test file has a separate fixture-initialization hunk in openclaw#169432.

The optional two-machine measurement could not complete worker installation through the relay, so no remote-node performance claim is made.

Release-note context: worker-turn final replies no longer wait for workspace synchronization; queued follow-ups still use the reconciled workspace, and workspace problems remain visible separately.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. 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