Skip to content

Commit 509a5f0

Browse files
authored
fix(sqlite): reject schema data loss during upgrades (#113473)
* fix(sqlite): reject schema data loss during upgrades * test(macos): align native state schema boundary
1 parent c780bfb commit 509a5f0

24 files changed

Lines changed: 629 additions & 127 deletions

‎apps/macos/Tests/OpenClawIPCTests/PortGuardianRecordStoreTests.swift‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ struct PortGuardianRecordStoreTests {
532532
let fixture = try Self.fixture()
533533
defer { fixture.cleanup() }
534534

535-
for version in [4, 5] {
535+
for version in [4, 5, 6] {
536536
let databaseURL = fixture.root.appendingPathComponent("supported-v\(version).sqlite")
537537
try Self.seedVersionedPortGuardianDatabase(databaseURL, schemaVersion: version)
538538
let store = try PortGuardianRecordStore(databaseURL: databaseURL)
@@ -544,7 +544,7 @@ struct PortGuardianRecordStoreTests {
544544
#expect(try store.records() == [record])
545545
}
546546

547-
for version in [6, 99] {
547+
for version in [7, 99] {
548548
let databaseURL = fixture.root.appendingPathComponent("newer-v\(version).sqlite")
549549
try Self.seedVersionedPortGuardianDatabase(databaseURL, schemaVersion: version)
550550
#expect(throws: PortGuardianStoreError.self) {
@@ -592,7 +592,7 @@ struct PortGuardianRecordStoreTests {
592592
try store.upsert(existing)
593593
try JSONEncoder().encode([existing]).write(to: fixture.legacyURL, options: [.atomic])
594594

595-
try Self.execute(fixture.databaseURL, "PRAGMA user_version = 6")
595+
try Self.execute(fixture.databaseURL, "PRAGMA user_version = 7")
596596

597597
#expect(throws: PortGuardianStoreError.self) {
598598
try store.upsert(Self.record(pid: 4243, port: 18790, timestamp: 43))

‎apps/shared/OpenClawKit/Sources/OpenClawNativeState/OpenClawNativeStateSQLite.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public enum OpenClawNativeStateSQLiteValueType: Equatable, Sendable {
3535
/// One recursive connection lock serializes transactions and statement access.
3636
public final class OpenClawNativeStateSQLite: @unchecked Sendable {
3737
// Keep aligned with OPENCLAW_STATE_SCHEMA_VERSION. Native clients never upgrade this database.
38-
private static let maximumSupportedSchemaVersion: Int64 = 5
38+
private static let maximumSupportedSchemaVersion: Int64 = 6
3939
private static let defaultBusyTimeoutMilliseconds: Int32 = 5000
4040

4141
private struct SchemaObject: Hashable {

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
"version": "2026.7.2",
44
"openclaw": {
55
"schemaVersions": {
6-
"state": 5,
7-
"agent": 14
6+
"state": 6,
7+
"agent": 15
88
}
99
},
1010
"description": "Multi-channel AI gateway with extensible messaging integrations",

‎src/agents/worktrees/registry.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,11 @@ describe("managed worktree registry", () => {
130130
closeOpenClawStateDatabaseForTest();
131131
const { DatabaseSync } = requireNodeSqlite();
132132
const legacy = new DatabaseSync(databasePath);
133-
legacy.exec("ALTER TABLE worktrees DROP COLUMN provisioned_paths_json");
133+
legacy.exec(`
134+
ALTER TABLE worktrees DROP COLUMN provisioned_paths_json;
135+
PRAGMA user_version = 5;
136+
UPDATE schema_meta SET schema_version = 5 WHERE meta_key = 'primary';
137+
`);
134138
legacy.close();
135139

136140
expect(getRegistryWorktreeProvisionedPaths(env, "missing")).toBeUndefined();

‎src/boards/board-store.parity.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,7 @@ describe("SqliteBoardStore persistence", () => {
510510
expect(store.readWidgetMcpApp(sessionKey, "legacy-app")).toBeUndefined();
511511
});
512512

513-
it("lazily creates board tables for an existing v14 database", () => {
513+
it("migrates board tables into an existing v14 database", () => {
514514
const stateDir = tempDirs.make("openclaw-board-lazy-schema-");
515515
const env = { OPENCLAW_STATE_DIR: stateDir };
516516
const sessionKey = "agent:main:board";
@@ -535,13 +535,12 @@ describe("SqliteBoardStore persistence", () => {
535535
reopened.db
536536
.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'board_tabs'")
537537
.get(),
538-
).toBeUndefined();
538+
).toEqual({ name: "board_tabs" });
539539

540540
const store = new SqliteBoardStore({
541541
resolveSession: () => ({ agentId: "main", sessionKey }),
542542
env,
543543
});
544-
// Reads before any write must see "no boards", not "no such table".
545544
expect(store.getSnapshot(sessionKey)).toMatchObject({ revision: 0, tabs: [], widgets: [] });
546545
expect(store.readWidgetHtml(sessionKey, "status")).toBeUndefined();
547546
expect(store.listSessionsWithBoards()).toEqual([]);
@@ -579,7 +578,7 @@ describe("SqliteBoardStore persistence", () => {
579578
).toEqual({ name: "idx_agent_board_widgets_tab_position" });
580579
});
581580

582-
it("upgrades the unreleased v13 board constraint before storing plugin widgets", () => {
581+
it("upgrades the v14 board constraint before storing plugin widgets", () => {
583582
const stateDir = tempDirs.make("openclaw-board-plugin-kind-schema-");
584583
const env = { OPENCLAW_STATE_DIR: stateDir };
585584
const sessionKey = "agent:main:board";
@@ -622,6 +621,8 @@ describe("SqliteBoardStore persistence", () => {
622621
ON board_widgets(session_key, tab_id, position);
623622
COMMIT;
624623
PRAGMA foreign_keys = ON;
624+
PRAGMA user_version = 14;
625+
UPDATE schema_meta SET schema_version = 14 WHERE meta_key = 'primary';
625626
`);
626627
closeOpenClawAgentDatabasesForTest();
627628

‎src/config/sessions/session-sharing-store.test.ts‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
afterEach(() => closeOpenClawAgentDatabasesForTest());
2121

2222
describe("session sharing store", () => {
23-
it("lazily ensures the additive membership table and keeps deterministic rows", async () => {
23+
it("keeps deterministic membership rows", async () => {
2424
await withTempDir({ prefix: "openclaw-session-sharing-" }, async (dir) => {
2525
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };
2626
const scope = { agentId: "main", env, sessionKey: "agent:main:main" };
@@ -30,13 +30,6 @@ describe("session sharing store", () => {
3030
visibility: "shared",
3131
});
3232
expect(loadSessionEntry(scope)?.visibility).toBe("shared");
33-
const database = openOpenClawAgentDatabase({ agentId: "main", env });
34-
database.db.exec("DROP TABLE session_members;");
35-
expect(
36-
database.db
37-
.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'session_members'")
38-
.get(),
39-
).toBeUndefined();
4033

4134
expect(listSessionMembers(scope)).toEqual([]);
4235
expect(
@@ -67,6 +60,23 @@ describe("session sharing store", () => {
6760
});
6861
});
6962

63+
it("does not recreate a missing canonical membership table", async () => {
64+
await withTempDir({ prefix: "openclaw-session-sharing-missing-" }, async (dir) => {
65+
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };
66+
const scope = { agentId: "main", env, sessionKey: "agent:main:main" };
67+
await upsertSessionEntry(scope, { sessionId: "session-main", updatedAt: 1 });
68+
const database = openOpenClawAgentDatabase({ agentId: "main", env });
69+
database.db.exec("DROP TABLE session_members;");
70+
71+
expect(() => listSessionMembers(scope)).toThrow(/no such table: session_members/);
72+
expect(
73+
database.db
74+
.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'session_members'")
75+
.get(),
76+
).toBeUndefined();
77+
});
78+
});
79+
7080
it("refuses member writes whose expected session instance no longer matches", async () => {
7181
await withTempDir({ prefix: "openclaw-session-sharing-instance-" }, async (dir) => {
7282
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };

‎src/config/sessions/session-sharing-store.ts‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import type { DatabaseSync } from "node:sqlite";
21
import {
32
executeSqliteQuerySync,
43
executeSqliteQueryTakeFirstSync,
@@ -11,7 +10,6 @@ import {
1110
type OpenClawAgentDatabase,
1211
type OpenClawAgentDatabaseOptions,
1312
} from "../../state/openclaw-agent-db.js";
14-
import { ensureOpenClawAgentSessionSharingSchemaInTransaction } from "../../state/openclaw-agent-session-sharing-schema.js";
1513
import type { SessionAccessScope } from "./session-accessor.sqlite-contract.js";
1614
import { resolveSqliteScope, toDatabaseOptions } from "./session-accessor.sqlite-scope.js";
1715

@@ -23,31 +21,18 @@ type SessionMember = {
2321
addedAt: number;
2422
};
2523

26-
const ensuredDatabases = new WeakSet<DatabaseSync>();
2724
const SESSION_MEMBERSHIP_QUERY_CHUNK_SIZE = 400;
2825

2926
function resolveDatabaseOptions(scope: SessionAccessScope): OpenClawAgentDatabaseOptions {
3027
return toDatabaseOptions(resolveSqliteScope(scope));
3128
}
3229

33-
function ensureSessionSharingSchema(options: OpenClawAgentDatabaseOptions): OpenClawAgentDatabase {
34-
const database = openOpenClawAgentDatabase(options);
35-
if (ensuredDatabases.has(database.db)) {
36-
return database;
37-
}
38-
runOpenClawAgentWriteTransaction((transactionDatabase) => {
39-
ensureOpenClawAgentSessionSharingSchemaInTransaction(transactionDatabase.db);
40-
}, options);
41-
ensuredDatabases.add(database.db);
42-
return database;
43-
}
44-
4530
function getSessionMemberKysely(database: OpenClawAgentDatabase) {
4631
return getNodeSqliteKysely<SessionMemberDatabase>(database.db);
4732
}
4833

4934
export function listSessionMembers(scope: SessionAccessScope): SessionMember[] {
50-
const database = ensureSessionSharingSchema(resolveDatabaseOptions(scope));
35+
const database = openOpenClawAgentDatabase(resolveDatabaseOptions(scope));
5136
const db = getSessionMemberKysely(database);
5237
return executeSqliteQuerySync(
5338
database.db,
@@ -73,7 +58,7 @@ export function listSessionMembershipKeys(
7358
if (!normalizedIdentityId || normalizedSessionKeys.length === 0) {
7459
return new Set();
7560
}
76-
const database = ensureSessionSharingSchema(resolveDatabaseOptions(scope));
61+
const database = openOpenClawAgentDatabase(resolveDatabaseOptions(scope));
7762
const db = getSessionMemberKysely(database);
7863
const memberships = new Set<string>();
7964
for (
@@ -102,7 +87,7 @@ export function isSessionMember(scope: SessionAccessScope, identityId: string):
10287
if (!normalizedIdentityId) {
10388
return false;
10489
}
105-
const database = ensureSessionSharingSchema(resolveDatabaseOptions(scope));
90+
const database = openOpenClawAgentDatabase(resolveDatabaseOptions(scope));
10691
const db = getSessionMemberKysely(database);
10792
return Boolean(
10893
executeSqliteQueryTakeFirstSync(
@@ -160,7 +145,6 @@ export function addSessionMember(
160145
throw new Error("session member identity and actor are required");
161146
}
162147
const options = resolveDatabaseOptions(scope);
163-
ensureSessionSharingSchema(options);
164148
const addedAt = params.addedAt ?? Date.now();
165149
const inserted = runOpenClawAgentWriteTransaction((database) => {
166150
assertAuthorizedSessionInstance(
@@ -197,7 +181,6 @@ export function removeSessionMember(
197181
return null;
198182
}
199183
const options = resolveDatabaseOptions(scope);
200-
ensureSessionSharingSchema(options);
201184
return runOpenClawAgentWriteTransaction((database) => {
202185
assertAuthorizedSessionInstance(
203186
database,

‎src/config/sessions/session-suggestion-store.test.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,11 @@ function resolvePendingSuggestion(params: {
4040
afterEach(() => closeOpenClawAgentDatabasesForTest());
4141

4242
describe("session suggestion store", () => {
43-
it("lazily ensures deterministic rows and resolves only pending suggestions", async () => {
43+
it("keeps deterministic rows and resolves only pending suggestions", async () => {
4444
await withTempDir({ prefix: "openclaw-session-suggestions-" }, async (dir) => {
4545
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };
4646
const scope = { agentId: "main", env, sessionKey: "agent:main:main" };
4747
await upsertSessionEntry(scope, { sessionId: "session-a", updatedAt: 1 });
48-
const database = openOpenClawAgentDatabase({ agentId: "main", env });
49-
database.db.exec("DROP TABLE session_suggestions;");
5048

5149
expect(listSessionSuggestions(scope)).toEqual([]);
5250
addSessionSuggestion(scope, {
@@ -91,6 +89,25 @@ describe("session suggestion store", () => {
9189
});
9290
});
9391

92+
it("does not recreate a missing canonical suggestions table", async () => {
93+
await withTempDir({ prefix: "openclaw-session-suggestions-missing-" }, async (dir) => {
94+
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };
95+
const scope = { agentId: "main", env, sessionKey: "agent:main:main" };
96+
await upsertSessionEntry(scope, { sessionId: "session-a", updatedAt: 1 });
97+
const database = openOpenClawAgentDatabase({ agentId: "main", env });
98+
database.db.exec("DROP TABLE session_suggestions;");
99+
100+
expect(() => listSessionSuggestions(scope)).toThrow(/no such table: session_suggestions/);
101+
expect(
102+
database.db
103+
.prepare(
104+
"SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'session_suggestions'",
105+
)
106+
.get(),
107+
).toBeUndefined();
108+
});
109+
});
110+
94111
it("binds writes to the session instance and clears rows on replacement", async () => {
95112
await withTempDir({ prefix: "openclaw-session-suggestions-reset-" }, async (dir) => {
96113
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };

‎src/config/sessions/session-suggestion-store.ts‎

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { randomUUID } from "node:crypto";
2-
import type { DatabaseSync } from "node:sqlite";
32
import {
43
executeSqliteQuerySync,
54
executeSqliteQueryTakeFirstSync,
@@ -12,7 +11,6 @@ import {
1211
type OpenClawAgentDatabase,
1312
type OpenClawAgentDatabaseOptions,
1413
} from "../../state/openclaw-agent-db.js";
15-
import { ensureOpenClawAgentSessionSharingSchemaInTransaction } from "../../state/openclaw-agent-session-sharing-schema.js";
1614
import { SessionWorkStartInvalidatedError } from "./lifecycle.js";
1715
import type { SessionAccessScope } from "./session-accessor.sqlite-contract.js";
1816
import { resolveSqliteScope, toDatabaseOptions } from "./session-accessor.sqlite-scope.js";
@@ -31,7 +29,6 @@ export type StoredSessionSuggestion = {
3129
state: StoredSessionSuggestionState;
3230
};
3331

34-
const ensuredDatabases = new WeakSet<DatabaseSync>();
3532
const MAX_PENDING_SESSION_SUGGESTIONS_PER_AUTHOR = 20;
3633
const MAX_PENDING_SESSION_SUGGESTIONS_PER_SESSION = 100;
3734
const MAX_RETAINED_RESOLVED_SESSION_SUGGESTIONS = 200;
@@ -41,18 +38,6 @@ function resolveDatabaseOptions(scope: SessionAccessScope): OpenClawAgentDatabas
4138
return toDatabaseOptions(resolveSqliteScope(scope));
4239
}
4340

44-
function ensureSuggestionSchema(options: OpenClawAgentDatabaseOptions): OpenClawAgentDatabase {
45-
const database = openOpenClawAgentDatabase(options);
46-
if (ensuredDatabases.has(database.db)) {
47-
return database;
48-
}
49-
runOpenClawAgentWriteTransaction((transactionDatabase) => {
50-
ensureOpenClawAgentSessionSharingSchemaInTransaction(transactionDatabase.db);
51-
}, options);
52-
ensuredDatabases.add(database.db);
53-
return database;
54-
}
55-
5641
function suggestionDb(database: OpenClawAgentDatabase) {
5742
return getNodeSqliteKysely<SuggestionDatabase>(database.db);
5843
}
@@ -154,7 +139,6 @@ export function addSessionSuggestion(
154139
throw new Error("suggestion author and text are required");
155140
}
156141
const options = resolveDatabaseOptions(scope);
157-
ensureSuggestionSchema(options);
158142
const sessionKey = resolveSqliteScope(scope).sessionKey;
159143
const suggestion: StoredSessionSuggestion = {
160144
id: params.id ?? randomUUID(),
@@ -209,7 +193,7 @@ export function listSessionSuggestions(
209193
params: { authorId?: string; pendingOnly?: boolean } = {},
210194
): StoredSessionSuggestion[] {
211195
const options = resolveDatabaseOptions(scope);
212-
const database = ensureSuggestionSchema(options);
196+
const database = openOpenClawAgentDatabase(options);
213197
const sessionKey = resolveSqliteScope(scope).sessionKey;
214198
let query = suggestionDb(database)
215199
.selectFrom("session_suggestions")
@@ -243,7 +227,6 @@ export function claimSessionSuggestionDispatch(
243227
},
244228
): SessionSuggestionDispatchClaim | null {
245229
const options = resolveDatabaseOptions(scope);
246-
ensureSuggestionSchema(options);
247230
const sessionKey = resolveSqliteScope(scope).sessionKey;
248231
return runOpenClawAgentWriteTransaction((database) => {
249232
assertSessionInstance(database, sessionKey, params.expectedSessionId);
@@ -308,7 +291,6 @@ export function releaseSessionSuggestionDispatch(
308291
params: { id: string; token: string; expectedSessionId?: string },
309292
): boolean {
310293
const options = resolveDatabaseOptions(scope);
311-
ensureSuggestionSchema(options);
312294
const sessionKey = resolveSqliteScope(scope).sessionKey;
313295
return runOpenClawAgentWriteTransaction((database) => {
314296
assertSessionInstance(database, sessionKey, params.expectedSessionId);
@@ -336,7 +318,6 @@ export function finalizeSessionSuggestionClaim(
336318
},
337319
): StoredSessionSuggestion | null {
338320
const options = resolveDatabaseOptions(scope);
339-
ensureSuggestionSchema(options);
340321
const sessionKey = resolveSqliteScope(scope).sessionKey;
341322
return runOpenClawAgentWriteTransaction((database) => {
342323
assertSessionInstance(database, sessionKey, params.expectedSessionId);

0 commit comments

Comments
 (0)