Skip to content

Commit 334c182

Browse files
authored
refactor(diffs): move ephemeral artifacts to SQLite (#109328)
* refactor(diffs): move ephemeral artifacts to SQLite * fix(plugin-state): satisfy SDK validation gates * test(diffs): satisfy lint contracts * fix(plugin-state): count expired blobs toward quotas * fix(plugin-state): harden blob storage boundaries * fix(plugins): replace stale install provenance
1 parent 7a58956 commit 334c182

41 files changed

Lines changed: 3001 additions & 636 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-
e92bead6ecd7b79e789e67ef631a125aa9f69887e82112c99471932ebd578587 plugin-sdk-api-baseline.json
2-
ab0f1f57323d75ade752d6961834a94ddf9eb4fe78c334d43b7ddce26ea0d6c1 plugin-sdk-api-baseline.jsonl
1+
4b3a5f9dde74285c16fba05eb16e6fd5eaa00386143db82a00a9cf7bfa8fa9bb plugin-sdk-api-baseline.json
2+
6c650cf131c85bb8f67fb8c053124aa59c3062be24951e6e3ba45c00440d6f61 plugin-sdk-api-baseline.jsonl

‎docs/plugins/sdk-runtime.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -715,16 +715,32 @@ two-party event loops that do not go through the shared inbound reply runner.
715715
await store.deleteIf?.("key-1", (current) => current.value === "hello");
716716
await store.consume("key-1");
717717
await store.clear();
718+
719+
const blobs = api.runtime.state.openBlobStore<MyBlobMetadata>({
720+
namespace: "rendered-artifacts",
721+
maxEntries: 100,
722+
maxBytesPerEntry: 4 * 1024 * 1024,
723+
maxBytesPerNamespace: 64 * 1024 * 1024,
724+
defaultTtlMs: 15 * 60_000,
725+
});
726+
await blobs.register(
727+
"artifact-1",
728+
new TextEncoder().encode("binary or text payload"),
729+
{ contentType: "text/plain" },
730+
);
731+
const blob = await blobs.lookup("artifact-1");
718732
```
719733

720734
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.
721735

722736
`openSyncKeyedStore<T>(...)` returns the same store shape with synchronous methods (`register`, `registerIfAbsent`, `deleteIf`, `lookup`, `consume`, `clear` all return values directly instead of promises) for callers that cannot await.
723737

738+
`openBlobStore<TMetadata>(...)` stores bounded binary payloads in shared SQLite without base64 or file sidecars. It requires per-entry, per-namespace byte, and row limits; copies byte arrays at the API boundary; and lists metadata without loading every BLOB. `register(...)` is an explicit upsert, including for expired keys. `registerIfAbsent(...)` provides collision-safe creation: an expired key remains occupied until its owner claims it with `deleteExpiredKey(key)` or `deleteExpired()`, preserving metadata needed to remove related named artifacts after the SQLite commit. Any row with a TTL is transient and excluded from backup/restore even before it expires; omit TTL for durable, restorable state. Host fuses cap each BLOB at 100 MiB, each plugin at 512 MiB of physically stored BLOBs, and each plugin at 50,000 physically stored rows, including expired rows awaiting owner cleanup. Use `registerIfAbsent(...)` with `overflowPolicy: "reject-new"` when external materializations must not be silently orphaned by replacement or eviction.
739+
724740
`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.
725741

726742
<Warning>
727-
`openKeyedStore`, `openSyncKeyedStore`, and `openChannelIngressQueue` are available only to bundled plugins and trusted official plugin installations in this release.
743+
`openBlobStore`, `openKeyedStore`, `openSyncKeyedStore`, and `openChannelIngressQueue` are available only to bundled plugins and trusted official plugin installations in this release.
728744
</Warning>
729745

730746
</Accordion>

‎docs/refactor/database-first.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,8 +1193,10 @@ sessionId})`; create, branch, continue, list, and fork flows live in their
11931193
- Zalo hosted outbound media now uses shared SQLite `plugin_blob_entries`
11941194
instead of `openclaw-zalo-outbound-media` JSON/bin temp sidecars.
11951195
- Diffs viewer HTML and metadata now use shared SQLite `plugin_blob_entries`
1196-
instead of `meta.json`/`viewer.html` temp files. Rendered PNG/PDF outputs stay
1197-
temp materializations because channel delivery still needs a file path.
1196+
instead of `meta.json`/`viewer.html` temp files. Viewer HTML is stored as a
1197+
gzip blob and only the URL token hash is persisted. Rendered PNG/PDF outputs
1198+
stay temp materializations because channel delivery still needs a file path;
1199+
their expiry metadata is SQLite-owned without JSON sidecars.
11981200
- Canvas managed documents now use shared SQLite `plugin_blob_entries` instead
11991201
of a default `state/canvas/documents` directory. The Canvas host serves those
12001202
blobs directly; local files are created only for explicit `host.root`

‎docs/tools/diffs.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -289,11 +289,11 @@ Supported `defaults` keys: `fontFamily`, `fontSize`, `lineSpacing`, `layout`, `s
289289

290290
## Artifact lifecycle and storage
291291

292-
- Artifacts live under `$TMPDIR/openclaw-diffs`.
293-
- Viewer metadata stores a random 20-hex-char artifact ID, a random 48-hex-char token, `createdAt`/`expiresAt`, and the stored `viewer.html` path.
292+
- Viewer HTML and metadata live in the shared `state/openclaw.sqlite` database under the Diffs plugin blob namespace. HTML is gzip-compressed; SQLite stores only a SHA-256 hash of the random URL token, not the token itself.
293+
- Rendered PNG/PDF files remain temporary materializations under `$TMPDIR/openclaw-diffs` because channel delivery requires a file path. SQLite owns their expiry metadata; no JSON sidecars are written.
294294
- Default artifact TTL: 30 minutes. Maximum accepted TTL: 6 hours.
295-
- Cleanup runs opportunistically after each artifact create call; expired artifacts are deleted.
296-
- Fallback sweep removes stale folders older than 24 hours when metadata is missing.
295+
- Cleanup runs opportunistically after each artifact create call. Expired SQLite rows are deleted first, followed by any corresponding PNG/PDF directory.
296+
- A fallback sweep removes rowless temporary folders older than 24 hours. Legacy `meta.json`, `file-meta.json`, and `viewer.html` caches are not imported or read.
297297

298298
## Viewer URL and network behavior
299299

‎extensions/diffs/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,8 @@ diff --git a/src/example.ts b/src/example.ts
220220
- Multi-file patches start with a changed-files summary card: totals, per-file `+N`/`-N` stats, change badges, and anchor links.
221221
- Rendered PNG/PDF files keep the per-file header counts but omit the interactive view toggles.
222222
- The viewer is hosted locally through the gateway under `/plugins/diffs/...`.
223-
- Artifacts are ephemeral and stored in the plugin temp subfolder (`$TMPDIR/openclaw-diffs`).
223+
- Viewer HTML and metadata are ephemeral SQLite plugin blobs. The URL token is returned to the caller while SQLite stores only its SHA-256 hash.
224+
- Rendered PNG/PDF files remain temporary materializations in `$TMPDIR/openclaw-diffs` because delivery APIs require a file path. No JSON metadata sidecars are written or imported.
224225
- Default viewer URLs use loopback (`127.0.0.1`) unless you set plugin `viewerBaseUrl`, pass `baseUrl`, or use `gateway.bind=custom` + `gateway.customBindHost`.
225226
- If `gateway.trustedProxies` includes loopback for a same-host proxy (for example Tailscale Serve), raw `127.0.0.1` viewer requests without forwarded client-IP headers fail closed by design.
226227
- In that topology, prefer `mode=file` / `mode=both` for attachments, or intentionally enable remote viewers and set plugin `viewerBaseUrl` (or pass a proxy/public `baseUrl`) when you need a shareable viewer URL.

‎extensions/diffs/src/browser.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ import fs from "node:fs/promises";
33
import type { IncomingMessage, ServerResponse } from "node:http";
44
import path from "node:path";
55
import { expectDefined } from "@openclaw/normalization-core";
6+
import type {
7+
PluginBlobEntry,
8+
PluginBlobEntryInfo,
9+
PluginBlobStore,
10+
} from "openclaw/plugin-sdk/plugin-state-runtime";
611
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
712
import { createMockServerResponse } from "openclaw/plugin-sdk/test-env";
813
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -319,6 +324,7 @@ describe("diffs plugin registration", () => {
319324
},
320325
},
321326
} as OpenClawConfig;
327+
const blobStore = createMemoryBlobStore();
322328

323329
const api = createTestPluginApi({
324330
id: "diffs",
@@ -347,6 +353,7 @@ describe("diffs plugin registration", () => {
347353
config: {
348354
current: () => configFile,
349355
},
356+
state: { openBlobStore: () => blobStore },
350357
} as never,
351358
registerTool(tool: Parameters<OpenClawPluginApi["registerTool"]>[0]) {
352359
registeredToolFactory = typeof tool === "function" ? tool : () => tool;
@@ -445,6 +452,7 @@ describe("diffs plugin registration", () => {
445452
},
446453
},
447454
} as OpenClawConfig;
455+
const blobStore = createMemoryBlobStore();
448456

449457
const api = createTestPluginApi({
450458
id: "diffs",
@@ -475,6 +483,7 @@ describe("diffs plugin registration", () => {
475483
config: {
476484
current: () => configFile,
477485
},
486+
state: { openBlobStore: () => blobStore },
478487
} as never,
479488
registerTool(tool: Parameters<OpenClawPluginApi["registerTool"]>[0]) {
480489
registeredToolFactory = typeof tool === "function" ? tool : () => tool;
@@ -601,6 +610,7 @@ describe("diffs plugin registration", () => {
601610
},
602611
},
603612
} as OpenClawConfig;
613+
const blobStore = createMemoryBlobStore();
604614

605615
const api = createTestPluginApi({
606616
id: "diffs",
@@ -622,6 +632,7 @@ describe("diffs plugin registration", () => {
622632
config: {
623633
current: () => configFile,
624634
},
635+
state: { openBlobStore: () => blobStore },
625636
} as never,
626637
registerTool(tool: Parameters<OpenClawPluginApi["registerTool"]>[0]) {
627638
registeredToolFactory = typeof tool === "function" ? tool : () => tool;
@@ -672,6 +683,105 @@ describe("diffs plugin registration", () => {
672683
});
673684
});
674685

686+
function createMemoryBlobStore<TMetadata>(): PluginBlobStore<TMetadata> {
687+
const entries = new Map<
688+
string,
689+
{
690+
bytes: Uint8Array;
691+
metadata: TMetadata;
692+
createdAt: number;
693+
expiresAt?: number;
694+
}
695+
>();
696+
const read = (key: string): PluginBlobEntry<TMetadata> | undefined => {
697+
const entry = entries.get(key);
698+
if (!entry) {
699+
return undefined;
700+
}
701+
if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) {
702+
entries.delete(key);
703+
return undefined;
704+
}
705+
return {
706+
key,
707+
bytes: entry.bytes.slice(),
708+
metadata: entry.metadata,
709+
sizeBytes: entry.bytes.byteLength,
710+
createdAt: entry.createdAt,
711+
...(entry.expiresAt !== undefined ? { expiresAt: entry.expiresAt } : {}),
712+
};
713+
};
714+
const register: PluginBlobStore<TMetadata>["register"] = async (key, bytes, metadata, opts) => {
715+
const createdAt = Date.now();
716+
entries.set(key, {
717+
bytes: bytes.slice(),
718+
metadata,
719+
createdAt,
720+
...(opts?.ttlMs ? { expiresAt: createdAt + opts.ttlMs } : {}),
721+
});
722+
};
723+
return {
724+
register,
725+
async registerIfAbsent(key, bytes, metadata, opts) {
726+
if (read(key)) {
727+
return false;
728+
}
729+
await register(key, bytes, metadata, opts);
730+
return true;
731+
},
732+
async lookup(key) {
733+
return read(key);
734+
},
735+
async entries() {
736+
return [...entries.keys()].flatMap((key) => {
737+
const entry = read(key);
738+
if (!entry) {
739+
return [];
740+
}
741+
const { bytes: _bytes, ...info } = entry;
742+
return [info];
743+
});
744+
},
745+
async delete(key) {
746+
return entries.delete(key);
747+
},
748+
async deleteExpiredKey(key) {
749+
const entry = entries.get(key);
750+
if (!entry || entry.expiresAt === undefined || entry.expiresAt > Date.now()) {
751+
return undefined;
752+
}
753+
entries.delete(key);
754+
return {
755+
key,
756+
metadata: entry.metadata,
757+
sizeBytes: entry.bytes.byteLength,
758+
createdAt: entry.createdAt,
759+
expiresAt: entry.expiresAt,
760+
};
761+
},
762+
async deleteExpired() {
763+
const expired: PluginBlobEntryInfo<TMetadata>[] = [];
764+
for (const [key, entry] of entries) {
765+
if (entry.expiresAt === undefined || entry.expiresAt > Date.now()) {
766+
continue;
767+
}
768+
entries.delete(key);
769+
expired.push({
770+
key,
771+
metadata: entry.metadata,
772+
sizeBytes: entry.bytes.byteLength,
773+
createdAt: entry.createdAt,
774+
expiresAt: entry.expiresAt,
775+
});
776+
}
777+
return expired;
778+
},
779+
async clear() {
780+
entries.clear();
781+
},
782+
};
783+
}
784+
675785
function createConfig(): OpenClawConfig {
676786
return {
677787
browser: {

‎extensions/diffs/src/http.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -97,23 +97,24 @@ export function createDiffsHttpHandler(params: {
9797
return true;
9898
}
9999

100-
const artifact = await params.store.getArtifact(id, token);
101-
if (!artifact) {
102-
recordRemoteFailure(viewerFailureLimiter, access);
103-
respondText(res, 404, "Diff not found or expired");
104-
return true;
105-
}
106-
107100
try {
108-
const html = await params.store.readHtml(id);
101+
// Authorization and payload read share one SQLite row snapshot. Keeping
102+
// them together prevents a replacement between token check and response.
103+
const viewer = await params.store.readAuthorizedViewer(id, token);
104+
if (!viewer) {
105+
recordRemoteFailure(viewerFailureLimiter, access);
106+
respondText(res, 404, "Diff not found or expired");
107+
return true;
108+
}
109109
resetRemoteFailures(viewerFailureLimiter, access);
110110
res.statusCode = 200;
111111
setSharedHeaders(res, "text/html; charset=utf-8");
112112
res.setHeader("content-security-policy", VIEWER_CONTENT_SECURITY_POLICY);
113+
res.setHeader("content-length", String(viewer.html.byteLength));
113114
if (req.method === "HEAD") {
114115
res.end();
115116
} else {
116-
res.end(html);
117+
res.end(Buffer.from(viewer.html));
117118
}
118119
return true;
119120
} catch (error) {

‎extensions/diffs/src/plugin.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ describe("diffs plugin language-pack discovery", () => {
3535
'{"id":"diffs-language-pack"}\n',
3636
);
3737
const config = { plugins: {} } as OpenClawConfig;
38+
const openBlobStore = vi.fn(() => createBlobStoreStub());
3839
let registeredToolFactory:
3940
| ((
4041
ctx: OpenClawPluginToolContext,
@@ -43,13 +44,23 @@ describe("diffs plugin language-pack discovery", () => {
4344
const api = createTestPluginApi({
4445
rootDir: diffsRoot,
4546
config,
46-
runtime: { config: { current: () => config } } as never,
47+
runtime: {
48+
config: { current: () => config },
49+
state: { openBlobStore },
50+
} as never,
4751
registerTool(tool: Parameters<OpenClawPluginApi["registerTool"]>[0]) {
4852
registeredToolFactory = typeof tool === "function" ? tool : () => tool;
4953
},
5054
});
5155

5256
registerDiffsPlugin(api);
57+
expect(openBlobStore).toHaveBeenCalledWith({
58+
namespace: "diff-artifacts",
59+
maxEntries: 2_048,
60+
maxBytesPerEntry: 32 * 1024 * 1024,
61+
maxBytesPerNamespace: 256 * 1024 * 1024,
62+
overflowPolicy: "reject-new",
63+
});
5364
const context = {
5465
agentId: "main",
5566
sessionId: "session-1",
@@ -76,3 +87,15 @@ describe("diffs plugin language-pack discovery", () => {
7687
},
7788
);
7889
});
90+
91+
function createBlobStoreStub() {
92+
return {
93+
register: vi.fn(),
94+
registerIfAbsent: vi.fn(),
95+
lookup: vi.fn(),
96+
entries: vi.fn(),
97+
delete: vi.fn(),
98+
deleteExpired: vi.fn(),
99+
clear: vi.fn(),
100+
};
101+
}

‎extensions/diffs/src/plugin.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,24 @@ import { createDiffsHttpHandler } from "./http.js";
1616
import { DIFFS_AGENT_GUIDANCE } from "./prompt-guidance.js";
1717
import { DiffArtifactStore } from "./store.js";
1818
import { createDiffsTool } from "./tool.js";
19+
import type { DiffArtifactBlobMetadata } from "./types.js";
1920

2021
const DIFFS_LANGUAGE_PACK_PLUGIN_ID = "diffs-language-pack";
22+
const DIFF_ARTIFACT_NAMESPACE = "diff-artifacts";
23+
const DIFF_ARTIFACT_MAX_ENTRIES = 2_048;
24+
const DIFF_ARTIFACT_MAX_BYTES_PER_ENTRY = 32 * 1024 * 1024;
25+
const DIFF_ARTIFACT_MAX_BYTES_PER_NAMESPACE = 256 * 1024 * 1024;
2126

2227
export function registerDiffsPlugin(api: OpenClawPluginApi): void {
2328
const store = new DiffArtifactStore({
2429
rootDir: path.join(resolvePreferredOpenClawTmpDir(), "openclaw-diffs"),
30+
blobStore: api.runtime.state.openBlobStore<DiffArtifactBlobMetadata>({
31+
namespace: DIFF_ARTIFACT_NAMESPACE,
32+
maxEntries: DIFF_ARTIFACT_MAX_ENTRIES,
33+
maxBytesPerEntry: DIFF_ARTIFACT_MAX_BYTES_PER_ENTRY,
34+
maxBytesPerNamespace: DIFF_ARTIFACT_MAX_BYTES_PER_NAMESPACE,
35+
overflowPolicy: "reject-new",
36+
}),
2537
logger: api.logger,
2638
});
2739
const resolveCurrentPluginConfig = () =>

0 commit comments

Comments
 (0)