Skip to content

refactor(sessions): add actor-owned memory storage operations - #169227

Merged
steipete merged 22 commits into
mainfrom
dbasync/phasee2
Oct 11, 2026
Merged

steipete merged 22 commits into
mainfrom
dbasync/phasee2

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The session actor's memory backend needs entry, transcript, and history operations before production incognito consumers can move to it. This adds those operations to the existing actor owner; native incognito remains the production owner during this step.

User Impact

Production acquisition still declines incognito. The retained acquisition regression checks that this path creates no memory owner. This is the second inactive Phase E layer; activation and native-owner deletion remain in the final cutover. No incognito statement or request saving is claimed while the backend is inactive.

Why This Change Was Made

Add optional SessionActor.storage operations for entry creation/patch/replacement, reset/delete/reclaim, parent fork/message cut, transcript metadata/rewrite, bounded history and exact-message reads, retained windows, replay anchors, pending inputs, and Goal receipts. Storage and phase commands share one owner queue. Mutations install atomically and publish detached receipts; prepared overwrites reject intervening writes, while typed patches preserve unrelated fields.

The durable worker and memory backend share cursor, cut, media, visibility, context, and accounting policies. Large durable payload projections stay in SQL. These superseded internal export paths are removed, with all callers moved together:

Export Removed source → shared owner
isVisibleHistoryNonMessageEvent session-accessor.sqlite-history-interval.ts → session-history-visibility.ts
createTranscriptRawDeltaCursor, normalizeRawDeltaLimits session-accessor.sqlite-raw-delta-read.ts → session-transcript-raw-cursor.ts
normalizeSessionEntryTimestamp session-accessor.sqlite-session-row.ts → session-entry-json.ts
canonicalizeTranscriptEventMedia session-accessor.sqlite-transcript-store.ts → transcript-event-media.ts
SqliteJsonlReadBudgetExceededError sqlite-jsonl-budget.ts → sqlite-jsonl-budget-error.ts
stripEnvelope re-export gateway/chat-sanitize.ts → existing shared/chat-envelope.ts

Accepted edges: memory state survives handle release but is lost on owner close or process exit by design. A synchronous authorization callback may close already accepted work reentrantly; that accepted installation can settle, and existing transport teardown remains the effect boundary. No production paranoid check is removed in this inactive step. Commit authorization and transcript identity predicates remain because they protect real user data and disclosure.

Evidence

All 68 selected test files passed, and three alternating SQL pairs completed against landed PR1 5bd4f88535c66197b6d07442b82f7f68d94be6fa, measuring c4bd93131784bc262bc605a539dd70792db8058b. The later 4476999d040063d18af0d8d05a4948cb20e69bbc repair moves an unchanged authority type to remove a type-import cycle, shortens its safety comment, and expresses the same three-string predicate with includes; it changes no SQL path. The later assertion-baseline change is shrink-only, and 6380045266bca7c0c2ad51c870bbb43fda4a508f repairs three test fixture type errors. Head 3b492259ef5bab82f906d28518f6c1b67e6594ba integrates main c400e2aff410b0107d2333c2028177c8958dad99: the sole conflict retains main’s narrowed authority-facts type, moves it beside the existing authority type, and re-exports both through the original contract. These later changes do not alter SQL paths. Final static checks ran on that head. Scoped types, type-aware lint, export collisions, source boundaries, Madge, T1/dialect ratchets, SDK surface/exports and the runtime guard pass. The full changed check reports only the unchanged UI fixture’s TS2353 at ui/src/components/session-background.browser.test.tsx:42; the exact same rule and file fail on baseline c400e2aff410 (16.48 seconds). This is an inherited static failure, not a passing full check. The SQL counts below remain evidence from the measured candidate, not final-head measurements. The earlier ENOSPC attempt failed during build and contributed no observations.

Counts below are medians [min–max], base → measured candidate. Warmed observations each contain ten turns and are divided by ten before comparison. Requests include all non-continuation transport sends.

Window All-thread statements Requests MAIN statements
First turn 1179 [1177–1179] → 1178 [1178–1178] 193 [192–193] → 193 [193–193] 61 [61–61] → 61 [61–61]
Warmed turn 320.0 [319.6–320.9] → 320.1 [319.6–320.1] 88.9 [88.7–89.3] → 88.8 [88.8–88.8] 0 [0–0] → 0 [0–0]
Startup through shutdown 9564 [9561–9568] → 9568 [9553–9571] 1724 [1722–1727] → 1723 [1721–1723] 2054 [2054–2057] → 2054 [2054–2056]

The +0.1 warmed statement (+0.03125%) is one additional ACP shared-facts SELECT across ten turns: the median observations contain 27 → 28 such statements, while their shared-facts requests decrease 60 → 59. Worker/thread, timestamp, SQL, and caller evidence attributes it to the unchanged session-row projection refresh path and selectAcpSessionRowsByKeys. Whole-workload +4 statements (+0.0418%) resolve to one extra unchanged five-statement row-facts read, offset by one fewer ACP shared-facts SELECT in the median observations. All relevant owner files are unchanged. First/warmed/whole duration ratios are 1.005/0.996/1.001. These are attributed timing variations below the turn noise floor; no extra pair is indicated.

Every warmed actor operation is unchanged (statements/requests): acceptInput 16/2, adoptRun 4/1, appendTranscriptEvent 23/2, completeTurn 6/1, deliverySettled 7/2, and read 4/4. Their combined delta is 0 statements and 0 requests. Database-only warmed requests are 81.9 [81.7–82.3] → 81.8 [81.8–81.8].

T1 inventory is unchanged: 39 → 39 in touched files and 612 → 612 overall; the explicitly classified incognito subset remains 11 → 11 (not a complete native-owner inventory). Native-owner retirement belongs to the final cutover. Dialect counts are unchanged: mechanical 6 → 6, design 50 → 50, engine-maintenance 0 → 0.

The 68-file test proof covers the memory storage, fork, history/facts, metadata, pending-input, Goal, and transcript owners; actor queue/release/worker/replica siblings and inactive acquisition; durable history, model context, media, entry, cut, and fork consumers; display sanitization; and SDK runtime/delta/preparation contracts. It includes every discovered literal mock consumer of the changed modules, including the Discord and Telegram shared-harness consumers. Individual pnpm test <file> --maxWorkers=1 wall seconds: fork 26.60, goals 3.14, history-facts 24.14, history 24.07, metadata 24.07, pending 3.22, storage 24.18, transcript 24.18, transcript-events worker 34.15. The worker-boundary suite includes compiled-worker setup; it verifies serialized error identity across the actual worker boundary. The integrated head additionally passes all 49 tests in the five affected actor/fixture files. CI results are recorded separately below.

Knip's script and production scans pass. Its full-tree scan reports the same seven existing exports on base and candidate in extensions/telegram/src/bot-native-commands.runtime.ts and src/agents/subagents/registry/subagent-registry.store.sqlite.ts; both file blobs are also identical on checked main d7e26112cce8d. Final base c400e2aff410 and head 3b492259ef5b scans reproduce the same seven findings. The candidate’s changed-file type-aware lint takes 32 seconds, scoped type graphs 59 seconds, export-collision scan 32 seconds, Madge 17 seconds, and SDK runtime guard 26 seconds.

Two Codex autoreview rounds completed on the preceding candidate. Fixed commit-stage authorization before memory installation and distinguished oversized exact-message results from missing IDs; the recorded negative controls fail with each fix removed and pass with it restored. Focused repair proof also caught two behavior bugs: visible-cursor construction inherited a field order that its canonical parser rejected, and transcript rewrite dropped appendMode: "side", allowing a side branch to change active history. Cursors now encode their fields in canonical order, and rewritten messages preserve side-branch mode. Recorded before/after controls reproduce both defects and pass with the fixes. Fixture repairs use the prepared message envelope and reacquire after reset closes the old handle; they do not weaken those contracts.

No durable schema, retention-policy, update, Doctor, plugin-loading, or service lifecycle changes. The SDK facade imports its existing raw-delta limit normalizer from the shared cursor owner.

SDK API diff acknowledged: d7fed80dfbab85913990f8e3d91344383406b54a959331fddb3dcb88cf333cfc (c400e2aff410 → 3b492259ef5b). All 157 affected exports are reachable-type changes: no entrypoint or public export is added or removed, and no top-level signature changes. The substantive addition is optional SessionActor.storage, a source-compatible memory capability using the existing actor lifetime and authority. Its storage types account for the expanded reachable declarations; the internal media helper moves unchanged to its shared owner.

Final-head CI run 38158196356 completed red. Security-fast, dependency review, and security-sensitive review passed. The UI type error has the exact baseline reproduction above. Native-incognito history, lifecycle, progress-card, and subagent-list failures report worker-capacity exhaustion or existing completion/maintenance assertions; production native ownership remains unchanged in this inactive layer. The history, progress-card, and subagent-list signatures also occur in retained PR1 evidence. Codex steering settlement reproduces on baseline c400e2aff410 with the same missing accepted callback and subsequent 180-second cleanup timeout. The HTTP streaming-disconnect case hit its one-second wait before the agent mock started; the exact case passes in isolation on both baseline (55.46 seconds) and final candidate (56.15 seconds). This remains an intermittent CI failure; no root-cause fix is claimed. The coordinator accepts these recorded CI dispositions under the relaxed landing rules; no proven product regression has been identified. No CI retry or additional autoreview was used to turn these failures green.

LOC at 3b492259 against integrated main c400e2aff: production/tooling +4488/−921 across 66 files; tests +2184/−1 across 9 files.

# Conflicts:
#	scripts/pr-lib/wrapper-components.txt
#	src/config/sessions/session-accessor.sqlite-replacement-state.ts
#	src/config/sessions/session-turn.kernel.ts
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts size: XL labels Oct 11, 2026
@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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds entry, transcript, history, and lifecycle operations to the inactive memory session actor and shares existing policies with durable storage.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The approved inactive scope has meaningful actor-boundary coverage and no additional established blocker; memory activation is unproven and CI remains red with recorded dispositions.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored inactive prerequisite is outside the ordinary contributor proof gate; actor-boundary tests exercise storage operations, while the reported SQL workload covers durable behavior and does not establish memory activation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: Maintainer direction approves the inactive storage prerequisite, its optional actor capability, and deferral of the two reader defects until activation.

Merge readiness

✅ Ready for maintainer review

Keep this maintainer-owned prerequisite open. Production incognito remains on its native owner, and the maintainer explicitly deferred the two prior reader findings to activation work; no additional blocking defect was established.

Priority: P2
Reviewed head: 3b492259ef5bab82f906d28518f6c1b67e6594ba

Before merge

None.

Findings

None.

Agent review details

How this fits together

Session actors sit between session callers and storage owners, accepting ordered operations and returning detached state and receipts; production incognito acquisition still selects the existing native owner.

flowchart TD
Callers[Session callers] --> Factory[Actor acquisition]
Factory --> Native[Production native incognito owner]
Factory --> Durable[Durable worker actor]
Factory --> Memory[Inactive memory actor]
Memory --> Queue[Shared operation queue]
Queue --> Receipts[Detached state and receipts]
Durable --> Receipts
Loading

Technical review

Best possible solution:

Complete the inactive storage prerequisite while retaining native production ownership, then repair the deferred reader contracts before memory activation.

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

This is an inactive refactor rather than a current production bug report; source confirms both deferred reader defects, and no runtime reproduction was performed.

Is this the best way to solve the issue?

Extending the existing actor and sharing pure policies fits the approved staged cutover, provided activation retains the deferred reader repairs.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Inactive memory backend and acquisition keeps the original intent (5bd4f88: The predecessor adds a memory backend while preserving native incognito ownership until a complete consumer cutover.)
  • Rewind, fork, and branch planning keeps the original intent (0acece4: Non-destructive history cuts rotate transcript identity, preserve retained history, and restore editor input.)
  • Active transcript accounting keeps the original intent (9988da6: Accounting reads execute through the history worker using one admitted projection snapshot.)
  • Model-context projection keeps the original intent (c09f136: Select the context window before hydrating payloads and omit storage-only metadata to bound memory use.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +3565, Tests +2183, Other +2. Total +5750 across 75 files. Added test files: 5.

View PR surface stats
Area Files Added Removed Net
Source 64 4485 920 +3565
Tests 9 2184 1 +2183
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 3 1 +2
Total 75 6672 922 +5750

Review metrics

Metric Value Why it matters
Production versus test LOC Production/tooling +4488/−921; tests +2184/−1 Growth supplies the explicitly approved inactive storage layer and actor-boundary coverage; retirement of the old production owners belongs to the final cutover.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a planned internal session-storage prerequisite with no immediate production incognito change.
  • merge-risk: 🚨 compatibility: Optional SessionActor.storage expands reachable SDK types; the maintainer explicitly acknowledges the source-compatible addition and unchanged top-level exports.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • 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 (1 earlier review cycle)
  • reviewed 2026-10-11T17:14:56.952Z sha 3b49225 :: blocked before merge. :: [P2] Reject stale versions before returning current-turn entries | [P2] Suppress anchors outside the admitted transcript prefix

Reviewed October 11, 2026, 1:57 PM ET / 17:57 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

The two ClawSweeper P2 findings are retained as follow-ups for the memory-backend activation work: preserve the captured-version contract for session.history.current-turn-entry, and restrict its returned anchor to the admitted transcript prefix alongside the event rows.

This PR leaves production incognito acquisition on the native owner. These inactive-reader contract findings do not demonstrate current production data loss or a security issue, so this prerequisite proceeds under the maintainer-authorized relaxed landing policy. The final static proof and CI failure dispositions are recorded in the PR body.

@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. 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. labels Oct 11, 2026
@steipete
steipete merged commit 268ff00 into main Oct 11, 2026
197 of 206 checks passed
@steipete
steipete deleted the dbasync/phasee2 branch October 11, 2026 17:59
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…aw#169227)

* refactor(sessions): add inactive memory backend to session actor

* test(sessions): align memory fixtures with actor types

* style(sessions): satisfy memory actor static checks

* feat(sessions): add inactive actor memory storage operations

* fix(tooling): include extracted session actor modules in wrapper

* fix(tooling): include memory history policies in wrapper

* fix(sessions): preserve memory history cursor and branch contracts

* fix(sessions): separate actor authority from storage contracts

* chore(sessions): shrink the extracted message-cut assertion baseline

* test(sessions): type memory fork and transcript fixtures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL 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