Skip to content

Commit e873a7f

Browse files
authored
refactor(memory): move QMD coordination to SQLite (#109636)
* refactor(memory): move QMD coordination to SQLite * chore: keep release notes in PR body * chore: annotate lease SQLite primitive
1 parent 571f1dc commit e873a7f

58 files changed

Lines changed: 3614 additions & 377 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
fc0f82fe0c44af5bde731e7792f5cb4d93e643f7087b60db5f0c92b7309f1350 plugin-sdk-api-baseline.json
2-
c78cdefd79531c5e3aff099bcebbd228eb8809b9e3e60091fa781b3cbed07114 plugin-sdk-api-baseline.jsonl
1+
f6306d8082be6dcde00435a02db2a5cf46f0983fccb8ed6a39a60f1931546fce plugin-sdk-api-baseline.json
2+
7c11aba346798e6db5be30a9b61141d1904a09764ea029656fd0fca79929df61 plugin-sdk-api-baseline.jsonl

‎docs/concepts/memory-qmd.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,17 @@ present.
5656
`5m`). Refreshes run through QMD subprocesses, not an in-process filesystem
5757
crawl. Semantic search modes also run `qmd embed`
5858
(`memory.qmd.update.embedInterval`, default `60m`).
59+
- QMD continues to own its `index.sqlite`, YAML collection config, and model
60+
downloads under the per-agent QMD home; these are external-tool artifacts,
61+
not OpenClaw state tables. OpenClaw-owned coordination lives only in SQLite:
62+
one shared lease limits embedding work across agents, while one lease in each
63+
agent database serializes that agent's collection, update, and embed writes.
64+
Runtime no longer creates QMD file-lock sidecars. `openclaw doctor --fix`
65+
removes retired sidecars only after proving their old process owner is stale.
66+
Upgrades are a clean cutover: stop and restart every OpenClaw process that
67+
shares the state directory before using the new version. Mixed old/new QMD
68+
writers are unsupported; runtime intentionally does not dual-lock the retired
69+
sidecars.
5970
- The default workspace collection tracks `MEMORY.md` plus the `memory/`
6071
tree. Lowercase `memory.md` is not indexed as a root memory file.
6172
- QMD's own scanner ignores hidden paths and common dependency/build

‎docs/plugins/sdk-runtime.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,20 @@ two-party event loops that do not go through the shared inbound reply runner.
729729
{ contentType: "text/plain" },
730730
);
731731
const blob = await blobs.lookup("artifact-1");
732+
733+
await api.runtime.state.withLease(
734+
{
735+
namespace: "my-feature",
736+
key: "writer",
737+
database: { scope: "agent", agentId },
738+
leaseMs: 5 * 60_000,
739+
waitMs: 30_000,
740+
},
741+
async ({ signal, assertOwned }) => {
742+
await runExternalWriter({ signal });
743+
assertOwned();
744+
},
745+
);
732746
```
733747

734748
Keyed stores survive restarts and are isolated by the runtime-bound plugin id. Use `registerIfAbsent(...)` for atomic dedupe claims: it returns `true` when the key was missing or expired and registered, or `false` when a live value already exists without overwriting its value, creation time, or TTL. Use `deleteIf(...)` when cleanup must remove only the value previously observed; its synchronous predicate and deletion run in one SQLite transaction. Limits: `maxEntries` per namespace, 50,000 live rows per plugin, JSON values under 64KB, and optional TTL expiry. By default, a write at either row limit sheds the oldest live rows from the namespace being written; sibling namespaces are not evicted for that write, and the write still fails if the namespace cannot free enough rows. Set `overflowPolicy: "reject-new"` for durable ownership records that must never be evicted: new keys fail at either limit, while existing keys remain updateable.
@@ -739,10 +753,12 @@ two-party event loops that do not go through the shared inbound reply runner.
739753

740754
`openChannelIngressQueue<TPayload>(...)` opens a persisted ingress queue scoped to the calling plugin, for buffering inbound events that need at-least-once processing across restarts. When stale-claim recovery uses `shouldRecover`, also provide `shouldRecoverCorrupt` if corrupt claimed payloads should be quarantined: its payload-independent claim identity lets the plugin preserve live owner and lane policy before the queue tombstones the row.
741755

756+
`withLease(...)` serializes cooperative plugin work across OpenClaw processes. Choose `database: { scope: "shared" }` for one global owner or `{ scope: "agent", agentId }` for independent per-agent ownership. Forward the callback's `AbortSignal` into every fallible operation. `assertOwned()` is a point-in-time checkpoint before starting another important step; the host also verifies ownership after the callback. Lease loss or caller cancellation aborts the signal. Acquisition waits and heartbeats happen outside short synchronous SQLite transactions; plugins never receive database paths or handles. This is cooperative cancellation, not a fencing token or authorization for unfenced external writes.
757+
742758
`openChannelIngressDrain(...)` opens the core channel-agnostic worker over that queue (or creates a queue when none is supplied). The drain owns stale-claim recovery, per-lane claim serialization, complete-at-adoption or complete-on-dispatch-return, retry/dead-letter disposition, optional pre-adoption supersede, and claim→adoption stall timeout. Wire claim ownership into reply generation with `turnAdoptionLifecycle` (via `bindIngressLifecycleToReplyOptions` from `plugin-sdk/channel-outbound`). Channel plugins keep accept-side enqueue, lane derivation, non-retryable classification, and any supersede authorization policy.
743759

744760
<Warning>
745-
`openBlobStore`, `openKeyedStore`, `openSyncKeyedStore`, `openChannelIngressQueue`, and `openChannelIngressDrain` are available only to bundled plugins and trusted official plugin installations in this release.
761+
`openBlobStore`, `openKeyedStore`, `openSyncKeyedStore`, `withLease`, `openChannelIngressQueue`, and `openChannelIngressDrain` are available only to bundled plugins and trusted official plugin installations in this release.
746762
</Warning>
747763

748764
</Accordion>

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ usage endpoint failed or returned no usable usage data.
278278
| `plugin-sdk/sqlite-runtime` | Focused SQLite agent-schema, path, and transaction helpers for first-party runtime, without database lifecycle controls |
279279
| `plugin-sdk/cron-store-runtime` | Cron store path/load/save helpers |
280280
| `plugin-sdk/state-paths` | State/OAuth dir path helpers |
281-
| `plugin-sdk/plugin-state-runtime` | Plugin sidecar SQLite keyed-state types plus centralized connection pragma, verified WAL maintenance, and atomic STRICT-schema migration helpers for plugin-owned databases |
281+
| `plugin-sdk/plugin-state-runtime` | Plugin-scoped keyed-state, BLOB, and cooperative SQLite lease contracts plus connection pragma, verified WAL maintenance, and atomic STRICT-schema migration helpers. Lease callbacks receive an abort signal and typed errors distinguish timeout, cancellation, lost ownership, invalid input, and storage failure |
282282
| `plugin-sdk/routing` | Route/session-key/account binding helpers such as `resolveAgentRoute`, `buildAgentSessionKey`, and `resolveDefaultAgentBoundAccountId` |
283283
| `plugin-sdk/status-helpers` | Shared channel/account status summary helpers, runtime-state defaults, and issue metadata helpers |
284284
| `plugin-sdk/target-resolver-runtime` | Shared target resolver helpers |
@@ -297,7 +297,7 @@ usage endpoint failed or returned no usable usage data.
297297
| `plugin-sdk/talk-config-runtime` | Talk provider config resolution helpers |
298298
| `plugin-sdk/json-store` | Small JSON state read/write helpers |
299299
| `plugin-sdk/json-unsafe-integers` | JSON parsing helpers that preserve unsafe integer literals as strings |
300-
| `plugin-sdk/file-lock` | Re-entrant file-lock helpers |
300+
| `plugin-sdk/file-lock` | Re-entrant file-lock helpers plus Doctor-safe reclaim of definitely stale, unchanged retired lock sidecars |
301301
| `plugin-sdk/persistent-dedupe` | Disk-backed dedupe cache helpers |
302302
| `plugin-sdk/acp-runtime` | ACP runtime/session and reply-dispatch helpers |
303303
| `plugin-sdk/acp-runtime-backend` | Lightweight ACP backend registration and reply-dispatch helpers for startup-loaded plugins |

‎docs/refactor/database-first.md‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,16 +1451,17 @@ create` validates the written archive by default; `--no-verify` is the
14511451
`ensureOpenClawModelCatalog`; there is no `models.json` compatibility API in
14521452
runtime code. The implementation writes SQLite and the embedded PI registry is
14531453
hydrated from that stored payload without creating a `models.json` file.
1454-
- QMD session transcript markdown export and `memory.qmd.sessions` config were
1455-
removed. There is no QMD transcript collection, no `qmd/sessions*` runtime
1456-
path, and no file-backed session memory bridge.
1457-
- Memory-core runtime imports SQLite transcript indexing helpers from
1458-
`openclaw/plugin-sdk/memory-core-host-engine-session-transcripts`, not the
1459-
QMD SDK subpath. The QMD subpath keeps a compatibility re-export only for
1460-
external callers until a major SDK cleanup can remove it.
1461-
- QMD's own `index.sqlite` is now a temp runtime materialization backed by the
1462-
main SQLite `plugin_blob_entries` table. Runtime no longer creates a durable
1463-
`~/.openclaw/agents/<agentId>/qmd` sidecar.
1454+
- Optional `memory.qmd.sessions` export reads canonical transcript rows from
1455+
the per-agent database and materializes sanitized Markdown under the QMD home
1456+
as an explicit QMD input artifact. QMD session collections and artifact
1457+
identity mappings therefore remain part of the configured external-tool
1458+
bridge; they are not a second canonical transcript store.
1459+
- QMD's own `index.sqlite`, YAML collection config, and model downloads remain
1460+
external-tool artifacts under `~/.openclaw/agents/<agentId>/qmd`; they are not
1461+
mirrored into `plugin_blob_entries`. OpenClaw-owned QMD coordination is
1462+
database-first: shared `state_leases` serialize embeds globally and per-agent
1463+
`state_leases` serialize collection/update/embed writers. Runtime creates no
1464+
QMD lock sidecars.
14641465
- The optional `memory-lancedb` plugin no longer creates
14651466
`~/.openclaw/memory/lancedb` as an implicit OpenClaw-managed store. It is an
14661467
external LanceDB backend and stays disabled until the operator configures an
@@ -2030,8 +2031,10 @@ payload.
20302031
`gateway_locks` and no longer exposes a file-lock directory seam.
20312032
- Generic plugin SDK dedupe persistence no longer uses file locks or JSON
20322033
files; it writes shared SQLite plugin-state rows. Done.
2033-
- QMD embed coordination uses a SQLite state lease instead of
2034-
`qmd/embed.lock`. Done.
2034+
- QMD coordination uses a shared SQLite lease for embeds and a per-agent
2035+
SQLite lease for every collection/update/embed writer. Runtime no longer
2036+
creates `qmd/embed.lock.lock` or `agents/<agentId>/qmd-write.lock.lock`;
2037+
Doctor removes only definitely stale retired sidecars. Done.
20352038

20362039
7. Make workers database-aware.
20372040
- Workers open their own SQLite connections.
@@ -2282,7 +2285,8 @@ Add a repo check that fails new runtime writes to legacy state paths:
22822285
- `gateway-restart-intent.json`
22832286
- `gateway-supervisor-restart-handoff.json`
22842287
- `gateway.<hash>.lock`
2285-
- `qmd/embed.lock`
2288+
- `qmd/embed.lock.lock`
2289+
- `agents/<agentId>/qmd-write.lock.lock`
22862290
- `commands.log`
22872291
- `config-health.json`
22882292
- `port-guard.json`
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Memory Core tests cover metadata-only CLI host propagation.
2+
import { Command } from "commander";
3+
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
4+
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
5+
import { describe, expect, it, vi } from "vitest";
6+
7+
const registerMemoryCliMock = vi.hoisted(() => vi.fn());
8+
9+
vi.mock("./src/cli.js", () => ({
10+
registerMemoryCli: registerMemoryCliMock,
11+
}));
12+
13+
import plugin from "./cli-metadata.js";
14+
15+
describe("memory-core CLI metadata", () => {
16+
it("passes the bound SQLite lease host to the lazy CLI registrar", async () => {
17+
let registrar: Parameters<OpenClawPluginApi["registerCli"]>[0] | undefined;
18+
const hostWithLease = vi.fn();
19+
const acquireLocalService = vi.fn(async () => undefined);
20+
plugin.register(
21+
createTestPluginApi({
22+
runtime: {
23+
llm: { acquireLocalService },
24+
state: { withLease: hostWithLease },
25+
} as unknown as OpenClawPluginApi["runtime"],
26+
registerCli(nextRegistrar) {
27+
registrar = nextRegistrar;
28+
},
29+
}),
30+
);
31+
if (!registrar) {
32+
throw new Error("CLI registrar missing");
33+
}
34+
const program = new Command();
35+
36+
await registrar({ program } as never);
37+
38+
expect(registerMemoryCliMock).toHaveBeenCalledWith(program, {
39+
acquireLocalService,
40+
withLease: expect.any(Function),
41+
});
42+
const withLease = registerMemoryCliMock.mock.calls[0]?.[1]?.withLease as
43+
| ((...args: unknown[]) => unknown)
44+
| undefined;
45+
if (!withLease) {
46+
throw new Error("bound lease hook missing");
47+
}
48+
withLease("options", "callback");
49+
expect(hostWithLease).toHaveBeenCalledWith("options", "callback");
50+
});
51+
});

‎extensions/memory-core/cli-metadata.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export default definePluginEntry({
1111
const { registerMemoryCli } = await import("./cli.js");
1212
registerMemoryCli(program, {
1313
acquireLocalService: api.runtime.llm?.acquireLocalService,
14+
withLease: api.runtime.state.withLease.bind(api.runtime.state),
1415
});
1516
},
1617
{

‎extensions/memory-core/doctor-contract-api.test.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ function legacyMemoryIndexMigration() {
5757
return migration;
5858
}
5959

60+
function qmdFileLockMigration() {
61+
const migration = stateMigrations.find(
62+
(entry) => entry.id === "memory-core-qmd-file-locks-to-sqlite-leases",
63+
);
64+
if (!migration) {
65+
throw new Error("expected memory-core QMD file-lock migration");
66+
}
67+
return migration;
68+
}
69+
6070
function vectorToBlob(embedding: number[]): Buffer {
6171
return Buffer.from(new Float32Array(embedding).buffer);
6272
}
@@ -1711,5 +1721,96 @@ describe("memory-core doctor dreaming migration", () => {
17111721
await expect(fs.access(legacyPath)).rejects.toThrow();
17121722
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
17131723
});
1724+
1725+
it("removes only exact stale QMD lock sidecars and is idempotent", async () => {
1726+
const stateDir = path.join(rootDir, "state");
1727+
const globalLockPath = path.join(stateDir, "qmd", "embed.lock.lock");
1728+
const agentLockPath = path.join(stateDir, "agents", "main", "qmd-write.lock.lock");
1729+
const ignoredPaths = [
1730+
path.join(stateDir, "qmd", "other.lock.lock"),
1731+
path.join(stateDir, "agents", "main", "nested", "qmd-write.lock.lock"),
1732+
path.join(stateDir, "agents", "main!", "qmd-write.lock.lock"),
1733+
path.join(stateDir, "agents", "main", "qmd-write.lock.lock.extra"),
1734+
];
1735+
const stalePayload = `${JSON.stringify({ pid: 2 ** 30, createdAt: new Date().toISOString() })}\n`;
1736+
for (const filePath of [globalLockPath, agentLockPath, ...ignoredPaths]) {
1737+
await fs.mkdir(path.dirname(filePath), { recursive: true });
1738+
await fs.writeFile(filePath, stalePayload, "utf8");
1739+
}
1740+
1741+
const migration = qmdFileLockMigration();
1742+
await expect(migration.detectLegacyState(migrationParams())).resolves.toEqual({
1743+
preview: [
1744+
`- Retired Memory Core QMD file lock: ${globalLockPath} -> remove only if definitely stale (coordination now uses SQLite leases)`,
1745+
`- Retired Memory Core QMD file lock: ${agentLockPath} -> remove only if definitely stale (coordination now uses SQLite leases)`,
1746+
],
1747+
});
1748+
1749+
await expect(migration.migrateLegacyState(migrationParams())).resolves.toEqual({
1750+
changes: [
1751+
`Removed retired Memory Core QMD file lock: ${globalLockPath}`,
1752+
`Removed retired Memory Core QMD file lock: ${agentLockPath}`,
1753+
],
1754+
warnings: [],
1755+
});
1756+
await expect(fs.access(globalLockPath)).rejects.toMatchObject({ code: "ENOENT" });
1757+
await expect(fs.access(agentLockPath)).rejects.toMatchObject({ code: "ENOENT" });
1758+
await expect(fs.access(path.join(stateDir, "openclaw.sqlite"))).rejects.toMatchObject({
1759+
code: "ENOENT",
1760+
});
1761+
await expect(
1762+
fs.access(path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite")),
1763+
).rejects.toMatchObject({ code: "ENOENT" });
1764+
for (const filePath of ignoredPaths) {
1765+
await expect(fs.access(filePath)).resolves.toBeUndefined();
1766+
}
1767+
await expect(migration.detectLegacyState(migrationParams())).resolves.toBeNull();
1768+
await expect(migration.migrateLegacyState(migrationParams())).resolves.toEqual({
1769+
changes: [],
1770+
warnings: [],
1771+
});
1772+
});
1773+
1774+
it("retains live and ambiguous QMD locks and ignores symlink candidates", async () => {
1775+
const stateDir = path.join(rootDir, "state");
1776+
const globalLockPath = path.join(stateDir, "qmd", "embed.lock.lock");
1777+
const malformedLockPath = path.join(stateDir, "agents", "main", "qmd-write.lock.lock");
1778+
const symlinkLockPath = path.join(stateDir, "agents", "other", "qmd-write.lock.lock");
1779+
const symlinkTargetPath = path.join(rootDir, "stale-lock-target");
1780+
await fs.mkdir(path.dirname(globalLockPath), { recursive: true });
1781+
await fs.mkdir(path.dirname(malformedLockPath), { recursive: true });
1782+
await fs.mkdir(path.dirname(symlinkLockPath), { recursive: true });
1783+
await fs.writeFile(
1784+
globalLockPath,
1785+
`${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() })}\n`,
1786+
"utf8",
1787+
);
1788+
await fs.writeFile(malformedLockPath, "{", "utf8");
1789+
await fs.writeFile(
1790+
symlinkTargetPath,
1791+
`${JSON.stringify({ pid: 2 ** 30, createdAt: new Date().toISOString() })}\n`,
1792+
"utf8",
1793+
);
1794+
await fs.symlink(symlinkTargetPath, symlinkLockPath);
1795+
1796+
const migration = qmdFileLockMigration();
1797+
await expect(migration.detectLegacyState(migrationParams())).resolves.toEqual({
1798+
preview: [
1799+
`- Retired Memory Core QMD file lock: ${globalLockPath} -> remove only if definitely stale (coordination now uses SQLite leases)`,
1800+
`- Retired Memory Core QMD file lock: ${malformedLockPath} -> remove only if definitely stale (coordination now uses SQLite leases)`,
1801+
],
1802+
});
1803+
await expect(migration.migrateLegacyState(migrationParams())).resolves.toEqual({
1804+
changes: [],
1805+
warnings: [
1806+
`Retained retired Memory Core QMD file lock because its owner is live or ambiguous: ${globalLockPath}`,
1807+
`Retained retired Memory Core QMD file lock because its owner is live or ambiguous: ${malformedLockPath}`,
1808+
],
1809+
});
1810+
await expect(fs.access(globalLockPath)).resolves.toBeUndefined();
1811+
await expect(fs.readFile(malformedLockPath, "utf8")).resolves.toBe("{");
1812+
expect((await fs.lstat(symlinkLockPath)).isSymbolicLink()).toBe(true);
1813+
await expect(fs.access(symlinkTargetPath)).resolves.toBeUndefined();
1814+
});
17141815
});
17151816
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

0 commit comments

Comments
 (0)