Repository navigation
perf(sessions): reuse committed identity after entry patches - #136361
Conversation
…ntry patch patchSqliteSessionEntrySnapshot read and JSON-decoded the session row at preparation, again inside the write transaction to revalidate (then JSON.stringify-compared both copies), a third time inside writeSessionEntry for the canonical previous entry, and a fourth time after the write for the identity diff, running the participants projection query on every decode. A streamed reply turn issues about eleven such patches, so with a prod-shaped ~17 KB entry_json the session store took 29% of a saturated gateway main thread on 2026.8.2 against 3.6% for the JSON store on 2026.7.1-2. Snapshot rows now carry the raw persisted row they were decoded from. At commit, readUnchangedLifecycleTargetSnapshot re-reads the raw rows for exactly the keys the snapshot reader consults and reuses the prepared snapshot when every column is identical; any difference falls back to the original full re-decode and deep compare, so conflict detection is unchanged. writeSessionEntry accepts the canonical previous entry the commit already holds, and the post-commit identity map is built from the persisted entry, which is all the diff reads. No transaction boundary, writer ownership, publication fencing, schema or persisted representation changes. The revalidation reader lives in its own module because the entry store is at its max-lines limit. AI-assisted (Claude Code); measured, tested and reviewed by the author.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 5, 2026, 7:15 PM ET / 23:15 UTC. ClawSweeper reviewWhat this changesReuse the committed session entry for identity notifications, avoiding an extra saved-prompt decode, with regression coverage for both SQLite patch APIs. Merge readiness⛔ Blocked before merge - 1 item remains The optimization remains useful on current main, and the new standalone runtime evidence resolves the previous proof blocker. No actionable correctness or security defects were found. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw's session store persists session updates from runtime and plugin callers. After committing an update, it publishes identity changes to lifecycle observers and schedules maintenance. flowchart TD
A[Runtime or plugin update] --> B[Prepare session patch]
B --> C[Revalidate current session]
C --> D[Canonical SQLite writer]
D --> E[Reuse committed identity]
E --> F[Notify lifecycle observers]
F --> G[Schedule maintenance]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +1, Tests +61. Total +62 across 2 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Retain the canonical writer and its revalidation guarantees while eliminating the redundant identity-publication read. Do we have a high-confidence way to reproduce the issue? Yes: current main visibly rereads and decodes the entry after the canonical writer returns it, and the supplied baseline regression records forty decodes across ten updates. This review verified the source path without executing it. Is this the best way to solve the issue? Yes: reusing the writer's committed result removes the redundant work without weakening provenance checks, changing stored representations, or introducing a parallel cache. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3f946f93da4e. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
|
FYI: I independently implemented the same fix (decode once at preparation + raw-row fingerprint revalidation at the commit edge) in #136371 and closed it as a duplicate in favor of this earlier, author-owned PR. No action needed. |
Use the canonical writer result for identity publication instead of decoding saved prompts again. Preserve preparation, commit revalidation, the writer's provenance read, callback ordering, and all persisted representations. Both SQLite patch APIs now stay within three saved-prompt decodes per write; 65 owner and conformance tests pass. This narrows the original optimization without introducing raw-row cache state or changing callback contracts. Co-authored-by: Tran Quang <[email protected]>
|
The current head narrows this to the redundant identity-publication decode: the canonical writer already owns the session ID being published. It keeps full commit revalidation, fresh writer provenance, and deferred maintenance. The raw-row cache and its separate test file are removed; the replacement tests use synthetic session identifiers in the existing SQLite owner suite. Both prior rank-up items are addressed: current main is integrated with the maintenance path preserved, and the release-like model fixtures are gone. The actual SQLite regression fails on the pinned main with 40 saved-prompt decodes for ten writes, then passes the 30-decode bound after the repair. All 65 row/conformance tests pass. The updated PR body distinguishes this proof from a whole-Gateway throughput claim; exact-head CI is still pending. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
The requested standalone runtime proof is complete on the PR's exact source tree. This uses the built public plugin SDK in a separate production Node process with normal temporary configuration and a real SQLite store; no Vitest or production-owner mocks. The observer only records the runtime's existing identity notifications. The normal CLI then reads the persisted result in a fresh process. {
"sourceTree": "6ec1f7bc11405b764e7bd438f56fca27ce45878c",
"prHead": "7bacafe8faac1d693ed1d014ebc45523a4267b55",
"runtime": "built plugin SDK in standalone Node process; no Vitest or mocked owners",
"node": "v24.20.0",
"patches": 10,
"savedPromptBytes": 16407,
"fullSavedPromptDecodes": 30,
"identities": [
{
"kind": "replace",
"previous": "runtime-seed",
"current": "runtime-generation-0"
},
{
"kind": "replace",
"previous": "runtime-generation-0",
"current": "runtime-generation-1"
},
{
"kind": "replace",
"previous": "runtime-generation-1",
"current": "runtime-generation-2"
},
{
"kind": "replace",
"previous": "runtime-generation-2",
"current": "runtime-generation-3"
},
{
"kind": "replace",
"previous": "runtime-generation-3",
"current": "runtime-generation-4"
}
],
"persistedAndReopenedSessionId": "runtime-generation-4",
"savedPromptPreserved": true,
"schemaUnchanged": true,
"userVersion": 19,
"instrumentedElapsedMs": 28.220416000000114,
"processRssBytes": 403259392,
"freshCli": {
"count": 1,
"key": "agent:main:runtime-identity-proof",
"sessionId": "runtime-generation-4"
}
}The schema comparison and fresh reads also confirm the data-model flag is not applicable to this change: no schema, row binding, serializer, or persisted representation changes. The native SDK/CLI proof complements the 65 passing owner/conformance tests and green exact-head CI. Standalone runtime probe (synthetic data only)After import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { pathToFileURL } from 'node:url';
const root = process.cwd();
const sdk = await import(pathToFileURL(path.join(root, 'dist/plugin-sdk/session-store-runtime.js')).href);
const sessionKey = 'agent:main:runtime-identity-proof';
const prompt = 'runtime-identity-proof:' + 'x'.repeat(16_384);
const storePath = path.join(process.env.OPENCLAW_STATE_DIR, 'agents/main/agent/openclaw-agent.sqlite');
const scope = { agentId: 'main', sessionKey, storePath };
const stamp = Date.now();
await sdk.upsertSessionEntry({ ...scope, entry: {
sessionId: 'runtime-seed', updatedAt: stamp, createdVia: 'operator', createdAt: stamp,
label: 'Runtime identity proof', skillsSnapshot: { prompt, skills: [] },
} });
const inspect = () => {
const db = new DatabaseSync(storePath, { readOnly: true });
try {
const row = db.prepare('SELECT current_session_id, entry_json FROM session_nodes WHERE session_key = ?').get(sessionKey);
const schema = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name").all();
return {
row,
schemaSha256: createHash('sha256').update(JSON.stringify(schema)).digest('hex'),
userVersion: db.prepare('PRAGMA user_version').get().user_version,
};
} finally { db.close(); }
};
const before = inspect();
const identities = [];
const listeners = globalThis[Symbol.for('openclaw.sessionIdentityMutationListeners')];
assert(listeners instanceof Set, 'built runtime identity observer registry exists');
const observe = event => {
if (event.current?.sessionKeys.includes(sessionKey)) {
identities.push({ kind: event.kind, previous: event.previous.sessionId, current: event.current.sessionId });
}
};
listeners.add(observe);
const realParse = JSON.parse;
let decodes = 0;
JSON.parse = function(text, reviver) {
const value = realParse(text, reviver);
if (value && value.skillsSnapshot?.prompt === prompt && typeof value.sessionId === 'string') decodes++;
return value;
};
const started = performance.now();
try {
for (let index = 0; index < 10; index++) {
const sessionId = `runtime-generation-${Math.floor(index / 2)}`;
const result = await sdk.patchSessionEntry({ ...scope, skipMaintenance: true,
update: entry => {
assert.equal(entry.skillsSnapshot.prompt, prompt);
return { sessionId, updatedAt: stamp + index + 1 };
},
});
assert.equal(result.sessionId, sessionId);
assert.equal(result.skillsSnapshot.prompt, prompt);
}
} finally {
JSON.parse = realParse;
listeners.delete(observe);
}
const elapsedMs = performance.now() - started;
assert.equal(decodes, 30);
assert.deepEqual(identities.map(x => x.current), Array.from({ length: 5 }, (_, n) => `runtime-generation-${n}`));
assert(identities.every(x => x.kind === 'replace'));
const after = inspect();
assert.equal(after.schemaSha256, before.schemaSha256);
assert.equal(after.userVersion, before.userVersion);
assert.equal(after.row.current_session_id, 'runtime-generation-4');
assert.equal(realParse(after.row.entry_json).skillsSnapshot.prompt, prompt);
const reopened = sdk.getSessionEntry(scope);
assert.equal(reopened.sessionId, 'runtime-generation-4');
assert.equal(reopened.skillsSnapshot.prompt, prompt);
console.log(JSON.stringify({
runtime: 'built plugin SDK in standalone Node process; no Vitest or mocked owners',
node: process.version, patches: 10, savedPromptBytes: Buffer.byteLength(prompt),
fullSavedPromptDecodes: decodes, identities, persistedAndReopenedSessionId: reopened.sessionId,
savedPromptPreserved: true, schemaUnchanged: true, userVersion: after.userVersion,
instrumentedElapsedMs: elapsedMs, processRssBytes: process.memoryUsage().rss,
}, null, 2)); |
|
Merged via squash.
|
* origin/main: (95 commits) perf(build): avoid unrelated gateway artifact scans (#127757) fix(update): deliver terminal progress after long updates (#139289) fix(ui): show session hover cards for local chat URLs (#139384) perf(ui): reuse unchanged transcript key snapshots (#139400) fix(ui): make subagent sessions view-only (#139381) fix: open agent state on SQLite builds without extensions (#139487) perf(skills): detach cached metadata from source strings (#139478) fix(ui): show primary user in multi-agent profile hero (#136736) perf(sessions): stop decoding the session row four times per SQLite entry patch (#136361) refactor(exec): share package-manager option scans (#139482) fix(ci): authorize frozen mobile release candidates (#139441) fix: avoid session deletion slowdown in large session stores (#139467) perf(gateway): reuse node invocation idle timers (#139354) fix(auth): preserve selected profiles across plugin scopes (#139413) fix(discord): retain voice input until transcription completes (#139484) fix(agents): name Gateway storage failures in run-failure copy (#139409) fix: keep subagent checks responsive in large session stores (#139450) fix(memory): index notes when optional embeddings cannot start (#139463) fix: refresh pending approvals when reopening chat (#139457) fix(tooling): preserve Git hook choices during install (#139461) ...
…ntry patch (openclaw#136361) patchSqliteSessionEntrySnapshot read and JSON-decoded the session row at preparation, again inside the write transaction to revalidate (then JSON.stringify-compared both copies), a third time inside writeSessionEntry for the canonical previous entry, and a fourth time after the write for the identity diff, running the participants projection query on every decode. A streamed reply turn issues about eleven such patches, so with a prod-shaped ~17 KB entry_json the session store took 29% of a saturated gateway main thread on 2026.8.2 against 3.6% for the JSON store on 2026.7.1-2. Snapshot rows now carry the raw persisted row they were decoded from. At commit, readUnchangedLifecycleTargetSnapshot re-reads the raw rows for exactly the keys the snapshot reader consults and reuses the prepared snapshot when every column is identical; any difference falls back to the original full re-decode and deep compare, so conflict detection is unchanged. writeSessionEntry accepts the canonical previous entry the commit already holds, and the post-commit identity map is built from the persisted entry, which is all the diff reads. No transaction boundary, writer ownership, publication fencing, schema or persisted representation changes. The revalidation reader lives in its own module because the entry store is at its max-lines limit. AI-assisted (Claude Code); measured, tested and reviewed by the author. Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Tran Quang <[email protected]>
Related: #136338, #119720, #136283
Session entry patches decoded the entire saved entry again after the canonical writer had already returned the committed value. Identity notifications only consume the session ID and canonical key, so they can reuse that result. This removes one full saved-prompt decode and participant projection from each successful patch.
The final change keeps preparation, commit revalidation, the writer's fresh provenance check, and callback ordering. It replaces the proposed raw-row snapshot cache with a direct reuse of the committed identity. Schema, persisted representations, writer ownership, and public behavior stay unchanged. Production delta: +2/-1; tests: +62/-1.
Validation:
74b764e81d4b5ba62ffb7441ebe0d4ba85909388, ten patches produce 40 full-payload JSON decodes and fail the 30-decode budget. The repair passes that budget, retains the complete prompt, and emits exactly five identity changes across the ten writes.7bacafe8faac1d693ed1d014ebc45523a4267b55.Standalone built-runtime proof now also passes. A normal sourcePerformance build used the complete source tree
6ec1f7bc11405b764e7bd438f56fca27ce45878c, identical to this PR head. A separate Node 24.20 process loaded normal temporary configuration and the built public session-store SDK, with no Vitest or mocked production owners. Ten SDK updates produced exactly 30 full saved-prompt decodes and five correct identity replacements; all 16,407 prompt bytes survived. SQLite schema hashes stayed equal atuser_version19, and a reopened SDK read returned the final identity and prompt. The instrumented update sequence took 28.2 ms; this is not a whole-Gateway throughput measurement.A separate real
pnpm --silent openclaw sessions --agent main --json --limit allinvocation read the same store and returned count 1, keyagent:main:runtime-identity-proof, and final sessionIdruntime-generation-4. The data-model classifier is not applicable: row bindings, serialization, schemas, and stored representations are unchanged; only the in-memory identity map after the write is reused.This establishes reduced per-patch decoding work; it does not establish a total Gateway throughput improvement or resolve the broader issues above.
Thanks @quangtran88 for identifying the repeated decode and contributing the original PR.