@powerhousedao/switchboard 6.2.3-dev.85 → 6.2.3-dev.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  4. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  5. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  6. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  7. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  8. package/CHANGELOG.md +20 -0
  9. package/README.md +33 -0
  10. package/dist/boot.d.mts +1 -1
  11. package/dist/boot.mjs +1 -1
  12. package/dist/config/from-env.d.mts +1 -1
  13. package/dist/config/from-env.d.mts.map +1 -1
  14. package/dist/config/from-env.mjs +3 -3
  15. package/dist/config/schema.d.mts +1 -1
  16. package/dist/config/schema.mjs +3 -3
  17. package/dist/{from-env-BO0n9R02.mjs → from-env-BgyZQAxw.mjs} +79 -7
  18. package/dist/from-env-BgyZQAxw.mjs.map +1 -0
  19. package/dist/index.mjs +3 -3
  20. package/dist/{plugin-host-C1sYEm8g.d.mts → plugin-host-C0bSz1Oe.d.mts} +2 -2
  21. package/dist/{plugin-host-C1sYEm8g.d.mts.map → plugin-host-C0bSz1Oe.d.mts.map} +1 -1
  22. package/dist/plugins/ai.d.mts +37 -0
  23. package/dist/plugins/ai.d.mts.map +1 -0
  24. package/dist/plugins/ai.mjs +352 -0
  25. package/dist/plugins/ai.mjs.map +1 -0
  26. package/dist/plugins/attachments.d.mts +1 -1
  27. package/dist/plugins/attachments.mjs +3 -3
  28. package/dist/plugins/mcp.d.mts +1 -1
  29. package/dist/plugins/privacy.d.mts +1 -1
  30. package/dist/plugins/workflows.d.mts +2 -2
  31. package/dist/plugins/workflows.mjs +3 -3
  32. package/dist/{schema-ivUWPQOn.d.mts → schema-DhempFjb.d.mts} +41 -1
  33. package/dist/schema-DhempFjb.d.mts.map +1 -0
  34. package/dist/{schema-0g_QdOWn.mjs → schema-XEZrdmag.mjs} +55 -6
  35. package/dist/schema-XEZrdmag.mjs.map +1 -0
  36. package/dist/{server-YNY3Qw9a.mjs → server-BRVMofWD.mjs} +102 -14
  37. package/dist/server-BRVMofWD.mjs.map +1 -0
  38. package/dist/server.d.mts +7 -3
  39. package/dist/server.d.mts.map +1 -1
  40. package/dist/server.mjs +5 -5
  41. package/dist/{workflow-runtime-7GaJ13c9.d.mts → workflow-runtime-CF5pc8mt.d.mts} +5 -2
  42. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  43. package/dist/{workflows-DkIrfmdn.mjs → workflows-C_pWcP2u.mjs} +4 -3
  44. package/dist/{workflows-DkIrfmdn.mjs.map → workflows-C_pWcP2u.mjs.map} +1 -1
  45. package/package.json +22 -16
  46. package/test/ai-gateway.test.ts +555 -0
  47. package/test/config-from-env.test.ts +184 -0
  48. package/test/config-schema.test.ts +28 -0
  49. package/test/goldens/supergraph.graphql +122 -0
  50. package/test/keyframe-reclaim-store.test.ts +156 -0
  51. package/test/processor-timing-log.test.ts +109 -0
  52. package/tsdown.config.ts +1 -0
  53. package/dist/from-env-BO0n9R02.mjs.map +0 -1
  54. package/dist/schema-0g_QdOWn.mjs.map +0 -1
  55. package/dist/schema-ivUWPQOn.d.mts.map +0 -1
  56. package/dist/server-YNY3Qw9a.mjs.map +0 -1
  57. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +0 -1
@@ -17,6 +17,7 @@ import { resolveAttachmentUrlSigning } from "../src/attachments/url-signer.js";
17
17
  import { reactorDbUrlOf } from "../src/boot-preconditions.mjs";
18
18
  import { switchboardConfigFromEnv } from "../src/config/from-env.js";
19
19
  import {
20
+ mergeSwitchboardConfig,
20
21
  switchboardConfigSchema,
21
22
  type SwitchboardConfig,
22
23
  } from "../src/config/schema.js";
@@ -85,6 +86,25 @@ const KEYS = [
85
86
  "REACTOR_LEGACY_PROCESSOR_IDS",
86
87
  "MAX_SKIP_THRESHOLD",
87
88
  "PH_CATCH_UP_PRIORITY",
89
+ "PH_TELEMETRY",
90
+ "PH_TELEMETRY_DIR",
91
+ "PH_PROCESSOR_TIMING",
92
+ "PH_PROCESSOR_TIMING_WINDOW_MS",
93
+ "PH_PROCESSOR_SLOW_BATCH_MS",
94
+ "PH_PROCESSOR_TIMING_LOG_MS",
95
+ "PH_MEMORY_TELEMETRY",
96
+ "PH_MEMORY_TELEMETRY_INTERVAL_MS",
97
+ "PH_MEMORY_TELEMETRY_OUTPUT",
98
+ "PH_MEMORY_TELEMETRY_FILE",
99
+ "PH_MEMORY_TELEMETRY_FILE_MAX_MB",
100
+ "PH_MEMORY_TELEMETRY_FILE_KEEP",
101
+ "PH_MEMORY_TELEMETRY_RING",
102
+ "PH_MEMORY_TELEMETRY_CONSOLE",
103
+ "PH_MEMORY_TELEMETRY_CONSOLE_INTERVAL_MS",
104
+ "PH_MEMORY_TELEMETRY_WORKERS",
105
+ "PH_MEMORY_TELEMETRY_WINDOW_MIN",
106
+ "PH_HEAP_SNAPSHOT_DIR",
107
+ "PH_KEYFRAMES",
88
108
  "AUTH_ENABLED",
89
109
  "RESOLVE_CALLER_IDENTITY",
90
110
  "REQUIRE_AUTHENTICATED_CALLER",
@@ -617,6 +637,94 @@ describe("switchboardConfigFromEnv errors", () => {
617
637
  });
618
638
  });
619
639
 
640
+ describe("switchboardConfigFromEnv telemetry", () => {
641
+ const layer = (env: Env) => switchboardConfigFromEnv(env, { logger: silent });
642
+
643
+ it("maps the processor timing settings", () => {
644
+ expect(
645
+ layer({
646
+ PH_PROCESSOR_TIMING: "detailed",
647
+ PH_PROCESSOR_TIMING_WINDOW_MS: "120000",
648
+ PH_PROCESSOR_SLOW_BATCH_MS: "250",
649
+ PH_PROCESSOR_TIMING_LOG_MS: "60000",
650
+ }).protocol,
651
+ ).toEqual({
652
+ processorTiming: "detailed",
653
+ processorTimingWindowMs: 120_000,
654
+ processorSlowBatchMs: 250,
655
+ processorTimingLogMs: 60_000,
656
+ });
657
+ });
658
+
659
+ it("maps the memory telemetry settings", () => {
660
+ expect(
661
+ layer({
662
+ PH_MEMORY_TELEMETRY: "on",
663
+ PH_MEMORY_TELEMETRY_INTERVAL_MS: "5000",
664
+ PH_MEMORY_TELEMETRY_OUTPUT: "file,console",
665
+ PH_MEMORY_TELEMETRY_FILE_MAX_MB: "20",
666
+ PH_MEMORY_TELEMETRY_FILE_KEEP: "3",
667
+ PH_MEMORY_TELEMETRY_RING: "100",
668
+ PH_MEMORY_TELEMETRY_CONSOLE_INTERVAL_MS: "60000",
669
+ PH_MEMORY_TELEMETRY_WORKERS: "false",
670
+ PH_MEMORY_TELEMETRY_WINDOW_MIN: "10",
671
+ PH_HEAP_SNAPSHOT_DIR: "/snapshots",
672
+ }).telemetry,
673
+ ).toEqual({
674
+ memory: {
675
+ enabled: true,
676
+ intervalMs: 5000,
677
+ outputs: ["memory", "file", "console"],
678
+ file: { maxMb: 20, keep: 3 },
679
+ ringSize: 100,
680
+ consoleIntervalMs: 60_000,
681
+ workers: false,
682
+ windowMin: 10,
683
+ },
684
+ heapSnapshotDir: "/snapshots",
685
+ });
686
+ });
687
+
688
+ it("leaves the telemetry block out with nothing set", () => {
689
+ expect(layer({}).telemetry).toBeUndefined();
690
+ });
691
+
692
+ it("drops the console output when told to", () => {
693
+ expect(
694
+ layer({
695
+ PH_MEMORY_TELEMETRY_OUTPUT: "console,file",
696
+ PH_MEMORY_TELEMETRY_CONSOLE: "false",
697
+ }).telemetry?.memory?.outputs,
698
+ ).toEqual(["memory", "file"]);
699
+ });
700
+
701
+ it("adds the file output for an explicit path", () => {
702
+ expect(
703
+ layer({
704
+ PH_MEMORY_TELEMETRY_OUTPUT: "memory",
705
+ PH_MEMORY_TELEMETRY_FILE: "/x/memory.jsonl",
706
+ }).telemetry?.memory,
707
+ ).toEqual({
708
+ outputs: ["memory", "file"],
709
+ file: { path: "/x/memory.jsonl" },
710
+ });
711
+ });
712
+
713
+ it("lets PH_TELEMETRY=off win over both switches", () => {
714
+ const off = layer({
715
+ PH_TELEMETRY: "off",
716
+ PH_PROCESSOR_TIMING: "detailed",
717
+ PH_MEMORY_TELEMETRY: "on",
718
+ });
719
+ expect(off.protocol?.processorTiming).toBe("off");
720
+ expect(off.telemetry?.memory?.enabled).toBe(false);
721
+ });
722
+
723
+ it("carries the shared telemetry directory", () => {
724
+ expect(layer({ PH_TELEMETRY_DIR: "/t" }).telemetry?.dir).toBe("/t");
725
+ });
726
+ });
727
+
620
728
  describe("switchboardConfigFromEnv warnings", () => {
621
729
  it.each<
622
730
  [
@@ -630,6 +738,27 @@ describe("switchboardConfigFromEnv warnings", () => {
630
738
  { PH_CATCH_UP_PRIORITY: "fast" },
631
739
  (l) => l.protocol,
632
740
  ],
741
+ ["PH_PROCESSOR_TIMING", { PH_PROCESSOR_TIMING: "full" }, (l) => l.protocol],
742
+ [
743
+ "PH_PROCESSOR_TIMING_WINDOW_MS",
744
+ { PH_PROCESSOR_TIMING_WINDOW_MS: "0" },
745
+ (l) => l.protocol,
746
+ ],
747
+ [
748
+ "PH_MEMORY_TELEMETRY",
749
+ { PH_MEMORY_TELEMETRY: "maybe" },
750
+ (l) => l.telemetry,
751
+ ],
752
+ [
753
+ "PH_MEMORY_TELEMETRY_OUTPUT",
754
+ { PH_MEMORY_TELEMETRY_OUTPUT: "memory,otel" },
755
+ (l) => l.telemetry,
756
+ ],
757
+ [
758
+ "PH_MEMORY_TELEMETRY_INTERVAL_MS",
759
+ { PH_MEMORY_TELEMETRY_INTERVAL_MS: "soon" },
760
+ (l) => l.telemetry,
761
+ ],
633
762
  ["GATEWAY_ADAPTER", { GATEWAY_ADAPTER: "nginx" }, (l) => l.server],
634
763
  ["LOG_LEVEL", { LOG_LEVEL: "INFO" }, (l) => l.logLevel],
635
764
  ["PORT", { PORT: "http" }, (l) => l.server],
@@ -756,3 +885,58 @@ describe("switchboardConfigFromEnv for the bin", () => {
756
885
  expect(switchboardConfigFromEnv(env, { logger: silent })).toEqual({});
757
886
  });
758
887
  });
888
+
889
+ describe("PH_KEYFRAMES", () => {
890
+ it("leaves keyframes unset without it", () => {
891
+ expect(switchboardConfigFromEnv({}).storage?.keyframes).toBeUndefined();
892
+ expect(
893
+ switchboardConfigFromEnv({ PH_KEYFRAMES: " " }).storage?.keyframes,
894
+ ).toBeUndefined();
895
+ });
896
+
897
+ it("reads the rules", () => {
898
+ const rules = {
899
+ default: { interval: 10, keep: 4 },
900
+ types: { "a/b": { interval: 50, keep: 1 }, "a/c": { keep: null } },
901
+ };
902
+
903
+ const config = switchboardConfigFromEnv({
904
+ PH_KEYFRAMES: JSON.stringify(rules),
905
+ });
906
+
907
+ expect(config.storage?.keyframes).toEqual(rules);
908
+ expect(switchboardConfigSchema.parse(config).storage.keyframes).toEqual(
909
+ rules,
910
+ );
911
+ });
912
+
913
+ it("stops the boot on JSON it cannot read", () => {
914
+ expect(() =>
915
+ switchboardConfigFromEnv({ PH_KEYFRAMES: "{keep:1}" }),
916
+ ).toThrow("PH_KEYFRAMES is not valid JSON");
917
+ });
918
+
919
+ it("stops the boot on a rule it cannot use", () => {
920
+ expect(() =>
921
+ switchboardConfigFromEnv({
922
+ PH_KEYFRAMES: JSON.stringify({ default: { keep: 0 } }),
923
+ }),
924
+ ).toThrow("PH_KEYFRAMES.default.keep");
925
+ });
926
+
927
+ it("is replaced whole by a later layer", () => {
928
+ const merged = mergeSwitchboardConfig(
929
+ {
930
+ storage: {
931
+ keyframes: {
932
+ default: { keep: 4 },
933
+ types: { "a/b": { keep: 1 } },
934
+ },
935
+ },
936
+ },
937
+ { storage: { keyframes: { default: { keep: 2 } } } },
938
+ );
939
+
940
+ expect(merged.storage?.keyframes).toEqual({ default: { keep: 2 } });
941
+ });
942
+ });
@@ -35,6 +35,22 @@ describe("switchboardConfigSchema", () => {
35
35
  unsupportedStoredDocuments: "refuse",
36
36
  legacyProcessorIds: true,
37
37
  catchUpPriority: "dynamic",
38
+ processorTiming: "basic",
39
+ processorTimingWindowMs: 60_000,
40
+ processorSlowBatchMs: 1_000,
41
+ processorTimingLogMs: 0,
42
+ });
43
+ expect(config.telemetry).toEqual({
44
+ memory: {
45
+ enabled: false,
46
+ intervalMs: 30_000,
47
+ outputs: ["memory", "file"],
48
+ file: { maxMb: 10, keep: 5 },
49
+ ringSize: 720,
50
+ consoleIntervalMs: 300_000,
51
+ workers: true,
52
+ windowMin: 30,
53
+ },
38
54
  });
39
55
  expect(config.workers).toEqual({
40
56
  executor: { count: 0, poolSize: 2, acquireTimeoutMs: 5000 },
@@ -75,6 +91,18 @@ describe("switchboardConfigSchema", () => {
75
91
  ["a fractional worker count", { workers: { executor: { count: 1.5 } } }],
76
92
  ["a host pool of 0", { workers: { hostPoolSize: 0 } }],
77
93
  ["a catch-up level above 7", { protocol: { catchUpPriority: 8 } }],
94
+ [
95
+ "an unknown timing level",
96
+ { protocol: { processorTiming: "full" as never } },
97
+ ],
98
+ [
99
+ "a sampling interval under a second",
100
+ { telemetry: { memory: { intervalMs: 10 } } },
101
+ ],
102
+ [
103
+ "an unknown memory output",
104
+ { telemetry: { memory: { outputs: ["otel" as never] } } },
105
+ ],
78
106
  [
79
107
  "an unknown signature policy",
80
108
  { protocol: { createSignaturePolicy: "v3" as "legacy" } },
@@ -2582,6 +2582,22 @@ type InspectionMailboxDepths {
2582
2582
  deadLetter: Int!
2583
2583
  }
2584
2584
 
2585
+ """
2586
+ Memory samples correlated with operations processed. samples are newest
2587
+ last; summary holds the rates over the correlation window and is null until
2588
+ two samples exist.
2589
+ """
2590
+ type InspectionMemoryTelemetry {
2591
+ enabled: Boolean!
2592
+ intervalMs: Float!
2593
+ consoleIntervalMs: Float!
2594
+ outputs: [String!]!
2595
+ file: String
2596
+ startedAt: String
2597
+ summary: JSONObject
2598
+ samples: [JSONObject!]!
2599
+ }
2600
+
2585
2601
  type InspectionProcessor {
2586
2602
  processorId: String!
2587
2603
  factoryId: String!
@@ -2597,6 +2613,107 @@ type InspectionProcessor {
2597
2613
  phase: String!
2598
2614
  }
2599
2615
 
2616
+ type InspectionProcessorQueueDepth {
2617
+ tasks: Float!
2618
+ ops: Float!
2619
+ }
2620
+
2621
+ """
2622
+ One processor's timing. The horizons are null while timing is off.
2623
+ """
2624
+ type InspectionProcessorTiming {
2625
+ processorId: String!
2626
+ name: String!
2627
+ driveLabel: String!
2628
+ factoryId: String!
2629
+ driveId: String!
2630
+ phase: String!
2631
+ lastOrdinal: Float!
2632
+ queueDepth: InspectionProcessorQueueDepth!
2633
+ ordinalsBehind: Float!
2634
+ opsPerSecond: Float!
2635
+ ordinalsPerSecond: Float!
2636
+ etaMs: Float
2637
+ sinceUtcMs: Float
2638
+ total: InspectionProcessorTimingHorizon
2639
+ window: InspectionProcessorTimingHorizon
2640
+ windowMs: Float!
2641
+ currentRun: InspectionProcessorTimingRun
2642
+ lastRun: InspectionProcessorTimingLastRun
2643
+ lastBatch: InspectionProcessorTimingBatch
2644
+ byDocumentType: [InspectionProcessorTimingDocumentType!]!
2645
+ }
2646
+
2647
+ type InspectionProcessorTimingBatch {
2648
+ atUtcMs: Float!
2649
+ path: String!
2650
+ ops: Float!
2651
+ ms: Float!
2652
+ fromOrdinal: Float!
2653
+ toOrdinal: Float!
2654
+ }
2655
+
2656
+ """
2657
+ One path's numbers over one horizon. Times are wall-clock milliseconds the
2658
+ processor's queue awaited, not CPU; read time includes waiting for the store.
2659
+ slotWaitMs and pauseMs are throttling and count toward no busy time.
2660
+ """
2661
+ type InspectionProcessorTimingCounters {
2662
+ batches: Float!
2663
+ opsDelivered: Float!
2664
+ opsScanned: Float!
2665
+ opsMatched: Float!
2666
+ pages: Float!
2667
+ handlerMs: Float!
2668
+ maxBatchMs: Float!
2669
+ readMs: Float!
2670
+ lookupMs: Float!
2671
+ fillMs: Float!
2672
+ slotWaitMs: Float!
2673
+ pauseMs: Float!
2674
+ errors: Float!
2675
+ }
2676
+
2677
+ type InspectionProcessorTimingDocumentType {
2678
+ documentType: String!
2679
+ ops: Float!
2680
+ handlerMs: Float!
2681
+ }
2682
+
2683
+ type InspectionProcessorTimingHorizon {
2684
+ live: InspectionProcessorTimingCounters!
2685
+ replay: InspectionProcessorTimingCounters!
2686
+ ordinalsAdvanced: Float!
2687
+ busyMs: Float!
2688
+ }
2689
+
2690
+ type InspectionProcessorTimingLastRun {
2691
+ startedAtUtcMs: Float!
2692
+ durationMs: Float!
2693
+ ordinals: Float!
2694
+ opsDelivered: Float!
2695
+ busyMs: Float!
2696
+ }
2697
+
2698
+ """
2699
+ level is off, basic or detailed. Without a catch-up status, head is the
2700
+ highest cursor and headKnown is false.
2701
+ """
2702
+ type InspectionProcessorTimingReport {
2703
+ level: String!
2704
+ windowMs: Float!
2705
+ head: Float!
2706
+ headKnown: Boolean!
2707
+ processors: [InspectionProcessorTiming!]!
2708
+ }
2709
+
2710
+ type InspectionProcessorTimingRun {
2711
+ startedAtUtcMs: Float!
2712
+ runFrom: Float!
2713
+ counters: InspectionProcessorTimingCounters!
2714
+ ordinalsAdvanced: Float!
2715
+ }
2716
+
2600
2717
  """
2601
2718
  A queued job without its actions or operations.
2602
2719
  """
@@ -3959,6 +4076,11 @@ type ReactorInspection {
3959
4076
  attachmentInfo: InspectionAttachmentInfo!
3960
4077
  queueState: InspectionQueueState!
3961
4078
  processors: [InspectionProcessor!]!
4079
+ processorTiming: InspectionProcessorTimingReport!
4080
+ """
4081
+ Refused on a host without memory telemetry.
4082
+ """
4083
+ memoryTelemetry(limit: Int, sinceIso: String): InspectionMemoryTelemetry!
3962
4084
  catchUpStatus: JSONObject!
3963
4085
  catchUpPriority: InspectionCatchUpPriority!
3964
4086
  storageHealth: InspectionStorageHealth!
@@ -0,0 +1,156 @@
1
+ import {
2
+ EventBus,
3
+ ReactorBuilder,
4
+ type InProcessReactorModule,
5
+ } from "@powerhousedao/reactor";
6
+ import { documentModelDocumentModelModule } from "document-model";
7
+ import type { ILogger } from "document-model";
8
+ import { mkdtemp, rm } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { afterEach, describe, expect, it, vi } from "vitest";
12
+ import { createReactorKysely, resolveKeyframes } from "../src/server.mjs";
13
+
14
+ const LONG = 180_000;
15
+
16
+ function stubLogger(): ILogger {
17
+ const logger = {
18
+ level: "info",
19
+ verbose: () => undefined,
20
+ debug: () => undefined,
21
+ info: () => undefined,
22
+ warn: () => undefined,
23
+ error: () => undefined,
24
+ errorHandler: () => undefined,
25
+ child: () => logger,
26
+ };
27
+ return logger as unknown as ILogger;
28
+ }
29
+
30
+ function emptyDocument() {
31
+ return documentModelDocumentModelModule.utils.createDocument();
32
+ }
33
+
34
+ describe("resolveKeyframes", () => {
35
+ const CONFIG = "/project/powerhouse.config.json";
36
+
37
+ it("is unset with neither source, which keeps today's behaviour", () => {
38
+ expect(resolveKeyframes(undefined, undefined, CONFIG)).toBeUndefined();
39
+ });
40
+
41
+ it("reads the project config", () => {
42
+ expect(
43
+ resolveKeyframes(undefined, { default: { keep: 4 } }, CONFIG),
44
+ ).toEqual({ default: { keep: 4 } });
45
+ });
46
+
47
+ it("lets the configured rules win whole over the project config", () => {
48
+ expect(
49
+ resolveKeyframes(
50
+ { default: { keep: 1 } },
51
+ { default: { interval: 50 }, types: { "a/b": { keep: 9 } } },
52
+ CONFIG,
53
+ ),
54
+ ).toEqual({ default: { keep: 1 } });
55
+ });
56
+
57
+ it("stops the boot on a project config it cannot use, naming the file", () => {
58
+ expect(() =>
59
+ resolveKeyframes(undefined, { default: { keep: 0 } }, CONFIG),
60
+ ).toThrow(`${CONFIG} reactor.keyframes.default.keep`);
61
+ });
62
+ });
63
+
64
+ describe("keyframe clean-up and reclaim on a reactor's own store", () => {
65
+ let dataDir: string | undefined;
66
+ let module: InProcessReactorModule | undefined;
67
+
68
+ afterEach(async () => {
69
+ await module?.shutdown();
70
+ module = undefined;
71
+ if (dataDir) {
72
+ await rm(dataDir, { recursive: true, force: true, maxRetries: 5 });
73
+ }
74
+ dataDir = undefined;
75
+ });
76
+
77
+ it.each([
78
+ ["in a worker thread", true],
79
+ ["in the main thread", false],
80
+ ])(
81
+ "shrinks the table %s, after a dry run that left it alone",
82
+ async (_where, pgliteWorkers) => {
83
+ dataDir = await mkdtemp(join(tmpdir(), "ph-keyframe-reclaim-"));
84
+ const storage = await createReactorKysely({
85
+ reactorDbUrl: undefined,
86
+ reactorPgliteDir: join(dataDir, "reactor"),
87
+ reactorPgliteMajor: 17,
88
+ inMemory: false,
89
+ hostPoolSize: () => 1,
90
+ pgliteWorkers,
91
+ logger: stubLogger(),
92
+ });
93
+ expect(storage.storeMaintenance).toBeDefined();
94
+
95
+ module = await new ReactorBuilder()
96
+ .withEventBus(new EventBus())
97
+ .withKysely(storage.kysely)
98
+ .withKeyframes({ default: { keep: 1 } })
99
+ .withStoreMaintenance(storage.storeMaintenance!)
100
+ .buildModule();
101
+ const { keyframeCleanup, keyframeStore } = module;
102
+
103
+ const padded = emptyDocument();
104
+ const large = {
105
+ ...padded,
106
+ state: { ...padded.state, padding: "x".repeat(200_000) },
107
+ };
108
+ for (let revision = 10; revision <= 100; revision += 10) {
109
+ await keyframeStore.putKeyframe(
110
+ "doc",
111
+ "global",
112
+ "main",
113
+ revision,
114
+ large,
115
+ );
116
+ }
117
+
118
+ keyframeCleanup.start({ dryRun: true });
119
+ await vi.waitFor(
120
+ () => expect(keyframeCleanup.status()?.state).toBe("done"),
121
+ { timeout: 30_000 },
122
+ );
123
+ expect(keyframeCleanup.status()?.totals.removableRows).toBe(9);
124
+ expect(await keyframeStore.listKeyframes("doc")).toHaveLength(10);
125
+
126
+ keyframeCleanup.start({ dryRun: false });
127
+ await vi.waitFor(
128
+ () => expect(keyframeCleanup.status()?.state).toBe("done"),
129
+ { timeout: 30_000 },
130
+ );
131
+ const kept = await keyframeStore.listKeyframes("doc");
132
+ expect(kept.map((row) => row.revision)).toEqual([100]);
133
+
134
+ await keyframeCleanup.reclaim();
135
+ await vi.waitFor(
136
+ () =>
137
+ expect(keyframeCleanup.reclaimStatus()?.state).not.toBe("running"),
138
+ { timeout: 120_000, interval: 100 },
139
+ );
140
+
141
+ const reclaim = keyframeCleanup.reclaimStatus()!;
142
+ expect(reclaim.message).toBe("The Keyframe table was rewritten.");
143
+ expect(reclaim.state).toBe("done");
144
+ expect(reclaim.tableBytesAfter).toBeLessThan(reclaim.tableBytesBefore!);
145
+
146
+ const after = await keyframeStore.findNearestKeyframe(
147
+ "doc",
148
+ "global",
149
+ "main",
150
+ 100,
151
+ );
152
+ expect(after?.revision).toBe(100);
153
+ },
154
+ LONG,
155
+ );
156
+ });
@@ -0,0 +1,109 @@
1
+ import type { InspectorProcessorTimingReport } from "@powerhousedao/reactor";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { startProcessorTimingLog } from "../src/processor-timing-log.mjs";
4
+
5
+ function report(
6
+ level: InspectorProcessorTimingReport["level"],
7
+ phase: "catching-up" | "live",
8
+ ): InspectorProcessorTimingReport {
9
+ const counters = {
10
+ batches: 1,
11
+ opsDelivered: 1,
12
+ opsScanned: 1,
13
+ opsMatched: 1,
14
+ pages: 1,
15
+ handlerMs: 2_000,
16
+ maxBatchMs: 0,
17
+ readMs: 0,
18
+ lookupMs: 0,
19
+ fillMs: 0,
20
+ slotWaitMs: 0,
21
+ pauseMs: 0,
22
+ errors: 0,
23
+ };
24
+ const horizon = {
25
+ live: { ...counters, handlerMs: 0 },
26
+ replay: counters,
27
+ ordinalsAdvanced: 1,
28
+ busyMs: 2_000,
29
+ };
30
+ return {
31
+ level,
32
+ windowMs: 60_000,
33
+ head: 10,
34
+ headKnown: true,
35
+ processors: [
36
+ {
37
+ processorId: "p",
38
+ name: "Index",
39
+ driveLabel: "files",
40
+ factoryId: "f",
41
+ driveId: "d",
42
+ phase,
43
+ lastOrdinal: 5,
44
+ queueDepth: { tasks: 0, ops: 0 },
45
+ ordinalsBehind: 5,
46
+ opsPerSecond: 1,
47
+ ordinalsPerSecond: 1,
48
+ etaMs: null,
49
+ sinceUtcMs: 0,
50
+ total: horizon,
51
+ window: horizon,
52
+ windowMs: 60_000,
53
+ currentRun: null,
54
+ lastRun: null,
55
+ lastBatch: null,
56
+ byDocumentType: [],
57
+ },
58
+ ],
59
+ };
60
+ }
61
+
62
+ describe("startProcessorTimingLog", () => {
63
+ beforeEach(() => {
64
+ vi.useFakeTimers();
65
+ });
66
+
67
+ afterEach(() => {
68
+ vi.useRealTimers();
69
+ });
70
+
71
+ it("logs while catching up and one summary when it ends", () => {
72
+ let current = report("basic", "catching-up");
73
+ const lines: string[] = [];
74
+ const stop = startProcessorTimingLog({
75
+ intervalMs: 1_000,
76
+ read: () => current,
77
+ log: (line) => lines.push(line),
78
+ });
79
+
80
+ vi.advanceTimersByTime(2_000);
81
+ expect(lines).toHaveLength(2);
82
+ expect(lines[0]).toContain("catch-up slowest (60 s): Index·files 2.0s");
83
+
84
+ current = report("basic", "live");
85
+ vi.advanceTimersByTime(3_000);
86
+ expect(lines).toHaveLength(3);
87
+ expect(lines[2]).toMatch(/^catch-up done in .*Index·files 2\.0s$/);
88
+ stop();
89
+ });
90
+
91
+ it("stays quiet when live, when off, and after the stop", () => {
92
+ let current = report("basic", "live");
93
+ const log = vi.fn();
94
+ const stop = startProcessorTimingLog({
95
+ intervalMs: 1_000,
96
+ read: () => current,
97
+ log,
98
+ });
99
+ vi.advanceTimersByTime(2_000);
100
+
101
+ current = report("off", "catching-up");
102
+ vi.advanceTimersByTime(2_000);
103
+ stop();
104
+
105
+ current = report("basic", "catching-up");
106
+ vi.advanceTimersByTime(2_000);
107
+ expect(log).not.toHaveBeenCalled();
108
+ });
109
+ });
package/tsdown.config.ts CHANGED
@@ -17,6 +17,7 @@ export default defineConfig({
17
17
  "src/plugins/attachments.mts",
18
18
  "src/plugins/privacy.mts",
19
19
  "src/plugins/workflows.mts",
20
+ "src/plugins/ai.mts",
20
21
  ],
21
22
  platform: "node",
22
23
  outDir: "dist",