Skip to content

perf(sessions): avoid repeated target discovery during chat turns - #169598

Merged
steipete merged 4 commits into
mainfrom
dbasync/reqbatch
Oct 12, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/reqbatch

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Ordinary session writes invalidated the target-inventory memo even for per-agent stores, whose topology depends on paths and registered database ownership. A warmed turn repeatedly sent discovery and reader-cleanup requests that executed no SQL.

Design and Impact

Keep the existing Gateway-owned inventory memo across row writes only for per-agent stores. Every fixed-store selection retains row-write invalidation because its visibility can depend on session rows. Registry receipts, configuration keys and physical file identity still invalidate reusable topology. No new cache, worker command, schema, SDK or update behavior is introduced.

Removed check and accepted edge case: an ordinary per-agent activity write no longer invalidates topology; that write cannot introduce a store owner. Registry/configuration changes and physical replacement remain covered by their existing invalidation. Current authorization at real effects is unchanged.

Live Measurement

Shared SQL harness, alternating M1/C1/M2/C2, base c832c45aff53c2cb060ca10b0c3ab6668cd1b4e1 and final candidate e4b4c650a59d5eb080d68c7b5058e8f744e450be. All four isolated fixtures completed the 13 turns, child session, cron, compaction and shutdown with exact statement/request census reconciliation. Under RELAXED TESTING v6 one pair was required; the second pair resolved timing ambiguity. Both sides used the same supported 120-second handshake timeout after an initial baseline failed before its first turn. The original harness was not edited.

Values are median [min–max] across the two runs. Each warmed measurement is the total over ten warmed turns divided by ten.

Metric Base Candidate Median delta
Warmed all-thread statements/turn 354.4 [340.9–367.9] 341.2 [319.5–362.9] -13.2 (-3.7%)
Warmed requests/turn 108.2 [103.5–112.9] 91.2 [85.3–97.1] -17.0 (-15.7%)
Warmed MAIN statements/turn 0.1 [0.0–0.2] 0.1 [0.0–0.2] 0.0
session-target-inventory requests/turn 7.2 [7.0–7.4] 0.0 [0.0–0.0] -7.2
closeResource requests/turn 7.2 [7.0–7.4] 0.0 [0.0–0.0] -7.2
Inventory + cleanup statements/turn 0.0 0.0 0.0
Whole workload statements 9909.5 [9702–10117] 9738.5 [9455–10022] -171.0 (-1.7%)
Whole workload requests 2057 [1966–2148] 1775 [1684–1866] -282 (-13.7%)

The directly attributable saving is 14.4 worker requests per warmed turn, with no SQL added. The remaining overall change includes unchanged background owners. Pair 1 alone measured 367.9 → 362.9 statements and 112.9 → 97.1 requests. Warmed duration ratio was 0.86; durations are context, not a performance benchmark.

Phase Base statements Candidate statements Base requests Candidate requests
Boot 2034.5 2035.0 75.5 79.0
Connect 1146.5 934.5 62.5 39.0
First turn 798.0 1082.5 182.5 203.5
Second session 1424.5 1344.0 401.5 329.0
Control plane 33.5 35.0 8.0 9.5
Cron 629.5 624.5 177.5 153.5
Compaction 205.0 182.0 52.0 35.5
Shutdown 94.0 89.0 15.5 14.0

First-turn work shifts between startup and the first request: boot + connect + first turn is 3979.0 → 4052.0 statements (+1.8%), while the complete workload and warmed turns decrease. The first-turn increase comes from unchanged owners: memory schema admission +64 statements (combined startup total unchanged), domain publication +63 (whole-workload total 1028 → 980), prepare-write +31.5 (78.5 → 63), domain execute +22.5 (67.5 → 65), and cron mutation +11 (24 → 24). Background memory indexing completed in both candidate runs but only one baseline, adding source replacement +16 and vector ensure +11 in the first window; this is completed background work, not purely shifted work. Target-inventory first-turn SQL falls 11.5 → 8.0. No SQL or request-producing path is added in the changed owner. The measured cold-window increase is attributed to unchanged background owners, not claimed as a cold-start optimization.

Proof and Landing Disposition

  • Regression fails before the fix because a second selection issues another discovery request. After the fix, an in-process row write preserves the returned inventory and both discovery/cleanup request counts.
  • Transcript identity suite: 18/18 passed (24 seconds test work; 81.1 seconds wall time including compiled-worker preparation). Inventory/availability suites: 13/13 passed. Existing fixed-store and registered-sibling tests cover fresh visibility after in-process writes. These runs preceded the relaxed-testing update; final local proof was scoped oxfmt, oxlint and git diff --check.
  • Two Codex autoreview rounds completed with no actionable findings. The second reviewed the final fixed-store correction.
  • T1 in the changed runtime file: 0 → 0. No SQLite call moves between threads.
  • Final-head CI run 38211504829 passed production types, all five core test-type shards and aggregate, lint, source contracts/export collisions, architecture/Madge, and baseline/T1/dialect/worker ratchets. Earlier Knip found only the inherited src/agents/agent-run-result.ts: agentRunHasVisibleReply unused export, identical on the measured base; main subsequently removed it in 1f5c14590afaa. This PR adds or removes no exports.
  • Admin landing uses the unchanged concurrent-deletion built-CLI failure: waitForAgentRunSettled rejects AbortError: agent run aborted without stopReason. The same failure predates this patch in run 38200828665, and the fixture, helper and termination owner are unchanged. Final build-artifacts failed; two remaining test shards were cancelled by fail-fast and are not claimed as passing. The patch does not change cancellation or terminal result publication.
  • No SDK diff or published-driver update cell applies: no SDK, update, Doctor, migration/schema, plugin loading or service lifecycle change.
  • LOC: production +4/-1; tests +33/-0; docs +5/-1.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XS labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses per-agent session-store inventories across ordinary writes while preserving row-sensitive invalidation for fixed stores.

Example: The main agent updates agent:main:global from updatedAt 1 to 2 in its default per-agent store.

  • Before: The next inventory selection repeats discovery and reader cleanup.
  • After: The next selection returns the same inventory without those worker requests.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The reported paired production workloads now support the focused performance benefit, and source review finds the invalidation correction sound; inherited CI failures remain separately documented.
Proof confidence 🐚 platinum hermit (4/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; its current body supplies paired Gateway workload measurements at the exact reviewed head and reports unchanged completed scenarios with eliminated warmed discovery and cleanup requests.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary chat activity repeats discovery and reader cleanup for unchanged per-agent store topology.
Reason: The maintainer-authored direction removes measured unnecessary work through the existing owner with a focused change.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it provides a focused optimization absent from current main, resolves the earlier fixed-store invalidation finding, and has no remaining actionable code findings.

Priority: P2
Reviewed head: e4b4c650a59d5eb080d68c7b5058e8f744e450be

Before merge

None.

Findings

None.

Agent review details

How this fits together

Session-target discovery turns configuration, physical paths, and registered database ownership into inventories consumed by session readers and maintenance.

flowchart TD
  A[Configuration and candidate paths] --> B[Inventory preparation]
  B --> C[Existing selection memo]
  D[Registry and physical identity] --> C
  E[Fixed store write receipts] --> C
  C --> F[Discovery worker on cache miss]
  F --> G[Session readers and maintenance]
  C --> G
Loading

Technical review

Best possible solution:

Retain the narrow optimization through the existing memo owner with fixed-store invalidation and current effect checks intact.

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

Current main includes the row-write token in every inventory memo key, so an ordinary session write invalidates per-agent reuse; the supplied regression and paired measurements match that path, while this review executed no target code.

Is this the best way to solve the issue?

The existing configuration classification separates row-independent per-agent topology from row-sensitive fixed stores without introducing another cache or discovery owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Inventory memo invalidation changes intended behavior with a stated reason (3bbc221: Reuse prepared targets while retaining invalidation for fixed-store visibility and incompletely captured sibling-row dependencies.)
  • Discovery documentation keeps the original intent (3eff8f0: Keep discovery worker-owned and captured per operation while preserving current authorization at real effects.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3bbc221 adds src/config/sessions/session-store-target-runtime.ts:45 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3bbc221d1c8c; files: src/config/sessions/session-store-target-runtime.ts)

PR surface

Source +3, Tests +33, Docs +4. Total +40 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 4 1 +3
Tests 1 33 0 +33
Docs 1 5 1 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 42 2 +40

Review metrics

Metric Value Why it matters
Production versus test growth Production +4/-1; tests +33/-0 A small predicate change gains one production-owner regression protecting inventory results and avoided worker requests after a real write.
Reported attributable request saving 14.4 fewer worker requests per warmed turn The paired measurements attribute 7.2 avoided inventory requests and 7.2 avoided cleanup requests to this change, without claiming those operations previously executed SQL.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This reduces repeated internal work during ordinary chat turns without changing configuration, persisted data, or public interfaces.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • 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 (3 earlier review cycles)
  • reviewed 2026-10-12T04:16:06.879Z sha b427a87 :: needs changes before merge. :: [P2] Preserve row invalidation for fixed-store known-owner discovery
  • reviewed 2026-10-12T05:27:08.957Z sha feb773e :: needs changes before merge. :: [P2] Preserve row invalidation for fixed-store known-owner discovery
  • reviewed 2026-10-12T06:19:09.338Z sha e4b4c65 :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 3:07 AM ET / 07:07 UTC (Revision 4).

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@steipete
steipete merged commit d9e7692 into main Oct 12, 2026
142 of 149 checks passed
@steipete
steipete deleted the dbasync/reqbatch branch October 12, 2026 07:17
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…enclaw#169598)

## What Problem This Solves

Ordinary session writes invalidated the target-inventory memo even for per-agent stores, whose topology depends on paths and registered database ownership. A warmed turn repeatedly sent discovery and reader-cleanup requests that executed no SQL.

## Design and Impact

Keep the existing Gateway-owned inventory memo across row writes only for per-agent stores. Every fixed-store selection retains row-write invalidation because its visibility can depend on session rows. Registry receipts, configuration keys and physical file identity still invalidate reusable topology. No new cache, worker command, schema, SDK or update behavior is introduced.

Removed check and accepted edge case: an ordinary per-agent activity write no longer invalidates topology; that write cannot introduce a store owner. Registry/configuration changes and physical replacement remain covered by their existing invalidation. Current authorization at real effects is unchanged.

## Live Measurement

Shared SQL harness, alternating M1/C1/M2/C2, base `0bb704e3e510e668cf8a8f6b19d9378f6ab1b6cb` and final candidate `e4b4c650a59d5eb080d68c7b5058e8f744e450be`. All four isolated fixtures completed the 13 turns, child session, cron, compaction and shutdown with exact statement/request census reconciliation. Under RELAXED TESTING v6 one pair was required; the second pair resolved timing ambiguity. Both sides used the same supported 120-second handshake timeout after an initial baseline failed before its first turn. The original harness was not edited.

Values are median [min–max] across the two runs. Each warmed measurement is the total over ten warmed turns divided by ten.

| Metric | Base | Candidate | Median delta |
|---|---:|---:|---:|
| Warmed all-thread statements/turn | 354.4 [340.9–367.9] | 341.2 [319.5–362.9] | -13.2 (-3.7%) |
| Warmed requests/turn | 108.2 [103.5–112.9] | 91.2 [85.3–97.1] | -17.0 (-15.7%) |
| Warmed MAIN statements/turn | 0.1 [0.0–0.2] | 0.1 [0.0–0.2] | 0.0 |
| session-target-inventory requests/turn | 7.2 [7.0–7.4] | 0.0 [0.0–0.0] | -7.2 |
| closeResource requests/turn | 7.2 [7.0–7.4] | 0.0 [0.0–0.0] | -7.2 |
| Inventory + cleanup statements/turn | 0.0 | 0.0 | 0.0 |
| Whole workload statements | 9909.5 [9702–10117] | 9738.5 [9455–10022] | -171.0 (-1.7%) |
| Whole workload requests | 2057 [1966–2148] | 1775 [1684–1866] | -282 (-13.7%) |

The directly attributable saving is 14.4 worker requests per warmed turn, with no SQL added. The remaining overall change includes unchanged background owners. Pair 1 alone measured 367.9 → 362.9 statements and 112.9 → 97.1 requests. Warmed duration ratio was 0.86; durations are context, not a performance benchmark.

| Phase | Base statements | Candidate statements | Base requests | Candidate requests |
|---|---:|---:|---:|---:|
| Boot | 2034.5 | 2035.0 | 75.5 | 79.0 |
| Connect | 1146.5 | 934.5 | 62.5 | 39.0 |
| First turn | 798.0 | 1082.5 | 182.5 | 203.5 |
| Second session | 1424.5 | 1344.0 | 401.5 | 329.0 |
| Control plane | 33.5 | 35.0 | 8.0 | 9.5 |
| Cron | 629.5 | 624.5 | 177.5 | 153.5 |
| Compaction | 205.0 | 182.0 | 52.0 | 35.5 |
| Shutdown | 94.0 | 89.0 | 15.5 | 14.0 |

First-turn work shifts between startup and the first request: boot + connect + first turn is 3979.0 → 4052.0 statements (+1.8%), while the complete workload and warmed turns decrease. The first-turn increase comes from unchanged owners: memory schema admission +64 statements (combined startup total unchanged), domain publication +63 (whole-workload total 1028 → 980), prepare-write +31.5 (78.5 → 63), domain execute +22.5 (67.5 → 65), and cron mutation +11 (24 → 24). Background memory indexing completed in both candidate runs but only one baseline, adding source replacement +16 and vector ensure +11 in the first window; this is completed background work, not purely shifted work. Target-inventory first-turn SQL falls 11.5 → 8.0. No SQL or request-producing path is added in the changed owner. The measured cold-window increase is attributed to unchanged background owners, not claimed as a cold-start optimization.

## Proof and Landing Disposition

- Regression fails before the fix because a second selection issues another discovery request. After the fix, an in-process row write preserves the returned inventory and both discovery/cleanup request counts.
- Transcript identity suite: 18/18 passed (24 seconds test work; 81.1 seconds wall time including compiled-worker preparation). Inventory/availability suites: 13/13 passed. Existing fixed-store and registered-sibling tests cover fresh visibility after in-process writes. These runs preceded the relaxed-testing update; final local proof was scoped oxfmt, oxlint and `git diff --check`.
- Two Codex autoreview rounds completed with no actionable findings. The second reviewed the final fixed-store correction.
- T1 in the changed runtime file: **0 → 0**. No SQLite call moves between threads.
- Final-head [CI run 38211504829](https://github.com/openclaw/openclaw/actions/runs/38211504829) passed production types, all five core test-type shards and aggregate, lint, source contracts/export collisions, architecture/Madge, and baseline/T1/dialect/worker ratchets. Earlier Knip found only the inherited `src/agents/agent-run-result.ts: agentRunHasVisibleReply` unused export, identical on the measured base; main subsequently removed it in `ebbb97d182786`. This PR adds or removes no exports.
- Admin landing uses the unchanged concurrent-deletion built-CLI failure: `waitForAgentRunSettled` rejects `AbortError: agent run aborted` without `stopReason`. The same failure predates this patch in [run 38200828665](https://github.com/openclaw/openclaw/actions/runs/38200828665), and the fixture, helper and termination owner are unchanged. Final `build-artifacts` failed; two remaining test shards were cancelled by fail-fast and are not claimed as passing. The patch does not change cancellation or terminal result publication.
- No SDK diff or published-driver update cell applies: no SDK, update, Doctor, migration/schema, plugin loading or service lifecycle change.
- LOC: production +4/-1; tests +33/-0; docs +5/-1.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
First-parent upstream fa23864..e099f44 (100 commits, including
openclaw#169594 lifecycle/mention bookkeeping in workers, openclaw#169573 input completion,
openclaw#169724 fact-only refresh rows, openclaw#169598 target discovery).

Conflicts:
- session-entry-patch-source.ts: upstream routes host-only commit guards
  through the worker (`!commitGuard?.nativeSource`); kept our condition that
  a patch with afterPersistInTransaction (a main-thread closure) stays on
  the native writer.
- compact.types.ts: our "volitional" trigger plus upstream's
  modelCallUrgency.
- session-accessor.ts: upstream dropped the sync
  updateSessionProfileInvolvement export (no fork caller); recipient
  authority exports kept.
- worker inventory regenerated.

Auto-merged files carrying continuation overlay (21) keep it byte-for-byte.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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