Skip to content

Commit 38fabc4

Browse files
authored
refactor(state): retire tenant-free agent lease schema (#121943)
* refactor(state): retire agent lease schema * chore(plugin-sdk): refresh schema version closure * test(state): preserve v17 migration fixtures * docs(state): align lease schema inventory
1 parent 30530ae commit 38fabc4

12 files changed

Lines changed: 234 additions & 166 deletions

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 66 additions & 66 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎docs/refactor/database-first.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,9 +1470,8 @@ create` validates the written archive by default; `--no-verify` is the
14701470
- QMD's own `index.sqlite`, YAML collection config, and model downloads remain
14711471
external-tool artifacts under `~/.openclaw/agents/<agentId>/qmd`; they are not
14721472
mirrored into `plugin_blob_entries`. Current host-owned lease consumers use
1473-
shared `state_leases`; the per-agent `state_leases` table remains in the
1474-
canonical schema but has no runtime tenants. Runtime creates no QMD lock
1475-
sidecars.
1473+
the shared `state_leases` table; agent schema 17 retires the tenant-free
1474+
per-agent table. Runtime creates no QMD lock sidecars.
14761475
- The optional `memory-lancedb` plugin no longer creates
14771476
`~/.openclaw/memory/lancedb` as an implicit OpenClaw-managed store. It is an
14781477
external LanceDB backend and stays disabled until the operator configures an

‎docs/reference/database-schemas.md‎

Lines changed: 41 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -55,17 +55,23 @@ Use a SQLite online backup or another WAL-aware snapshot produced while the sour
5555

5656
## Agent schema history
5757

58-
| Version | Change | First release |
59-
| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
60-
| 1 | Initial per-agent store ([#88349](https://github.com/openclaw/openclaw/pull/88349)) | `v2026.5.30-beta.1`, stable through `v2026.7.1` |
61-
| 2 | Memory index identity ([#104449](https://github.com/openclaw/openclaw/pull/104449)) | `v2026.7.2-beta.1` |
62-
| 4 | Sessions and transcripts moved into SQLite ([#98236](https://github.com/openclaw/openclaw/pull/98236)) | `v2026.7.2-beta.1` |
63-
| 5-6 | Terminal freshness and state lifecycle ([#104859](https://github.com/openclaw/openclaw/pull/104859)) | `v2026.7.2-beta.1` |
64-
| 7 | Per-entry lifecycle status projection ([#106151](https://github.com/openclaw/openclaw/pull/106151)) | `v2026.7.2-beta.1` |
65-
| 8 | Per-transcript session provenance ([#106766](https://github.com/openclaw/openclaw/pull/106766)) | `v2026.7.2-beta.2` |
66-
| 9 | `STRICT` tables ([#108663](https://github.com/openclaw/openclaw/pull/108663)) | `v2026.7.2-beta.2` |
67-
| 10 | Materialized active transcript paths ([#108851](https://github.com/openclaw/openclaw/pull/108851)) | Unreleased |
68-
| 11 | Leases, durable delivery, conversation addresses, and heartbeat outcomes ([#109636](https://github.com/openclaw/openclaw/pull/109636), [#95838](https://github.com/openclaw/openclaw/pull/95838), [#109999](https://github.com/openclaw/openclaw/pull/109999)) | Unreleased |
58+
| Version | Change | First release |
59+
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- |
60+
| 1 | Initial per-agent store ([#88349](https://github.com/openclaw/openclaw/pull/88349)) | `v2026.5.30-beta.1`, stable through `v2026.7.1` |
61+
| 2 | Memory index identity ([#104449](https://github.com/openclaw/openclaw/pull/104449)) | `v2026.7.2-beta.1` |
62+
| 4 | Sessions and transcripts moved into SQLite ([#98236](https://github.com/openclaw/openclaw/pull/98236)) | `v2026.7.2-beta.1` |
63+
| 5-6 | Terminal freshness and state lifecycle ([#104859](https://github.com/openclaw/openclaw/pull/104859)) | `v2026.7.2-beta.1` |
64+
| 7 | Per-entry lifecycle status projection ([#106151](https://github.com/openclaw/openclaw/pull/106151)) | `v2026.7.2-beta.1` |
65+
| 8 | Per-transcript session provenance ([#106766](https://github.com/openclaw/openclaw/pull/106766)) | `v2026.7.2-beta.2` |
66+
| 9 | `STRICT` tables ([#108663](https://github.com/openclaw/openclaw/pull/108663)) | `v2026.7.2-beta.2` |
67+
| 10 | Materialized active transcript paths ([#108851](https://github.com/openclaw/openclaw/pull/108851)) | Unreleased |
68+
| 11 | Durable delivery, conversation addresses, and heartbeat outcomes ([#109636](https://github.com/openclaw/openclaw/pull/109636), [#95838](https://github.com/openclaw/openclaw/pull/95838), [#109999](https://github.com/openclaw/openclaw/pull/109999)) | Unreleased |
69+
| 12 | Session-owned ACP parent-stream events | Unreleased |
70+
| 13 | Durable transcript rewrite watermarks | Unreleased |
71+
| 14 | Logical session nodes, generation windows, and node-owned artifact foreign keys | Unreleased |
72+
| 15 | Board and session-sharing tables | Unreleased |
73+
| 16 | Legacy top-level transcript media fields retired | Unreleased |
74+
| 17 | Tenant-free per-agent lease table retired after the last writer and routing arm were removed ([#121113](https://github.com/openclaw/openclaw/pull/121113), [#121615](https://github.com/openclaw/openclaw/pull/121615)) | Unreleased |
6975

7076
Version 3 was an unshipped development step folded into version 4.
7177

@@ -129,31 +135,41 @@ The general procedure is:
129135
3. Set `PRAGMA user_version` and `schema_meta.schema_version` to the target version.
130136
4. Run the target release's full database verification before starting the Gateway.
131137

132-
### Example: agent schema 11 to 9
138+
### Example: agent schema 17 to 16
133139

134-
Schema 10 added the active transcript projection. Schema 11 added leases, durable delivery, conversation-address state, and heartbeat outcomes.
140+
Schema 17 removed the tenant-free per-agent lease table. A schema 16 build still requires that canonical table, so a manual downgrade must recreate its exact schema before lowering the version.
135141

136142
Run equivalent SQL against each affected per-agent database after inspecting the exact schema that wrote it:
137143

138144
```sql
139145
BEGIN IMMEDIATE;
140146

141-
DROP TABLE IF EXISTS heartbeat_outcomes;
142-
DROP TABLE IF EXISTS conversation_deliveries;
143-
DROP TABLE IF EXISTS state_leases;
144-
DROP TABLE IF EXISTS session_transcript_active_events;
145-
146-
ALTER TABLE session_transcript_index_state DROP COLUMN active_event_count;
147-
ALTER TABLE session_transcript_index_state DROP COLUMN active_message_count;
148-
ALTER TABLE conversations DROP COLUMN delivery_target;
149-
150-
PRAGMA user_version = 9;
147+
CREATE TABLE state_leases (
148+
scope TEXT NOT NULL,
149+
lease_key TEXT NOT NULL,
150+
owner TEXT NOT NULL,
151+
expires_at INTEGER,
152+
heartbeat_at INTEGER,
153+
payload_json TEXT,
154+
created_at INTEGER NOT NULL,
155+
updated_at INTEGER NOT NULL,
156+
PRIMARY KEY (scope, lease_key)
157+
) STRICT;
158+
159+
CREATE INDEX idx_agent_state_leases_expiry
160+
ON state_leases(expires_at, scope, lease_key)
161+
WHERE expires_at IS NOT NULL;
162+
163+
CREATE INDEX idx_agent_state_leases_owner
164+
ON state_leases(owner, updated_at DESC);
165+
166+
PRAGMA user_version = 16;
151167
UPDATE schema_meta
152-
SET schema_version = 9,
168+
SET schema_version = 16,
153169
updated_at = unixepoch('now') * 1000
154170
WHERE meta_key = 'primary';
155171

156172
COMMIT;
157173
```
158174

159-
This discards version 10-11 state, including in-flight delivery operations, leases, heartbeat outcomes, and the derived active transcript projection. A botched downgrade means restore from the verified backup.
175+
The recreated table starts empty because schema 17 has no agent-DB lease tenants to preserve. A botched downgrade means restore from the verified backup.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"openclaw": {
55
"schemaVersions": {
66
"state": 6,
7-
"agent": 16
7+
"agent": 17
88
}
99
},
1010
"description": "Multi-channel AI gateway with extensible messaging integrations",

‎src/infra/backup-create.test.ts‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,16 +1193,6 @@ describe("createBackupArchive", () => {
11931193
.run(`keeper-${"y".repeat(16_384)}`);
11941194
liveDb.exec("PRAGMA wal_checkpoint(TRUNCATE)");
11951195
liveDb.prepare("DELETE FROM deleted_secrets WHERE value = ?").run(deletedSecret);
1196-
liveDb
1197-
.prepare(
1198-
`
1199-
INSERT INTO state_leases (
1200-
scope, lease_key, owner, expires_at, heartbeat_at,
1201-
payload_json, created_at, updated_at
1202-
) VALUES ('core:test-fixture', 'write', 'worker', 9999999999999, 1, NULL, 1, 1)
1203-
`,
1204-
)
1205-
.run();
12061196
} finally {
12071197
liveDb.close();
12081198
}
@@ -1244,20 +1234,9 @@ describe("createBackupArchive", () => {
12441234
provider: "openai",
12451235
key: "sk-backup",
12461236
});
1247-
expect(archivedDb.prepare("SELECT COUNT(*) AS count FROM state_leases").get()).toEqual({
1248-
count: 0,
1249-
});
12501237
} finally {
12511238
archivedDb.close();
12521239
}
1253-
const sourceDb = new sqlite.DatabaseSync(liveDbPath, { readOnly: true });
1254-
try {
1255-
expect(sourceDb.prepare("SELECT COUNT(*) AS count FROM state_leases").get()).toEqual({
1256-
count: 1,
1257-
});
1258-
} finally {
1259-
sourceDb.close();
1260-
}
12611240
},
12621241
);
12631242
});

‎src/infra/state-migrations.media-persistence.historical-schema.test-support.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,34 @@
11
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.js";
22

3+
const HISTORICAL_AGENT_LEASE_SCHEMA = `CREATE TABLE IF NOT EXISTS state_leases (
4+
scope TEXT NOT NULL,
5+
lease_key TEXT NOT NULL,
6+
owner TEXT NOT NULL,
7+
expires_at INTEGER,
8+
heartbeat_at INTEGER,
9+
payload_json TEXT,
10+
created_at INTEGER NOT NULL,
11+
updated_at INTEGER NOT NULL,
12+
PRIMARY KEY (scope, lease_key)
13+
) STRICT;
14+
15+
CREATE INDEX IF NOT EXISTS idx_agent_state_leases_expiry
16+
ON state_leases(expires_at, scope, lease_key)
17+
WHERE expires_at IS NOT NULL;
18+
19+
CREATE INDEX IF NOT EXISTS idx_agent_state_leases_owner
20+
ON state_leases(owner, updated_at DESC);
21+
22+
`;
23+
24+
function restoreHistoricalAgentLeaseSchema(sql: string): string {
25+
const marker = "CREATE TABLE IF NOT EXISTS session_nodes (";
26+
if (!sql.includes(marker)) {
27+
throw new Error(`Historical agent schema marker is missing: ${marker}`);
28+
}
29+
return sql.replace(marker, `${HISTORICAL_AGENT_LEASE_SCHEMA}${marker}`);
30+
}
31+
332
function removeSchemaRange(sql: string, startMarker: string, endMarker: string): string {
433
const start = sql.indexOf(startMarker);
534
const end = sql.indexOf(endMarker, start);
@@ -11,7 +40,7 @@ function removeSchemaRange(sql: string, startMarker: string, endMarker: string):
1140

1241
/** Exact schema bytes from 509a5f0373764, derived from current SQL with later additions removed. */
1342
export function historicalV15AgentSchemaSql(): string {
14-
let sql = OPENCLAW_AGENT_SCHEMA_SQL.replace(
43+
let sql = restoreHistoricalAgentLeaseSchema(OPENCLAW_AGENT_SCHEMA_SQL).replace(
1544
" entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),\n",
1645
"",
1746
);

‎src/snapshot/local-repository.test.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1467,12 +1467,11 @@ describe("local SQLite snapshot repository", () => {
14671467
).rejects.toThrow(/expected global/u);
14681468
});
14691469

1470-
it("sanitizes transient leases from agent snapshots without touching the source", async () => {
1470+
it("snapshots agents without requiring legacy lease storage", async () => {
14711471
const tempDir = await createTempDir();
14721472
const sourcePath = path.join(tempDir, "openclaw-agent.sqlite");
14731473
const repositoryPath = path.join(tempDir, "snapshots");
14741474
createAgentDatabase(sourcePath, "worker-1");
1475-
seedStateLease(sourcePath);
14761475
const provider = createLocalSqliteSnapshotProvider({ repositoryPath });
14771476

14781477
const snapshot = await provider.create({
@@ -1482,18 +1481,26 @@ describe("local SQLite snapshot repository", () => {
14821481
withDatabase(
14831482
path.join(snapshot.ref.path, SNAPSHOT_SQLITE_FILENAME),
14841483
(artifact) => {
1485-
expect(artifact.prepare("SELECT COUNT(*) AS count FROM state_leases").get()).toEqual({
1486-
count: 0,
1487-
});
1484+
expect(
1485+
artifact
1486+
.prepare(
1487+
"SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'state_leases'",
1488+
)
1489+
.get(),
1490+
).toBeUndefined();
14881491
},
14891492
{ readOnly: true },
14901493
);
14911494
withDatabase(
14921495
sourcePath,
14931496
(source) => {
1494-
expect(source.prepare("SELECT COUNT(*) AS count FROM state_leases").get()).toEqual({
1495-
count: 1,
1496-
});
1497+
expect(
1498+
source
1499+
.prepare(
1500+
"SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'state_leases'",
1501+
)
1502+
.get(),
1503+
).toBeUndefined();
14971504
},
14981505
{ readOnly: true },
14991506
);

‎src/state/openclaw-agent-db-contract.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ import type { DatabaseSync } from "node:sqlite";
22
import type { SqliteWalMaintenance } from "../infra/sqlite-wal.js";
33
import type { OpenClawStateDatabaseOptions } from "./openclaw-state-db.js";
44

5+
// v17 retires the tenant-free per-agent state lease table.
56
// v16 retires legacy top-level Media* transcript fields. It is a downgrade
67
// guard only; the physical schema is unchanged and Doctor owns the data rewrite.
78
// v15 makes board and session-sharing tables part of the canonical agent schema.
89
// v14 = logical session nodes, generation windows, and node-owned artifact FKs.
910
// v13 = one durable rewrite watermark per raw session transcript.
1011
// v12 = session-owned ACP parent-stream events.
11-
// v11 = agent-scoped runtime leases, durable delivery operations, canonical
12-
// external conversation addresses, and bounded per-session heartbeat outcome context.
12+
// v11 = durable delivery operations, canonical external conversation addresses,
13+
// and bounded per-session heartbeat outcome context.
1314
// v10 = materialized active transcript paths.
1415
// v9 = SQLite STRICT tables.
1516
// v8 added per-transcript session provenance. v7 added per-entry lifecycle status projection.
@@ -18,7 +19,7 @@ import type { OpenClawStateDatabaseOptions } from "./openclaw-state-db.js";
1819
// The v4 session/transcript flip and main's v2 memory-identity
1920
// change is folded in structure-gated migrations, so v2 main DBs and
2021
// pre-merge v4 flip DBs both converge on this schema.
21-
export const OPENCLAW_AGENT_SCHEMA_VERSION = 16;
22+
export const OPENCLAW_AGENT_SCHEMA_VERSION = 17;
2223

2324
/** Open per-agent SQLite database handle plus lifecycle maintenance. */
2425
export type OpenClawAgentDatabase = {

‎src/state/openclaw-agent-db-schema.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,23 @@ function migrateOpenClawAgentSchema(db: DatabaseSync): void {
292292
backfillTranscriptMutationWatermarks(db);
293293
}
294294

295+
function migrateRetiredAgentStateLeaseSchema(
296+
db: DatabaseSync,
297+
previousVersion: number,
298+
targetVersion: number,
299+
): void {
300+
if (previousVersion >= 17 || targetVersion < 17) {
301+
return;
302+
}
303+
// The 2026-08-10 tenant audit found no agent-DB lease writers after #121113;
304+
// #121615 removed the unreachable routing arm, so v17 retires this table.
305+
db.exec(`
306+
DROP INDEX IF EXISTS idx_agent_state_leases_owner;
307+
DROP INDEX IF EXISTS idx_agent_state_leases_expiry;
308+
DROP TABLE IF EXISTS state_leases;
309+
`);
310+
}
311+
295312
/** Backfill one generation token without copying or rewriting transcript rows. */
296313
function migrateSessionTranscriptGenerations(db: DatabaseSync, previousVersion: number): void {
297314
// Remove after 2026-10-01: drop the generation backfill once the minimum supported agent schema is 13.
@@ -623,6 +640,7 @@ function ensureAgentSchema(
623640
dropLegacyRuntimeJournalSchemas(db);
624641
migrateMemoryIndexSourcesIdentity(db);
625642
migrateOpenClawAgentSchema(db);
643+
migrateRetiredAgentStateLeaseSchema(db, previousVersion, targetVersion);
626644
migrateConversationDeliveryTargetColumn(db);
627645
backfillOpenClawAgentSchema(db, previousVersion);
628646
// Remove after 2026-10-01: drop the pre-v11 conversation backfill once schema 11 is the support floor.

0 commit comments

Comments
 (0)