@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
@@ -0,0 +1,216 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import { runPure } from '../testing/run-pure';
4
+ import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
5
+ import * as R from '../state/reducers';
6
+ import { materialize, streamUpdate } from './materialize.saga';
7
+
8
+ describe('materialize', () => {
9
+ const plan = { table: 'thing' } as any;
10
+ it('no entry: nothing', async () => {
11
+ const out = await runPure(materialize('zz'), { state: buildState() });
12
+ expect(out.log.filter((e) => e.kind !== 'state.read')).toHaveLength(0);
13
+ });
14
+ const vouch = (...ids: string[]) => R.reloadViews(new Map([['other-view', ids]]));
15
+ it('cold: predicate scan through the plan; rows land, dirt clears, subscribers hear once', async () => {
16
+ const s = R.markDirty(['a'])(buildState([buildEntry({ def: { hash: 'a', plan } })], vouch('thing:1')));
17
+ const out = await runPure(materialize('a'), { state: s, handlers: { 'local.select': (e: any) => (e.plan.ids ? [] : [{ id: 'thing:1' }]) } });
18
+ const en = out.state.queries.get('a')!;
19
+ expect(en.records).toEqual([{ id: 'thing:1' }]);
20
+ expect(en.lifecycle.notified).toBe(true);
21
+ expect(en.telemetry.updateCount).toBe(1);
22
+ expect(en.telemetry.lastUpdatedAt).toBe(1_700_000_000_000);
23
+ expect(out.state.dirty.has('a')).toBe(false);
24
+ expect(out.emitted).toEqual([{ type: 'query:records', hash: 'a', records: [{ id: 'thing:1' }] }]);
25
+ const again = await runPure(materialize('a'), { state: out.state, handlers: { 'local.select': () => [{ id: 'thing:1' }] } });
26
+ expect(again.emitted).toEqual([]);
27
+ expect(again.state.queries.get('a')!.telemetry.updateCount).toBe(1);
28
+ });
29
+ it('names its read after the query, and confirms rows painted at registration without telling subscribers twice', async () => {
30
+ // As `registerLocal` leaves an entry it could paint: rows in place, nothing notified.
31
+ const painted = buildEntry({ def: { hash: 'a', viewKey: 'view-a', plan }, records: [{ id: 'thing:1' }] });
32
+ expect(painted.lifecycle.notified).toBe(false);
33
+ const s = R.markDirty(['a'])(buildState([painted], vouch('thing:1')));
34
+ const same = await runPure(materialize('a'), { state: s, handlers: { 'local.select': () => [{ id: 'thing:1' }] } });
35
+ // A cold scan here (no membership yet), kept apart from the membership render's copy.
36
+ expect((same.log.find((e) => e.kind === 'local.select') as any).paintKey).toBe(`${JSON.stringify({ surql: painted.def.surql, params: painted.def.params })}\ncold`);
37
+ expect(same.emitted).toEqual([]);
38
+ expect(same.state.queries.get('a')!.lifecycle.notified).toBe(true);
39
+ // And when the store says otherwise, the read wins.
40
+ const other = await runPure(materialize('a'), { state: s, handlers: { 'local.select': () => [] } });
41
+ expect(other.state.queries.get('a')!.records).toEqual([]);
42
+ expect(other.emitted).toEqual([{ type: 'query:records', hash: 'a', records: [] }]);
43
+ });
44
+
45
+ it('cold: a body no view vouches for (an orphan) does not paint; vouched, optimistic, _00_ and id-less rows do', async () => {
46
+ const s = buildState(
47
+ [buildEntry({ def: { hash: 'a', plan } })],
48
+ vouch('thing:1', 'thing:4'),
49
+ R.outboxReplace([buildOutboxItem({ id: 'c', type: 'create', recordId: 'thing:3' })])
50
+ );
51
+ const scanned = [
52
+ { id: 'thing:1' },
53
+ { id: 'thing:2' },
54
+ { id: 'thing:3' },
55
+ { id: '_00_user_feature:f' },
56
+ { name: 'no id' },
57
+ { id: new RecordId('thing', '4') },
58
+ { id: new RecordId('thing', '5') },
59
+ ];
60
+ const out = await runPure(materialize('a'), { state: s, handlers: { 'local.select': () => scanned } });
61
+ expect(out.state.queries.get('a')!.records).toEqual([
62
+ { id: 'thing:1' },
63
+ { id: 'thing:3' },
64
+ { id: '_00_user_feature:f' },
65
+ { name: 'no id' },
66
+ { id: new RecordId('thing', '4') },
67
+ ]);
68
+ // Once the server has answered, membership decides and the index is not consulted.
69
+ const live = buildState([buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'live' }, remoteArray: [['thing:2', 1]] })]);
70
+ const l = await runPure(materialize('a'), { state: live, handlers: { 'local.select': (e: any) => e.plan.ids.map((id: any) => ({ id: `${id.table}:${id.id}` })) } });
71
+ expect(l.state.queries.get('a')!.records).toEqual([{ id: 'thing:2' }]);
72
+ });
73
+ it("cold: a peer's unconfirmed delete hides the row the store still holds", async () => {
74
+ const s = buildState(
75
+ [buildEntry({ def: { hash: 'a', plan } })],
76
+ vouch('thing:1', 'thing:2'),
77
+ R.setPeerWrite('thing:2', { kind: 'delete', table: 'thing', expiresAt: 1 })
78
+ );
79
+ const out = await runPure(materialize('a'), {
80
+ state: s,
81
+ handlers: { 'local.select': () => [{ id: 'thing:1' }, { id: 'thing:2' }, { name: 'no id' }] },
82
+ });
83
+ expect(out.state.queries.get('a')!.records).toEqual([{ id: 'thing:1' }, { name: 'no id' }]);
84
+ });
85
+ it('cold window renders the SSP local window (orphans dropped); live renders membership with the overlay', async () => {
86
+ const win = buildState(
87
+ [buildEntry({ def: { hash: 'w', plan: { ...plan, offset: 5 }, surql: 'SELECT * FROM thing LIMIT 5 START 5' }, localArray: [['thing:7', 1], ['thing:8', 1]] })],
88
+ vouch('thing:7')
89
+ );
90
+ const w = await runPure(materialize('w'), { state: win, handlers: { 'local.select': (e: any) => e.plan.ids.map((id: any) => ({ id: `${id.table}:${id.id}` })) } });
91
+ expect(w.state.queries.get('w')!.records).toEqual([{ id: 'thing:7' }]);
92
+ const live = buildState(
93
+ [buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'live' }, remoteArray: [['thing:2', 1], ['thing:1', 1]], localArray: [['thing:9', 1]] })],
94
+ R.outboxReplace([buildOutboxItem({ id: 'c', type: 'create', recordId: 'thing:9' }), buildOutboxItem({ id: 'd', type: 'delete', recordId: 'thing:2' })])
95
+ );
96
+ const l = await runPure(materialize('a'), { state: live, handlers: { 'local.select': (e: any) => e.plan.ids.map((id: any) => ({ id: `${id.table}:${id.id}` })) } });
97
+ expect(l.state.queries.get('a')!.records).toEqual([{ id: 'thing:1' }, { id: 'thing:9' }]);
98
+ const ordered = buildState([buildEntry({ def: { hash: 'o', plan: { ...plan, orderBy: [['a', 'asc']] } }, lifecycle: { phase: 'live' }, remoteArray: [['thing:2', 1], ['thing:1', 1]] })]);
99
+ const o = await runPure(materialize('o'), { state: ordered, handlers: { 'local.select': (e: any) => e.plan.ids.map((id: any) => ({ id: `${id.table}:${id.id}` })) } });
100
+ expect(o.state.queries.get('o')!.records).toEqual([{ id: 'thing:2' }, { id: 'thing:1' }]);
101
+ });
102
+ it('a failing read counts an error and clears dirt; an entry removed mid-read is left alone', async () => {
103
+ const s = R.markDirty(['a'])(buildState([buildEntry({ def: { hash: 'a', plan } })]));
104
+ const fail = await runPure(materialize('a'), {
105
+ state: s,
106
+ handlers: {
107
+ 'local.select': () => {
108
+ throw new Error('locked');
109
+ },
110
+ },
111
+ });
112
+ expect(fail.state.queries.get('a')!.telemetry.errorCount).toBe(1);
113
+ expect(fail.state.dirty.has('a')).toBe(false);
114
+ expect(fail.emitted).toEqual([expect.objectContaining({ level: 'warn' })]);
115
+ const gone = await runPure(materialize('a'), {
116
+ state: s,
117
+ handlers: {
118
+ 'local.select': (_e, ctx) => {
119
+ ctx.state = R.removeQuery('a')(ctx.state);
120
+ return [];
121
+ },
122
+ },
123
+ });
124
+ expect(gone.emitted).toEqual([]);
125
+ });
126
+ });
127
+
128
+ describe('materialize answers the query', () => {
129
+ const plan = { table: 'thing' } as any;
130
+ const byIds = { 'local.select': (e: any) => (e.plan.ids ?? []).map((id: any) => ({ id: `${id.table}:${id.id}` })) };
131
+ const authority = (out: { emitted: Array<{ type: string }> }) => out.emitted.filter((e) => e.type === 'query:authority');
132
+
133
+ it('a cached re-seed: rows first, then authority; the next render flips nothing', async () => {
134
+ // The bucket-switch window: a durable view was found, `records` is not
135
+ // painted yet. Authority comes from this render, after the rows.
136
+ const s = R.markDirty(['a'])(
137
+ buildState([buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'cached' }, remoteArray: [['thing:1', 1]] })])
138
+ );
139
+ const out = await runPure(materialize('a'), { state: s, handlers: byIds });
140
+ expect(out.state.queries.get('a')!.lifecycle).toMatchObject({ phase: 'cached', notified: true, answered: true });
141
+ expect(out.emitted).toEqual([
142
+ { type: 'query:records', hash: 'a', records: [{ id: 'thing:1' }] },
143
+ { type: 'query:authority', hash: 'a', known: true },
144
+ ]);
145
+ const again = await runPure(materialize('a'), { state: R.markDirty(['a'])(out.state), handlers: byIds });
146
+ expect(again.emitted).toEqual([]);
147
+ });
148
+
149
+ it('a known empty set answers without a rows emission', async () => {
150
+ const s = buildState([buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'live' }, remoteArray: [] })]);
151
+ const out = await runPure(materialize('a'), { state: s, handlers: byIds });
152
+ expect(out.emitted).toEqual([{ type: 'query:authority', hash: 'a', known: true }]);
153
+ });
154
+
155
+ it('a cold render never answers', async () => {
156
+ const s = buildState([buildEntry({ def: { hash: 'a', plan } })], R.reloadViews(new Map([['v', ['thing:1']]])));
157
+ const out = await runPure(materialize('a'), { state: s, handlers: { 'local.select': () => [{ id: 'thing:1' }] } });
158
+ expect(out.state.queries.get('a')!.lifecycle).toMatchObject({ notified: true, answered: false });
159
+ expect(authority(out)).toEqual([]);
160
+ });
161
+
162
+ it('a server set whose bodies are still downloading is not an answer yet', async () => {
163
+ const s = buildState(
164
+ [buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'live' }, remoteArray: [['thing:1', 1], ['thing:2', 1]] })],
165
+ R.setVersions([['thing:1', 1]])
166
+ );
167
+ const out = await runPure(materialize('a'), { state: s, handlers: byIds });
168
+ expect(out.state.queries.get('a')!.lifecycle.answered).toBe(false);
169
+ expect(authority(out)).toEqual([]);
170
+ const landed = await runPure(materialize('a'), { state: R.setVersions([['thing:2', 1]])(out.state), handlers: byIds });
171
+ expect(landed.state.queries.get('a')!.lifecycle.answered).toBe(true);
172
+ expect(authority(landed)).toEqual([{ type: 'query:authority', hash: 'a', known: true }]);
173
+ });
174
+
175
+ it('a membership replaced while the read was out does not answer: the next render does', async () => {
176
+ const s = buildState([buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'cached' }, remoteArray: [['thing:1', 1]] })]);
177
+ const out = await runPure(materialize('a'), {
178
+ state: s,
179
+ handlers: {
180
+ 'local.select': (e: any, ctx) => {
181
+ ctx.state = R.rebindQuery('a', { id: new RecordId('_00_query', 'b'), lifecycle: { phase: 'cached', remote: 'unregistered', fetchDepth: 0, backgroundDepth: 0, notified: false, answered: false }, remoteArray: [['thing:2', 1]], localArray: [] })(ctx.state);
182
+ return byIds['local.select'](e);
183
+ },
184
+ },
185
+ });
186
+ expect(out.state.queries.get('a')!.lifecycle.answered).toBe(false);
187
+ expect(authority(out)).toEqual([]);
188
+ });
189
+
190
+ it('after a rebind, a new store that renders nothing clears what the old principal painted', async () => {
191
+ const s = buildState([buildEntry({ def: { hash: 'a', plan }, lifecycle: { phase: 'live', answered: true }, remoteArray: [['thing:1', 1]], records: [{ id: 'thing:1' }] })]);
192
+ const rebound = R.rebindQuery('a', { id: new RecordId('_00_query', 'b'), lifecycle: { phase: 'cached', remote: 'unregistered', fetchDepth: 0, backgroundDepth: 0, notified: false, answered: false }, remoteArray: [], localArray: [] })(s);
193
+ const out = await runPure(materialize('a'), { state: rebound, handlers: byIds });
194
+ expect(out.emitted).toEqual([
195
+ { type: 'query:records', hash: 'a', records: [] },
196
+ { type: 'query:authority', hash: 'a', known: true },
197
+ ]);
198
+ });
199
+ });
200
+
201
+ describe('streamUpdate', () => {
202
+ it('takes the local id-set (dirtying the query) and records ingest timings; unknown hashes are ignored', async () => {
203
+ const s = buildState([buildEntry({ def: { hash: 'a' } })]);
204
+ const out = await runPure(streamUpdate({ queryHash: 'a', localArray: [['thing:1', 1]], op: 'CREATE', materializationTimeMs: 4, storeApplyMs: 1, circuitStepMs: 2 }), { state: s });
205
+ const en = out.state.queries.get('a')!;
206
+ expect(en.localArray).toEqual([['thing:1', 1]]);
207
+ expect(out.state.dirty.has('a')).toBe(true);
208
+ expect(en.telemetry.lastIngestLatencyMs).toBe(4);
209
+ expect(en.telemetry.materializationSamples).toEqual([4]);
210
+ expect(en.telemetry.phaseLast).toEqual({ sspStoreApply: 1, sspCircuitStep: 2 });
211
+ const bare = await runPure(streamUpdate({ queryHash: 'a', localArray: [] }), { state: s });
212
+ expect(bare.state.queries.get('a')!.telemetry.lastIngestLatencyMs).toBeNull();
213
+ const unknown = await runPure(streamUpdate({ queryHash: 'zz', localArray: [] }), { state: s });
214
+ expect(unknown.log.filter((e) => e.kind === 'state.update')).toHaveLength(0);
215
+ });
216
+ });
@@ -0,0 +1,83 @@
1
+ import type { QueryHash } from '../types';
2
+ import type { StreamUpdate } from '../services/stream-processor/index';
3
+ import type { Saga } from '../kernel/saga';
4
+ import { fx } from '../kernel/effects';
5
+ import type { QueryEntry } from '../state/client-state';
6
+ import * as R from '../state/reducers';
7
+ import { needed, overlay, vouched } from '../state/selectors';
8
+ import { isAnswered } from '../state/lifecycle';
9
+ import type { Overlay } from '../state/selectors';
10
+ import { materializeEffect, paintKeyOf, renderRead, rowsEqual, rowsFromResult } from './materialize';
11
+
12
+ const NONE: ReadonlySet<string> = new Set();
13
+
14
+ /**
15
+ * Render one query from state: membership (or a cold scan), the outbox
16
+ * overlay, one local read, then notify subscribers if the rows changed. The
17
+ * only writer of `records`. Runs on the `mat:<hash>` dedupe lane whenever the
18
+ * query is dirty. Before the server has answered (`cold`) only bodies some
19
+ * durable view vouches for paint (see `paintsCold`).
20
+ *
21
+ * Also the only place a query becomes answered (see `QueryLifecycle`): the
22
+ * authority flip is emitted here, after the rows it vouches for.
23
+ */
24
+ export function* materialize(hash: QueryHash): Saga<void> {
25
+ const [entry, ov, known, complete] = (yield fx.state.read((s) => {
26
+ const e = s.queries.get(hash);
27
+ return [e, overlay(s), e?.lifecycle.phase === 'cold' ? vouched(s) : NONE, needed(s, hash).length === 0];
28
+ })) as [QueryEntry | undefined, Overlay, ReadonlySet<string>, boolean];
29
+ if (!entry) return;
30
+ const t0 = (yield fx.now()) as number;
31
+ const read = renderRead(entry, ov, known);
32
+ // Named after the query, as a reload will name it again: the store may keep
33
+ // this read's answer for the next page load to paint from (`registerLocal`,
34
+ // and before the client is open `Sp00kyClient.peekQuery`).
35
+ const effect = materializeEffect(entry.def, read.ids, paintKeyOf(entry.def, read.ids));
36
+ let rows: Record<string, unknown>[];
37
+ try {
38
+ rows = read.shows(rowsFromResult(effect, yield effect));
39
+ } catch (error) {
40
+ yield fx.state.update(R.compose(R.recordError(hash), R.clearDirty(hash)));
41
+ yield fx.emit({ type: 'log', level: 'warn', message: 'materialize failed', data: { hash, error } });
42
+ return;
43
+ }
44
+ const current = (yield fx.state.read((s) => s.queries.get(hash))) as QueryEntry | undefined;
45
+ if (!current) return;
46
+ const t1 = (yield fx.now()) as number;
47
+ const changed = !rowsEqual(rows, current.records);
48
+ // These rows answer the query when they drew a known membership with no
49
+ // body of a server set still to download, and that membership is still
50
+ // the one in state. A server set applied, or a bucket switch, while the
51
+ // read was out dirtied the query again: the next render answers instead.
52
+ const answered =
53
+ complete && entry.lifecycle.phase !== 'cold' && current.lifecycle.phase !== 'cold' && current.remoteArray === entry.remoteArray;
54
+ yield fx.state.update(
55
+ R.compose(R.setRecords(hash, rows, changed, t1 - t0, answered), changed ? R.stampUpdated(hash, t1) : (s) => s)
56
+ );
57
+ if (changed) yield fx.emit({ type: 'query:records', hash, records: rows });
58
+ // After the rows: a subscriber told "known" must already hold them.
59
+ if (answered && !isAnswered(current.lifecycle)) yield fx.emit({ type: 'query:authority', hash, known: true });
60
+ }
61
+
62
+ /**
63
+ * A view update from the in-browser SSP: the query's local id-set moved.
64
+ * State takes the array (which dirties the query); the ingest timings feed
65
+ * telemetry. Synthetic updates no longer exist: re-materialization is dirt.
66
+ */
67
+ export function* streamUpdate(update: StreamUpdate): Saga<void> {
68
+ const hash = update.queryHash;
69
+ const exists = (yield fx.state.read((s) => s.queries.has(hash))) as boolean;
70
+ if (!exists) return;
71
+ const phases: Array<[string, number | undefined]> = [
72
+ ['sspStoreApply', update.storeApplyMs],
73
+ ['sspCircuitStep', update.circuitStepMs],
74
+ ['sspTransform', update.transformMs],
75
+ ];
76
+ yield fx.state.update(
77
+ R.compose(
78
+ R.setLocalArray(hash, update.localArray),
79
+ typeof update.materializationTimeMs === 'number' ? R.recordIngest(hash, update.materializationTimeMs) : (s) => s,
80
+ ...phases.filter((p): p is [string, number] => typeof p[1] === 'number').map(([phase, ms]) => R.recordPhase(hash, phase, ms))
81
+ )
82
+ );
83
+ }
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import { isWindowed, materializeEffect, rowKey, rowsEqual, rowsFromResult } from './materialize';
4
+
5
+ describe('materializeEffect', () => {
6
+ const plan = { table: 'thing', where: [{ field: 'a', op: '=', value: 1 }] } as any;
7
+ it('plan + ids: id-set plan select without where/limit/offset', () => {
8
+ const e = materializeEffect({ surql: 'SELECT * FROM thing', params: { a: 1 }, plan: { ...plan, limit: 5, offset: 2 } }, ['thing:1']);
9
+ expect(e.kind).toBe('local.select');
10
+ if (e.kind !== 'local.select') throw new Error();
11
+ expect(e.plan.ids).toEqual([new RecordId('thing', '1')]);
12
+ expect(e.plan.where).toBeUndefined();
13
+ expect(e.plan.limit).toBeUndefined();
14
+ expect(e.params).toEqual({ a: 1 });
15
+ });
16
+ it('surql + ids: id-set rewrite bound to __win; unparseable surql falls back to the raw query', () => {
17
+ const e = materializeEffect({ surql: 'SELECT * FROM thing WHERE a = $a ORDER BY b LIMIT 3', params: { a: 1 } }, ['thing:1']);
18
+ expect(e).toMatchObject({ kind: 'local.query', sql: 'SELECT * FROM (SELECT * FROM $__win) ORDER BY b' });
19
+ if (e.kind !== 'local.query') throw new Error();
20
+ expect(e.vars).toEqual({ a: 1, __win: [new RecordId('thing', '1')] });
21
+ const raw = materializeEffect({ surql: 'RETURN 1', params: {} }, ['thing:1']);
22
+ expect(raw).toMatchObject({ kind: 'local.query', sql: 'RETURN 1' });
23
+ });
24
+ it('null ids: predicate scan via plan or raw surql', () => {
25
+ expect(materializeEffect({ surql: 's', params: {}, plan }, null)).toMatchObject({ kind: 'local.select', plan });
26
+ expect(materializeEffect({ surql: 'SELECT * FROM thing', params: { x: 1 } }, null)).toMatchObject({
27
+ kind: 'local.query',
28
+ sql: 'SELECT * FROM thing',
29
+ vars: { x: 1 },
30
+ });
31
+ });
32
+ it('rowsFromResult reads both effect shapes; rowsEqual compares structurally', () => {
33
+ const sel = materializeEffect({ surql: 's', params: {}, plan }, null);
34
+ const q = materializeEffect({ surql: 'SELECT * FROM thing', params: {} }, null);
35
+ expect(rowsFromResult(sel, [{ id: 1 }])).toEqual([{ id: 1 }]);
36
+ expect(rowsFromResult(sel, undefined)).toEqual([]);
37
+ expect(rowsFromResult(q, [[{ id: 1 }]])).toEqual([{ id: 1 }]);
38
+ expect(rowsFromResult(q, [null])).toEqual([]);
39
+ expect(rowsFromResult(q, 'x')).toEqual([]);
40
+ const rows = [{ id: 1 }];
41
+ expect(rowsEqual(rows, rows)).toBe(true);
42
+ expect(rowsEqual(rows, [{ id: 1 }])).toBe(true);
43
+ expect(rowsEqual(rows, [{ id: 2 }])).toBe(false);
44
+ expect(rowsEqual(rows, [])).toBe(false);
45
+ });
46
+ it('isWindowed', () => {
47
+ expect(isWindowed('SELECT * FROM t LIMIT 10 START 10')).toBe(true);
48
+ expect(isWindowed('SELECT * FROM t LIMIT 10')).toBe(false);
49
+ });
50
+ });
51
+
52
+ describe('rowKey', () => {
53
+ it('reads a string id (SQLite) or a RecordId (SurrealDB); null when the row carries none', () => {
54
+ expect(rowKey({ id: 'thing:1' })).toBe('thing:1');
55
+ expect(rowKey({ id: new RecordId('thing', '2') })).toBe('thing:2');
56
+ for (const row of [{ name: 'x' }, { id: null }, { id: { other: 1 } }, null, 5]) expect(rowKey(row)).toBeNull();
57
+ });
58
+ });
@@ -0,0 +1,133 @@
1
+ import type { QueryPlan } from '@spooky-sync/query-builder';
2
+ import type { RecordId } from 'surrealdb';
3
+ import type { Effect } from '../kernel/effects';
4
+ import { fx } from '../kernel/effects';
5
+ import { encodeRecordId, parseRecordIdString } from '../utils/index';
6
+ import type { QueryEntry } from '../state/client-state';
7
+ import type { Overlay } from '../state/selectors';
8
+ import { viewKeyInput } from './hash';
9
+ import { buildRenderIds, paintsCold, resolveMembership } from './render-set';
10
+ import { buildIdSetPlan, buildIdSetSurql, buildWindowMaterialization } from './window-query';
11
+
12
+ export interface MaterializeSource {
13
+ surql: string;
14
+ params: Record<string, unknown>;
15
+ plan?: QueryPlan;
16
+ }
17
+
18
+ export const isWindowed = (surql: string): boolean => buildWindowMaterialization(surql) !== null;
19
+
20
+ /**
21
+ * The one read that materializes a query. `ids` is the render set (membership
22
+ * with the overlay applied); `null` means "no membership yet, scan the local
23
+ * store with the query's own predicate".
24
+ */
25
+ export function materializeEffect(src: MaterializeSource, ids: string[] | null, paintKey?: string): Effect {
26
+ if (ids !== null) {
27
+ const parsed = ids.map((id) => parseRecordIdString(id));
28
+ if (src.plan) return fx.local.select(buildIdSetPlan(src.plan, parsed), src.params, paintKey);
29
+ const idSet = buildIdSetSurql(src.surql);
30
+ if (idSet) return fx.local.query(idSet.query, { ...src.params, __win: parsed });
31
+ return fx.local.query(src.surql, src.params);
32
+ }
33
+ if (src.plan) return fx.local.select(src.plan, src.params, paintKey);
34
+ return fx.local.query(src.surql, src.params);
35
+ }
36
+
37
+ /**
38
+ * The peek that goes with {@link materializeEffect}: what the read named
39
+ * `paintKey` answered in an earlier page load, for a store that kept it.
40
+ * It takes the plan, since only a query that has one can be painted: no
41
+ * paint cache covers raw SurrealQL.
42
+ */
43
+ export function paintEffect(plan: QueryPlan, params: Record<string, unknown>, ids: string[] | null, paintKey: string): Effect {
44
+ const read = ids === null ? plan : buildIdSetPlan(plan, ids.map((id) => parseRecordIdString(id)));
45
+ return fx.local.peekSelect(read, params, paintKey);
46
+ }
47
+
48
+ /**
49
+ * The name a query's render read goes by in the store's paint cache. Built
50
+ * from what a page knows the moment it has the query (its text and its
51
+ * parameters), not from a digest that takes a turn of the event loop: a
52
+ * component asks for these rows while it renders, before the client is open.
53
+ *
54
+ * A cold scan is kept under a name of its own. Its rows are filtered before
55
+ * they show (`RenderRead.shows`), by what the client only knows once it is
56
+ * open; the rows of a membership render show as read. So a caller without
57
+ * the client's state (`Sp00kyClient.peekQuery`) asks for the membership name
58
+ * alone, and never paints a row a cold render would have hidden.
59
+ */
60
+ export const paintKeyOf = (src: Pick<MaterializeSource, 'surql' | 'params'>, ids: string[] | null): string =>
61
+ viewKeyInput(src) + (ids === null ? '\ncold' : '');
62
+
63
+ /** What one render of a query reads, and which of the rows it gets back may show. */
64
+ export interface RenderRead {
65
+ /** The render set, or `null` for a scan with the query's own predicate. */
66
+ ids: string[] | null;
67
+ shows(rows: Record<string, unknown>[]): Record<string, unknown>[];
68
+ }
69
+
70
+ /**
71
+ * Membership (or a cold scan) with the outbox overlay applied. `known` is the
72
+ * set of ids some durable view vouches for: before the server has answered
73
+ * (`cold`) only those bodies paint (see `paintsCold`).
74
+ */
75
+ export function renderRead(
76
+ entry: Pick<QueryEntry, 'def' | 'lifecycle' | 'remoteArray' | 'localArray'>,
77
+ ov: Overlay,
78
+ known: ReadonlySet<string>
79
+ ): RenderRead {
80
+ const isWindow = isWindowed(entry.def.surql);
81
+ const paints = (id: string | null) => id === null || paintsCold(id, known, ov);
82
+ const coldWindow = entry.lifecycle.phase === 'cold' && isWindow;
83
+ const membership = resolveMembership({
84
+ phase: entry.lifecycle.phase,
85
+ remoteArray: entry.remoteArray,
86
+ localArray: coldWindow ? entry.localArray.filter(([id]) => paints(id)) : entry.localArray,
87
+ isWindow,
88
+ });
89
+ const ids = membership
90
+ ? buildRenderIds(membership, entry.localArray, ov, {
91
+ hasExplicitOrder: (entry.def.plan?.orderBy?.length ?? 0) > 0,
92
+ isWindow,
93
+ })
94
+ : null;
95
+ return {
96
+ ids,
97
+ // A peer's delete leaves the row in the store until it is confirmed, so
98
+ // the predicate scan must drop it here (an own delete removed it already).
99
+ shows: (rows) =>
100
+ ids !== null
101
+ ? rows
102
+ : rows.filter((row) => {
103
+ const key = rowKey(row);
104
+ return paints(key) && !(key !== null && ov.deletes.has(key));
105
+ }),
106
+ };
107
+ }
108
+
109
+ /** Rows out of either read effect's result. */
110
+ export function rowsFromResult(effect: Effect, result: unknown): Record<string, unknown>[] {
111
+ if (effect.kind === 'local.select') return (result as Record<string, unknown>[] | undefined) ?? [];
112
+ const first = Array.isArray(result) ? result[0] : undefined;
113
+ return Array.isArray(first) ? (first as Record<string, unknown>[]) : [];
114
+ }
115
+
116
+ /**
117
+ * A row's encoded record id: a string on the SQLite engine, a `RecordId` on
118
+ * the SurrealDB one. `null` for a row that carries none (a projection
119
+ * without `id`, a `SELECT VALUE`).
120
+ */
121
+ export function rowKey(row: unknown): string | null {
122
+ const id = row !== null && typeof row === 'object' ? (row as { id?: unknown }).id : undefined;
123
+ if (typeof id === 'string') return id;
124
+ if (id !== null && typeof id === 'object' && 'table' in id && 'id' in id) return encodeRecordId(id as RecordId<string>);
125
+ return null;
126
+ }
127
+
128
+ /** Cheap structural equality for the "did the rows change" check. */
129
+ export function rowsEqual(a: ReadonlyArray<unknown>, b: ReadonlyArray<unknown>): boolean {
130
+ if (a === b) return true;
131
+ if (a.length !== b.length) return false;
132
+ return JSON.stringify(a) === JSON.stringify(b);
133
+ }