File size: 25,118 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import type { DatabaseSync } from "node:sqlite";
import { resolveExpiresAtMsFromDurationMs } from "@openclaw/normalization-core/number-coercion";
import type { Selectable } from "kysely";
import {
  executeSqliteQuerySync,
  executeSqliteQueryTakeFirstSync,
  getNodeSqliteKysely,
  iterateSqliteQuerySync,
  prepareSqliteQuerySync,
} from "../infra/kysely-sync.js";
import { coerceRequiredSqliteNumber, normalizeSqliteNumber } from "../infra/sqlite-number.js";
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
import {
  PluginStateStoreError,
  type PluginStateEntry,
  type PluginStateOverflowPolicy,
  type PluginStateStoreErrorCode,
  type PluginStateStoreOperation,
} from "./plugin-state-store.types.js";

export const MAX_PLUGIN_STATE_VALUE_BYTES = 1_048_576;
const PLUGIN_STATE_EXPIRY_BATCH_ROWS = 1_024;

type PluginStateStoreDatabase = Pick<OpenClawStateKyselyDatabase, "plugin_state_entries">;

type PluginStateRow = Selectable<PluginStateStoreDatabase["plugin_state_entries"]>;
export type PluginStateReadRow = Omit<PluginStateRow, "plugin_id" | "namespace">;

export type PluginStateDatabase = {
  db: DatabaseSync;
  path: string;
};

export function createPluginStateError(params: {
  code: PluginStateStoreErrorCode;
  operation: PluginStateStoreOperation;
  message: string;
  path?: string;
  cause?: unknown;
}): PluginStateStoreError {
  return new PluginStateStoreError(params.message, {
    code: params.code,
    operation: params.operation,
    ...(params.path ? { path: params.path } : {}),
    cause: params.cause,
  });
}

export function resolvePluginStateExpiresAtMs(params: {
  ttlMs: number | undefined;
  now: number;
  operation: PluginStateStoreOperation;
  path?: string;
}): number | null {
  if (params.ttlMs == null) {
    return null;
  }
  const expiresAt = resolveExpiresAtMsFromDurationMs(params.ttlMs, { nowMs: params.now });
  if (expiresAt === undefined) {
    throw createPluginStateError({
      code: "PLUGIN_STATE_INVALID_INPUT",
      operation: params.operation,
      message: "Plugin state ttlMs cannot produce a valid expiry timestamp.",
      ...(params.path ? { path: params.path } : {}),
    });
  }
  return expiresAt;
}

export function parseStoredJson(
  raw: string,
  operation: PluginStateStoreOperation,
  databasePath: string,
): unknown {
  try {
    return JSON.parse(raw) as unknown;
  } catch (error) {
    throw createPluginStateError({
      code: "PLUGIN_STATE_CORRUPT",
      operation,
      message: "Plugin state entry contains corrupt JSON.",
      path: databasePath,
      cause: error,
    });
  }
}

export function rowToEntry(
  row: PluginStateReadRow,
  operation: PluginStateStoreOperation,
  databasePath: string,
): PluginStateEntry<unknown> {
  const expiresAt = normalizeSqliteNumber(row.expires_at);
  return {
    key: row.entry_key,
    value: parseStoredJson(row.value_json, operation, databasePath),
    createdAt: normalizeSqliteNumber(row.created_at) ?? 0,
    ...(expiresAt != null ? { expiresAt } : {}),
  };
}

export function getPluginStateKysely(db: DatabaseSync) {
  return getNodeSqliteKysely<PluginStateStoreDatabase>(db);
}

export function bindPluginStateEntry(params: {
  pluginId: string;
  namespace: string;
  key: string;
  valueJson: string;
  createdAt: number;
  expiresAt: number | null;
}): PluginStateRow {
  return {
    plugin_id: params.pluginId,
    namespace: params.namespace,
    entry_key: params.key,
    value_json: params.valueJson,
    created_at: params.createdAt,
    expires_at: params.expiresAt,
  };
}

type PluginStateWriteQuery = ReturnType<typeof prepareSqliteQuerySync<PluginStateRow>>;
const pluginStateUpsertQueries = new WeakMap<DatabaseSync, PluginStateWriteQuery>();
const pluginStateInsertIfAbsentQueries = new WeakMap<DatabaseSync, PluginStateWriteQuery>();

export function upsertPluginStateEntry(db: DatabaseSync, row: PluginStateRow): void {
  let query = pluginStateUpsertQueries.get(db);
  if (!query) {
    query = prepareSqliteQuerySync<PluginStateRow>(db, (parameter) =>
      getPluginStateKysely(db)
        .insertInto("plugin_state_entries")
        .values({
          plugin_id: parameter((value) => value.plugin_id),
          namespace: parameter((value) => value.namespace),
          entry_key: parameter((value) => value.entry_key),
          value_json: parameter((value) => value.value_json),
          created_at: parameter((value) => value.created_at),
          expires_at: parameter((value) => value.expires_at),
        })
        .onConflict((conflict) =>
          conflict.columns(["plugin_id", "namespace", "entry_key"]).doUpdateSet({
            value_json: (eb) => eb.ref("excluded.value_json"),
            created_at: (eb) => eb.ref("excluded.created_at"),
            expires_at: (eb) => eb.ref("excluded.expires_at"),
          }),
        ),
    );
    pluginStateUpsertQueries.set(db, query);
  }
  query(row);
}

export function insertPluginStateEntryIfAbsent(db: DatabaseSync, row: PluginStateRow): boolean {
  let query = pluginStateInsertIfAbsentQueries.get(db);
  if (!query) {
    query = prepareSqliteQuerySync<PluginStateRow>(db, (parameter) =>
      getPluginStateKysely(db)
        .insertInto("plugin_state_entries")
        .orIgnore()
        .values({
          plugin_id: parameter((value) => value.plugin_id),
          namespace: parameter((value) => value.namespace),
          entry_key: parameter((value) => value.entry_key),
          value_json: parameter((value) => value.value_json),
          created_at: parameter((value) => value.created_at),
          expires_at: parameter((value) => value.expires_at),
        }),
    );
    pluginStateInsertIfAbsentQueries.set(db, query);
  }
  const result = query(row);
  return Number(result.numAffectedRows ?? 0) > 0;
}

type PluginStateEntryLookup = { pluginId: string; namespace: string; key: string; now: number };
const pluginStateEntryQueries = new WeakMap<
  DatabaseSync,
  ReturnType<typeof prepareSqliteQuerySync<PluginStateEntryLookup, PluginStateReadRow>>
>();
const pluginStateEntryExistsQueries = new WeakMap<
  DatabaseSync,
  ReturnType<typeof prepareSqliteQuerySync<PluginStateEntryLookup, { entry_key: string }>>
>();

export function hasPluginStateEntry(db: DatabaseSync, params: PluginStateEntryLookup): boolean {
  let query = pluginStateEntryExistsQueries.get(db);
  if (!query) {
    query = prepareSqliteQuerySync<PluginStateEntryLookup, { entry_key: string }>(
      db,
      (parameter) => {
        const pluginId = parameter((value) => value.pluginId);
        const namespace = parameter((value) => value.namespace);
        const key = parameter((value) => value.key);
        const now = parameter((value) => value.now);
        return getPluginStateKysely(db)
          .selectFrom("plugin_state_entries")
          .select("entry_key")
          .where("plugin_id", "=", pluginId)
          .where("namespace", "=", namespace)
          .where("entry_key", "=", key)
          .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", now)]));
      },
    );
    pluginStateEntryExistsQueries.set(db, query);
  }
  return query(params).rows.length !== 0;
}

export function selectPluginStateEntry(
  db: DatabaseSync,
  params: PluginStateEntryLookup,
): PluginStateReadRow | undefined {
  let query = pluginStateEntryQueries.get(db);
  if (!query) {
    // Retain compilation with the physical connection; keys and expiry stay invocation-local.
    query = prepareSqliteQuerySync<PluginStateEntryLookup, PluginStateReadRow>(db, (parameter) => {
      const pluginId = parameter((value) => value.pluginId);
      const namespace = parameter((value) => value.namespace);
      const key = parameter((value) => value.key);
      const now = parameter((value) => value.now);
      return getPluginStateKysely(db)
        .selectFrom("plugin_state_entries")
        .select(["entry_key", "value_json", "created_at", "expires_at"])
        .where("plugin_id", "=", pluginId)
        .where("namespace", "=", namespace)
        .where("entry_key", "=", key)
        .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", now)]));
    });
    pluginStateEntryQueries.set(db, query);
  }
  return query(params).rows[0];
}

export function iteratePluginStateEntries(
  db: DatabaseSync,
  params: { pluginId: string; namespace: string; now: number },
): IterableIterator<PluginStateReadRow> {
  return iterateSqliteQuerySync(
    db,
    getPluginStateKysely(db)
      .selectFrom("plugin_state_entries")
      .select(["entry_key", "value_json", "created_at", "expires_at"])
      .where("plugin_id", "=", params.pluginId)
      .where("namespace", "=", params.namespace)
      .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", params.now)]))
      .orderBy("created_at", "asc")
      .orderBy("entry_key", "asc"),
  );
}

export function selectPluginStateEntriesInKeyRange(
  db: DatabaseSync,
  params: {
    pluginId: string;
    namespace: string;
    keyStartInclusive: string;
    keyEndExclusive: string;
    limit: number;
    order: "asc" | "desc";
    now: number;
  },
): PluginStateReadRow[] {
  return executeSqliteQuerySync(
    db,
    getPluginStateKysely(db)
      .selectFrom("plugin_state_entries")
      .select(["entry_key", "value_json", "created_at", "expires_at"])
      .where("plugin_id", "=", params.pluginId)
      .where("namespace", "=", params.namespace)
      .where("entry_key", ">=", params.keyStartInclusive)
      .where("entry_key", "<", params.keyEndExclusive)
      .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", params.now)]))
      .orderBy("entry_key", params.order)
      .limit(params.limit),
  ).rows;
}

export function deletePluginStateEntry(
  db: DatabaseSync,
  params: { pluginId: string; namespace: string; key: string },
): number {
  const result = executeSqliteQuerySync(
    db,
    getPluginStateKysely(db)
      .deleteFrom("plugin_state_entries")
      .where("plugin_id", "=", params.pluginId)
      .where("namespace", "=", params.namespace)
      .where("entry_key", "=", params.key),
  );
  return Number(result.numAffectedRows ?? 0);
}

const pluginStateExpiryQueries = new WeakMap<
  DatabaseSync,
  ReturnType<typeof prepareSqliteQuerySync<number, { expires_at: number | bigint | null }>>
>();

export function deleteExpiredPluginStateEntries(
  db: DatabaseSync,
  now: number,
  scope?: { pluginId: string; namespace: string },
): number {
  const kysely = getPluginStateKysely(db);
  if (scope) {
    let query = pluginStateExpiryQueries.get(db);
    if (!query) {
      query = prepareSqliteQuerySync<number, { expires_at: number | bigint | null }>(
        db,
        (parameter) =>
          kysely
            .selectFrom("plugin_state_entries")
            .select("expires_at")
            .where("expires_at", "is not", null)
            .where(
              "expires_at",
              "<=",
              parameter((value) => value),
            )
            .limit(1),
      );
      pluginStateExpiryQueries.set(db, query);
    }
    // The expiry index can prove there is nothing due without scanning the namespace.
    // Only compilation is retained; expiry is checked in the caller's current transaction.
    if (query(now).rows.length === 0) {
      return 0;
    }
  }
  let expiredEntries = kysely
    .selectFrom("plugin_state_entries")
    .select(["plugin_id", "namespace", "entry_key"])
    .where("expires_at", "is not", null)
    .where("expires_at", "<=", now);
  // Global expiry ordering uses its index; namespace scans must stay unsorted
  // so SQLite never builds an unbounded temporary sort under the write lock.
  expiredEntries = scope
    ? expiredEntries
        .where("plugin_id", "=", scope.pluginId)
        .where("namespace", "=", scope.namespace)
    : expiredEntries.orderBy("expires_at", "asc");
  const result = executeSqliteQuerySync(
    db,
    kysely
      .deleteFrom("plugin_state_entries")
      .where((expression) =>
        expression(
          expression.refTuple("plugin_id", "namespace", "entry_key"),
          "in",
          expiredEntries
            .limit(PLUGIN_STATE_EXPIRY_BATCH_ROWS)
            .$asTuple("plugin_id", "namespace", "entry_key"),
        ),
      ),
  );
  return Number(result.numAffectedRows ?? 0);
}

type PluginStateNamespaceCountParams = { pluginId: string; namespace: string; now: number };
type PluginStateCountRow = { count: number | bigint };
const pluginStateNamespaceCountQueries = new WeakMap<
  DatabaseSync,
  ReturnType<typeof prepareSqliteQuerySync<PluginStateNamespaceCountParams, PluginStateCountRow>>
>();

export function countLivePluginStateNamespaceEntries(
  db: DatabaseSync,
  params: PluginStateNamespaceCountParams,
): number {
  let query = pluginStateNamespaceCountQueries.get(db);
  if (!query) {
    query = prepareSqliteQuerySync<PluginStateNamespaceCountParams, PluginStateCountRow>(
      db,
      (parameter) =>
        getPluginStateKysely(db)
          .selectFrom("plugin_state_entries")
          .select((eb) => eb.fn.countAll<number | bigint>().as("count"))
          .where(
            "plugin_id",
            "=",
            parameter((value) => value.pluginId),
          )
          .where(
            "namespace",
            "=",
            parameter((value) => value.namespace),
          )
          .where((eb) =>
            eb.or([
              eb("expires_at", "is", null),
              eb(
                "expires_at",
                ">",
                parameter((value) => value.now),
              ),
            ]),
          ),
    );
    pluginStateNamespaceCountQueries.set(db, query);
  }
  const row = query(params).rows[0];
  return coerceRequiredSqliteNumber(row?.count ?? 0);
}

export function allocatePluginStateNamespaceCreatedAt(
  db: DatabaseSync,
  params: { pluginId: string; namespace: string; now: number },
): number {
  const row = executeSqliteQueryTakeFirstSync(
    db,
    getPluginStateKysely(db)
      .selectFrom("plugin_state_entries")
      .select((eb) => eb.fn.max<number | bigint>("created_at").as("max_created_at"))
      .where("plugin_id", "=", params.pluginId)
      .where("namespace", "=", params.namespace),
  );
  const previous = normalizeSqliteNumber(row?.max_created_at ?? null);
  const next = previous === undefined ? params.now : Math.max(params.now, previous + 1);
  if (!Number.isSafeInteger(next)) {
    throw new RangeError("Plugin state namespace append order exhausted safe integer range");
  }
  return next;
}

type PluginStateCountParams = { pluginId: string; now: number };
const pluginStateCountQueries = new WeakMap<
  DatabaseSync,
  ReturnType<typeof prepareSqliteQuerySync<PluginStateCountParams, PluginStateCountRow>>
>();

export function countLivePluginStateEntries(
  db: DatabaseSync,
  params: PluginStateCountParams,
): number {
  let query = pluginStateCountQueries.get(db);
  if (!query) {
    query = prepareSqliteQuerySync<PluginStateCountParams, PluginStateCountRow>(db, (parameter) =>
      getPluginStateKysely(db)
        .selectFrom("plugin_state_entries")
        .select((eb) => eb.fn.countAll<number | bigint>().as("count"))
        .where(
          "plugin_id",
          "=",
          parameter((value) => value.pluginId),
        )
        .where((eb) =>
          eb.or([
            eb("expires_at", "is", null),
            eb(
              "expires_at",
              ">",
              parameter((value) => value.now),
            ),
          ]),
        ),
    );
    pluginStateCountQueries.set(db, query);
  }
  const row = query(params).rows[0];
  return coerceRequiredSqliteNumber(row?.count ?? 0);
}

function deleteOldestPluginStateNamespaceEntries(
  db: DatabaseSync,
  params: { pluginId: string; namespace: string; protectedKey: string; now: number; limit: number },
): number {
  const kysely = getPluginStateKysely(db);
  const keys = kysely
    .selectFrom("plugin_state_entries")
    .select("entry_key")
    .where("plugin_id", "=", params.pluginId)
    .where("namespace", "=", params.namespace)
    .where("entry_key", "!=", params.protectedKey)
    .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", params.now)]))
    .orderBy("created_at", "asc")
    .orderBy("entry_key", "asc")
    .limit(params.limit);
  const result = executeSqliteQuerySync(
    db,
    kysely
      .deleteFrom("plugin_state_entries")
      .where("plugin_id", "=", params.pluginId)
      .where("namespace", "=", params.namespace)
      .where("entry_key", "in", keys),
  );
  return Number(result.numAffectedRows ?? 0);
}

type PluginStateRetention = {
  namespaceCount: number;
  pluginCount: number;
  nextExpiry: number;
  now: number;
  sweepPending: boolean;
};

export function readPluginStateRetention(
  db: DatabaseSync,
  params: { pluginId: string; namespace: string; now: number },
): PluginStateRetention {
  const row = executeSqliteQueryTakeFirstSync(
    db,
    getPluginStateKysely(db)
      .selectFrom("plugin_state_entries")
      .select((eb) => [
        eb.fn.countAll<number | bigint>().as("plugin_count"),
        eb.fn
          .countAll<number | bigint>()
          .filterWhere("namespace", "=", params.namespace)
          .as("namespace_count"),
        eb.fn.min<number | bigint | null>("expires_at").as("next_expiry"),
      ])
      .where("plugin_id", "=", params.pluginId)
      .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", params.now)])),
  );
  return {
    namespaceCount: coerceRequiredSqliteNumber(row?.namespace_count ?? 0),
    pluginCount: coerceRequiredSqliteNumber(row?.plugin_count ?? 0),
    nextExpiry: normalizeSqliteNumber(row?.next_expiry ?? null) ?? Infinity,
    now: params.now,
    sweepPending: true,
  };
}

export function enforcePostRegisterLimits(params: {
  store: PluginStateDatabase;
  pluginId: string;
  namespace: string;
  maxEntries: number;
  overflowPolicy: PluginStateOverflowPolicy;
  now: number;
  retention?: PluginStateRetention;
  protectedKey: string;
  maxPluginEntries: number | undefined;
}): void {
  if (params.overflowPolicy === "reject-new") {
    return;
  }
  const maxPluginEntries = params.maxPluginEntries;
  // A plugin cap no larger than the namespace cap sheds the same oldest prefix.
  if (params.retention || maxPluginEntries === undefined || params.maxEntries < maxPluginEntries) {
    const namespaceCount =
      params.retention?.namespaceCount ??
      countLivePluginStateNamespaceEntries(params.store.db, {
        pluginId: params.pluginId,
        namespace: params.namespace,
        now: params.now,
      });
    if (namespaceCount > params.maxEntries) {
      const deleted = deleteOldestPluginStateNamespaceEntries(params.store.db, {
        pluginId: params.pluginId,
        namespace: params.namespace,
        protectedKey: params.protectedKey,
        now: params.now,
        limit: namespaceCount - params.maxEntries,
      });
      if (params.retention) {
        params.retention.namespaceCount -= deleted;
        params.retention.pluginCount -= deleted;
      }
    }
  }

  if (maxPluginEntries === undefined) {
    return;
  }

  const pluginCount =
    params.retention?.pluginCount ??
    countLivePluginStateEntries(params.store.db, {
      pluginId: params.pluginId,
      now: params.now,
    });
  if (pluginCount <= maxPluginEntries) {
    return;
  }

  // Shed only rows from the namespace that grew. Sibling namespaces can hold
  // durable state; if this namespace cannot cover the overflow, fail so the
  // surrounding transaction rolls every insertion and deletion back.
  const deleted = deleteOldestPluginStateNamespaceEntries(params.store.db, {
    pluginId: params.pluginId,
    namespace: params.namespace,
    protectedKey: params.protectedKey,
    now: params.now,
    limit: pluginCount - maxPluginEntries,
  });
  if (params.retention) {
    params.retention.namespaceCount -= deleted;
    params.retention.pluginCount -= deleted;
  }
  // The deletion uses the same live-row predicate and transaction as pluginCount.
  const remainingPluginCount = params.retention?.pluginCount ?? pluginCount - deleted;
  if (remainingPluginCount > maxPluginEntries) {
    throw createPluginStateError({
      code: "PLUGIN_STATE_LIMIT_EXCEEDED",
      operation: "register",
      message: `Plugin state for ${params.pluginId} exceeds the ${maxPluginEntries} live row limit.`,
      path: params.store.path,
    });
  }
}

export function assertCanInsertPluginStateEntry(params: {
  store: PluginStateDatabase;
  pluginId: string;
  namespace: string;
  maxEntries: number;
  overflowPolicy: PluginStateOverflowPolicy;
  now: number;
  retention?: PluginStateRetention;
  maxPluginEntries: number;
}): void {
  if (params.overflowPolicy !== "reject-new") {
    return;
  }
  const namespaceCount =
    params.retention?.namespaceCount ??
    countLivePluginStateNamespaceEntries(params.store.db, {
      pluginId: params.pluginId,
      namespace: params.namespace,
      now: params.now,
    });
  if (namespaceCount >= params.maxEntries) {
    throw createPluginStateError({
      code: "PLUGIN_STATE_LIMIT_EXCEEDED",
      operation: "register",
      message: `Plugin state namespace ${params.namespace} for ${params.pluginId} reached its ${params.maxEntries}-row limit.`,
      path: params.store.path,
    });
  }
  const maxPluginEntries = params.maxPluginEntries;
  const pluginCount =
    params.retention?.pluginCount ??
    countLivePluginStateEntries(params.store.db, {
      pluginId: params.pluginId,
      now: params.now,
    });
  if (pluginCount >= maxPluginEntries) {
    throw createPluginStateError({
      code: "PLUGIN_STATE_LIMIT_EXCEEDED",
      operation: "register",
      message: `Plugin state for ${params.pluginId} reached the ${maxPluginEntries} live row limit.`,
      path: params.store.path,
    });
  }
}

export type PluginStateRegisterEntryParams = {
  pluginId: string;
  namespace: string;
  key: string;
  valueJson: string;
  maxEntries: number;
  overflowPolicy: PluginStateOverflowPolicy;
  ttlMs?: number;
  // Migration-only override: eviction orders rows by created_at, so imported
  // legacy rows must keep their original age instead of the import time.
  createdAtMs?: number;
};

/** The caller owns the write transaction, including expiry cleanup and quota eviction. */
export function registerPluginStateEntry(
  store: PluginStateDatabase,
  params: PluginStateRegisterEntryParams,
  maxPluginEntries: number,
  retention?: PluginStateRetention,
): void {
  const now = Date.now();
  const expiresAt = resolvePluginStateExpiresAtMs({
    ttlMs: params.ttlMs,
    now,
    operation: "register",
    path: store.path,
  });
  // Counts belong to this transaction. Expiry (including sibling rows) or a
  // backward clock invalidates them; ordinary writes update them incrementally.
  if (retention && (now < retention.now || now >= retention.nextExpiry)) {
    Object.assign(retention, readPluginStateRetention(store.db, { ...params, now }));
  }
  if (!retention || retention.sweepPending) {
    const deleted = deleteExpiredPluginStateEntries(store.db, now, params);
    if (retention) {
      retention.sweepPending = deleted === PLUGIN_STATE_EXPIRY_BATCH_ROWS;
    }
  }
  // Quotas and batch counts need existence, never the previous JSON payload.
  const existing =
    retention || params.overflowPolicy === "reject-new"
      ? hasPluginStateEntry(store.db, {
          pluginId: params.pluginId,
          namespace: params.namespace,
          key: params.key,
          now,
        })
      : false;
  if (!existing) {
    assertCanInsertPluginStateEntry({
      store,
      pluginId: params.pluginId,
      namespace: params.namespace,
      maxEntries: params.maxEntries,
      overflowPolicy: params.overflowPolicy,
      now,
      retention,
      maxPluginEntries,
    });
  }
  upsertPluginStateEntry(
    store.db,
    bindPluginStateEntry({
      pluginId: params.pluginId,
      namespace: params.namespace,
      key: params.key,
      valueJson: params.valueJson,
      createdAt: params.createdAtMs ?? now,
      expiresAt,
    }),
  );
  if (retention) {
    if (!existing) {
      retention.namespaceCount += 1;
      retention.pluginCount += 1;
    }
    retention.nextExpiry = Math.min(retention.nextExpiry, expiresAt ?? Infinity);
    retention.now = now;
  }
  enforcePostRegisterLimits({
    store,
    pluginId: params.pluginId,
    namespace: params.namespace,
    maxEntries: params.maxEntries,
    overflowPolicy: params.overflowPolicy,
    now,
    protectedKey: params.key,
    retention,
    maxPluginEntries,
  });
}

export function lookupPluginStateEntry(
  store: PluginStateDatabase,
  params: { pluginId: string; namespace: string; key: string },
): unknown {
  const row = selectPluginStateEntry(store.db, {
    pluginId: params.pluginId,
    namespace: params.namespace,
    key: params.key,
    now: Date.now(),
  });
  return row ? parseStoredJson(row.value_json, "lookup", store.path) : undefined;
}