|
| 1 | +import type { DatabaseSync } from "node:sqlite"; |
| 2 | +import { readSqliteUserVersion } from "../infra/sqlite-user-version.js"; |
| 3 | +import { |
| 4 | + tableExists, |
| 5 | + tableHasColumn, |
| 6 | + tablePrimaryKeyColumns, |
| 7 | +} from "./openclaw-state-db-schema-helpers.js"; |
| 8 | + |
| 9 | +const AUDIT_EVENT_STATE_SCHEMA_VERSION = 2; |
| 10 | + |
| 11 | +const AUDIT_EVENT_LEGACY_COLUMNS = [ |
| 12 | + "sequence", |
| 13 | + "event_id", |
| 14 | + "source_id", |
| 15 | + "source_sequence", |
| 16 | + "occurred_at", |
| 17 | + "kind", |
| 18 | + "action", |
| 19 | + "status", |
| 20 | + "error_code", |
| 21 | + "actor_type", |
| 22 | + "actor_id", |
| 23 | + "agent_id", |
| 24 | + "session_key", |
| 25 | + "session_id", |
| 26 | + "run_id", |
| 27 | + "tool_call_id", |
| 28 | + "tool_name", |
| 29 | +] as const; |
| 30 | + |
| 31 | +const AUDIT_EVENT_V2_COLUMNS = [ |
| 32 | + "sequence", |
| 33 | + "event_id", |
| 34 | + "source_id", |
| 35 | + "schema_version", |
| 36 | + "source_sequence", |
| 37 | + "occurred_at", |
| 38 | + "kind", |
| 39 | + "action", |
| 40 | + "status", |
| 41 | + "error_code", |
| 42 | + "actor_type", |
| 43 | + "actor_id", |
| 44 | + "agent_id", |
| 45 | + "session_key", |
| 46 | + "session_id", |
| 47 | + "run_id", |
| 48 | + "tool_call_id", |
| 49 | + "tool_name", |
| 50 | + "direction", |
| 51 | + "channel", |
| 52 | + "conversation_kind", |
| 53 | + "message_outcome", |
| 54 | + "reason_code", |
| 55 | + "delivery_kind", |
| 56 | + "failure_stage", |
| 57 | + "duration_ms", |
| 58 | + "result_count", |
| 59 | + "account_ref", |
| 60 | + "conversation_ref", |
| 61 | + "message_ref", |
| 62 | + "target_ref", |
| 63 | +] as const; |
| 64 | + |
| 65 | +type TableColumnInfo = { |
| 66 | + name?: unknown; |
| 67 | + notnull?: unknown; |
| 68 | + pk?: unknown; |
| 69 | +}; |
| 70 | + |
| 71 | +function tableColumnInfo(db: DatabaseSync, tableName: string): TableColumnInfo[] { |
| 72 | + return db.prepare(`PRAGMA table_info(${tableName})`).all() as TableColumnInfo[]; |
| 73 | +} |
| 74 | + |
| 75 | +function tableHasExactColumns( |
| 76 | + db: DatabaseSync, |
| 77 | + tableName: string, |
| 78 | + expected: readonly string[], |
| 79 | +): boolean { |
| 80 | + const names = tableColumnInfo(db, tableName).map((column) => column.name); |
| 81 | + return names.length === expected.length && names.every((name, index) => name === expected[index]); |
| 82 | +} |
| 83 | + |
| 84 | +function tableHasRequiredColumns( |
| 85 | + db: DatabaseSync, |
| 86 | + tableName: string, |
| 87 | + required: readonly string[], |
| 88 | +): boolean { |
| 89 | + const columns = new Map(tableColumnInfo(db, tableName).map((column) => [column.name, column])); |
| 90 | + return required.every((name) => Number(columns.get(name)?.notnull ?? 0) === 1); |
| 91 | +} |
| 92 | + |
| 93 | +function tableSql(db: DatabaseSync, tableName: string): string | undefined { |
| 94 | + const row = db |
| 95 | + .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?") |
| 96 | + .get(tableName) as { sql?: unknown } | undefined; |
| 97 | + return typeof row?.sql === "string" ? row.sql : undefined; |
| 98 | +} |
| 99 | + |
| 100 | +function tableHasUniqueColumn(db: DatabaseSync, tableName: string, columnName: string): boolean { |
| 101 | + const indexes = db.prepare(`PRAGMA index_list(${tableName})`).all() as Array<{ |
| 102 | + name?: unknown; |
| 103 | + unique?: unknown; |
| 104 | + }>; |
| 105 | + return indexes.some((index) => { |
| 106 | + if (Number(index.unique ?? 0) !== 1 || typeof index.name !== "string") { |
| 107 | + return false; |
| 108 | + } |
| 109 | + const escaped = index.name.replaceAll("'", "''"); |
| 110 | + const columns = db.prepare(`PRAGMA index_info('${escaped}')`).all() as Array<{ |
| 111 | + name?: unknown; |
| 112 | + }>; |
| 113 | + return columns.length === 1 && columns[0]?.name === columnName; |
| 114 | + }); |
| 115 | +} |
| 116 | + |
| 117 | +function hasCanonicalAuditEventTable( |
| 118 | + db: DatabaseSync, |
| 119 | + expectedColumns: readonly string[], |
| 120 | + requiredColumns: readonly string[], |
| 121 | +): boolean { |
| 122 | + const sql = tableSql(db, "audit_events")?.toLowerCase(); |
| 123 | + return ( |
| 124 | + tableHasExactColumns(db, "audit_events", expectedColumns) && |
| 125 | + tablePrimaryKeyColumns(db, "audit_events").join(",") === "sequence" && |
| 126 | + tableHasRequiredColumns(db, "audit_events", requiredColumns) && |
| 127 | + typeof sql === "string" && |
| 128 | + /\bsequence\s+integer\s+primary\s+key\s+autoincrement\b/.test(sql) && |
| 129 | + tableHasUniqueColumn(db, "audit_events", "event_id") && |
| 130 | + tableHasUniqueColumn(db, "audit_events", "source_id") |
| 131 | + ); |
| 132 | +} |
| 133 | + |
| 134 | +function hasCanonicalAuditIdentityKeyTable(db: DatabaseSync): boolean { |
| 135 | + if (!tableExists(db, "audit_identity_keys")) { |
| 136 | + return false; |
| 137 | + } |
| 138 | + const sql = tableSql(db, "audit_identity_keys")?.toLowerCase(); |
| 139 | + return ( |
| 140 | + tableHasExactColumns(db, "audit_identity_keys", ["id", "key_id", "key", "created_at"]) && |
| 141 | + tablePrimaryKeyColumns(db, "audit_identity_keys").join(",") === "id" && |
| 142 | + tableHasRequiredColumns(db, "audit_identity_keys", ["id", "key_id", "key", "created_at"]) && |
| 143 | + typeof sql === "string" && |
| 144 | + /\bcheck\s*\(\s*id\s*=\s*1\s*\)/.test(sql) |
| 145 | + ); |
| 146 | +} |
| 147 | + |
| 148 | +export function hasCanonicalAuditEventsSchema(db: DatabaseSync): boolean { |
| 149 | + if (!tableExists(db, "audit_events")) { |
| 150 | + return ( |
| 151 | + readSqliteUserVersion(db) < AUDIT_EVENT_STATE_SCHEMA_VERSION && |
| 152 | + !tableExists(db, "audit_identity_keys") |
| 153 | + ); |
| 154 | + } |
| 155 | + return ( |
| 156 | + hasCanonicalAuditEventTable(db, AUDIT_EVENT_V2_COLUMNS, [ |
| 157 | + "event_id", |
| 158 | + "source_id", |
| 159 | + "schema_version", |
| 160 | + "source_sequence", |
| 161 | + "occurred_at", |
| 162 | + "kind", |
| 163 | + "action", |
| 164 | + "status", |
| 165 | + "actor_type", |
| 166 | + "actor_id", |
| 167 | + ]) && hasCanonicalAuditIdentityKeyTable(db) |
| 168 | + ); |
| 169 | +} |
| 170 | + |
| 171 | +export function canRepairLegacyAuditEventsSchema(db: DatabaseSync): boolean { |
| 172 | + // Our own transactional repair cannot leave audit_events_migration_new |
| 173 | + // behind, so an existing one is foreign data; fail closed rather than let |
| 174 | + // repair silently drop it. |
| 175 | + if ( |
| 176 | + !tableExists(db, "audit_events") || |
| 177 | + tableExists(db, "audit_events_migration_new") || |
| 178 | + tableHasColumn(db, "audit_events", "schema_version") |
| 179 | + ) { |
| 180 | + return false; |
| 181 | + } |
| 182 | + const identityTableIsSafe = |
| 183 | + !tableExists(db, "audit_identity_keys") || hasCanonicalAuditIdentityKeyTable(db); |
| 184 | + return ( |
| 185 | + identityTableIsSafe && |
| 186 | + hasCanonicalAuditEventTable(db, AUDIT_EVENT_LEGACY_COLUMNS, [ |
| 187 | + "event_id", |
| 188 | + "source_id", |
| 189 | + "source_sequence", |
| 190 | + "occurred_at", |
| 191 | + "kind", |
| 192 | + "action", |
| 193 | + "status", |
| 194 | + "actor_type", |
| 195 | + "actor_id", |
| 196 | + "agent_id", |
| 197 | + "run_id", |
| 198 | + ]) |
| 199 | + ); |
| 200 | +} |
| 201 | + |
| 202 | +function readAuditEventSequenceHighWater(db: DatabaseSync): number | undefined { |
| 203 | + if (!tableExists(db, "sqlite_sequence")) { |
| 204 | + return undefined; |
| 205 | + } |
| 206 | + const row = db |
| 207 | + .prepare("SELECT CAST(seq AS TEXT) AS seq FROM sqlite_sequence WHERE name = 'audit_events'") |
| 208 | + .get() as { seq?: unknown } | undefined; |
| 209 | + if (row === undefined) { |
| 210 | + return undefined; |
| 211 | + } |
| 212 | + if (typeof row.seq !== "string" || !/^\d+$/.test(row.seq)) { |
| 213 | + throw new Error("audit event sequence high-water mark is invalid"); |
| 214 | + } |
| 215 | + const sequence = BigInt(row.seq); |
| 216 | + if (sequence > BigInt(Number.MAX_SAFE_INTEGER)) { |
| 217 | + throw new Error("audit event sequence high-water mark exceeds the supported integer range"); |
| 218 | + } |
| 219 | + return Number(sequence); |
| 220 | +} |
| 221 | + |
| 222 | +function restoreAuditEventSequenceHighWater(db: DatabaseSync, sequence: number | undefined): void { |
| 223 | + if (sequence === undefined) { |
| 224 | + return; |
| 225 | + } |
| 226 | + db.prepare("DELETE FROM sqlite_sequence WHERE name = 'audit_events'").run(); |
| 227 | + db.prepare("INSERT INTO sqlite_sequence (name, seq) VALUES ('audit_events', ?)").run(sequence); |
| 228 | +} |
| 229 | + |
| 230 | +export function repairAuditEventsSchema(db: DatabaseSync): boolean { |
| 231 | + if (hasCanonicalAuditEventsSchema(db) || !canRepairLegacyAuditEventsSchema(db)) { |
| 232 | + return false; |
| 233 | + } |
| 234 | + const sequenceHighWater = readAuditEventSequenceHighWater(db); |
| 235 | + // This is the only shipped legacy shape. The surrounding doctor transaction |
| 236 | + // rolls back the table swap and sequence restore together on any bad row. |
| 237 | + // canRepairLegacyAuditEventsSchema refuses foreign audit_events_migration_new |
| 238 | + // tables, so this CREATE never clobbers existing data. |
| 239 | + db.exec(` |
| 240 | + CREATE TABLE audit_events_migration_new ( |
| 241 | + sequence INTEGER PRIMARY KEY AUTOINCREMENT, |
| 242 | + event_id TEXT NOT NULL UNIQUE, |
| 243 | + source_id TEXT NOT NULL UNIQUE, |
| 244 | + schema_version INTEGER NOT NULL DEFAULT 1, |
| 245 | + source_sequence INTEGER NOT NULL, |
| 246 | + occurred_at INTEGER NOT NULL, |
| 247 | + kind TEXT NOT NULL, |
| 248 | + action TEXT NOT NULL, |
| 249 | + status TEXT NOT NULL, |
| 250 | + error_code TEXT, |
| 251 | + actor_type TEXT NOT NULL, |
| 252 | + actor_id TEXT NOT NULL, |
| 253 | + agent_id TEXT, |
| 254 | + session_key TEXT, |
| 255 | + session_id TEXT, |
| 256 | + run_id TEXT, |
| 257 | + tool_call_id TEXT, |
| 258 | + tool_name TEXT, |
| 259 | + direction TEXT, |
| 260 | + channel TEXT, |
| 261 | + conversation_kind TEXT, |
| 262 | + message_outcome TEXT, |
| 263 | + reason_code TEXT, |
| 264 | + delivery_kind TEXT, |
| 265 | + failure_stage TEXT, |
| 266 | + duration_ms INTEGER, |
| 267 | + result_count INTEGER, |
| 268 | + account_ref TEXT, |
| 269 | + conversation_ref TEXT, |
| 270 | + message_ref TEXT, |
| 271 | + target_ref TEXT |
| 272 | + ); |
| 273 | + INSERT INTO audit_events_migration_new ( |
| 274 | + sequence, |
| 275 | + event_id, |
| 276 | + source_id, |
| 277 | + schema_version, |
| 278 | + source_sequence, |
| 279 | + occurred_at, |
| 280 | + kind, |
| 281 | + action, |
| 282 | + status, |
| 283 | + error_code, |
| 284 | + actor_type, |
| 285 | + actor_id, |
| 286 | + agent_id, |
| 287 | + session_key, |
| 288 | + session_id, |
| 289 | + run_id, |
| 290 | + tool_call_id, |
| 291 | + tool_name |
| 292 | + ) |
| 293 | + SELECT |
| 294 | + sequence, |
| 295 | + event_id, |
| 296 | + source_id, |
| 297 | + 1, |
| 298 | + source_sequence, |
| 299 | + occurred_at, |
| 300 | + kind, |
| 301 | + action, |
| 302 | + status, |
| 303 | + error_code, |
| 304 | + actor_type, |
| 305 | + actor_id, |
| 306 | + agent_id, |
| 307 | + session_key, |
| 308 | + session_id, |
| 309 | + run_id, |
| 310 | + tool_call_id, |
| 311 | + tool_name |
| 312 | + FROM audit_events; |
| 313 | + DROP TABLE audit_events; |
| 314 | + ALTER TABLE audit_events_migration_new RENAME TO audit_events; |
| 315 | + CREATE INDEX idx_audit_events_time |
| 316 | + ON audit_events(occurred_at DESC, sequence DESC); |
| 317 | + CREATE INDEX idx_audit_events_agent_sequence |
| 318 | + ON audit_events(agent_id, sequence DESC); |
| 319 | + CREATE INDEX idx_audit_events_session_sequence |
| 320 | + ON audit_events(session_key, sequence DESC); |
| 321 | + CREATE INDEX idx_audit_events_run_sequence |
| 322 | + ON audit_events(run_id, sequence DESC); |
| 323 | + CREATE INDEX idx_audit_events_kind_sequence |
| 324 | + ON audit_events(kind, sequence DESC); |
| 325 | + CREATE INDEX idx_audit_events_status_sequence |
| 326 | + ON audit_events(status, sequence DESC); |
| 327 | + CREATE INDEX idx_audit_events_channel_sequence |
| 328 | + ON audit_events(channel, sequence DESC); |
| 329 | + CREATE INDEX idx_audit_events_direction_sequence |
| 330 | + ON audit_events(direction, sequence DESC); |
| 331 | + CREATE TABLE IF NOT EXISTS audit_identity_keys ( |
| 332 | + id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1), |
| 333 | + key_id TEXT NOT NULL, |
| 334 | + key BLOB NOT NULL, |
| 335 | + created_at INTEGER NOT NULL |
| 336 | + ); |
| 337 | + `); |
| 338 | + // AUTOINCREMENT is part of the stable cursor contract. Rebuilding an empty |
| 339 | + // or sparsely retained table must not reuse a sequence already handed out. |
| 340 | + restoreAuditEventSequenceHighWater(db, sequenceHighWater); |
| 341 | + return true; |
| 342 | +} |
0 commit comments