@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

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 (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -38,12 +38,7 @@ class RecordingReceiver implements StreamUpdateReceiver {
38
38
  * real WASM does), so coalescing's last-write-wins must yield the final array.
39
39
  */
40
40
  function makeService(queryHashesFor: (id: string) => string[]) {
41
- const svc = new StreamProcessorService(
42
- {} as any,
43
- {} as any,
44
- { get: async () => undefined, set: async () => {} } as any,
45
- makeLogger()
46
- );
41
+ const svc = new StreamProcessorService({} as any, {} as any, makeLogger());
47
42
 
48
43
  const ingestedByQuery = new Map<string, Array<[string, number]>>();
49
44
  const mockProcessor: Partial<WasmProcessor> = {
@@ -54,7 +49,7 @@ function makeService(queryHashesFor: (id: string) => string[]) {
54
49
  const arr = ingestedByQuery.get(queryHash) ?? [];
55
50
  arr.push([id, version]);
56
51
  ingestedByQuery.set(queryHash, arr);
57
- updates.push({ query_id: queryHash, result_data: [...arr] });
52
+ updates.push({ query_id: queryHash, result_hash: '', result_data: [...arr] });
58
53
  }
59
54
  return updates;
60
55
  },
@@ -133,4 +128,59 @@ describe('StreamProcessor ingestMany bulk insert', () => {
133
128
  svc.ingest('user', 'CREATE', 'user:1', { id: 'user:1', _00_rv: 1 });
134
129
  expect(receiver.received).toHaveLength(1);
135
130
  });
131
+
132
+ // A WASM build that exposes `ingest_many` takes one circuit step for the whole
133
+ // batch. The per-record loop above stays as the fallback for older builds.
134
+ describe('with a WASM build that supports bulk ingest', () => {
135
+ function makeBulkService() {
136
+ const svc = new StreamProcessorService({} as any, {} as any, makeLogger());
137
+ const calls: { items: any[] }[] = [];
138
+ const mockProcessor: Partial<WasmProcessor> = {
139
+ ingest: () => {
140
+ throw new Error('per-record ingest must not be used when ingest_many exists');
141
+ },
142
+ ingest_many: (items): WasmStreamUpdate[] => {
143
+ calls.push({ items });
144
+ return [
145
+ {
146
+ query_id: 'q1',
147
+ result_data: items.map((i) => [i.id, 1] as [string, number]),
148
+ timing_circuit_step_ms: 4,
149
+ } as WasmStreamUpdate,
150
+ ];
151
+ },
152
+ };
153
+ (svc as any).processor = mockProcessor;
154
+ return { svc, calls };
155
+ }
156
+
157
+ it('takes a single bulk call and dispatches one update per affected query', () => {
158
+ const { svc, calls } = makeBulkService();
159
+ svc.addReceiver(receiver);
160
+
161
+ svc.ingestMany([
162
+ { table: 'user', op: 'CREATE', id: 'user:1', record: { id: 'user:1', _00_rv: 1 } },
163
+ { table: 'user', op: 'CREATE', id: 'user:2', record: { id: 'user:2', _00_rv: 1 } },
164
+ { table: 'user', op: 'CREATE', id: 'user:3', record: { id: 'user:3', _00_rv: 1 } },
165
+ ]);
166
+
167
+ expect(calls).toHaveLength(1);
168
+ expect(calls[0].items.map((i) => i.id)).toEqual(['user:1', 'user:2', 'user:3']);
169
+ expect(receiver.received).toHaveLength(1);
170
+ expect(receiver.received[0].queryHash).toBe('q1');
171
+ expect(receiver.received[0].localArray).toHaveLength(3);
172
+ expect(receiver.received[0].op).toBe('CREATE');
173
+ expect(receiver.received[0].circuitStepMs).toBe(4);
174
+ });
175
+
176
+ it('never calls the bulk path for an empty batch', () => {
177
+ const { svc, calls } = makeBulkService();
178
+ svc.addReceiver(receiver);
179
+
180
+ svc.ingestMany([]);
181
+
182
+ expect(calls).toHaveLength(0);
183
+ expect(receiver.received).toHaveLength(0);
184
+ });
185
+ });
136
186
  });
@@ -0,0 +1,234 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ // The boot-time prime: the circuit fills from the LOCAL store (a snapshot plus
4
+ // a reconcile against `(id, rv)`, or every cached row) instead of from the
5
+ // network. Before this, a reload left the circuit empty, every id in the
6
+ // server's list_ref classified as `added`, and the whole working set was
7
+ // re-downloaded, re-written and re-ingested.
8
+
9
+ const processorInstances: any[] = [];
10
+
11
+ vi.mock('@spooky-sync/ssp-wasm', () => ({
12
+ default: vi.fn(async () => {}),
13
+ Sp00kyProcessor: vi.fn(() => {
14
+ const instance = {
15
+ ingest: vi.fn(() => []),
16
+ ingest_many: vi.fn(() => []),
17
+ register_view: vi.fn(() => ({ query_id: 'q1', result_hash: '', result_data: [] })),
18
+ unregister_view: vi.fn(),
19
+ set_permissions: vi.fn(),
20
+ set_projection: vi.fn(),
21
+ save_store_state: vi.fn(() => new Uint8Array([1])),
22
+ load_store_state: vi.fn(() => [{ query_id: 'q1', result_hash: '', result_data: [['thing:a', 1]] }]),
23
+ reconcile: vi.fn(() => ({ fetch: [], deleted: 0, updates: [] })),
24
+ free: vi.fn(),
25
+ };
26
+ processorInstances.push(instance);
27
+ return instance;
28
+ }),
29
+ }));
30
+
31
+ import { StreamProcessorService, CIRCUIT_SNAPSHOT_FORMAT } from './index';
32
+ import type { StreamUpdate } from './index';
33
+
34
+ const silentLogger = {
35
+ child: () => silentLogger,
36
+ trace: () => {},
37
+ debug: () => {},
38
+ info: () => {},
39
+ warn: () => {},
40
+ error: () => {},
41
+ } as any;
42
+
43
+ function row(id: string, rv: number) {
44
+ return { id, _00_rv: rv, title: id };
45
+ }
46
+
47
+ function makeService(opts: { snapshot?: { bytes: Uint8Array; meta: any } | null; engineKind?: string } = {}) {
48
+ const versions: Record<string, [string, number][]> = {
49
+ thing: [
50
+ ['thing:a', 1],
51
+ ['thing:b', 2],
52
+ ],
53
+ other: [['other:x', 5]],
54
+ };
55
+ const db = {
56
+ epoch: 0,
57
+ engineKind: opts.engineKind ?? 'sqlite',
58
+ scanVersions: vi.fn(async (tables: string[]) =>
59
+ Object.fromEntries(tables.map((t) => [t, versions[t] ?? []]))
60
+ ),
61
+ selectByIds: vi.fn(async (table: string, ids: string[]) =>
62
+ ids.map((id) => row(id, versions[table]?.find(([i]) => i === id)?.[1] ?? 0))
63
+ ),
64
+ getSnapshot: vi.fn(async () => opts.snapshot ?? null),
65
+ putSnapshot: vi.fn(async () => {}),
66
+ };
67
+ const service = new StreamProcessorService({} as any, db as any, silentLogger);
68
+ service.configureCircuitPersistence(true);
69
+ const received: StreamUpdate[] = [];
70
+ service.addReceiver({ onStreamUpdate: (u) => received.push(u) });
71
+ return { service, db, received };
72
+ }
73
+
74
+ const goodMeta = { formatVersion: CIRCUIT_SNAPSHOT_FORMAT, schemaHash: 'h', savedAt: 1 };
75
+ const ctx = () => ({
76
+ tables: ['thing', 'other'],
77
+ schemaHash: 'h',
78
+ pendingIds: new Set<string>(),
79
+ onVersions: vi.fn(),
80
+ });
81
+
82
+ beforeEach(() => {
83
+ processorInstances.length = 0;
84
+ });
85
+
86
+ describe('StreamProcessorService.primeFromLocal', () => {
87
+ it('without a snapshot, ingests every cached row and reports their versions', async () => {
88
+ const { service, db } = makeService();
89
+ await service.init();
90
+ const c = ctx();
91
+ await service.primeFromLocal(c);
92
+ const p = processorInstances[0];
93
+ expect(p.load_store_state).not.toHaveBeenCalled();
94
+ expect(db.selectByIds).toHaveBeenCalledWith('thing', ['thing:a', 'thing:b']);
95
+ expect(db.selectByIds).toHaveBeenCalledWith('other', ['other:x']);
96
+ const items = p.ingest_many.mock.calls.flatMap((call: any[]) => call[0]);
97
+ expect(items.map((i: any) => [i.table, i.op, i.id])).toEqual([
98
+ ['thing', 'CREATE', 'thing:a'],
99
+ ['thing', 'CREATE', 'thing:b'],
100
+ ['other', 'CREATE', 'other:x'],
101
+ ]);
102
+ expect(c.onVersions).toHaveBeenCalledWith('thing', [
103
+ ['thing:a', 1],
104
+ ['thing:b', 2],
105
+ ]);
106
+ await expect(service.whenPrimed()).resolves.toBeUndefined();
107
+ });
108
+
109
+ it('resets tables whose columns changed BEFORE reading the versions it reports', async () => {
110
+ const { service, db } = makeService();
111
+ const order: string[] = [];
112
+ // The engine zeroes `thing`'s cached versions (a column was added).
113
+ const reset = vi.fn(async () => {
114
+ order.push('reset');
115
+ db.scanVersions.mockImplementation(async (tables: string[]) => {
116
+ order.push('scan');
117
+ return Object.fromEntries(tables.map((t) => [t, t === 'thing' ? [['thing:a', 0], ['thing:b', 0]] : [['other:x', 5]]]));
118
+ });
119
+ return ['thing'];
120
+ });
121
+ (db as any).resetChangedTables = reset;
122
+ await service.init();
123
+ const c = { ...ctx(), pendingIds: new Set(['thing:b']), columnFingerprints: { thing: 'layout,title', other: 'title' } };
124
+ await service.primeFromLocal(c);
125
+ expect(reset).toHaveBeenCalledWith({ thing: 'layout,title', other: 'title' }, new Set(['thing:b']));
126
+ expect(order).toEqual(['reset', 'scan']);
127
+ // Reported as stale, so the fetch plan pulls the bodies again.
128
+ expect(c.onVersions).toHaveBeenCalledWith('thing', [['thing:a', 0]]);
129
+ });
130
+
131
+ it('keeps priming when the column check fails', async () => {
132
+ const { service, db } = makeService();
133
+ (db as any).resetChangedTables = vi.fn(async () => {
134
+ throw new Error('worker gone');
135
+ });
136
+ await service.init();
137
+ const c = { ...ctx(), columnFingerprints: { thing: 'title' } };
138
+ await service.primeFromLocal(c);
139
+ expect(c.onVersions).toHaveBeenCalledWith('thing', [
140
+ ['thing:a', 1],
141
+ ['thing:b', 2],
142
+ ]);
143
+ });
144
+
145
+ it('with a snapshot, restores it under the registered views and only fetches what reconcile asks for', async () => {
146
+ const { service, db, received } = makeService({ snapshot: { bytes: new Uint8Array([7]), meta: goodMeta } });
147
+ await service.init();
148
+ const p = processorInstances[0];
149
+ p.reconcile.mockImplementation((table: string) =>
150
+ table === 'thing'
151
+ ? { fetch: ['thing:b'], deleted: 1, updates: [{ query_id: 'q1', result_hash: '', result_data: [] }] }
152
+ : { fetch: [], deleted: 0, updates: [] }
153
+ );
154
+ await service.primeFromLocal(ctx());
155
+ expect(p.load_store_state).toHaveBeenCalledWith(new Uint8Array([7]));
156
+ // The restore's re-primed view result and reconcile's retraction reached
157
+ // the receivers.
158
+ expect(received.map((u) => u.queryHash)).toEqual(['q1', 'q1']);
159
+ expect(p.reconcile).toHaveBeenCalledWith('thing', [
160
+ ['thing:a', 1],
161
+ ['thing:b', 2],
162
+ ]);
163
+ expect(db.selectByIds).toHaveBeenCalledTimes(1);
164
+ expect(db.selectByIds).toHaveBeenCalledWith('thing', ['thing:b']);
165
+ const items = p.ingest_many.mock.calls.flatMap((call: any[]) => call[0]);
166
+ expect(items.map((i: any) => i.id)).toEqual(['thing:b']);
167
+ });
168
+
169
+ it('ignores a snapshot written under another schema or format', async () => {
170
+ const { service } = makeService({
171
+ snapshot: { bytes: new Uint8Array([7]), meta: { ...goodMeta, schemaHash: 'other' } },
172
+ });
173
+ await service.init();
174
+ await service.primeFromLocal(ctx());
175
+ expect(processorInstances[0].load_store_state).not.toHaveBeenCalled();
176
+ expect(processorInstances[0].ingest_many).toHaveBeenCalled();
177
+ });
178
+
179
+ it('leaves out ids with a pending local mutation when reporting versions', async () => {
180
+ const { service } = makeService();
181
+ await service.init();
182
+ const c = ctx();
183
+ c.pendingIds.add('thing:b');
184
+ await service.primeFromLocal(c);
185
+ expect(c.onVersions).toHaveBeenCalledWith('thing', [['thing:a', 1]]);
186
+ });
187
+
188
+ it('aborts when the store epoch moves under it (bucket switch)', async () => {
189
+ const { service, db } = makeService();
190
+ await service.init();
191
+ db.scanVersions.mockImplementation(async () => {
192
+ db.epoch++;
193
+ return { thing: [['thing:a', 1]], other: [] };
194
+ });
195
+ const c = ctx();
196
+ await service.primeFromLocal(c);
197
+ expect(db.selectByIds).not.toHaveBeenCalled();
198
+ expect(processorInstances[0].ingest_many).not.toHaveBeenCalled();
199
+ expect(c.onVersions).not.toHaveBeenCalled();
200
+ });
201
+
202
+ it('is a no-op on an engine without scanVersions', async () => {
203
+ const service = new StreamProcessorService({} as any, {} as any, silentLogger);
204
+ await service.init();
205
+ await service.primeFromLocal(ctx());
206
+ expect(processorInstances[0].ingest_many).not.toHaveBeenCalled();
207
+ });
208
+
209
+ it('widens projected rows when a new view evaluates fields they lack', async () => {
210
+ const { service, db } = makeService();
211
+ await service.init();
212
+ const p = processorInstances[0];
213
+ p.register_view.mockReturnValue({
214
+ query_id: 'q2',
215
+ result_hash: '',
216
+ result_data: [],
217
+ missing_fields: { thing: ['score'] },
218
+ });
219
+ service.registerQueryPlan({
220
+ queryHash: 'q2',
221
+ surql: 'SELECT * FROM thing ORDER BY score;',
222
+ params: {},
223
+ ttl: '10m',
224
+ lastActiveAt: new Date(),
225
+ localArray: [],
226
+ remoteArray: [],
227
+ meta: { tableName: 'thing' },
228
+ } as any);
229
+ await vi.waitFor(() => expect(p.ingest_many).toHaveBeenCalled());
230
+ expect(db.selectByIds).toHaveBeenCalledWith('thing', ['thing:a', 'thing:b'], { select: ['score'] });
231
+ const items = p.ingest_many.mock.calls.flatMap((call: any[]) => call[0]);
232
+ expect(items.map((i: any) => i.op)).toEqual(['MERGE', 'MERGE']);
233
+ });
234
+ });
@@ -0,0 +1,226 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ // `StreamProcessorService.reset()` is the SSP half of a local-bucket switch:
4
+ // the old circuit holds the previous user's rows and views registered with the
5
+ // previous `$auth`, so reset must swap in a FRESH processor (no state load),
6
+ // and a checkpoint racing the reset must not persist the old circuit into the
7
+ // new bucket's store.
8
+
9
+ const processorInstances: any[] = [];
10
+
11
+ vi.mock('@spooky-sync/ssp-wasm', () => ({
12
+ default: vi.fn(async () => {}),
13
+ Sp00kyProcessor: vi.fn(() => {
14
+ const instance = {
15
+ ingest: vi.fn(() => []),
16
+ register_view: vi.fn(() => ({ query_id: 'q1', result_data: [] })),
17
+ unregister_view: vi.fn(),
18
+ set_permissions: vi.fn(),
19
+ set_projection: vi.fn(),
20
+ save_store_state: vi.fn(() => new Uint8Array([1, 2, 3])),
21
+ load_store_state: vi.fn(() => []),
22
+ reconcile: vi.fn(() => ({ fetch: [], deleted: 0, updates: [] })),
23
+ free: vi.fn(),
24
+ };
25
+ processorInstances.push(instance);
26
+ return instance;
27
+ }),
28
+ }));
29
+
30
+ import { StreamProcessorService } from './index';
31
+
32
+ const silentLogger = {
33
+ child: () => silentLogger,
34
+ trace: () => {},
35
+ debug: () => {},
36
+ info: () => {},
37
+ warn: () => {},
38
+ error: () => {},
39
+ } as any;
40
+
41
+ function makeService() {
42
+ const snapshots: Record<string, { bytes: Uint8Array; meta: any }> = {};
43
+ const db = {
44
+ epoch: 0,
45
+ engineKind: 'sqlite' as const,
46
+ scanVersions: vi.fn(async () => ({})),
47
+ selectByIds: vi.fn(async () => []),
48
+ getSnapshot: vi.fn(async (key: string) => snapshots[key] ?? null),
49
+ putSnapshot: vi.fn(async (key: string, bytes: Uint8Array, meta: any) => {
50
+ snapshots[key] = { bytes, meta };
51
+ }),
52
+ };
53
+ const service = new StreamProcessorService({} as any, db as any, silentLogger);
54
+ return { service, db, snapshots };
55
+ }
56
+
57
+ const primeCtx = { tables: [], schemaHash: 'schema-1', pendingIds: new Set<string>() };
58
+
59
+ beforeEach(() => {
60
+ processorInstances.length = 0;
61
+ });
62
+
63
+ describe('StreamProcessorService.reset', () => {
64
+ it('swaps in a fresh processor without loading persisted state', async () => {
65
+ const { service } = makeService();
66
+ await service.init();
67
+ expect(processorInstances).toHaveLength(1);
68
+ const first = processorInstances[0];
69
+
70
+ await service.reset();
71
+ expect(processorInstances).toHaveLength(2);
72
+ const second = processorInstances[1];
73
+ // Fresh circuit: nothing loaded into it (a persisted snapshot references
74
+ // views under a dead sessionId salt and the previous user's data).
75
+ expect(second.load_store_state).not.toHaveBeenCalled();
76
+
77
+ // New registrations land on the fresh processor, not the old circuit.
78
+ service.registerQueryPlan({
79
+ queryHash: 'q1',
80
+ surql: 'SELECT * FROM thing;',
81
+ params: {},
82
+ ttl: '10m',
83
+ lastActiveAt: new Date(),
84
+ localArray: [],
85
+ remoteArray: [],
86
+ meta: { tableName: 'thing' },
87
+ } as any);
88
+ expect(second.register_view).toHaveBeenCalled();
89
+ expect(first.register_view).not.toHaveBeenCalled();
90
+ });
91
+
92
+ it('writes a store-only snapshot through the engine on checkpoint', async () => {
93
+ const { service, db, snapshots } = makeService();
94
+ service.configureCircuitPersistence(true);
95
+ await service.init();
96
+ await service.primeFromLocal(primeCtx);
97
+ await service.checkpoint('test');
98
+ expect(processorInstances[0].save_store_state).toHaveBeenCalledTimes(1);
99
+ expect(db.putSnapshot).toHaveBeenCalledTimes(1);
100
+ expect(snapshots.circuit.bytes).toEqual(new Uint8Array([1, 2, 3]));
101
+ expect(snapshots.circuit.meta.schemaHash).toBe('schema-1');
102
+ expect(snapshots.circuit.meta.formatVersion).toBe(1);
103
+ });
104
+
105
+ it('drops a checkpoint that raced a reset (old circuit never persists into the new bucket)', async () => {
106
+ const { service, db } = makeService();
107
+ service.configureCircuitPersistence(true);
108
+ await service.init();
109
+ await service.primeFromLocal(primeCtx);
110
+ // The bytes are taken, then a reset lands before the write step,
111
+ // simulated by resetting from inside save_store_state().
112
+ processorInstances[0].save_store_state.mockImplementation(() => {
113
+ void service.reset();
114
+ return new Uint8Array([9]);
115
+ });
116
+ await service.checkpoint('test');
117
+ expect(db.putSnapshot).not.toHaveBeenCalled();
118
+ });
119
+
120
+ it('does not write a snapshot from a follower tab', async () => {
121
+ const { service, db } = makeService();
122
+ service.configureCircuitPersistence(true);
123
+ await service.init();
124
+ await service.primeFromLocal(primeCtx);
125
+ service.setPersistenceEnabled(false);
126
+ await service.checkpoint('test');
127
+ expect(db.putSnapshot).not.toHaveBeenCalled();
128
+ });
129
+
130
+ it('frees the replaced wasm circuit on reset', async () => {
131
+ const { service } = makeService();
132
+ await service.init();
133
+ const first = processorInstances[0];
134
+ await service.reset();
135
+ // V8 cannot see wasm-internal bytes, so the FinalizationRegistry may never
136
+ // run. The old circuit must be freed explicitly or its whole store stays
137
+ // resident for the rest of the session.
138
+ expect(first.free).toHaveBeenCalledTimes(1);
139
+ });
140
+ });
141
+
142
+ // The renderer-OOM guardrail. A snapshot walks every row of the store, so it
143
+ // must never run inline with an ingest or a query register/unregister: on a
144
+ // large windowed list that meant hundreds of whole-store serializations per
145
+ // scroll. Snapshots are checkpointed on a timer, and only once enough rows
146
+ // changed to be worth the write.
147
+ describe('StreamProcessorService circuit snapshots', () => {
148
+ const plan = {
149
+ queryHash: 'q1',
150
+ surql: 'SELECT * FROM thing;',
151
+ params: {},
152
+ ttl: '10m',
153
+ lastActiveAt: new Date(),
154
+ localArray: [],
155
+ remoteArray: [],
156
+ meta: { tableName: 'thing' },
157
+ } as any;
158
+
159
+ it('never snapshots on ingest or register/unregister when persistence is off', async () => {
160
+ const { service, db } = makeService();
161
+ service.configureCircuitPersistence(false);
162
+ await service.init();
163
+ const processor = processorInstances[0];
164
+
165
+ service.registerQueryPlan(plan);
166
+ service.ingest('thing', 'CREATE', 'thing:a', { id: 'thing:a' });
167
+ service.ingestMany([
168
+ { table: 'thing', op: 'CREATE', id: 'thing:b', record: { id: 'thing:b' } },
169
+ { table: 'thing', op: 'CREATE', id: 'thing:c', record: { id: 'thing:c' } },
170
+ ]);
171
+ service.unregisterQueryPlan('q1');
172
+
173
+ expect(processor.save_store_state).not.toHaveBeenCalled();
174
+ expect(db.putSnapshot).not.toHaveBeenCalled();
175
+ });
176
+
177
+ it('still never snapshots inline when persistence is on', async () => {
178
+ const { service, db } = makeService();
179
+ service.configureCircuitPersistence(true, 30_000);
180
+ await service.init();
181
+ await service.primeFromLocal(primeCtx);
182
+ const processor = processorInstances[0];
183
+
184
+ service.registerQueryPlan(plan);
185
+ service.ingest('thing', 'CREATE', 'thing:a', { id: 'thing:a' });
186
+ service.unregisterQueryPlan('q1');
187
+
188
+ // Marked dirty, but the write waits for the checkpoint interval.
189
+ expect(processor.save_store_state).not.toHaveBeenCalled();
190
+ expect(db.putSnapshot).not.toHaveBeenCalled();
191
+ service.stopCheckpoints();
192
+ });
193
+
194
+ it('writes at most one snapshot per checkpoint tick, and none for a handful of rows', async () => {
195
+ vi.useFakeTimers();
196
+ try {
197
+ const { service, db } = makeService();
198
+ service.configureCircuitPersistence(true, 1000);
199
+ await service.init();
200
+ await service.primeFromLocal(primeCtx);
201
+ const processor = processorInstances[0];
202
+
203
+ // Below the row threshold: the tick stays quiet.
204
+ for (let i = 0; i < 10; i++) {
205
+ service.ingest('thing', 'CREATE', `thing:${i}`, { id: `thing:${i}` });
206
+ }
207
+ await vi.advanceTimersByTimeAsync(1000);
208
+ expect(processor.save_store_state).not.toHaveBeenCalled();
209
+
210
+ for (let i = 10; i < 60; i++) {
211
+ service.ingest('thing', 'CREATE', `thing:${i}`, { id: `thing:${i}` });
212
+ }
213
+ await vi.advanceTimersByTimeAsync(1000);
214
+ expect(processor.save_store_state).toHaveBeenCalledTimes(1);
215
+ expect(db.putSnapshot).toHaveBeenCalledTimes(1);
216
+
217
+ // Idle interval: nothing changed, so nothing is serialized.
218
+ await vi.advanceTimersByTimeAsync(1000);
219
+ expect(processor.save_store_state).toHaveBeenCalledTimes(1);
220
+
221
+ service.stopCheckpoints();
222
+ } finally {
223
+ vi.useRealTimers();
224
+ }
225
+ });
226
+ });
@@ -31,10 +31,30 @@ export interface WasmIngestItem {
31
31
  version?: number;
32
32
  }
33
33
 
34
+ /** `register_view`'s result: the initial update plus, under projection, the
35
+ * fields this plan evaluates that already-stored rows were kept without. */
36
+ export interface WasmRegistration extends WasmStreamUpdate {
37
+ missing_fields?: Record<string, string[]>;
38
+ }
39
+
40
+ /** `reconcile`'s result. */
41
+ export interface WasmReconciled {
42
+ /** Ids (caller's spelling) whose body the store lacks or holds stale. */
43
+ fetch: string[];
44
+ /** Rows deleted because the caller's list did not have them. */
45
+ deleted: number;
46
+ /** View updates produced by those deletes. */
47
+ updates: WasmStreamUpdate[];
48
+ }
49
+
34
50
  // Interface matching the Sp00kyProcessor class from WASM
35
51
  export interface WasmProcessor {
36
52
  ingest(table: string, op: string, id: string, record: any): WasmStreamUpdate[];
37
- register_view(config: WasmQueryConfig): WasmStreamUpdate | undefined;
53
+ // Bulk ingest: ONE circuit step for the whole array, returning the coalesced
54
+ // updates. Optional because a stale WASM build won't have it — callers guard
55
+ // with `typeof x === 'function'` and fall back to a loop over `ingest`.
56
+ ingest_many?(items: WasmIngestItem[]): WasmStreamUpdate[];
57
+ register_view(config: WasmQueryConfig): WasmRegistration | undefined;
38
58
  unregister_view(id: string): void;
39
59
  // Seed per-table `select` permission predicates ({ [table]: whereText }) so
40
60
  // register_view can inject them instead of default-denying the table.
@@ -44,4 +64,24 @@ export interface WasmProcessor {
44
64
  // build degrades gracefully instead of throwing.
45
65
  load_state?(state: string): void;
46
66
  save_state?(): string;
67
+ // Store-only snapshot as bytes (views are re-registered per session, so
68
+ // they are never persisted). `load_store_state` installs it UNDER the views
69
+ // already registered and returns their re-primed results.
70
+ save_store_state?(): Uint8Array;
71
+ load_store_state?(bytes: Uint8Array): WasmStreamUpdate[];
72
+ // Client-side `_00_rv` catch-up against the durable store's `[id, rv][]`.
73
+ reconcile?(table: string, entries: [string, number][]): WasmReconciled;
74
+ max_row_versions?(): Record<string, number>;
75
+ // Row-arena hygiene. `compact` decodes every row, so checkpoint-time only.
76
+ compact?(): number;
77
+ dead_bytes?(): number;
78
+ live_bytes?(): number;
79
+ // Keep only the fields registered plans evaluate per stored row.
80
+ set_projection?(enabled: boolean): void;
81
+ size_report?(): unknown;
82
+ // wasm-bindgen destructor. Releases the circuit (store + every view cache)
83
+ // inside wasm linear memory. Without it the bytes only come back when V8
84
+ // happens to GC the JS wrapper, which it has no reason to hurry since it
85
+ // cannot see how much wasm memory the wrapper is holding.
86
+ free?(): void;
47
87
  }