File size: 7,944 Bytes
76289e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getNodeSqliteKysely } from "../infra/kysely-sync.js";
import { closeOpenClawStateDatabaseByPath } from "../state/openclaw-state-db-cache.js";
import {
  openOpenClawStateDatabase,
  runOpenClawStateWriteTransaction,
} from "../state/openclaw-state-db.js";
import {
  createOpenClawTestState,
  type OpenClawTestState,
} from "../test-utils/openclaw-test-state.js";
import {
  createPluginStateSyncKeyedStore,
  resetPluginStateStoreForTests,
} from "./plugin-state-store.js";
import { lookupPluginStateEntry, registerPluginStateEntry } from "./plugin-state-store.kernel.js";
import { closePluginStateDatabase } from "./plugin-state-store.sqlite.js";
import {
  clearPluginStateStoreForTests,
  seedPluginStateEntriesForTests,
} from "./plugin-state-store.test-helpers.js";

let testState: OpenClawTestState;
beforeAll(async () => {
  testState = await createOpenClawTestState({ label: "plugin-state-prepared" });
});
beforeEach(() => {
  testState.applyEnv();
  clearPluginStateStoreForTests();
});
afterEach(() => {
  resetPluginStateStoreForTests();
});
afterAll(async () => {
  await testState.cleanup();
});

describe("plugin state prepared queries", () => {
  it("uses the supplied connection and keeps registration eviction in its owner's transaction", () => {
    const scope = { pluginId: "discord", namespace: "owned-kernel" };
    const defaultStore = createPluginStateSyncKeyedStore<string>(scope.pluginId, {
      namespace: scope.namespace,
      maxEntries: 1,
    });
    defaultStore.register("original", "default database");
    const pathname = testState.statePath("kernel-owned.sqlite");
    const database = openOpenClawStateDatabase({ path: pathname, env: testState.env });
    const options = { database, env: testState.env };
    const entry = { ...scope, maxEntries: 1, overflowPolicy: "evict-oldest" as const };
    runOpenClawStateWriteTransaction(() => {
      registerPluginStateEntry(database, { ...entry, key: "original", valueJson: '"owned"' }, 10);
    }, options);

    const aborted = new Error("abort the caller's transaction");
    expect(() =>
      runOpenClawStateWriteTransaction(() => {
        registerPluginStateEntry(
          database,
          { ...entry, key: "pending", valueJson: '"pending"' },
          10,
        );
        expect(lookupPluginStateEntry(database, { ...scope, key: "pending" })).toBe("pending");
        expect(lookupPluginStateEntry(database, { ...scope, key: "original" })).toBeUndefined();
        throw aborted;
      }, options),
    ).toThrow(aborted);
    expect(lookupPluginStateEntry(database, { ...scope, key: "pending" })).toBeUndefined();
    expect(lookupPluginStateEntry(database, { ...scope, key: "original" })).toBe("owned");
    expect(defaultStore.lookup("original")).toBe("default database");
    closeOpenClawStateDatabaseByPath(pathname);
    const reopened = openOpenClawStateDatabase({ path: pathname, env: testState.env });
    expect(lookupPluginStateEntry(reopened, { ...scope, key: "original" })).toBe("owned");
    expect(lookupPluginStateEntry(reopened, { ...scope, key: "pending" })).toBeUndefined();
  });

  it("compiles exact reads once per connection with fresh scope and expiry bindings", () => {
    const now = Date.now();
    seedPluginStateEntriesForTests([
      { pluginId: "discord", namespace: "prepared", key: "first", value: 1, expiresAt: now + 100 },
      { pluginId: "discord", namespace: "prepared", key: "second", value: 2 },
      { pluginId: "telegram", namespace: "prepared", key: "first", value: 3 },
      { pluginId: "discord", namespace: "sibling", key: "first", value: 4 },
    ]);
    const store = createPluginStateSyncKeyedStore<number>("discord", {
      namespace: "prepared",
      maxEntries: 10,
    });
    const pluginSibling = createPluginStateSyncKeyedStore<number>("telegram", {
      namespace: "prepared",
      maxEntries: 10,
    });
    const namespaceSibling = createPluginStateSyncKeyedStore<number>("discord", {
      namespace: "sibling",
      maxEntries: 10,
    });
    const clock = vi.spyOn(Date, "now").mockReturnValue(now);
    try {
      for (let connection = 0; connection < 2; connection++) {
        closePluginStateDatabase();
        const { db } = openOpenClawStateDatabase();
        const compile = vi.spyOn(getNodeSqliteKysely(db).getExecutor(), "compileQuery");
        try {
          clock.mockReturnValue(now);
          expect(store.lookup("first")).toBe(1);
          expect(store.lookup("second")).toBe(2);
          expect(pluginSibling.lookup("first")).toBe(3);
          expect(namespaceSibling.lookup("first")).toBe(4);
          expect(store.lookup("missing")).toBeUndefined();
          clock.mockReturnValue(now + 100);
          expect(store.lookup("first")).toBeUndefined();
          expect(store.lookup("second")).toBe(2);
          expect(compile).toHaveBeenCalledOnce();
        } finally {
          compile.mockRestore();
        }
      }
    } finally {
      clock.mockRestore();
    }
  });

  it.each([
    ["register", "evict-oldest"],
    ["register", "reject-new"],
    ["registerIfAbsent", "evict-oldest"],
  ] as const)(
    "reuses %s %s write and quota compilation with fresh bindings after reopening",
    (operation, overflowPolicy) => {
      const options = { namespace: "prepared-writes", maxEntries: 20, overflowPolicy };
      const stores = [
        createPluginStateSyncKeyedStore<string>("discord", options),
        createPluginStateSyncKeyedStore<string>("telegram", options),
        createPluginStateSyncKeyedStore<string>("discord", {
          ...options,
          namespace: "prepared-sibling",
        }),
      ];
      const clock = vi.spyOn(Date, "now").mockReturnValue(10_000);
      try {
        for (let connection = 0; connection < 2; connection++) {
          closePluginStateDatabase();
          const { db } = openOpenClawStateDatabase();
          const compile = vi.spyOn(getNodeSqliteKysely(db).getExecutor(), "compileQuery");
          try {
            const key = `round-${connection}`;
            for (const [index, store] of stores.entries()) {
              clock.mockReturnValue(10_000 + index);
              store[operation](key, `value-${index}`, { ttlMs: 100 });
              clock.mockReturnValue(10_010 + index);
              store[operation](`${key}-durable`, `durable-${index}`);
              const result = store[operation](key, `replacement-${index}`);
              if (operation === "registerIfAbsent") {
                expect(result).toBe(false);
              }
              const expected =
                operation === "registerIfAbsent"
                  ? {
                      key,
                      value: `value-${index}`,
                      createdAt: 10_000 + index,
                      expiresAt: 10_100 + index,
                    }
                  : { key, value: `replacement-${index}`, createdAt: 10_010 + index };
              expect(store.entries().filter((entry) => entry.key.startsWith(key))).toEqual([
                expected,
                { key: `${key}-durable`, value: `durable-${index}`, createdAt: 10_010 + index },
              ]);
            }
            const writes = compile.mock.results.filter(
              (result) => result.type === "return" && result.value.sql.startsWith("insert"),
            );
            expect(writes).toHaveLength(1);
            const counts = compile.mock.results.filter(
              (result) =>
                result.type === "return" &&
                result.value.sql.startsWith(
                  'select count(*) as "count" from "plugin_state_entries"',
                ),
            );
            expect(counts).toHaveLength(2);
          } finally {
            compile.mockRestore();
          }
        }
      } finally {
        clock.mockRestore();
      }
    },
  );
});