Skip to content

fix(sessions): read remaining metadata-only session listings at the list projection - #149358

Closed
DakshK-02 wants to merge 7 commits into
openclaw:mainfrom
DakshK-02:fix/sessions-list-projection-metadata-reads
Closed

DakshK-02 wants to merge 7 commits into
openclaw:mainfrom
DakshK-02:fix/sessions-list-projection-metadata-reads

Conversation

@DakshK-02

@DakshK-02 DakshK-02 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: a gateway with a large session store burns memory and CPU re-parsing every stored session's saved skills-catalog prompt when a whole-store listing only needs identity or ownership fields. On a Slack gateway with ~600 stored sessions this materialized the 17–35 KB catalog string tens of thousands of times per inbound message and kept thousands of copies live in the heap.

User Impact

User impact: operators running a gateway with a large session store see lower heap and far less per-message JSON parsing; no behavior, config, or API change. The plugin runtime gains one optional, default-unchanged projection parameter on listSessionEntries.

Why This Change Was Made

Whole-store session listings default to the "full" projection, which parses every row's skillsSnapshot and systemPromptReport and bypasses the entry cache (readSessionEntryCache returns loadSessionEntrySnapshot for "full"). Main has already moved most of this surface to "list" (62 call sites today), plus the metadata-only maintenance candidate scans and the keyed reply-init reads. This PR finishes the remaining metadata-only whole-store reads.

Twelve whole-store reads now pass projection: "list". Each site was re-audited on current main against four checks before flipping: no downstream read of the two large fields, no whole-entry write-back sourced from the listing, no whole-entry equality fence (sqliteSessionEntriesEqual / expectedEntry), and no entry crossing a plugin/RPC/CLI boundary that can observe the payload.

site fields actually read
run-session-target.ts legacy-marker resolve sessionId, updatedAt, sessionKey
btw-transcript.ts marker matcher sessionId + resolvePreferredSessionKeyForSessionIdMatches (updatedAt/key only)
compaction-successor.ts marker matcher same
run/session-bootstrap.ts marker matcher same
run/attempt-session-identity.ts marker matcher same
run/attempt-history-prepare.ts sibling subagents spawnedBy, sessionId, subagentRole, status
acp-spawn-requester.ts resume-ownership scan spawnedBy, parentSessionKey (via sessionEntryIsOwnedByRequester)
trajectory/export.ts marker matcher sessionId + preferred-key helper
registry-runtime-session-ownership.ts ×2 sessionId, agentHarnessId, pluginOwnerId (via assertLockedSessionEntryOwned)
session-catalog.ts fallback listing sessionId, initializationPending, agentHarnessId, modelSelectionLocked, pluginExtensions, pluginOwnerId
memory-core-host-engine-sessions.ts resolveMemorySessionTargets sessionId, sessionKey, sourceMetadata (hook source / channel / accountId / chatType / createdAt)

One call site needed more than a flag. validateAcpResumeSessionOwnership called readAcpSessionMeta for every key it scanned, decoding one complete stored entry — saved catalog prompt included — per session in the store, only to read lifecycleRevision / sessionId / sessionStartedAt. The listing was never the dominant cost there, so projecting it alone changed nothing measurable. It now resolves each key through resolveSessionStorePathForAcp (the same owner resolution the keyed read performs, including its retired/conflicting-owner rejections) and passes the already-listed row to readAcpSessionMetaForEntry. Only the redundant entry decode is removed; the resolved ACP row and the ownership decision are unchanged.

The session-catalog fallback listing is now consistent with its own precomputed path: session-catalog-entry-snapshot.ts already builds entriesForAgent at projection: "list", so both branches of listSessionCatalogEntries return the same shape.

The plugin runtime listSessionEntries gains an optional projection (types-core.ts, forwarded in runtime-agent.ts only when defined). The wrapper default stays "full" deliberately, because SDK consumers such as the extensions/zalouser doctor contract read a listed entry and then upsertSessionEntry(entry), which would drop the two fields on a list-projected row. Projection is chosen per call site, never at the wrapper.

Sites deliberately left at "full": the lifecycle store read, the maintenance full pass, agent-command session resolve, usage contextWeight (reads systemPromptReport), the plugin-SDK transcript hit, the zalouser doctor path, and the purge/rename equality fences. Each fails at least one of the four checks.

Evidence

Incremental effect of this diff on current main

Counted prompt-bearing JSON.parse results, and the bytes handed to them, per invocation of each changed entry point against a 200-row store with 17.6 KB saved prompts — main (eee60cd68f) versus this branch, same process and harness:

call site main this PR
resolveAgentRunSessionTarget (legacy marker) 200 parses / 3.5 MB 0 / 0
validateAcpResumeSessionOwnership 400 parses / 6.9 MB 0 / 0
resolveMemorySessionTargets 200 parses / 3.5 MB 0 / 0
total 800 parses / 13.9 MB 0 / 0

One decode per stored row per call, so the cost scales with store size rather than with the work being done. All three sites carry zero-parse assertions in session-store-listing-projection.test.ts, so these are reproducible from the suite.

Live gateway, combined Phase A build

Measured on a live Slack gateway (~600 stored sessions, avg prompt 17.5 KB, 488 stale rows), v2026.8.2 + the complete Phase A change set, same 18-send protocol across builds, heap snapshot taken after the load drained.

Attribution: these numbers come from the full Phase A set. Most of that set — the metadata-only maintenance candidate scans, the dead entry_json column in the lifecycle cleanup planner, the keyed reply-init reads that replaced two whole-store listings, and 13 of the 25 original flips — has since landed on main independently. This PR is the remaining 12 sites plus the runtime parameter. The table is what the combined surface achieves, not what this diff alone adds on top of today's main.

after load list-default only + prompt interning + full Phase A set
copies of the skills-catalog prompt (top 3) 2,681 / 2,355 / 2,250 2,281 / 1,580 / 1,504 45 / 10
skill-string allocations ≥ 2 KB 9,389 7,130 1,356
skill-string MB 291.6 216.8 18.9
MB wasted on redundant copies 298.1 222.4 24.8
all string bytes 604.2 MB 473.2 MB 150.0 MB
heap snapshot size — 627 MB 322 MB

Parse probe (temporary instrumentation in parseSessionEntryJson, not part of this PR), per inbound message net of idle: prompt-bearing parses ~31.5k → ~4.9k (−84%), JSON bytes parsed ~690 MB → ~84 MB (−88%), idle whole-store loads −70%, stale-candidate scan prompt bytes ~1.1 GB → 0.

Write-back guard: every session row written during the test still carried skillsSnapshot.prompt and systemPromptReport after the run drained (11/11 rows written; 618 rows total, 615 with prompt, 604 with report). Slack stayed connected; 11/11 replies delivered.

Composition of the remaining 150 MB: 67.7 MB module source text (static), 43.8 MB small strings, 16.5 MB SKILL.md bodies held ×12 at startup, 12.2 MB injected docs held once per run — none of it the catalog string. Those are separate retention paths, untouched here.

The full run log, probe tables and heap census/bucket output are posted as a comment on this PR.

Review. Three independent reviewers traced all 30 sites of the original change set (fields read, write-back, equality fence, contract boundary, cache freshness, borrowed-row mutation) and returned 30/30 list-safe. For this PR every surviving site was re-traced from scratch on current main, because main had rewritten several of the files: attempt-history.ts → attempt-history-prepare.ts, run-session-target.ts gained a new candidateMarkerEntry read (sessionId only), and the plugin-catalog consumers in extensions/codex and extensions/anthropic were re-checked for reads of the two large fields (none found).

Tests. New src/config/sessions/session-store-listing-projection.test.ts counts prompt-bearing JSON.parse results and asserts: they are independent of store size for the legacy-marker resolve; transcript-instance listings return no prompt at "list" while "full" still does; and the ACP resume-ownership scan and resolveMemorySessionTargets parse zero prompts. The one-time canonical-key validation scan is warmed first so the assertions measure the listing itself, the way a long-lived gateway process experiences it. session-catalog.test.ts gains a contract test that both catalog paths omit the two payload fields while retaining the fields adoption and ownership matching read, and its call-argument expectation is updated.

Checks run
  • pnpm tsgo — clean.
  • pnpm check:changed — all lanes pass except typecheck extensions, which fails identically on clean origin/main (extensions/qa-lab/src/crabline-transport.ts, DiscordServerManifest missing driverBotToken/fixture). Verified by running the same lane on a detached origin/main; pre-existing and unrelated.
  • oxlint and oxfmt — clean on changed files.
  • node scripts/run-vitest.mjs run — green for the new test plus run-session-target, compaction-successor, acp-spawn, acp-spawn.authority, memory-core-host-engine-sessions, runtime-agent, export-trajectory, plugin-sdk/session-catalog, plugins/session-catalog, and the extensions/codex + extensions/anthropic session-catalog consumers.

Not in this PR (follow-ups)

  • Every inbound message still forces a full maintenance pass (maintenanceConfig always set → forceMaintenance), and the lifecycle mutation still reads the whole store at full projection once per message — both need fullEntryKeys-style structural changes, not a flag flip.
  • ~600 full whole-store loads right after gateway startup (count ≈ row count, ~100 s event-loop freeze) remain unattributed; the probe stack bottoms out at readSessionEntrySnapshot at depth 5.
  • Per-run retention of ~2.7 MB of small records, and every SKILL.md body held ×12 from startup, are separate retention paths.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 15, 2026
@DakshK-02

Copy link
Copy Markdown
Contributor Author

Phase A dev-box A/B — measurement detail

Run log and probe tables from the live-gateway measurement referenced in the PR body, plus the heap census and bucket aggregates derived from the snapshots with analyze-heap2.mjs / analyze-heap-buckets.mjs.

Redaction note: this ran on a private deployment. Deployment identifiers (instance id, channel id, host paths) and every string preview have been removed — the previews list customer names, internal workspace documents and private skill bodies. Only counts, sizes and shapes are reproduced. Snapshots themselves are not attached (50–137 MB gzipped each).

Phase A dev-box A/B — 2026-09-15 (UTC times), dev box (identifier redacted)

Build under test: v2026.8.2 + intern (b5fd1b8851) + Phase A (23199840cd, cf025d1a40, 7a6ca30949) + temporary parse probe.
Deployed 18:07:39, MainPID redacted. Rollback dir on box: <rollback-dir> (= build that ran before).
Store: 607 rows / 604 with prompt at start; 618 / 615 at end (11 new thread sessions). Avg prompt 17.5 KB. 488 stale (>3 d, unarchived) rows.

Load

Same 18 sends as the earlier runs (10 @mentions in new threads + 8 thread follow-ups), the test channel, 18:18:34 -> 18:25:31.
Processed by the bot: 10 mentions + 1 stray 7.6 KB @mention from another user at 18:24:48 = 11 runs. The 8 follow-ups produced
no inbound log line and no reply (this Slack config reacts to @mentions only) — most likely the same in the earlier runs.
All 11 replies delivered; 0 gateway errors (3 benign agent tool misses). Drained 18:30:51.

Probe (parseSessionEntryJson counts; "with prompt" = a 17.5 KB skills catalog was materialized)

Window = baseline dump 18:17:05 -> pre-snapshot dump 18:30:13 (13 min, 11 runs + idle).

old build (4 runs + 12 min idle, 17:45->17:57) Phase A (11 runs + 13 min idle)
total parses +245,895 +260,426 (most now prompt-less metadata parses)
parses WITH prompt +170,212 +62,121
MB of JSON parsed +2,917 +1,064
idle churn (no traffic) 3.6k parses/min = 2-4 whole-store full loads / 30 s 1.1k parses/min ≈ 1 full load / min (-70%)
hasStale scan (per write) +65.5k parses with prompt (~1.1 GB) 0 MB — metadata select, gone from top sites
forced maintenance full pass 1 full load / message 1 full load / message (unchanged, FULL-REQ, Phase B)
lifecycle-mutation store read 1 full load / message 1 full load / message (unchanged, FULL-REQ, Phase B)
top chain readSessionEntrySnapshot FULL loads ~23 / message ~5 / message (-78%)

Per-message, net of idle: prompt parses ~31.5k -> ~4.9k (-84%); JSON parsed ~690 MB -> ~84 MB (-88%).

Startup finding (new)

Right after start the process froze ~100 s (host timing gap 18:09:20->18:11:04, Slack socket errored, memory-pressure warning
rss 1.46 GiB). Probe shows ~600 whole-store FULL loads (365k prompt parses, 6.2 GB) in that window — count ≈ row count, so it
looks like an O(n²) startup path listing the store once per session at full projection. Unattributed at probe depth 5
(stack ends at readSessionEntrySnapshot). Same chain the old build showed as the "unattributed 590 loads". Needs depth-12 probe.

Remaining prompt-less cost

~240k parses in the window came from sites below the top 8: hasStale metadata scans (2 x ~490 stale rows per write) and
list-cache revalidation. Cheap (≈1 KB each) but still O(stale rows) per write — Phase B: stop the per-write stale scan (§3.4 divergence).

Regression guard

All 11 session rows written during the test still carry skillsSnapshot.prompt (17.5 KB) and systemPromptReport after drain.
Whole store: 618 rows, 615 with prompt, 604 with report. Slack connected throughout after the startup freeze.

Heap census (analyze-heap2.mjs, strings >= 2000 B)

Same 18-send protocol, same box, snapshot after drain. Earlier columns from the previous session's runs (list-only, +intern).

after load list-only +intern +Phase A change vs +intern
top catalog copies 2,681 / 2,355 / 2,250 2,281 / 1,580 / 1,504 45 / 10 -98%
skill allocations 9,389 7,130 1,356 -81%
skill-string MB 291.6 216.8 18.9 -91%
waste MB (redundant copies) 298.1 222.4 24.8 -89%
all strings MB 604.2 473.2 150.0 -68%
strings >= 2000 B allocations - 11,528 5,935 -49%
heap snapshot size - 627 MB 322 MB -49%
RSS at final snapshot - - 2.40 GB before / 2.06 GB after GC

Baseline (Phase A, 9 min uptime, 1 message — not a fresh-process point like the earlier 23 s baselines):
all strings 121.2 MB, skill-looking 1,287 allocs / 16.7 MB, waste 19.2 MB, catalog copies 27. So under the 11-run load the
catalog went 27 -> 55 copies (vs 3 -> 2,281 for +intern). The remaining 1,3xx skill allocations are every SKILL.md body held
live 12x (and 19x/24x for a few) — a different retention path from the catalog string, present at baseline too, unchanged by
Phase A; worth a retainer walk later.

Caveats: 11 processed runs here vs 15 logged in the earlier runs; sends were paced 7 min instead of 16; another user's 7.6 KB
message landed mid-test. None of these can explain a 98% drop in catalog copies.

Files: heap snapshots and census output retained locally; not attached (50-137 MB gzipped each).

Where the remaining 150 MB of strings comes from (analyze-heap-buckets.mjs, all string nodes)

bucket +intern after load (473 MB) Phase A baseline p0 (121 MB) Phase A after load p1 (150 MB) grows under load?
skills catalog prompt 200.5 MB (5,848 nodes) 1.5 MB (44) 2.4 MB (72) barely
small strings <256 B 169.7 MB (3.66 M nodes) 25.2 MB (553 k) 43.8 MB (950 k) yes: +18.6 MB / +397 k nodes over 12 runs
JS module source (dist chunks + node internals) 66.9 MB 66.5 MB 67.7 MB no (static)
SKILL.md bodies 16.4 MB 15.3 MB (117 files x 12 copies) 16.5 MB slightly: used skills gain +1 copy per use (three most-used skills at x24 / x19 / x17)
other large text >=2 KB (workspace docs, memory files, system prompts) 11.3 MB 8.3 MB 12.2 MB yes: doc copies ~= run count (three injected workspace docs at x9 / x10 / x13)
other JSON / medium text / UUIDs / session keys ~8 MB ~4.4 MB ~7.2 MB UUIDs 10 k -> 30 k (+1.8 k per run)

Before Phase A the small-string bucket was parsed-entry debris (17,306 copies of each skill NAME, 22,685 copies of one sha256 hash =
skillsSnapshot.skills arrays from full-projection parses). Phase A removed that with the catalog: 473 -> 150 MB = catalog -198 MB,
small strings -126 MB, everything else unchanged.

What is left and still grows: ~2.7 MB per run of small retained records. After 12 runs: 23,400 x one channel-id string (p0: 7,253),
32,913 / 32,154 / 25,678 x three short route labels, 11,875 x model id, 11,631 x provider id, 30 k UUIDs, 112 k V8 cons strings.
~2,000 records per run, each carrying channel + provider + model + a UUID — looks like per-event records (transcript/tool/usage/
telemetry) retained after the run ends, plus one copy per run of injected docs. Static floor ~115 MB (67 code + 25 small + 15 SKILL.md
x12 + 8 docs). Next step to name the holder: retainer walk (retain-trace.mjs) from one channel-id string and from one
SKILL.md body in p1-phaseA-after18.heapsnapshot.

Heap census aggregates — baseline (before load) vs after the 18-send load
file: p0-phaseA-baseline.heapsnapshot
all string nodes: 583,658  121.2 MB
strings >= 2000 bytes: 5,360 allocations, 3,762 distinct
  total: 90.6 MB
  duplicated (>1 copy): 393 distinct, 1,991 allocations
  WASTED on redundant copies: 19.2 MB
SKILL-LOOKING: 116 distinct, 1,287 allocations, 16.7 MB

file: p1-phaseA-after18.heapsnapshot
all string nodes: 1,004,635  150.0 MB
strings >= 2000 bytes: 5,935 allocations, 3,972 distinct
  total: 98.7 MB
  duplicated (>1 copy): 445 distinct, 2,408 allocations
  WASTED on redundant copies: 24.8 MB
SKILL-LOOKING: 117 distinct, 1,356 allocations, 18.9 MB
String bucket breakdown after load
file: p1-phaseA-after18.heapsnapshot
all string nodes: 1,004,635  150.0 MB

BUCKET                                                    nodes       MB   share
JS module source (dist chunks, node internals)            6,392     67.7   45.1%
other small (<256 B)                                    950,334     43.8   29.2%
SKILL.md bodies                                           1,369     16.5   11.0%
other large text (>=2 KB)                                 1,171     12.2    8.1%
other JSON                                                4,380      2.7    1.8%
other medium text (256 B - 2 KB)                          3,256      2.5    1.6%
skills catalog prompt (skillsSnapshot.prompt)                72      2.4    1.6%
UUIDs                                                    30,748      1.6    1.1%
session keys                                              5,992      0.4    0.3%
base64 / tokens                                              47      0.1    0.1%
URLs                                                        715      0.0    0.0%
ISO timestamps                                              158      0.0    0.0%
session entry JSON                                            1      0.0    0.0%

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 8:25 PM ET / October 6, 2026, 00:25 UTC (Revision 5).

ClawSweeper review

What this changes

The branch makes metadata-only session scans avoid decoding saved prompts, reuses listed rows for ACP resume checks, and exposes an optional lightweight listing projection to plugins.

Merge readiness

⛔ Blocked before merge - 5 items remain

Useful work remains beyond current main’s related optimizations. The prior SDK compatibility decision is still unresolved, and the pinned branch has merge conflicts; neither warrants closing this contribution.

Priority: P2
Reviewed head: 3515b01ec2c5559ce450fa7e662db4de12cc94eb
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-supported performance patch with no discrete correctness finding; SDK acceptance and conflict refresh remain merge blockers.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The redacted real Slack Gateway run exercised session-store reads under load, observed lower prompt allocation, delivered 11 replies, and preserved written payloads. Its combined-build attribution is explicit; incremental measurements supplement coverage of three changed entry points. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The redacted real Slack Gateway run exercised session-store reads under load, observed lower prompt allocation, delivered 11 replies, and preserved written payloads. Its combined-build attribution is explicit; incremental measurements supplement coverage of three changed entry points. No stored-data contract changes.
Evidence reviewed 10 items Pinned introduced change: Reviewed the complete merge-base-to-head patch. Its changes are session read projections, ACP row reuse, an optional runtime parameter, documentation, and focused tests; endpoint drift was excluded from PR ownership.
Central optimization remains necessary: Current main’s legacy-marker listing still omits a projection argument, as does the BTW marker listing. Current main’s plugin runtime wrapper also does not forward a projection parameter. These distinct remaining changes prevent an implemented-on-main or duplicate close.
Shipped catalog fallback: The v2026.9.8 source calls runtime listSessionEntries without selecting the lightweight projection when no snapshot is supplied. The PR changes that fallback to omit saved prompt fields. Release source was read through GitHub REST after local tag-object retrieval failed.
Findings None None.
Security None None.

How this fits together

OpenClaw’s session store supplies identity, ownership, lifecycle, and saved prompt data to agent execution and plugins. Lightweight listings let metadata consumers read session facts without allocating each session’s saved prompt payload.

flowchart TD
  A[Agent and plugin requests] --> B[Session read owner]
  C[Stored session rows] --> B
  B --> D{Requested projection}
  D --> E[Complete session entries]
  D --> F[Lightweight metadata entries]
  F --> G[Identity and ownership matching]
  E --> H[Prompt consumers and complete writes]
Loading

Decision needed

Question Recommendation
Should the shipped catalog helper’s direct-listing fallback become metadata-only, or should this PR preserve complete fallback entries? Preserve the shipped fallback: Remove the unconditional catalog fallback projection and its metadata-only fallback guarantee while retaining the safe internal optimizations.

Why: The existing snapshot path supports metadata-only results, but the released direct fallback returns complete entries; contributor documentation alone cannot authorize that compatibility change.

Before merge

  • Resolve merge risk (P2) - External plugins using the shipped catalog fallback may receive entries without saved prompt fields after upgrade; SDK-owner acceptance or preservation of the existing fallback is still required.
  • Resolve merge risk (P1) - The pinned head conflicts with current main, where several affected reads have moved to workers or indexed lookup; the refreshed branch must preserve those newer owners.
  • Complete next step (P2) - Refresh the branch to resolve current-main conflicts and obtain the SDK owner’s catalog fallback decision, or preserve the shipped complete fallback.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +44, Tests +207, Docs +4. Total +255 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 13 49 5 +44
Tests 4 208 1 +207
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 261 6 +255

Review metrics

Metric Value Why it matters
Plugin API parameter 1 optional projection parameter; full-entry default preserved The parameter is additive, while the catalog helper’s unconditional use introduces a separate compatibility choice.
Production versus test LOC production +49/−5; tests +208/−1 Production growth is explained by ACP row reuse and the runtime contract; most added coverage guards prompt parsing and catalog results.

Stored data model

Persistent data-model change detected: vector/embedding metadata: src/plugin-sdk/memory-core-host-engine-sessions.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Keep the released fallback shape (recommended)
    Preserve complete direct catalog fallback entries and refresh the remaining optimizations onto current main’s read owners.
  2. Accept the catalog contract change
    Have the SDK owner explicitly approve metadata-only fallback results and the documented keyed-read upgrade path.

Technical review

Best possible solution:

Keep lightweight reads at metadata-only consumers, preserve current worker and indexed owners, and retain the shipped catalog fallback unless the SDK owner explicitly approves changing its result contract.

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

Yes, source establishes the path: current-main legacy-marker and BTW scans use complete listings for metadata matching, causing saved prompt decoding to scale with store size. No target code was executed during this read-only review.

Is this the best way to solve the issue?

Yes for internal metadata consumers using the existing projection; the public catalog fallback change needs a separate compatibility decision, and obsolete scans should yield to current main’s newer owners.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded performance improvement for gateways with large session stores.
  • merge-risk: 🚨 compatibility: The introduced catalog fallback can stop returning saved prompt fields to existing external SDK callers without recorded owner acceptance.
  • 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. Sufficient (logs): The redacted real Slack Gateway run exercised session-store reads under load, observed lower prompt allocation, delivered 11 replies, and preserved written payloads. Its combined-build attribution is explicit; incremental measurements supplement coverage of three changed entry points. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The redacted real Slack Gateway run exercised session-store reads under load, observed lower prompt allocation, delivered 11 replies, and preserved written payloads. Its combined-build attribution is explicit; incremental measurements supplement coverage of three changed entry points. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the complete merge-base-to-head patch. Its changes are session read projections, ACP row reuse, an optional runtime parameter, documentation, and focused tests; endpoint drift was excluded from PR ownership. (3515b01ec2c5)
  • Central optimization remains necessary: Current main’s legacy-marker listing still omits a projection argument, as does the BTW marker listing. Current main’s plugin runtime wrapper also does not forward a projection parameter. These distinct remaining changes prevent an implemented-on-main or duplicate close. (src/agents/run-session-target.ts, c1005a2ee593)
  • Shipped catalog fallback: The v2026.9.8 source calls runtime listSessionEntries without selecting the lightweight projection when no snapshot is supplied. The PR changes that fallback to omit saved prompt fields. Release source was read through GitHub REST after local tag-object retrieval failed. (src/plugins/session-catalog.ts, fc23bc864e45)
  • Public SDK compatibility boundary: The catalog helper is publicly re-exported by src/plugin-sdk/session-catalog.ts. The introduced fallback projection changes observable results for direct callers; the Gateway snapshot already uses lightweight entries, which supports the contributor’s consistency argument but does not establish owner acceptance of the changed fallback contract. (src/plugins/session-catalog.ts:280, 3515b01ec2c5)
  • Prior blocker remains a human choice: The previous completed review requested an SDK-owner decision. The contributor’s response documents metadata-only results and explicitly leaves acceptance to maintainers, offering removal of the catalog hunk as an alternative. No accepting human review is recorded in the supplied discussion or REST review results. Contributor response: fix(sessions): read remaining metadata-only session listings at the list projection #149358 (comment).
  • Real gateway behavior proof: The supplied redacted live Slack run exercised a roughly 600-session store with the combined Phase A build, delivered all 11 processed replies, reduced prompt allocation and parsing, and retained saved payloads in all 11 written rows. The body clearly attributes those aggregate results to the combined build; separate main-versus-branch measurements cover three changed entry points. Full observations: fix(sessions): read remaining metadata-only session listings at the list projection #149358 (comment).

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Resolve conflicts against current main while preserving worker-backed reads and indexed ACP resume lookup.
  • Record the SDK owner’s fallback-contract decision or preserve the released complete fallback.

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 (4 earlier review cycles)
  • reviewed 2026-09-15T19:25:14.884Z sha 37df656b52c40df1de8e4db9a11cca662c73273d :: blocked before merge. :: none
  • reviewed 2026-09-15T23:45:16.551Z sha 1f26c1a :: blocked before merge. :: none
  • reviewed 2026-09-16T01:44:33.623Z sha b562f4f :: blocked before merge. :: none
  • reviewed 2026-09-24T14:05:26.391Z sha 3515b01 :: blocked before merge. :: none

DakshK-02 and others added 5 commits September 16, 2026 05:04
…ist projection

Whole-store session listings default to the "full" projection, which parses
every row's skillsSnapshot (the skills-catalog prompt, 17-35 KB) and
systemPromptReport on every call and bypasses the entry cache. Most of these
listings only read identity, timestamp or ownership fields.

Flip the twelve remaining metadata-only whole-store reads to
projection: "list": the legacy-marker resolve in run-session-target, the five
marker matchers (btw-transcript, compaction-successor, session-bootstrap,
attempt-session-identity, trajectory export), the sibling-subagent scan in
attempt-history-prepare, the ACP resume-ownership scan, both plugin
session-ownership assertions, the session-catalog fallback listing, and
resolveMemorySessionTargets. Each site was audited for downstream reads of the
two large fields, whole-entry write-back, whole-entry equality fences, and
entries crossing a plugin, RPC or CLI boundary.

The session-catalog fallback now matches its own precomputed path, which
already lists at "list" in session-catalog-entry-snapshot.

Add an optional projection to the plugin runtime listSessionEntries params and
forward it when defined. The wrapper default stays "full" on purpose: SDK
consumers that read a listed entry and write it back whole would otherwise drop
the two fields.

Co-Authored-By: Claude Opus 5 <[email protected]>
…-reading each key

validateAcpResumeSessionOwnership scans the whole session store and called
readAcpSessionMeta for every key, which decoded one complete entry — including
the saved skills-catalog prompt — per stored session. That per-row read, not
the listing, dominated the scan, so projecting the listing alone changed
nothing measurable.

Pass the already-listed row to readAcpSessionMetaForEntry. Its binding input is
lifecycleRevision/sessionId/sessionStartedAt, all of which the list projection
retains, so the resolved ACP metadata and the ownership decision are unchanged.

Measured over a 200-row store with 17.6 KB saved prompts: 200 prompt-bearing
JSON parses (3.5 MB) before, 0 after.

Co-Authored-By: Claude Opus 5 <[email protected]>
…tadata contract

Document the optional projection on the plugin runtime listSessionEntries: the
default stays "full", "list" omits the saved skillsSnapshot and
systemPromptReport payloads, and a listed entry must never be written back.

State that listSessionCatalogEntries returns metadata-only entries on both of
its paths. The Gateway-supplied entry snapshot already listed at the metadata
projection, so its fallback branch now matches rather than returning a
different shape for the same helper. Consumers needing a saved prompt read that
one session with a keyed getSessionEntry.

Cover the guarantee with a test asserting both paths omit the two payload
fields while retaining the identity, harness, ownership and pluginExtensions
fields catalog adoption actually reads.

Co-Authored-By: Claude Opus 5 <[email protected]>
…prompt parsing

Both whole-store scans now assert zero prompt-bearing JSON parses, so a
regression to the full projection — or a return to the per-key ACP metadata
read — fails here instead of only showing up as heap growth on a large store.

Co-Authored-By: Claude Opus 5 <[email protected]>
…solution

The agent id is part of the ACP database key, so deriving it from the target
agent changed which row an unscoped session key resolved to. Resolve each
listed key through resolveSessionStorePathForAcp, the same owner resolution the
keyed read performs, and pass its canonical store key and agent id to
readAcpSessionMetaForEntry. Only the redundant per-key entry decode is removed;
the resolved ACP row and the ownership decision are unchanged.

Also drop a cast in the catalog contract test and assert on the typed entry.

Co-Authored-By: Claude Opus 5 <[email protected]>
@DakshK-02
DakshK-02 force-pushed the fix/sessions-list-projection-metadata-reads branch from 37df656 to 1f26c1a Compare September 15, 2026 23:38
@DakshK-02

Copy link
Copy Markdown
Contributor Author

Thanks — worked through all five items. Four new commits.

1 & 3 — catalog compatibility (P2)

Took the recommended option: accept the metadata-only fallback and document it.

The guarantee is now stated in three places:

  • docs/plugins/sdk-runtime/agent.md documents the optional projection on the runtime listSessionEntries (default stays "full", "list" omits the two payloads, a listed entry must never be written back), and states that listSessionCatalogEntries returns metadata-only entries on both paths.
  • A JSDoc contract on listSessionCatalogEntries itself.
  • A test asserting both paths omit skillsSnapshot and systemPromptReport while retaining the fields catalog adoption and ownership matching read (sessionId, agentHarnessId, modelSelectionLocked, pluginExtensions).

The argument for accepting rather than reverting: the Gateway-supplied sessionEntries snapshot path already listed at projection: "list" before this PR (session-catalog-entry-snapshot.ts), so the helper already returned metadata-only entries whenever the Gateway passed a snapshot. External callers could not rely on the payload being present; the fallback was simply inconsistent with the path that runs in the Gateway. This PR removes the inconsistency and writes the contract down. Reverting the fallback would restore a helper that returns two different shapes for the same call depending on who invoked it.

The maintainer decision is still yours — option 2 (drop only the session-catalog.ts hunk, keep everything else) is a one-line revert if you would rather not settle the public contract in this PR.

2 — incremental proof on current main (P1)

Fair criticism: the live-box numbers cover the combined Phase A build. Measured this diff alone against current main, same process, same harness — a 200-row store with 17.6 KB saved prompts, counting prompt-bearing JSON.parse results and the bytes handed to them, per invocation of each changed entry point:

call site main (eee60cd68f) this PR
resolveAgentRunSessionTarget (legacy marker) 200 parses / 3.5 MB 0 / 0
validateAcpResumeSessionOwnership 400 parses / 6.9 MB 0 / 0
resolveMemorySessionTargets 200 parses / 3.5 MB 0 / 0
total 800 parses / 13.9 MB 0 / 0

One decode per stored row per call, so it scales with store size, not with the work being done. Those three sites are now covered by zero-parse assertions in session-store-listing-projection.test.ts, so the numbers are reproducible from the suite rather than only from the live box.

The measurement found a real defect

validateAcpResumeSessionOwnership showed 400 parses on main and still 200 after the projection flip alone. The listing was never the dominant cost there: the loop called readAcpSessionMeta per key, which decoded one complete stored entry — saved catalog prompt included — for every session in the store, just to read lifecycleRevision / sessionId / sessionStartedAt.

Fixed by passing the already-listed row to readAcpSessionMetaForEntry. First attempt was wrong and worth flagging: I passed targetAgentId as the owner, but the agent id is part of the ACP database key (buildAcpDatabaseSessionKey), so an unscoped session key would have resolved to a different row. The committed version resolves each key through resolveSessionStorePathForAcp — the same owner resolution the keyed read performs, including its retired/conflicting-owner rejections — and passes its canonical store key and agent id. Only the redundant entry decode is removed; the resolved ACP row and the ownership decision are unchanged. acp-spawn.test.ts and acp-spawn.authority.test.ts pass (101 tests).

5 — data-model compatibility proof

This looks like a false positive on src/plugin-sdk/memory-core-host-engine-sessions.ts. The change there is one read argument — listSessionTranscriptInstances(params, …) → listSessionTranscriptInstances({ ...params, projection: "list" }, …) — on resolveMemorySessionTargets. No stored shape, schema, column, index, or serialized format changes anywhere in this PR; there is nothing to migrate and no upgrade path to prove. The projection is applied in SQL by the existing sessionEntryMetadataJson owner, which only strips two JSON fields from the read projection; rows on disk are untouched, and the write-back guard on the live run confirmed 618/618 rows still carried both fields afterwards. Happy to add a specific proof if you meant something narrower.

CI

check-lint-core-5 was failing on extensions/codex/src/app-server/run-attempt.model-attribution.test.ts:173 — oxlint(no-duplicate-case) on a duplicated case "thread/backgroundTerminals/list" arm. That was pre-existing on main, not from this branch. I had it fixed locally, but main landed the same removal in the meantime, so I rebased onto 60c24d7192 and dropped my commit as redundant. The branch is now on current main with no unrelated files in the diff.

Local on the rebased tree: pnpm tsgo clean, oxlint and oxfmt clean on all 17 changed files, and every touched suite passes — the projection regression test, session-catalog (core + SDK), acp-spawn + acp-spawn.authority (101), acp/runtime/session-meta, run-session-target, compaction-successor, memory-core-host-engine-sessions, runtime-agent, export-trajectory, plus the extensions/codex and extensions/anthropic catalog consumers.

…ll assertion

The side-question marker resolve now lists at projection: "list"; its exact
call-argument assertion still expected the unprojected arguments.

Co-Authored-By: Claude Opus 5 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation plugin: file-transfer size: M and removed size: S labels Sep 16, 2026
@DakshK-02

Copy link
Copy Markdown
Contributor Author

CI update on the rebased head (b562f4f01e): 178 pass, 1 real failure left, and it is not from this branch.

One genuine break was mine and is fixed: src/agents/btw.test.ts asserts the exact call arguments of the side-question marker resolve, so adding projection: "list" there broke the expectation. Updated it (78 tests pass), and swept every other test that mocks these listings — session-accessor, session-accessor.sqlite-data-version, memory-core-host-engine-sessions, the usage owner-attribution integration test, and registry.runtime-session-ownership — no other exact-argument assertion covers a site this PR touches.

The remaining red is test/scripts/pr-wrappers.test.ts in checks-node-compact-small-14 (openclaw/ci-gate just aggregates it). Every case in "alias wrapper trust delegation" fails with expected 1 to be 73 — the wrapper refuses before reaching the recorded supervisor handoff. It reproduces identically on a clean detached origin/main, so it is pre-existing and unrelated; nothing in this branch touches scripts/.

I deliberately did not fix it here. It is scripts/pr trust-delegation machinery — a maintainer-owned security path with its own guide — and folding a fix for it into a session-store performance PR would mix an unrelated trust-boundary change into this diff. Happy to open a separate issue or PR for it if that is useful; I did not find an existing one.

roboclaw-bot added a commit that referenced this pull request Nov 3, 2026
)

Avoid saved-prompt decoding in metadata-only trajectory, memory-target, and
catalog listings using the existing list projection. Reuse listed trajectory
rows instead of two additional keyed reads, preserving canonical keys and
the full runtime listing default.

Supersedes #149358, thanks @DakshK-02.

Evidence: saved-prompt decode regressions red on main and green after the
fix; 87 distinct focused tests pass; touched-file lint and format pass;
final committed-range Codex autoreview P0-P2 has no actionable findings.
Production LOC net zero. Exact-head PR CI retains the inherited 443-line
test-ceiling failure, reproduced on clean main in Crabbox; the change's 70
new test lines have matching allocation credit. Native attributed-failure
admission preserves that failed result and enforces the other gates.

Co-authored-by: DakshK-02 <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @DakshK-02! The remaining metadata-only session reads are now fixed in merged #191677, building on the projection work already on main. It also removes the redundant trajectory reads and includes red/green prompt-decoding tests. Your contribution is credited in the merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 4, 2026
…claw#191677)

Avoid saved-prompt decoding in metadata-only trajectory, memory-target, and
catalog listings using the existing list projection. Reuse listed trajectory
rows instead of two additional keyed reads, preserving canonical keys and
the full runtime listing default.

Supersedes openclaw#149358, thanks @DakshK-02.

Evidence: saved-prompt decode regressions red on main and green after the
fix; 87 distinct focused tests pass; touched-file lint and format pass;
final committed-range Codex autoreview P0-P2 has no actionable findings.
Production LOC net zero. Exact-head PR CI retains the inherited 443-line
test-ceiling failure, reproduced on clean main in Crabbox; the change's 70
new test lines have matching allocation credit. Native attributed-failure
admission preserves that failed result and enforces the other gates.

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants