@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
@@ -2,10 +2,12 @@
2
2
  import init, { Sp00kyProcessor } from '@spooky-sync/ssp-wasm';
3
3
  import type { EventDefinition, EventSystem } from '../../events/index';
4
4
  import type { Logger } from 'pino';
5
- import type { LocalDatabaseService } from '../database/index';
5
+ import type { LocalStore } from '../database/index';
6
6
  import type { WasmProcessor, WasmStreamUpdate } from './wasm-types';
7
7
  import type { Duration } from 'surrealdb';
8
- import type { PersistenceClient, QueryTimeToLive, RecordVersionArray } from '../../types';
8
+ import type { QueryTimeToLive, RecordVersionArray } from '../../types';
9
+ import { encodeRecordId } from '../../utils/index';
10
+ import { recordIdKey } from '../database/relation-resolver';
9
11
 
10
12
  // Simple interface for query plan registration (replaces Incantation class)
11
13
  interface QueryPlanConfig {
@@ -28,6 +30,14 @@ export interface StreamUpdate {
28
30
  queryHash: string;
29
31
  localArray: RecordVersionArray;
30
32
  op?: 'CREATE' | 'UPDATE' | 'DELETE'; // Operation type for conditional debouncing
33
+ /**
34
+ * Client-internal: not from the circuit. A membership-only change that
35
+ * needed no fetch is re-materialized through this same path so it cannot
36
+ * race a real update (DataModule.scheduleRematerialize). Carries the last
37
+ * known `localArray`; consumers that describe an INGEST (persist, metrics,
38
+ * devtools events) skip it.
39
+ */
40
+ synthetic?: boolean;
31
41
  /**
32
42
  * End-to-end ingest latency for the WASM call that produced this update,
33
43
  * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
@@ -57,6 +67,62 @@ export interface StreamUpdateReceiver {
57
67
  onStreamUpdate(update: StreamUpdate): void;
58
68
  }
59
69
 
70
+ /** One row change in the shape `ingestMany` consumes. */
71
+ export interface IngestRecord {
72
+ table: string;
73
+ /** `MERGE` overlays the given fields on the stored row (projection widening). */
74
+ op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
75
+ id: string;
76
+ record: any;
77
+ }
78
+
79
+ /**
80
+ * What the boot-time prime needs from the client: which tables to walk, how
81
+ * to recognise a snapshot written under a different schema, and which rows'
82
+ * local `_00_rv` must not be reported as the server's.
83
+ */
84
+ export interface CircuitPrimeContext {
85
+ tables: string[];
86
+ schemaHash: string;
87
+ /** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
88
+ * locally and may exceed the server's next version). */
89
+ pendingIds: Set<string>;
90
+ /** Each table's client column set (`columnFingerprints`). An engine that
91
+ * keeps bodies across schema changes resets the versions of a table whose
92
+ * set changed before they are read, so its rows are fetched again whole. */
93
+ columnFingerprints?: Record<string, string>;
94
+ /** Receives every `(id, rv)` the prime put into the circuit, per table, so
95
+ * the sync layer can skip re-downloading bodies it already has. */
96
+ onVersions?: (table: string, entries: [string, number][]) => void;
97
+ }
98
+
99
+ /** Storage key of the circuit snapshot inside the local store. */
100
+ export const CIRCUIT_SNAPSHOT_KEY = 'circuit';
101
+ /** Bump when the bytes `load_store_state` reads change shape. */
102
+ export const CIRCUIT_SNAPSHOT_FORMAT = 1;
103
+ /** Rows per `ingest_many` call. Bounds the transient the wasm side allocates
104
+ * to parse a batch (measured: one 7700-row call of 20 KB bodies peaked at
105
+ * 500 MB, 128-row chunks at 335 MB, and under projection at 24 MB). */
106
+ const INGEST_CHUNK = 128;
107
+ /** Ids per `selectByIds` when priming bodies out of the local store. */
108
+ const PRIME_CHUNK = 256;
109
+ /** Rows the SurrealDB (main-thread, IndexedDB) engine is allowed to prime
110
+ * through; above this the circuit boots empty as it always did. */
111
+ const SURREAL_PRIME_ROW_CAP = 20_000;
112
+ /** Below this many changed rows the checkpoint timer stays quiet. */
113
+ const CHECKPOINT_MIN_ROWS = 50;
114
+
115
+ /** Stable `table:id` for a row id that may already be a string. */
116
+ function idString(id: unknown): string {
117
+ return typeof id === 'string' ? id : encodeRecordId(id as any);
118
+ }
119
+
120
+ function chunks<T>(items: T[], size: number): T[][] {
121
+ const out: T[][] = [];
122
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
123
+ return out;
124
+ }
125
+
60
126
  export class StreamProcessorService {
61
127
  private logger: Logger;
62
128
  private processor: WasmProcessor | undefined;
@@ -75,11 +141,42 @@ export class StreamProcessorService {
75
141
  // rejecting `$auth`-gated tables; the predicate just degrades to its public
76
142
  // branch. Set via `setSessionAuth` on every auth state change.
77
143
  private sessionAuth: { authId: string; access: string } = { authId: '', access: '' };
144
+ // Bumped by `reset()`. Anything captured before a reset (a checkpoint's
145
+ // bytes, a prime's chunk, a widening read) must not land on the NEW
146
+ // processor, which belongs to a different bucket.
147
+ private stateGeneration = 0;
148
+ // Shared-tabs: follower circuits are in-memory ONLY. Only the tab that owns
149
+ // the store writes its snapshot; a promoted follower flips this back on.
150
+ private persistState = true;
151
+ // Snapshot persistence. Store-only bytes, written by the checkpoint timer
152
+ // and on the page going hidden, never per ingest: `save_store_state` walks
153
+ // every row. The snapshot is what lets a reload restore the circuit and
154
+ // step in only what changed since (`reconcile`), instead of re-downloading
155
+ // and re-ingesting the whole working set.
156
+ private persistCircuit = false;
157
+ private checkpointMs = 30_000;
158
+ private checkpointTimer: ReturnType<typeof setInterval> | null = null;
159
+ private snapshotDirty = false;
160
+ private dirtyRows = 0;
161
+ private hideHandler: (() => void) | null = null;
162
+ private checkpointInFlight: Promise<void> | null = null;
163
+ // Keep only the fields registered plans evaluate per stored row. The client
164
+ // renders bodies from the local store, so a 20 KB game row in the circuit
165
+ // is ~150 B of predicate/sort fields under projection.
166
+ private projection = true;
167
+ // Prime state: `primed` resolves when the boot-time prime (snapshot restore
168
+ // + reconcile, or a full read of the local store) has finished, aborted or
169
+ // been skipped. Sync waits on it before its first diff.
170
+ private primed: Promise<void> = Promise.resolve();
171
+ private schemaHash: string | null = null;
172
+ // Projection widening, serialised: fields a new view evaluates that stored
173
+ // rows lack are merged in table by table.
174
+ private widenQueue: Promise<void> = Promise.resolve();
175
+ private widenPending: Map<string, Set<string>> = new Map();
78
176
 
79
177
  constructor(
80
178
  public events: EventSystem<StreamProcessorEvents>,
81
- private db: LocalDatabaseService,
82
- private persistenceClient: PersistenceClient,
179
+ private db: LocalStore,
83
180
  logger: Logger
84
181
  ) {
85
182
  this.logger = logger.child({ name: 'StreamProcessorService' });
@@ -128,35 +225,89 @@ export class StreamProcessorService {
128
225
  }
129
226
 
130
227
  /**
131
- * Ingest a batch of record changes as a single bulk operation, firing only
132
- * one coalesced `StreamUpdate` per affected query once every record has been
133
- * ingested (instead of one update per record). Use this whenever multiple
134
- * records land at once — e.g. sync fetching N missing rows — so a list query
135
- * re-runs and the UI re-renders once for the whole batch rather than
136
- * row-by-row.
228
+ * Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
229
+ * affected query once every record has been ingested. Use this whenever
230
+ * multiple records land at once (sync fetching N rows, the boot prime).
231
+ *
232
+ * The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
233
+ * circuit step per chunk (a step walks every registered view, so per-record
234
+ * ingest paid that fixed cost N times), but never the whole batch at once,
235
+ * because the wasm side has to hold every parsed row of a call at the same
236
+ * time and wasm32 dlmalloc never returns that peak.
137
237
  *
138
- * Internally opens a coalescing window, ingests each record, then flushes;
139
- * processor state is persisted once for the whole batch. No-op for an empty
140
- * batch.
238
+ * Returns the records that were ingested. A chunk that fails is reported
239
+ * and skipped, not retried (a retry would double-apply whatever the failed
240
+ * step already committed), and the remaining chunks still run.
141
241
  */
142
- ingestMany(
143
- records: Array<{
144
- table: string;
145
- op: 'CREATE' | 'UPDATE' | 'DELETE';
146
- id: string;
147
- record: any;
148
- }>
149
- ): void {
150
- if (records.length === 0) return;
242
+ ingestMany(records: IngestRecord[]): IngestRecord[] {
243
+ if (records.length === 0) return [];
244
+
245
+ if (!this.processor) {
246
+ this.logger.warn(
247
+ { Category: 'sp00ky-client::StreamProcessorService::ingestMany' },
248
+ 'Not initialized, skipping ingest'
249
+ );
250
+ return [];
251
+ }
151
252
 
253
+ const bulkIngest = this.processor.ingest_many;
254
+ if (typeof bulkIngest !== 'function') {
255
+ // Stale wasm build: per-record steps, still coalesced into one update.
256
+ this.beginCoalescing();
257
+ try {
258
+ for (const record of records) {
259
+ this.ingest(record.table, record.op, record.id, record.record);
260
+ }
261
+ } finally {
262
+ this.flushCoalescing();
263
+ }
264
+ return records;
265
+ }
266
+
267
+ const ingested: IngestRecord[] = [];
152
268
  this.beginCoalescing();
153
269
  try {
154
- for (const record of records) {
155
- this.ingest(record.table, record.op, record.id, record.record);
270
+ for (const chunk of chunks(records, INGEST_CHUNK)) {
271
+ try {
272
+ const items = chunk.map((record) => ({
273
+ table: record.table,
274
+ op: record.op,
275
+ id: record.id,
276
+ record: this.normalizeValue(record.record),
277
+ }));
278
+ const t0 = performance.now();
279
+ const rawUpdates = bulkIngest.call(this.processor, items) ?? [];
280
+ const materializationTimeMs = performance.now() - t0;
281
+ if (rawUpdates.length > 0) {
282
+ this.notifyUpdates(
283
+ rawUpdates.map((u: WasmStreamUpdate) => ({
284
+ queryHash: u.query_id,
285
+ localArray: u.result_data,
286
+ op: 'CREATE' as const,
287
+ materializationTimeMs,
288
+ storeApplyMs: u.timing_store_apply_ms,
289
+ circuitStepMs: u.timing_circuit_step_ms,
290
+ transformMs: u.timing_transform_ms,
291
+ }))
292
+ );
293
+ }
294
+ ingested.push(...chunk);
295
+ } catch (e) {
296
+ this.logger.error(
297
+ { error: e, count: chunk.length, Category: 'sp00ky-client::StreamProcessorService::ingestMany' },
298
+ 'Ingesting chunk into ssp failed'
299
+ );
300
+ }
156
301
  }
157
302
  } finally {
158
303
  this.flushCoalescing();
159
304
  }
305
+ this.logger.debug(
306
+ { count: records.length, ingested: ingested.length, Category: 'sp00ky-client::StreamProcessorService::ingestMany' },
307
+ 'Ingested batch into ssp'
308
+ );
309
+ this.markSnapshotDirty(ingested.length);
310
+ return ingested;
160
311
  }
161
312
 
162
313
  /**
@@ -187,10 +338,6 @@ export class StreamProcessorService {
187
338
  if (buffered.length > 0) {
188
339
  this.dispatchUpdates(buffered);
189
340
  }
190
- // The processor state after the last ingest is cumulative, so a single
191
- // snapshot covers the whole batch. Kept fire-and-forget like the per-ingest
192
- // call it replaces.
193
- this.saveState();
194
341
  }
195
342
 
196
343
  /**
@@ -208,9 +355,7 @@ export class StreamProcessorService {
208
355
  await init(); // Initialize the WASM module (web target)
209
356
  // We cast the generated Sp00kyProcessor to our interface which is safer
210
357
  this.processor = new Sp00kyProcessor() as unknown as WasmProcessor;
211
-
212
- // Try to load state
213
- await this.loadState();
358
+ this.applyProjection();
214
359
 
215
360
  this.isInitialized = true;
216
361
  this.logger.info(
@@ -226,47 +371,448 @@ export class StreamProcessorService {
226
371
  }
227
372
  }
228
373
 
229
- async loadState() {
230
- if (!this.processor) return;
374
+ /**
375
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
376
+ * local-bucket switches: the old circuit holds the previous user's rows AND
377
+ * views registered with the previous `$auth` context, so neither may survive.
378
+ * Deliberately loads nothing: the snapshot in the store being swapped away
379
+ * from belongs to the previous bucket; the caller primes the new bucket's
380
+ * circuit (`primeFromLocal`) once its store is open, and the DataModule
381
+ * rebind re-registers every live view against this fresh processor. Caller
382
+ * must re-seed `setPermissions` afterwards (a fresh circuit default-denies
383
+ * every table).
384
+ */
385
+ async reset(): Promise<void> {
386
+ if (!this.isInitialized) return;
387
+ this.stateGeneration++;
388
+ this.batching = false;
389
+ this.batchBuffer.clear();
390
+ this.snapshotDirty = false;
391
+ this.dirtyRows = 0;
392
+ this.widenPending.clear();
393
+ const previous = this.processor;
394
+ this.processor = new Sp00kyProcessor() as unknown as WasmProcessor;
395
+ this.applyProjection();
396
+ this.freeProcessor(previous);
397
+ this.logger.info(
398
+ { Category: 'sp00ky-client::StreamProcessorService::reset' },
399
+ 'Stream processor reset (fresh circuit)'
400
+ );
401
+ }
402
+
403
+ /**
404
+ * Release the wasm circuit and stop checkpointing. Call when the client is
405
+ * torn down; a recreated client (provider remount, HMR) would otherwise stack
406
+ * one full circuit per instance.
407
+ */
408
+ dispose(): void {
409
+ this.stopCheckpoints();
410
+ const previous = this.processor;
411
+ this.processor = undefined;
412
+ this.isInitialized = false;
413
+ this.batching = false;
414
+ this.batchBuffer.clear();
415
+ this.receivers = [];
416
+ this.freeProcessor(previous);
417
+ }
418
+
419
+ /**
420
+ * Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
421
+ * not expose `free`, and a double free must not take the app down.
422
+ */
423
+ private freeProcessor(processor: WasmProcessor | undefined): void {
424
+ if (!processor || typeof processor.free !== 'function') return;
231
425
  try {
232
- const result = await this.persistenceClient.get('_00_stream_processor_state');
426
+ processor.free();
427
+ } catch (e) {
428
+ this.logger.debug(
429
+ { error: e, Category: 'sp00ky-client::StreamProcessorService::freeProcessor' },
430
+ 'Failed to free previous wasm circuit'
431
+ );
432
+ }
433
+ }
233
434
 
234
- // Check if we have a valid result from the query
235
- if (
236
- Array.isArray(result) &&
237
- result.length > 0 &&
238
- Array.isArray(result[0]) &&
239
- result[0].length > 0 &&
240
- result[0][0]?.state
241
- ) {
242
- const state = result[0][0].state;
243
- this.logger.info(
244
- {
245
- stateLength: state.length,
246
- Category: 'sp00ky-client::StreamProcessorService::loadState',
247
- },
248
- 'Loading state from DB'
435
+ /** Toggle circuit-state persistence (shared-tabs follower/leader role). */
436
+ setPersistenceEnabled(enabled: boolean): void {
437
+ this.persistState = enabled;
438
+ if (!enabled) this.stopCheckpoints();
439
+ }
440
+
441
+ /**
442
+ * Snapshot persistence (`persistCircuit`). When on, the circuit's store is
443
+ * written to the local store on a checkpoint interval and when the page
444
+ * goes hidden, and restored by {@link primeFromLocal} on the next boot.
445
+ */
446
+ configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void {
447
+ this.persistCircuit = enabled;
448
+ if (checkpointMs && checkpointMs > 0) this.checkpointMs = checkpointMs;
449
+ if (!enabled) this.stopCheckpoints();
450
+ }
451
+
452
+ /**
453
+ * Field projection (`circuitProjection`, default on). Takes effect on the
454
+ * next processor (`init`/`reset`) and on rows written after that.
455
+ */
456
+ configureProjection(enabled: boolean): void {
457
+ this.projection = enabled;
458
+ this.applyProjection();
459
+ }
460
+
461
+ private applyProjection(): void {
462
+ if (!this.processor || typeof this.processor.set_projection !== 'function') return;
463
+ try {
464
+ this.processor.set_projection(this.projection);
465
+ } catch (e) {
466
+ this.logger.warn(
467
+ { error: e, Category: 'sp00ky-client::StreamProcessorService::applyProjection' },
468
+ 'set_projection failed'
469
+ );
470
+ }
471
+ }
472
+
473
+ /** Resolves once the boot-time prime has finished (or was skipped). */
474
+ whenPrimed(): Promise<void> {
475
+ return this.primed;
476
+ }
477
+
478
+ /**
479
+ * Fill the circuit from the LOCAL store, in the background.
480
+ *
481
+ * With a usable snapshot: install it under whatever views have registered
482
+ * meanwhile (`load_store_state` re-primes them), then `reconcile` each table
483
+ * against the store's `(id, rv)` list so rows deleted since the checkpoint
484
+ * are stepped out and only rows added or changed since are read back and
485
+ * ingested. Without one: read every row and ingest it, chunked.
486
+ *
487
+ * Either way the circuit ends up equal to the local store without touching
488
+ * the network, so the first sync diff is a real delta rather than "fetch
489
+ * everything". The returned promise never rejects; `whenPrimed` gates on it.
490
+ */
491
+ primeFromLocal(ctx: CircuitPrimeContext): Promise<void> {
492
+ this.schemaHash = ctx.schemaHash;
493
+ const run = this.runPrime(ctx).catch((e) => {
494
+ this.logger.warn(
495
+ { error: e, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
496
+ 'Circuit prime failed; the circuit fills from sync instead'
497
+ );
498
+ });
499
+ this.primed = run;
500
+ return run;
501
+ }
502
+
503
+ private async runPrime(ctx: CircuitPrimeContext): Promise<void> {
504
+ const processor = this.processor;
505
+ if (!processor || typeof this.db.scanVersions !== 'function') return;
506
+ const generation = this.stateGeneration;
507
+ const epoch = this.db.epoch;
508
+ // A bucket switch replaces the processor and the store under us; every
509
+ // step re-checks so a stale chunk never lands in the new bucket.
510
+ const alive = () =>
511
+ this.processor === processor && generation === this.stateGeneration && epoch === this.db.epoch;
512
+ const t0 = performance.now();
513
+
514
+ // Before anything reads a version: a table whose columns changed since its
515
+ // bodies were cached reads as stale from here on (see sqlite-column-reset).
516
+ if (ctx.columnFingerprints && typeof this.db.resetChangedTables === 'function') {
517
+ try {
518
+ const reset = await this.db.resetChangedTables(ctx.columnFingerprints, ctx.pendingIds);
519
+ if (!alive()) return;
520
+ if (reset.length > 0) {
521
+ this.logger.info(
522
+ { tables: reset, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
523
+ 'Columns changed since these rows were cached; they will be fetched again'
524
+ );
525
+ }
526
+ } catch (e) {
527
+ this.logger.warn(
528
+ { error: e, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
529
+ 'Column change check failed; cached versions kept'
249
530
  );
250
- // Assuming processor has a load_state method matching the save_state behavior
251
- // If not, we might need to adjust based on the actual WASM API
252
- if (typeof this.processor.load_state === 'function') {
253
- this.processor.load_state(state);
254
- } else {
255
- this.logger.warn(
256
- { Category: 'sp00ky-client::StreamProcessorService::loadState' },
257
- 'load_state method not found on processor'
531
+ }
532
+ }
533
+
534
+ let restored = false;
535
+ if (
536
+ this.persistCircuit &&
537
+ typeof this.db.getSnapshot === 'function' &&
538
+ typeof processor.load_store_state === 'function'
539
+ ) {
540
+ const snapshot = await this.db.getSnapshot(CIRCUIT_SNAPSHOT_KEY);
541
+ if (!alive()) return;
542
+ if (snapshot) {
543
+ const { meta } = snapshot;
544
+ if (meta.formatVersion !== CIRCUIT_SNAPSHOT_FORMAT || meta.schemaHash !== ctx.schemaHash) {
545
+ this.logger.info(
546
+ { meta, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
547
+ 'Circuit snapshot is from another format or schema; priming from rows'
258
548
  );
549
+ } else {
550
+ try {
551
+ const tLoad = performance.now();
552
+ const updates = processor.load_store_state(snapshot.bytes);
553
+ this.dispatchWasmUpdates(updates);
554
+ restored = true;
555
+ this.logger.info(
556
+ {
557
+ bytes: snapshot.bytes.byteLength,
558
+ views: updates.length,
559
+ loadMs: Math.round(performance.now() - tLoad),
560
+ Category: 'sp00ky-client::StreamProcessorService::primeFromLocal',
561
+ },
562
+ 'Circuit snapshot restored'
563
+ );
564
+ } catch (e) {
565
+ this.logger.warn(
566
+ { error: e, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
567
+ 'Circuit snapshot unreadable; priming from rows'
568
+ );
569
+ }
259
570
  }
571
+ }
572
+ }
573
+
574
+ // Read the versions AFTER the snapshot: a batch the leader writes between
575
+ // the two can only make the store side newer, which reconcile handles.
576
+ const versions = await this.db.scanVersions(ctx.tables);
577
+ if (!alive()) return;
578
+ const total = Object.values(versions).reduce((n, v) => n + v.length, 0);
579
+ if (!restored && this.db.engineKind !== 'sqlite' && total > SURREAL_PRIME_ROW_CAP) {
580
+ this.logger.warn(
581
+ { total, cap: SURREAL_PRIME_ROW_CAP, Category: 'sp00ky-client::StreamProcessorService::primeFromLocal' },
582
+ 'Too many cached rows to prime through the main-thread engine; circuit fills from sync'
583
+ );
584
+ return;
585
+ }
586
+
587
+ let ingested = 0;
588
+ let fetched = 0;
589
+ let deleted = 0;
590
+ for (const table of ctx.tables) {
591
+ const entries = versions[table] ?? [];
592
+ let toFetch: string[];
593
+ if (restored && typeof processor.reconcile === 'function') {
594
+ const result = processor.reconcile(table, entries);
595
+ this.dispatchWasmUpdates(result.updates);
596
+ deleted += result.deleted;
597
+ toFetch = result.fetch;
260
598
  } else {
261
- this.logger.info(
262
- { Category: 'sp00ky-client::StreamProcessorService::loadState' },
263
- 'No saved state found'
599
+ toFetch = entries.map(([id]) => id);
600
+ }
601
+ for (const chunk of chunks(toFetch, PRIME_CHUNK)) {
602
+ const rows = await this.db.selectByIds(table, chunk);
603
+ if (!alive()) return;
604
+ fetched += rows.length;
605
+ ingested += this.ingestMany(
606
+ rows.map((row) => ({
607
+ table,
608
+ op: 'CREATE' as const,
609
+ id: idString(row.id),
610
+ record: row,
611
+ }))
612
+ ).length;
613
+ }
614
+ if (entries.length > 0) {
615
+ ctx.onVersions?.(
616
+ table,
617
+ entries.filter(([id]) => !ctx.pendingIds.has(id))
264
618
  );
265
619
  }
620
+ }
621
+ // A prime from rows leaves the store with no snapshot to fall back on;
622
+ // let the next checkpoint write one even if nothing else changes.
623
+ if (!restored && ingested > 0) this.markSnapshotDirty(Math.max(ingested, CHECKPOINT_MIN_ROWS));
624
+ this.logger.info(
625
+ {
626
+ restored,
627
+ rows: total,
628
+ fetched,
629
+ ingested,
630
+ deleted,
631
+ ms: Math.round(performance.now() - t0),
632
+ Category: 'sp00ky-client::StreamProcessorService::primeFromLocal',
633
+ },
634
+ 'Circuit primed from the local store'
635
+ );
636
+ }
637
+
638
+ /** Publish wasm updates produced outside an ingest (restore, reconcile). */
639
+ private dispatchWasmUpdates(updates: WasmStreamUpdate[] | undefined): void {
640
+ if (!updates || updates.length === 0) return;
641
+ this.dispatchUpdates(
642
+ updates.map((u) => ({
643
+ queryHash: u.query_id,
644
+ localArray: u.result_data,
645
+ op: 'CREATE' as const,
646
+ }))
647
+ );
648
+ }
649
+
650
+ /**
651
+ * Record that the circuit changed by `rows` rows. Cheap; the snapshot is
652
+ * deferred to the checkpoint timer and skipped entirely when `persistCircuit`
653
+ * is off.
654
+ */
655
+ private markSnapshotDirty(rows = 1): void {
656
+ if (!this.persistCircuit || !this.persistState) return;
657
+ this.snapshotDirty = true;
658
+ this.dirtyRows += rows;
659
+ this.startCheckpoints();
660
+ }
661
+
662
+ private startCheckpoints(): void {
663
+ if (this.checkpointTimer) return;
664
+ this.checkpointTimer = setInterval(() => {
665
+ if (!this.snapshotDirty || this.dirtyRows < CHECKPOINT_MIN_ROWS) return;
666
+ void this.checkpoint('interval');
667
+ }, this.checkpointMs);
668
+ // Node/test environments have no `window`; the interval alone is enough there.
669
+ if (typeof window !== 'undefined' && !this.hideHandler) {
670
+ // `visibilitychange: hidden` is the reliable last chance: a 100 MB write
671
+ // cannot finish inside `pagehide`, which is kept only as best effort.
672
+ this.hideHandler = () => {
673
+ if (!this.snapshotDirty) return;
674
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') return;
675
+ void this.checkpoint('hidden');
676
+ };
677
+ window.addEventListener('visibilitychange', this.hideHandler);
678
+ window.addEventListener('pagehide', this.hideHandler);
679
+ }
680
+ }
681
+
682
+ /** Stop checkpointing and drop the visibility listeners. */
683
+ stopCheckpoints(): void {
684
+ if (this.checkpointTimer) {
685
+ clearInterval(this.checkpointTimer);
686
+ this.checkpointTimer = null;
687
+ }
688
+ if (this.hideHandler && typeof window !== 'undefined') {
689
+ window.removeEventListener('visibilitychange', this.hideHandler);
690
+ window.removeEventListener('pagehide', this.hideHandler);
691
+ }
692
+ this.hideHandler = null;
693
+ this.snapshotDirty = false;
694
+ this.dirtyRows = 0;
695
+ }
696
+
697
+ /**
698
+ * Write the circuit's store to the local store as a snapshot. Compacts the
699
+ * row arena first when dead bytes outweigh live ones. Serialised: a second
700
+ * call while one is in flight joins it. No-op unless persistence is on, this
701
+ * tab owns the store, and the engine can hold a snapshot.
702
+ */
703
+ checkpoint(reason = 'manual'): Promise<void> {
704
+ if (this.checkpointInFlight) return this.checkpointInFlight;
705
+ const run = this.runCheckpoint(reason).finally(() => {
706
+ this.checkpointInFlight = null;
707
+ });
708
+ this.checkpointInFlight = run;
709
+ return run;
710
+ }
711
+
712
+ private async runCheckpoint(reason: string): Promise<void> {
713
+ const processor = this.processor;
714
+ if (!processor || !this.persistState || !this.persistCircuit || !this.schemaHash) return;
715
+ if (typeof this.db.putSnapshot !== 'function' || typeof processor.save_store_state !== 'function') {
716
+ return;
717
+ }
718
+ const generation = this.stateGeneration;
719
+ const epoch = this.db.epoch;
720
+ const rows = this.dirtyRows;
721
+ this.snapshotDirty = false;
722
+ this.dirtyRows = 0;
723
+ try {
724
+ const t0 = performance.now();
725
+ let reclaimed = 0;
726
+ if (
727
+ typeof processor.compact === 'function' &&
728
+ typeof processor.dead_bytes === 'function' &&
729
+ typeof processor.live_bytes === 'function'
730
+ ) {
731
+ const dead = processor.dead_bytes();
732
+ if (dead > 1_000_000 && dead > processor.live_bytes()) reclaimed = processor.compact();
733
+ }
734
+ const bytes = processor.save_store_state();
735
+ const meta = {
736
+ formatVersion: CIRCUIT_SNAPSHOT_FORMAT,
737
+ schemaHash: this.schemaHash,
738
+ savedAt: Date.now(),
739
+ maxRv: typeof processor.max_row_versions === 'function' ? processor.max_row_versions() : undefined,
740
+ };
741
+ // A reset or bucket switch landed while we serialised: this snapshot
742
+ // describes the OLD bucket's circuit and must not be written into the
743
+ // new bucket's store.
744
+ if (generation !== this.stateGeneration || epoch !== this.db.epoch) return;
745
+ await this.db.putSnapshot(CIRCUIT_SNAPSHOT_KEY, bytes, meta);
746
+ this.logger.info(
747
+ {
748
+ reason,
749
+ rows,
750
+ bytes: bytes.byteLength,
751
+ reclaimed,
752
+ ms: Math.round(performance.now() - t0),
753
+ Category: 'sp00ky-client::StreamProcessorService::checkpoint',
754
+ },
755
+ 'Circuit snapshot written'
756
+ );
266
757
  } catch (e) {
267
- this.logger.error(
268
- { error: e, Category: 'sp00ky-client::StreamProcessorService::loadState' },
269
- 'Failed to load state'
758
+ this.logger.warn(
759
+ { error: e, reason, Category: 'sp00ky-client::StreamProcessorService::checkpoint' },
760
+ 'Circuit snapshot failed'
761
+ );
762
+ }
763
+ }
764
+
765
+ /**
766
+ * Projection widening: a newly registered view evaluates fields that rows
767
+ * already in the circuit were stored without. Merge just those fields in,
768
+ * table by table, from the local store. The view registered against what
769
+ * was present and converges as the merges step through.
770
+ */
771
+ private scheduleWiden(missing: Record<string, string[]>): void {
772
+ for (const [table, fields] of Object.entries(missing)) {
773
+ const set = this.widenPending.get(table) ?? new Set<string>();
774
+ for (const f of fields) set.add(f);
775
+ this.widenPending.set(table, set);
776
+ }
777
+ this.widenQueue = this.widenQueue.then(() => this.runWiden()).catch((e) => {
778
+ this.logger.warn(
779
+ { error: e, Category: 'sp00ky-client::StreamProcessorService::widen' },
780
+ 'Projection widening failed'
781
+ );
782
+ });
783
+ }
784
+
785
+ private async runWiden(): Promise<void> {
786
+ const processor = this.processor;
787
+ if (!processor || typeof this.db.scanVersions !== 'function') {
788
+ this.widenPending.clear();
789
+ return;
790
+ }
791
+ const generation = this.stateGeneration;
792
+ const epoch = this.db.epoch;
793
+ while (this.widenPending.size > 0) {
794
+ const [table, fields] = this.widenPending.entries().next().value as [string, Set<string>];
795
+ this.widenPending.delete(table);
796
+ const select = Array.from(fields);
797
+ const versions = await this.db.scanVersions([table]);
798
+ if (this.processor !== processor || generation !== this.stateGeneration || epoch !== this.db.epoch) return;
799
+ const ids = (versions[table] ?? []).map(([id]) => id);
800
+ let merged = 0;
801
+ for (const chunk of chunks(ids, PRIME_CHUNK)) {
802
+ const rows = await this.db.selectByIds(table, chunk, { select });
803
+ if (this.processor !== processor || generation !== this.stateGeneration || epoch !== this.db.epoch) return;
804
+ merged += this.ingestMany(
805
+ rows.map((row) => ({
806
+ table,
807
+ op: 'MERGE' as const,
808
+ id: idString(row.id),
809
+ record: row,
810
+ }))
811
+ ).length;
812
+ }
813
+ this.logger.info(
814
+ { table, fields: select, merged, Category: 'sp00ky-client::StreamProcessorService::widen' },
815
+ 'Widened projected rows with newly evaluated fields'
270
816
  );
271
817
  }
272
818
  }
@@ -317,28 +863,6 @@ export class StreamProcessorService {
317
863
  );
318
864
  }
319
865
 
320
- async saveState() {
321
- if (!this.processor) return;
322
- try {
323
- // Assuming processor has a save_state method that returns the state string/bytes
324
- if (typeof this.processor.save_state === 'function') {
325
- const state = this.processor.save_state();
326
- if (state) {
327
- await this.persistenceClient.set('_00_stream_processor_state', state);
328
- this.logger.trace(
329
- { Category: 'sp00ky-client::StreamProcessorService::saveState' },
330
- 'State saved'
331
- );
332
- }
333
- }
334
- } catch (e) {
335
- this.logger.error(
336
- { error: e, Category: 'sp00ky-client::StreamProcessorService::saveState' },
337
- 'Failed to save state'
338
- );
339
- }
340
- }
341
-
342
866
  /**
343
867
  * Ingest a record change into the processor.
344
868
  * Emits 'stream_update' event if materialized views are affected.
@@ -346,7 +870,7 @@ export class StreamProcessorService {
346
870
  */
347
871
  ingest(
348
872
  table: string,
349
- op: 'CREATE' | 'UPDATE' | 'DELETE',
873
+ op: IngestRecord['op'],
350
874
  id: string,
351
875
  record: any
352
876
  ): WasmStreamUpdate[] {
@@ -390,7 +914,8 @@ export class StreamProcessorService {
390
914
  const updates: StreamUpdate[] = rawUpdates.map((u: WasmStreamUpdate) => ({
391
915
  queryHash: u.query_id,
392
916
  localArray: u.result_data,
393
- op: op,
917
+ // A MERGE is a content update as far as consumers are concerned.
918
+ op: op === 'MERGE' ? 'UPDATE' : op,
394
919
  materializationTimeMs,
395
920
  storeApplyMs: u.timing_store_apply_ms,
396
921
  circuitStepMs: u.timing_circuit_step_ms,
@@ -399,10 +924,10 @@ export class StreamProcessorService {
399
924
  // Direct handler call instead of event
400
925
  this.notifyUpdates(updates);
401
926
  }
402
- // While batching (inside `ingestMany`), `flushCoalescing` persists once
403
- // for the whole batch — skip the redundant per-record snapshot here.
927
+ // While batching (inside `ingestMany`), `flushCoalescing` marks dirty once
928
+ // for the whole batch, skip the redundant per-record mark here.
404
929
  if (!this.batching) {
405
- this.saveState();
930
+ this.markSnapshotDirty();
406
931
  }
407
932
  return rawUpdates;
408
933
  } catch (e) {
@@ -479,7 +1004,9 @@ export class StreamProcessorService {
479
1004
  snapshotMs: initialUpdate.timing_snapshot_ms ?? 0,
480
1005
  },
481
1006
  };
482
- this.saveState();
1007
+ if (initialUpdate.missing_fields && Object.keys(initialUpdate.missing_fields).length > 0) {
1008
+ this.scheduleWiden(initialUpdate.missing_fields);
1009
+ }
483
1010
  this.logger.debug(
484
1011
  {
485
1012
  queryHash: queryPlan.queryHash,
@@ -506,7 +1033,6 @@ export class StreamProcessorService {
506
1033
  if (!this.processor) return;
507
1034
  try {
508
1035
  this.processor.unregister_view(queryHash);
509
- this.saveState();
510
1036
  } catch (e) {
511
1037
  this.logger.error(
512
1038
  { error: e, Category: 'sp00ky-client::StreamProcessorService::unregisterQueryPlan' },
@@ -543,7 +1069,9 @@ export class StreamProcessorService {
543
1069
  const isNotPlainObject = value.constructor !== Object;
544
1070
 
545
1071
  if (hasTable && hasId && hasToString && isNotPlainObject) {
546
- const result = value.toString();
1072
+ // The raw `table:id`, as the store spells it. `toString()` is escaped
1073
+ // SurrealQL (SDK 2.1.0: `game:⟨476g…⟩`); only a complex key uses it.
1074
+ const result = recordIdKey(value) ?? value.toString();
547
1075
  this.logger.trace(
548
1076
  { result, Category: 'sp00ky-client::StreamProcessorService::normalizeValue' },
549
1077
  'RecordId detected'