|
1 | 1 | /** Read-only transcript detection; positive repairs retain exact snapshots. */ |
2 | | -import type { DatabaseSync } from "node:sqlite"; |
| 2 | +import type { DatabaseSync, StatementSync } from "node:sqlite"; |
3 | 3 | import { isRecord } from "@openclaw/normalization-core/record-coerce"; |
4 | 4 | import type { SqliteTranscriptStorageRow } from "../config/sessions/session-accessor.sqlite-read.js"; |
5 | 5 | import { tableExists } from "../state/openclaw-state-db-schema-helpers.js"; |
6 | 6 |
|
7 | | -// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns). |
8 | | -// Queries transcript_events table (schema-stable) instead of sessions table. |
9 | | -// Returns read-only view of all distinct session IDs with events. |
10 | | -export function readOnlySqliteTranscriptSessionIds(database: DatabaseSync): string[] { |
11 | | - if (!tableExists(database, "transcript_events")) { |
12 | | - return []; |
13 | | - } |
14 | | - const rows = database |
15 | | - .prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC") |
16 | | - .all(); |
17 | | - return rows.flatMap((row) => (typeof row.session_id === "string" ? [row.session_id] : [])); |
18 | | -} |
19 | | - |
20 | | -function iterateTranscriptRows(database: DatabaseSync, sessionId: string, firstRowOnly = false) { |
21 | | - return database |
22 | | - .prepare( |
23 | | - `SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC${firstRowOnly ? " LIMIT 1" : ""}`, |
24 | | - ) |
25 | | - .iterate(sessionId); |
26 | | -} |
| 7 | +const LABEL_ROWS_SQL = |
| 8 | + "SELECT event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC"; |
27 | 9 |
|
28 | | -// Read-only transcript snapshot reader for dry-run detection phase. |
29 | | -// Avoids opening writable database lifecycle (lease/WAL/schema-ensure). |
30 | | -// Returns rows only; migration parses per-row during repair. |
31 | 10 | type ReadOnlyTranscriptSnapshot = |
32 | 11 | | { |
33 | 12 | ok: true; |
34 | 13 | rows: Array<{ eventJson: string; seq: number }>; |
35 | 14 | } |
36 | 15 | | { ok: false; error: unknown }; |
37 | 16 |
|
38 | | -export function readOnlySqliteTranscriptRepairSnapshot( |
39 | | - database: DatabaseSync, |
40 | | - sessionId: string, |
41 | | - needsRepair: (event: unknown) => boolean, |
42 | | -): ReadOnlyTranscriptSnapshot { |
43 | | - try { |
44 | | - // Unchanged histories retain one payload. Re-read positive candidates in full so |
45 | | - // malformed siblings and exact-snapshot guards still govern the surgical repair. |
46 | | - for (const row of iterateTranscriptRows(database, sessionId)) { |
47 | | - if (typeof row.event_json !== "string" || typeof row.seq !== "number") { |
48 | | - continue; |
| 17 | +export class ReadOnlySqliteTranscriptReader { |
| 18 | + private labelDetection?: StatementSync; |
| 19 | + private labelSnapshot?: StatementSync; |
| 20 | + private firstHeaderRow?: StatementSync; |
| 21 | + private headerSnapshot?: StatementSync; |
| 22 | + private sessionKey?: StatementSync; |
| 23 | + |
| 24 | + // Statements belong to one read-only pass, but no cursor survives a snapshot call. |
| 25 | + // Prepare lazily so older databases need only the schema used by that detection path. |
| 26 | + constructor(private readonly database: DatabaseSync) {} |
| 27 | + |
| 28 | + sessionIds(): string[] { |
| 29 | + if (!tableExists(this.database, "transcript_events")) { |
| 30 | + return []; |
| 31 | + } |
| 32 | + // Enumerate the schema-stable events table, not post-ship sessions columns. |
| 33 | + // Materialize IDs so enumeration cannot hold a read transaction across repairs. |
| 34 | + const rows = this.database |
| 35 | + .prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC") |
| 36 | + .all(); |
| 37 | + return rows.flatMap((row) => (typeof row.session_id === "string" ? [row.session_id] : [])); |
| 38 | + } |
| 39 | + |
| 40 | + repairSnapshot( |
| 41 | + sessionId: string, |
| 42 | + needsRepair: (event: unknown) => boolean, |
| 43 | + ): ReadOnlyTranscriptSnapshot { |
| 44 | + let iterator: ReturnType<StatementSync["iterate"]> | undefined; |
| 45 | + try { |
| 46 | + // Unchanged histories retain one payload. Re-read positive candidates in full so |
| 47 | + // malformed siblings and exact-snapshot guards still govern the surgical repair. |
| 48 | + this.labelDetection ??= this.database.prepare(LABEL_ROWS_SQL); |
| 49 | + iterator = this.labelDetection.iterate(sessionId); |
| 50 | + for (const row of iterator) { |
| 51 | + if (typeof row.event_json !== "string" || typeof row.seq !== "number") { |
| 52 | + continue; |
| 53 | + } |
| 54 | + let event: unknown; |
| 55 | + try { |
| 56 | + event = JSON.parse(row.event_json); |
| 57 | + } catch { |
| 58 | + continue; |
| 59 | + } |
| 60 | + if (!needsRepair(event)) { |
| 61 | + continue; |
| 62 | + } |
| 63 | + const rows: Array<{ eventJson: string; seq: number }> = []; |
| 64 | + // Detection is still iterating: its nested exact snapshot needs a distinct statement. |
| 65 | + this.labelSnapshot ??= this.database.prepare(LABEL_ROWS_SQL); |
| 66 | + iterator = this.labelSnapshot.iterate(sessionId); |
| 67 | + for (const candidate of iterator) { |
| 68 | + if (typeof candidate.event_json === "string" && typeof candidate.seq === "number") { |
| 69 | + rows.push({ eventJson: candidate.event_json, seq: candidate.seq }); |
| 70 | + } |
| 71 | + } |
| 72 | + return { ok: true, rows }; |
49 | 73 | } |
50 | | - let event: unknown; |
| 74 | + return { ok: true, rows: [] }; |
| 75 | + } catch (error) { |
| 76 | + // A throwing next() does not close its iterator; reset before the next session. |
51 | 77 | try { |
52 | | - event = JSON.parse(row.event_json); |
| 78 | + iterator?.return?.(); |
53 | 79 | } catch { |
54 | | - continue; |
55 | | - } |
56 | | - if (!needsRepair(event)) { |
57 | | - continue; |
58 | | - } |
59 | | - const rows: Array<{ eventJson: string; seq: number }> = []; |
60 | | - for (const candidate of iterateTranscriptRows(database, sessionId)) { |
61 | | - if (typeof candidate.event_json === "string" && typeof candidate.seq === "number") { |
62 | | - rows.push({ eventJson: candidate.event_json, seq: candidate.seq }); |
63 | | - } |
| 80 | + // Preserve the original read error if cleanup fails. |
64 | 81 | } |
65 | | - return { ok: true, rows }; |
| 82 | + return { ok: false, error }; |
66 | 83 | } |
67 | | - return { ok: true, rows: [] }; |
68 | | - } catch (error) { |
69 | | - return { ok: false, error }; |
70 | 84 | } |
71 | | -} |
72 | 85 |
|
73 | | -/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */ |
74 | | -export function readOnlySqliteHeaderlessTranscriptSnapshot( |
75 | | - database: DatabaseSync, |
76 | | - sessionId: string, |
77 | | -): |
78 | | - | { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string } |
79 | | - | { ok: false; error: unknown } { |
80 | | - try { |
81 | | - // Headers can live at nonzero seq. A current header needs no whole-history read; |
82 | | - // possible headerless repairs still take and validate the complete exact snapshot. |
83 | | - for (const row of iterateTranscriptRows(database, sessionId, true)) { |
84 | | - if (typeof row.event_json !== "string") { |
85 | | - break; |
| 86 | + /** Reads exact row metadata for a guarded transcript replacement without opening a writer. */ |
| 87 | + headerlessSnapshot( |
| 88 | + sessionId: string, |
| 89 | + ): |
| 90 | + | { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string } |
| 91 | + | { ok: false; error: unknown } { |
| 92 | + let iterator: ReturnType<StatementSync["iterate"]> | undefined; |
| 93 | + try { |
| 94 | + // Headers can live at nonzero seq. A current header needs no whole-history read; |
| 95 | + // possible headerless repairs still take and validate the complete exact snapshot. |
| 96 | + this.firstHeaderRow ??= this.database.prepare( |
| 97 | + "SELECT event_json FROM transcript_events WHERE session_id = ? ORDER BY seq ASC LIMIT 1", |
| 98 | + ); |
| 99 | + const firstRow = this.firstHeaderRow.get(sessionId); |
| 100 | + if (typeof firstRow?.event_json === "string") { |
| 101 | + let first: unknown; |
| 102 | + try { |
| 103 | + first = JSON.parse(firstRow.event_json); |
| 104 | + } catch { |
| 105 | + return { ok: true, rows: [] }; |
| 106 | + } |
| 107 | + if (!isRecord(first) || first.type === "session") { |
| 108 | + return { ok: true, rows: [] }; |
| 109 | + } |
| 110 | + } |
| 111 | + this.sessionKey ??= this.database.prepare( |
| 112 | + "SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1", |
| 113 | + ); |
| 114 | + const sessionKeyRow = this.sessionKey.get(sessionId); |
| 115 | + const storageRows: SqliteTranscriptStorageRow[] = []; |
| 116 | + this.headerSnapshot ??= this.database.prepare( |
| 117 | + "SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC", |
| 118 | + ); |
| 119 | + iterator = this.headerSnapshot.iterate(sessionId); |
| 120 | + for (const row of iterator) { |
| 121 | + if ( |
| 122 | + typeof row.created_at !== "number" || |
| 123 | + typeof row.event_json !== "string" || |
| 124 | + typeof row.seq !== "number" |
| 125 | + ) { |
| 126 | + return { |
| 127 | + ok: false, |
| 128 | + error: new Error(`Invalid transcript row metadata for session ${sessionId}`), |
| 129 | + }; |
| 130 | + } |
| 131 | + storageRows.push({ |
| 132 | + createdAt: row.created_at, |
| 133 | + eventJson: row.event_json, |
| 134 | + seq: row.seq, |
| 135 | + }); |
86 | 136 | } |
87 | | - let first: unknown; |
| 137 | + return { |
| 138 | + ok: true, |
| 139 | + rows: storageRows, |
| 140 | + ...(typeof sessionKeyRow?.session_key === "string" |
| 141 | + ? { sessionKey: sessionKeyRow.session_key } |
| 142 | + : {}), |
| 143 | + }; |
| 144 | + } catch (error) { |
| 145 | + // A throwing next() does not close its iterator; reset before the next session. |
88 | 146 | try { |
89 | | - first = JSON.parse(row.event_json); |
| 147 | + iterator?.return?.(); |
90 | 148 | } catch { |
91 | | - return { ok: true, rows: [] }; |
92 | | - } |
93 | | - if (!isRecord(first) || first.type === "session") { |
94 | | - return { ok: true, rows: [] }; |
95 | | - } |
96 | | - } |
97 | | - const sessionKeyRow = database |
98 | | - .prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1") |
99 | | - .get(sessionId); |
100 | | - const storageRows: SqliteTranscriptStorageRow[] = []; |
101 | | - for (const row of iterateTranscriptRows(database, sessionId)) { |
102 | | - if ( |
103 | | - typeof row.created_at !== "number" || |
104 | | - typeof row.event_json !== "string" || |
105 | | - typeof row.seq !== "number" |
106 | | - ) { |
107 | | - return { |
108 | | - ok: false, |
109 | | - error: new Error(`Invalid transcript row metadata for session ${sessionId}`), |
110 | | - }; |
| 149 | + // Preserve the original read error if cleanup fails. |
111 | 150 | } |
112 | | - storageRows.push({ |
113 | | - createdAt: row.created_at, |
114 | | - eventJson: row.event_json, |
115 | | - seq: row.seq, |
116 | | - }); |
| 151 | + return { ok: false, error }; |
117 | 152 | } |
118 | | - return { |
119 | | - ok: true, |
120 | | - rows: storageRows, |
121 | | - ...(typeof sessionKeyRow?.session_key === "string" |
122 | | - ? { sessionKey: sessionKeyRow.session_key } |
123 | | - : {}), |
124 | | - }; |
125 | | - } catch (error) { |
126 | | - return { ok: false, error }; |
127 | 153 | } |
128 | 154 | } |
0 commit comments