Skip to content

fix(sessions): share one diff-baseline record per checkout file - #150381

Closed
DakshK-02 wants to merge 8 commits into
openclaw:mainfrom
DakshK-02:fix/sessions-diff-baseline-record-interning
Closed

DakshK-02 wants to merge 8 commits into
openclaw:mainfrom
DakshK-02:fix/sessions-diff-baseline-record-interning

Conversation

@DakshK-02

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

Copy link
Copy Markdown
Contributor

What Problem This Solves

A session that has started operator work carries a diff baseline: the path and content
fingerprint of every file in the workspace checkout at that moment
(SessionDiffBaseline.files, src/config/sessions/types.ts). Sessions on one host baseline
the same checkout, so those records are byte-identical from row to row.

Every row still parses its own JSON document, so every row materializes its own copies. The
retained cost is O(rows × files) where the content is O(files), and any read that spans
the store mints the whole set again.

This interns the records at the parse chokepoint (parseSessionEntryJson), so all callers are
covered rather than whichever read path happens to be patched.

Why it is safe

Baselines are read-only once parsed. The only consumer folds them into a
path -> fingerprint map to decide which diff hunks predate the session:

// src/sessions/session-diff.runtime.ts
const fingerprints = new Map(baseline.files.map((file) => [file.path, file.fingerprint]));

Nothing writes a record back. Sharing one instance per distinct (path, fingerprint) pair is
therefore observationally identical to parsing fresh copies, and the shared records are
frozen, so a future in-place write is a loud TypeError rather than silent cross-entry
aliasing. A test covers that.

The table is keyed by path and bounded at 4096 entries with LRU eviction, so a rename wave
cannot grow it without limit. A changed fingerprint adopts a new record and leaves entries
already holding the old one untouched.

Evidence

src/config/sessions/session-diff-baseline-intern.measure.test.ts — 200 sessions over a
559-file checkout, read 10 times at the full projection:

baseline file references returned 1,118,000
distinct record instances 559
retained heap delta 9.4 MB
if every reference were a copy 213.2 MB

The 9.4 MB that remains is the per-entry pointer arrays, which are per-entry by design.

On a live gateway

A Slack gateway with 742 session rows, 22 of them carrying a baseline, over a 559-file
checkout. Heap snapshots taken with --heapsnapshot-signal at matched process uptimes, before
and after 18 agent sessions, with and without this change. Both runs used the same trivial
prompt, so these are a floor for a session rather than a typical one — but the record count is
rows carrying a baseline x files in the checkout, which does not vary with what the agent
does:

{ path, fingerprint } records retained without with
idle 8,604 — 1.61 MB 759 — 0.14 MB
after 18 sessions 8,604 — 1.61 MB 751 — 0.14 MB

A 91% reduction, holding at both points. (751 against 560 distinct values is the intended
behaviour: a path whose fingerprint differs between two rows' baselines adopts a new record,
and rows holding the old one keep it.)

Wider snapshot totals also moved — live heap 12.94 MB lower at idle — but those carry
run-to-run variation in lazily compiled code, so only the record delta is quoted as caused by
this change.

Why the shape matters more than today's number

On the same gateway running v2026.8.2, the same records grew from 24,312 (4.84 MB) to 79,014
(15.94 MB) across 18 sessions — 58% of all duplicate small-string growth in that window,
because the store was re-parsed and retained repeatedly. (Both halves of that ratio come from
the same pair of snapshots. The v2026.8.2 run drove real operator tasks and the v2026.9.2 runs
did not, so the two versions' absolute growth is not a controlled comparison and I am not
claiming one.)

#134891 removed the whole-store listing from the reply path, which is why the set no longer
multiplies per message. What it leaves is still O(rows × files) and grows with every session
that starts operator work: 22 of 742 rows carry a baseline today; at 742 the same checkout
would retain roughly 414,000 records.

Test plan

  • src/config/sessions/session-diff-baseline-intern.test.ts — sharing, fingerprint change,
    LRU bound, cross-entry identity, the frozen-record guard, and ragged/absent baselines.
  • src/config/sessions/session-diff-baseline-intern.measure.test.ts — the table above.
  • node scripts/run-vitest.mjs run src/config/sessions src/sessions — 2,916 passing. Two
    failures reproduce unchanged on the same commit without this patch:
    goals-operations.test.ts (a read-count budget, 12 vs 11) and
    session-accessor.sqlite-reclamation-memory.test.ts ("memory plugin unavailable").
  • pnpm tsgo, pnpm oxlint, pnpm oxfmt --check — clean.
  • Deployed to a dev Slack gateway for 18 sessions: 0 restarts, 0 ERR_MODULE_NOT_FOUND, and
    0 TypeError, so nothing in production writes to a baseline record.

🤖 Generated with Claude Code

A session that has started operator work carries a diff baseline: the path and
content fingerprint of every file in the workspace checkout at that moment.
Sessions on one host baseline the same checkout, so those records are
byte-identical from row to row. Each row still parses its own JSON document, so
each materializes its own copies, and the retained cost is O(rows x files) where
the content is O(files). Any read that spans the store mints the whole set again.

Intern the records at the parse chokepoint so every caller is covered rather than
whichever read path happens to be patched. Baselines are read-only once parsed --
the sole consumer folds them into a path -> fingerprint map to decide which diff
hunks predate the session -- so sharing one frozen instance per distinct pair is
observationally identical, and freezing turns a future in-place write into a loud
TypeError instead of silent cross-entry aliasing. The table is keyed by path and
bounded with LRU eviction, so a rename wave cannot grow it without limit.

Measured by session-diff-baseline-intern.measure.test.ts: 200 sessions over a
559-file checkout, read 10 times, return 1,118,000 references that resolve to 559
instances and retain 9.4 MB, against 213.2 MB if every reference were a copy.

On a dev Slack gateway with 742 session rows, 22 of them carrying a baseline over
a 559-file checkout, heap snapshots taken at matched process uptimes show 8,604
retained records (1.61 MB) before and 759 (0.14 MB) after -- a 91% reduction.

Co-Authored-By: Claude Opus 5 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. size: M and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 16, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR shares frozen file-fingerprint records across parsed session baselines and detaches them for plugin callers.

Example: Two sessions baseline src/a.ts with fingerprint aaa.

  • Before: Each parsed baseline retains a separate file record.
  • After: Both baselines share one frozen record; plugin results receive mutable copies.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful and supported by live memory measurements, but an established owned-read contract still breaks.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR supplies live Slack Gateway heap results comparing baseline-record retention before and after 18 sessions, demonstrating the changed parser's memory benefit; the downloaded Activity screenshots belong to related work and are not used to prove interning.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Gateways retaining many hydrated session baselines keep duplicate checkout-file records and consume avoidable heap memory.
Reason: The live heap comparison supports a focused optimization without adding configuration or changing intended session-diff behavior.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep open: this PR provides a useful memory optimization, but the previously reported native-read ownership regression remains unresolved.

Priority: P2
Reviewed head: 0be3595ed0054eb39e02dcc2d875defb23a0e470

Before merge

  • Preserve mutable baseline records on native owned reads (P1) - This unconditional call replaces baseline file records with frozen shared objects for native owned reads as well as borrowed reads. For a stored baseline containing src/a.ts with fingerprint aaa, loadSessionEntry(scope), loadSessionEntryReadOnly(scope), and a full listSessionEntriesCore result expose that frozen record directly: assigning entry.sessionDiffBaseline.files[0].fingerprint = 'zzz' throws instead of modifying an isolated owned result. The row decoder promises fresh owned nested JSON, and the full-list owner deliberately skips cloning on that basis. The plugin projection repair does not cover these native boundaries. Restrict sharing to borrowed reads or detach records at all native owned boundaries. This repeats the unresolved prior finding on the unchanged reviewed head.
  • Explain or restore the original intent of Native session decoding and ownership - improve(gateway): reduce session metadata read costs #136391: Centralize metadata projection while preserving full reads and raw comparison bytes; subsequent snapshot separation explicitly preserves mutable full-read ownership.

Findings

  • [P1] Preserve mutable baseline records on native owned reads — src/config/sessions/session-accessor.sqlite-status.ts:103

Provenance

  • Native session decoding and ownership changes intended behavior without addressing why it exists (improve(gateway): reduce session metadata read costs #136391: Centralize metadata projection while preserving full reads and raw comparison bytes; subsequent snapshot separation explicitly preserves mutable full-read ownership.)

Tests

  • Missing end-to-end proof: Add native exact-read and full-list regressions proving isolated mutable baseline edits, alongside borrowed sharing; base-fail/head-pass evidence for those cases is absent.
Agent review details

How this fits together

The SQLite session reader decodes persisted baselines for native and plugin consumers; those baselines let session diffs exclude checkout changes that predate the session.

flowchart TD
  A[SQLite session snapshots] --> B[Session entry parser]
  B --> C[Bounded baseline interning]
  C --> D[Native session reads]
  C --> E[Plugin projection]
  E --> F[Detached plugin results]
  D --> G[Session diff filtering]
Loading

Technical review

Best possible solution:

Share baseline records only within borrowed immutable owners and preserve detached mutable records at every native and plugin owned-read boundary.

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

Source establishes both separate baseline decoding on current main and the patch's ownership failure: assigning fingerprint on a baseline returned by a native exact read or full listing reaches an Object.freeze record and throws in ESM; no code was executed.

Is this the best way to solve the issue?

Bounded sharing is useful, but the common parser cannot impose immutability on owned results; the existing borrowed-versus-owned boundary should decide when sharing is permitted.

Full review comments:

  • [P1] Preserve mutable baseline records on native owned reads — src/config/sessions/session-accessor.sqlite-status.ts:103
    This unconditional call replaces baseline file records with frozen shared objects for native owned reads as well as borrowed reads. For a stored baseline containing src/a.ts with fingerprint aaa, loadSessionEntry(scope), loadSessionEntryReadOnly(scope), and a full listSessionEntriesCore result expose that frozen record directly: assigning entry.sessionDiffBaseline.files[0].fingerprint = 'zzz' throws instead of modifying an isolated owned result. The row decoder promises fresh owned nested JSON, and the full-list owner deliberately skips cloning on that basis. The plugin projection repair does not cover these native boundaries. Restrict sharing to borrowed reads or detach records at all native owned boundaries. This repeats the unresolved prior finding on the unchanged reviewed head.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Plugin session projection keeps the original intent (91d3f53: Keep session-generation bookkeeping private while exposing plugin-facing session values.)
  • Materialized wrapper inventory keeps the original intent (93625aa: Keep extracted worker and wrapper runtime imports available.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/config/sessions/session-diff-baseline-intern.test.ts src/config/sessions/session-diff-baseline-intern.measure.test.ts --maxWorkers=1
  • pnpm test src/config/sessions/session-accessor.sqlite-data-version.test.ts src/config/sessions/session-accessor.sqlite-canonical-read.test.ts --maxWorkers=1
  • pnpm test src/plugin-sdk/session-store-runtime.writer-claim.test.ts --maxWorkers=1
  • git diff --check

What I checked:

  • Introduced change: The pinned introduction diff installs interning unconditionally in the common parser; the plugin projection separately detaches baseline records. (src/config/sessions/session-accessor.sqlite-status.ts:103, 0be3595ed005)
  • Native ownership contract: Exact native reads return the decoded entry directly. Full listings deliberately skip cloning because their snapshots already own nested values; unconditional freezing violates that contract. (src/config/sessions/session-accessor.sqlite-entry-list.read.ts:217, 0be3595ed005)
  • Current main and related work: Current main still parses full baselines without interning. The merged perf(sessions): keep cold snapshots out of metadata reads #160358 avoids cold snapshots during metadata reads while expressly preserving mutable full-read ownership; it does not replace this optimization. (src/config/sessions/session-accessor.sqlite-status.ts:86, 4c7a1654f8f4)
  • Feature history: Path history shows sustained session-reader work by Peter Steinberger, including metadata projection, snapshot separation, and selective hydration; blame attributes the current parser return to the metadata-projection change. (src/config/sessions/session-accessor.sqlite-status.ts:87, 1212f991db46)
  • Live memory evidence: The complete PR body reports matched live Slack Gateway heap snapshots before and after 18 sessions: baseline records fell from 8,604 to roughly 750. Downloaded screenshots concern Activity changes in the linked memory PR, not this interning change; its video preparation failed with 'ffprobe failed: spawnSync ffprobe ENOENT' and is not needed for the supplied heap results. (0be3595ed005)
  • CI attribution limit: The failed security-fast job reached Audit production dependencies; the aggregate gate reports that failure. Log retrieval was blocked on productionresultssa17.blob.core.windows.net, so a diff-caused failure or inherited failure is not established. (0be3595ed005)

PR surface

Source +97, Tests +211, Other +4. Total +312 across 8 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 3 98 1 +97
Tests 3 211 0 +211
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 4 0 +4
Total 8 313 1 +312

Review metrics

Metric Value Why it matters
Production versus test LOC Production/tooling +102/-1; tests +211/-0 The measured memory reduction justifies focused interning and boundary coverage, but the tests currently omit the native ownership regression.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The item addresses bounded session-memory overhead without evidence of an urgent outage.
  • merge-risk: 🚨 compatibility: Native APIs that promise owned mutable nested values now return frozen baseline records.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (8 earlier review cycles)
  • reviewed 2026-09-16T23:44:50.303Z sha 8129ff8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-17T04:40:03.638Z sha dc49caa :: needs maintainer review before merge. :: none
  • reviewed 2026-09-17T09:28:07.554Z sha dc49caa :: needs maintainer review before merge. :: none
  • reviewed September 24, 2026, 10:37 AM ET / 14:37 UTC (Revision 4) sha unknown :: needs maintainer review before merge. :: none
  • reviewed 2026-10-02T19:09:48.508Z sha c9c9d02 :: blocked before merge. :: [P1] [P1] Preserve mutable baseline records on owned session reads
  • reviewed 2026-10-02T20:53:38.364Z sha 69b96ab :: blocked before merge. :: [P1] [P1] Preserve mutable baseline records on owned session reads
  • reviewed 2026-10-06T01:43:33.022Z sha dfac7ba :: blocked before merge. :: [P1] [P1] Preserve mutable records on native owned session reads
  • reviewed 2026-10-06T01:56:40.053Z sha 0be3595 :: blocked before merge. :: [P1] Preserve mutable records on native owned session reads

Reviewed October 20, 2026, 12:56 PM ET / 16:56 UTC (Revision 9).

…orts

The assertion ratchet requires a SAFETY invariant on every new non-const
assertion, and the production Knip scan does not count test files as
consumers, so the interning seams read as unused exports.

Annotate the stored-JSON cast with the invariant the surrounding guards
already enforce, stop exporting the record type that nothing outside the
module uses, and scope the remaining focused-test seams the way the config
already scopes equivalent ones. The bounded-LRU test needs the table-size
seam to prove the cap, which no production caller observes.
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. and removed 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 Oct 2, 2026
…tory

session-accessor.sqlite-status.ts now imports session-diff-baseline-intern.ts,
so the trusted-anchor PR wrapper no longer closes over its runtime imports and
the sqlite-readonly-location worker loses a relative ESM dependency.

Add the module to the inventory so the extracted wrapper keeps resolving it.
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 2, 2026
…eline-record-interning

# Conflicts:
#	src/config/sessions/session-accessor.sqlite-status.ts
Stored baselines share one frozen record per checkout file across every parsed
row, so getSessionEntry and listSessionEntries handed plugin callers frozen,
shared nested values where owned mutable results are promised. Writing to
entry.sessionDiffBaseline.files[0] threw instead of modifying a detached result.

Detach the records in projectPluginSessionEntry, the single projection both
reads already use, matching how restartRecoveryRuns is detached there.
…d rows

The interned record literal ordered fingerprint before path, so an entry that
held one re-serialized its diff baseline with reordered keys and stopped
matching the stored snapshot bytes. Adopt the canonical path-first shape.

Detaching for plugin callers also tripped oxc(no-map-spread); structuredClone
expresses the same deep detach without the per-element spread.
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 20, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 20, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

@openclaw-barnacle openclaw-barnacle Bot closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M stale Marked as stale due to inactivity 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