@spooky-sync/core 0.0.1-canary.240 → 0.0.1-canary.241

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 (289) hide show
  1. package/AGENTS.md +34 -15
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +1136 -1846
  4. package/dist/index.js +10168 -11267
  5. package/dist/types.d.ts +22 -79
  6. package/package.json +8 -4
  7. package/skills/sp00ky-core/SKILL.md +18 -0
  8. package/src/boot/auth-flip.saga.test.ts +82 -0
  9. package/src/boot/auth-flip.saga.ts +62 -0
  10. package/src/boot/boot.saga.test.ts +151 -0
  11. package/src/boot/boot.saga.ts +128 -0
  12. package/src/boot/bucket-switch.saga.test.ts +158 -0
  13. package/src/boot/bucket-switch.saga.ts +115 -0
  14. package/src/boot/preload.saga.test.ts +51 -0
  15. package/src/boot/preload.saga.ts +31 -0
  16. package/src/client/bucket-handle.test.ts +117 -0
  17. package/src/client/bucket-handle.ts +227 -0
  18. package/src/client/router.test.ts +56 -0
  19. package/src/client/router.ts +94 -0
  20. package/src/client/runtime.test.ts +192 -0
  21. package/src/client/runtime.ts +296 -0
  22. package/src/client/services.ts +349 -0
  23. package/src/client/sp00ky-client.test.ts +241 -0
  24. package/src/client/sp00ky-client.ts +482 -0
  25. package/src/index.ts +1 -0
  26. package/src/kernel/constants.test.ts +19 -0
  27. package/src/kernel/constants.ts +54 -0
  28. package/src/kernel/effects.test.ts +40 -0
  29. package/src/kernel/effects.ts +159 -0
  30. package/src/kernel/events.ts +55 -0
  31. package/src/kernel/interpreter.test.ts +116 -0
  32. package/src/kernel/interpreter.ts +143 -0
  33. package/src/kernel/saga.test.ts +89 -0
  34. package/src/kernel/saga.ts +73 -0
  35. package/src/modules/app-release/index.ts +13 -5
  36. package/src/modules/devtools/index.ts +10 -3
  37. package/src/modules/devtools/state-shape.test.ts +4 -1
  38. package/src/modules/feature-flag/index.ts +13 -5
  39. package/src/mutation/jobs.test.ts +25 -0
  40. package/src/mutation/jobs.ts +41 -0
  41. package/src/{modules/data → mutation}/mutation-id.test.ts +12 -0
  42. package/src/mutation/push.saga.test.ts +285 -0
  43. package/src/mutation/push.saga.ts +215 -0
  44. package/src/mutation/rows.test.ts +201 -0
  45. package/src/mutation/rows.ts +377 -0
  46. package/src/mutation/tray.saga.test.ts +63 -0
  47. package/src/mutation/tray.saga.ts +48 -0
  48. package/src/mutation/write.saga.test.ts +163 -0
  49. package/src/mutation/write.saga.ts +166 -0
  50. package/src/query/env.test.ts +23 -0
  51. package/src/query/env.ts +56 -0
  52. package/src/query/fetch.saga.test.ts +156 -0
  53. package/src/query/fetch.saga.ts +109 -0
  54. package/src/query/hash.test.ts +14 -0
  55. package/src/query/hash.ts +18 -0
  56. package/src/{modules/data → query}/id-set-plan.test.ts +12 -2
  57. package/src/query/lifecycle.saga.test.ts +122 -0
  58. package/src/query/lifecycle.saga.ts +101 -0
  59. package/src/query/materialize.saga.test.ts +82 -0
  60. package/src/query/materialize.saga.ts +75 -0
  61. package/src/query/materialize.test.ts +50 -0
  62. package/src/query/materialize.ts +44 -0
  63. package/src/query/membership.saga.test.ts +246 -0
  64. package/src/query/membership.saga.ts +208 -0
  65. package/src/query/membership.test.ts +118 -0
  66. package/src/query/membership.ts +158 -0
  67. package/src/query/register.saga.test.ts +251 -0
  68. package/src/query/register.saga.ts +190 -0
  69. package/src/query/render-set.test.ts +36 -0
  70. package/src/query/render-set.ts +60 -0
  71. package/src/query/sql.test.ts +62 -0
  72. package/src/query/sql.ts +79 -0
  73. package/src/{modules/data → query}/window-query.test.ts +18 -0
  74. package/src/{modules/data → query}/window-query.ts +2 -1
  75. package/src/services/database/connection-supervisor.test.ts +29 -0
  76. package/src/services/database/connection-supervisor.ts +7 -0
  77. package/src/services/database/database.responses.test.ts +43 -0
  78. package/src/services/database/database.ts +25 -10
  79. package/src/services/database/local-migrator.ts +2 -2
  80. package/src/services/database/plan-render.test.ts +1 -1
  81. package/src/services/database/sqlite-cache-engine.test.ts +4 -3
  82. package/src/services/database/sqlite-cache-engine.ts +2 -11
  83. package/src/services/database/sqlite-devtools-queries.integration.test.ts +1 -1
  84. package/src/services/tabs/protocol.ts +7 -3
  85. package/src/sp00ky.ts +5 -1854
  86. package/src/state/client-state.ts +184 -0
  87. package/src/state/lifecycle.test.ts +118 -0
  88. package/src/state/lifecycle.ts +86 -0
  89. package/src/state/reducers.test.ts +280 -0
  90. package/src/state/reducers.ts +476 -0
  91. package/src/state/selectors.test.ts +149 -0
  92. package/src/state/selectors.ts +184 -0
  93. package/src/sync/connection.saga.test.ts +86 -0
  94. package/src/sync/connection.saga.ts +85 -0
  95. package/src/sync/live.saga.test.ts +69 -0
  96. package/src/sync/live.saga.ts +49 -0
  97. package/src/sync/policy.health.test.ts +56 -0
  98. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +31 -3
  99. package/src/{modules/sync/utils.ts → sync/policy.ts} +67 -5
  100. package/src/sync/poll.saga.test.ts +51 -0
  101. package/src/sync/poll.saga.ts +36 -0
  102. package/src/sync/tabs.saga.test.ts +74 -0
  103. package/src/sync/tabs.saga.ts +92 -0
  104. package/src/testing/adapters.ts +133 -0
  105. package/src/testing/build.ts +61 -0
  106. package/src/testing/fake-services.ts +34 -0
  107. package/src/testing/run-pure.test.ts +92 -0
  108. package/src/testing/run-pure.ts +128 -0
  109. package/src/testing/services.ts +17 -0
  110. package/src/types.ts +8 -7
  111. package/src/utils/utils.test.ts +2 -1
  112. package/vitest.config.ts +48 -0
  113. package/coverage/lcov-report/base.css +0 -224
  114. package/coverage/lcov-report/block-navigation.js +0 -87
  115. package/coverage/lcov-report/favicon.png +0 -0
  116. package/coverage/lcov-report/index.html +0 -476
  117. package/coverage/lcov-report/prettify.css +0 -1
  118. package/coverage/lcov-report/prettify.js +0 -2
  119. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  120. package/coverage/lcov-report/sorter.js +0 -210
  121. package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +0 -271
  122. package/coverage/lcov-report/src/boot/boot.saga.ts.html +0 -469
  123. package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +0 -430
  124. package/coverage/lcov-report/src/boot/index.html +0 -161
  125. package/coverage/lcov-report/src/boot/preload.saga.ts.html +0 -178
  126. package/coverage/lcov-report/src/client/bucket-handle.ts.html +0 -766
  127. package/coverage/lcov-report/src/client/index.html +0 -161
  128. package/coverage/lcov-report/src/client/router.ts.html +0 -367
  129. package/coverage/lcov-report/src/client/runtime.ts.html +0 -940
  130. package/coverage/lcov-report/src/client/sp00ky-client.ts.html +0 -1531
  131. package/coverage/lcov-report/src/events/index.html +0 -116
  132. package/coverage/lcov-report/src/events/index.ts.html +0 -877
  133. package/coverage/lcov-report/src/index.html +0 -146
  134. package/coverage/lcov-report/src/index.ts.html +0 -202
  135. package/coverage/lcov-report/src/kernel/constants.ts.html +0 -247
  136. package/coverage/lcov-report/src/kernel/effects.ts.html +0 -562
  137. package/coverage/lcov-report/src/kernel/events.ts.html +0 -250
  138. package/coverage/lcov-report/src/kernel/index.html +0 -176
  139. package/coverage/lcov-report/src/kernel/interpreter.ts.html +0 -514
  140. package/coverage/lcov-report/src/kernel/saga.ts.html +0 -304
  141. package/coverage/lcov-report/src/modules/app-release/index.html +0 -116
  142. package/coverage/lcov-report/src/modules/app-release/index.ts.html +0 -712
  143. package/coverage/lcov-report/src/modules/auth/events/index.html +0 -116
  144. package/coverage/lcov-report/src/modules/auth/events/index.ts.html +0 -142
  145. package/coverage/lcov-report/src/modules/auth/index.html +0 -116
  146. package/coverage/lcov-report/src/modules/auth/index.ts.html +0 -1225
  147. package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +0 -967
  148. package/coverage/lcov-report/src/modules/crdt/index.html +0 -146
  149. package/coverage/lcov-report/src/modules/crdt/index.ts.html +0 -1474
  150. package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +0 -160
  151. package/coverage/lcov-report/src/modules/devtools/flags.ts.html +0 -1132
  152. package/coverage/lcov-report/src/modules/devtools/index.html +0 -161
  153. package/coverage/lcov-report/src/modules/devtools/index.ts.html +0 -2413
  154. package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +0 -589
  155. package/coverage/lcov-report/src/modules/devtools/versions.ts.html +0 -415
  156. package/coverage/lcov-report/src/modules/feature-flag/index.html +0 -116
  157. package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +0 -1033
  158. package/coverage/lcov-report/src/modules/index.html +0 -116
  159. package/coverage/lcov-report/src/modules/ref-tables.ts.html +0 -349
  160. package/coverage/lcov-report/src/mutation/index.html +0 -191
  161. package/coverage/lcov-report/src/mutation/jobs.ts.html +0 -208
  162. package/coverage/lcov-report/src/mutation/mutation-id.ts.html +0 -190
  163. package/coverage/lcov-report/src/mutation/push.saga.ts.html +0 -730
  164. package/coverage/lcov-report/src/mutation/rows.ts.html +0 -1216
  165. package/coverage/lcov-report/src/mutation/tray.saga.ts.html +0 -229
  166. package/coverage/lcov-report/src/mutation/write.saga.ts.html +0 -583
  167. package/coverage/lcov-report/src/otel/index.html +0 -116
  168. package/coverage/lcov-report/src/otel/index.ts.html +0 -466
  169. package/coverage/lcov-report/src/query/env.ts.html +0 -253
  170. package/coverage/lcov-report/src/query/fetch.saga.ts.html +0 -412
  171. package/coverage/lcov-report/src/query/hash.ts.html +0 -139
  172. package/coverage/lcov-report/src/query/index.html +0 -281
  173. package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +0 -388
  174. package/coverage/lcov-report/src/query/materialize.saga.ts.html +0 -310
  175. package/coverage/lcov-report/src/query/materialize.ts.html +0 -217
  176. package/coverage/lcov-report/src/query/membership.saga.ts.html +0 -709
  177. package/coverage/lcov-report/src/query/membership.ts.html +0 -559
  178. package/coverage/lcov-report/src/query/register.saga.ts.html +0 -655
  179. package/coverage/lcov-report/src/query/render-set.ts.html +0 -265
  180. package/coverage/lcov-report/src/query/sql.ts.html +0 -322
  181. package/coverage/lcov-report/src/query/window-query.ts.html +0 -670
  182. package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +0 -1894
  183. package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +0 -766
  184. package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +0 -1162
  185. package/coverage/lcov-report/src/services/blobs/index.html +0 -161
  186. package/coverage/lcov-report/src/services/blobs/index.ts.html +0 -295
  187. package/coverage/lcov-report/src/services/database/cache-engine.ts.html +0 -664
  188. package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +0 -1330
  189. package/coverage/lcov-report/src/services/database/database.ts.html +0 -658
  190. package/coverage/lcov-report/src/services/database/engine-factory.ts.html +0 -184
  191. package/coverage/lcov-report/src/services/database/errors.ts.html +0 -187
  192. package/coverage/lcov-report/src/services/database/events/index.html +0 -116
  193. package/coverage/lcov-report/src/services/database/events/index.ts.html +0 -184
  194. package/coverage/lcov-report/src/services/database/index.html +0 -386
  195. package/coverage/lcov-report/src/services/database/index.ts.html +0 -121
  196. package/coverage/lcov-report/src/services/database/local-migrator.ts.html +0 -703
  197. package/coverage/lcov-report/src/services/database/local.ts.html +0 -1633
  198. package/coverage/lcov-report/src/services/database/plan-render.ts.html +0 -409
  199. package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +0 -682
  200. package/coverage/lcov-report/src/services/database/remote.ts.html +0 -1036
  201. package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +0 -4132
  202. package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +0 -220
  203. package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +0 -577
  204. package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +0 -499
  205. package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +0 -478
  206. package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +0 -757
  207. package/coverage/lcov-report/src/services/database/surql-translate.ts.html +0 -1333
  208. package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +0 -568
  209. package/coverage/lcov-report/src/services/logger/index.html +0 -116
  210. package/coverage/lcov-report/src/services/logger/index.ts.html +0 -154
  211. package/coverage/lcov-report/src/services/persistence/index.html +0 -146
  212. package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +0 -163
  213. package/coverage/lcov-report/src/services/persistence/resilient.ts.html +0 -208
  214. package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +0 -271
  215. package/coverage/lcov-report/src/services/stream-processor/index.html +0 -146
  216. package/coverage/lcov-report/src/services/stream-processor/index.ts.html +0 -3313
  217. package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +0 -244
  218. package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +0 -346
  219. package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +0 -934
  220. package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +0 -1984
  221. package/coverage/lcov-report/src/services/tabs/index.html +0 -191
  222. package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +0 -310
  223. package/coverage/lcov-report/src/services/tabs/protocol.ts.html +0 -871
  224. package/coverage/lcov-report/src/services/tabs/support.ts.html +0 -193
  225. package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +0 -2005
  226. package/coverage/lcov-report/src/sp00ky.ts.html +0 -100
  227. package/coverage/lcov-report/src/state/client-state.ts.html +0 -637
  228. package/coverage/lcov-report/src/state/index.html +0 -161
  229. package/coverage/lcov-report/src/state/lifecycle.ts.html +0 -343
  230. package/coverage/lcov-report/src/state/reducers.ts.html +0 -1471
  231. package/coverage/lcov-report/src/state/selectors.ts.html +0 -637
  232. package/coverage/lcov-report/src/sync/connection.saga.ts.html +0 -343
  233. package/coverage/lcov-report/src/sync/index.html +0 -176
  234. package/coverage/lcov-report/src/sync/live.saga.ts.html +0 -232
  235. package/coverage/lcov-report/src/sync/policy.ts.html +0 -1606
  236. package/coverage/lcov-report/src/sync/poll.saga.ts.html +0 -193
  237. package/coverage/lcov-report/src/sync/tabs.saga.ts.html +0 -361
  238. package/coverage/lcov-report/src/types.ts.html +0 -2419
  239. package/coverage/lcov-report/src/utils/blurhash.ts.html +0 -355
  240. package/coverage/lcov-report/src/utils/error-classification.ts.html +0 -244
  241. package/coverage/lcov-report/src/utils/index.html +0 -191
  242. package/coverage/lcov-report/src/utils/index.ts.html +0 -820
  243. package/coverage/lcov-report/src/utils/parser.ts.html +0 -313
  244. package/coverage/lcov-report/src/utils/semver.ts.html +0 -175
  245. package/coverage/lcov-report/src/utils/surql.ts.html +0 -667
  246. package/coverage/lcov.info +0 -19079
  247. package/src/modules/cache/cache.relay.test.ts +0 -95
  248. package/src/modules/cache/index.ts +0 -361
  249. package/src/modules/cache/types.ts +0 -19
  250. package/src/modules/data/data.activity.test.ts +0 -109
  251. package/src/modules/data/data.authority.test.ts +0 -122
  252. package/src/modules/data/data.heartbeat-wake.test.ts +0 -115
  253. package/src/modules/data/data.hydration.test.ts +0 -142
  254. package/src/modules/data/data.membership.test.ts +0 -623
  255. package/src/modules/data/data.notify-table.test.ts +0 -41
  256. package/src/modules/data/data.pending-ids.test.ts +0 -199
  257. package/src/modules/data/data.rebind.test.ts +0 -170
  258. package/src/modules/data/data.rematerialize.test.ts +0 -114
  259. package/src/modules/data/data.run.test.ts +0 -113
  260. package/src/modules/data/data.settled-writes.test.ts +0 -235
  261. package/src/modules/data/data.status.test.ts +0 -249
  262. package/src/modules/data/data.test.ts +0 -58
  263. package/src/modules/data/index.ts +0 -2745
  264. package/src/modules/sync/engine.ts +0 -250
  265. package/src/modules/sync/events/index.ts +0 -84
  266. package/src/modules/sync/index.ts +0 -3
  267. package/src/modules/sync/queue/index.ts +0 -2
  268. package/src/modules/sync/queue/queue-down.test.ts +0 -228
  269. package/src/modules/sync/queue/queue-down.ts +0 -184
  270. package/src/modules/sync/queue/queue-up.forwarded.test.ts +0 -164
  271. package/src/modules/sync/queue/queue-up.ts +0 -407
  272. package/src/modules/sync/scheduler.pause.test.ts +0 -109
  273. package/src/modules/sync/scheduler.retry.test.ts +0 -237
  274. package/src/modules/sync/scheduler.ts +0 -286
  275. package/src/modules/sync/sync.cleanup.test.ts +0 -116
  276. package/src/modules/sync/sync.health.test.ts +0 -167
  277. package/src/modules/sync/sync.heartbeat.test.ts +0 -80
  278. package/src/modules/sync/sync.list-ref-meta.test.ts +0 -193
  279. package/src/modules/sync/sync.live-removal.test.ts +0 -289
  280. package/src/modules/sync/sync.reconnect.test.ts +0 -145
  281. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +0 -93
  282. package/src/modules/sync/sync.settled-poll.test.ts +0 -58
  283. package/src/modules/sync/sync.subquery.test.ts +0 -82
  284. package/src/modules/sync/sync.tabs.test.ts +0 -249
  285. package/src/modules/sync/sync.ts +0 -2626
  286. package/src/sp00ky.auth-order.test.ts +0 -112
  287. package/src/sp00ky.init-query.test.ts +0 -183
  288. package/src/sp00ky.local-first.test.ts +0 -60
  289. /package/src/{modules/data → mutation}/mutation-id.ts +0 -0
@@ -0,0 +1,476 @@
1
+ import type { ConnectionState, QueryHash, RecordVersionArray, SyncHealth } from '../types';
2
+ import type {
3
+ ClientState,
4
+ OutboxItem,
5
+ PendingWrite,
6
+ QueryEntry,
7
+ QueryTelemetry,
8
+ Row,
9
+ ServerViewState,
10
+ TabRole,
11
+ } from './client-state';
12
+ import type { LifecycleEvent } from './lifecycle';
13
+ import { transition } from './lifecycle';
14
+ import { TELEMETRY_SAMPLE_WINDOW } from '../kernel/constants';
15
+
16
+ /**
17
+ * Pure state updates. Every reducer returns a new `ClientState`; sagas apply
18
+ * them through `state.update`. Reducers that change a query's render inputs
19
+ * add it to `dirty` themselves, which is what drives materialization.
20
+ */
21
+ export type Reducer = (s: ClientState) => ClientState;
22
+
23
+ const addAll = <T>(set: ReadonlySet<T>, items: Iterable<T>): ReadonlySet<T> => {
24
+ const next = new Set(set);
25
+ for (const item of items) next.add(item);
26
+ return next;
27
+ };
28
+
29
+ const withoutAll = <T>(set: ReadonlySet<T>, items: Iterable<T>): ReadonlySet<T> => {
30
+ const next = new Set(set);
31
+ for (const item of items) next.delete(item);
32
+ return next;
33
+ };
34
+
35
+ function withEntry(s: ClientState, hash: QueryHash, fn: (e: QueryEntry) => QueryEntry): ClientState {
36
+ const entry = s.queries.get(hash);
37
+ if (!entry) return s;
38
+ const next = fn(entry);
39
+ if (next === entry) return s;
40
+ const queries = new Map(s.queries);
41
+ queries.set(hash, next);
42
+ return { ...s, queries };
43
+ }
44
+
45
+ const hashesForTable = (s: ClientState, table: string): QueryHash[] => {
46
+ const out: QueryHash[] = [];
47
+ for (const [hash, entry] of s.queries) if (entry.def.tableName === table) out.push(hash);
48
+ return out;
49
+ };
50
+
51
+ // ---- queries ---------------------------------------------------------------
52
+
53
+ export const putQuery =
54
+ (entry: QueryEntry): Reducer =>
55
+ (s) => {
56
+ const queries = new Map(s.queries);
57
+ queries.set(entry.def.hash, entry);
58
+ return { ...s, queries, dirty: addAll(s.dirty, [entry.def.hash]) };
59
+ };
60
+
61
+ export const removeQuery =
62
+ (hash: QueryHash): Reducer =>
63
+ (s) => {
64
+ if (!s.queries.has(hash)) return s;
65
+ const queries = new Map(s.queries);
66
+ queries.delete(hash);
67
+ const membershipReread = new Map(s.membershipReread);
68
+ membershipReread.delete(hash);
69
+ return {
70
+ ...s,
71
+ queries,
72
+ membershipReread,
73
+ dirty: withoutAll(s.dirty, [hash]),
74
+ membershipDirty: withoutAll(s.membershipDirty, [hash]),
75
+ };
76
+ };
77
+
78
+ export const applyLifecycle =
79
+ (hash: QueryHash, ev: LifecycleEvent): Reducer =>
80
+ (s) =>
81
+ withEntry(s, hash, (e) => ({ ...e, lifecycle: transition(e.lifecycle, ev) }));
82
+
83
+ export const setServerState =
84
+ (hash: QueryHash, serverState: ServerViewState): Reducer =>
85
+ (s) =>
86
+ withEntry(s, hash, (e) => (e.serverState === serverState ? e : { ...e, serverState }));
87
+
88
+ /**
89
+ * Accept a server membership set. Also releases every acked outbox item the
90
+ * set names: membership has caught up with the write, the overlay's job is
91
+ * done (invariant I7).
92
+ */
93
+ export const commitMembership =
94
+ (hash: QueryHash, remoteArray: RecordVersionArray, present: boolean): Reducer =>
95
+ (s) => {
96
+ const withArray = withEntry(s, hash, (e) => ({
97
+ ...e,
98
+ remoteArray,
99
+ lifecycle: transition(e.lifecycle, { type: 'membership-applied', present }),
100
+ }));
101
+ if (withArray === s) return s;
102
+ const named = new Set(remoteArray.map(([id]) => id));
103
+ const outbox = withArray.outbox.filter((item) => !(item.status === 'acked' && named.has(item.recordId)));
104
+ return { ...withArray, outbox, dirty: addAll(withArray.dirty, [hash]) };
105
+ };
106
+
107
+ export const setLocalArray =
108
+ (hash: QueryHash, localArray: RecordVersionArray): Reducer =>
109
+ (s) => {
110
+ const next = withEntry(s, hash, (e) => ({ ...e, localArray }));
111
+ return next === s ? s : { ...next, dirty: addAll(next.dirty, [hash]) };
112
+ };
113
+
114
+ export const setSubqueryRemoteArray =
115
+ (hash: QueryHash, subqueryRemoteArray: RecordVersionArray): Reducer =>
116
+ (s) =>
117
+ withEntry(s, hash, (e) => ({ ...e, subqueryRemoteArray }));
118
+
119
+ export const setRecords =
120
+ (hash: QueryHash, records: ReadonlyArray<Row>, changed: boolean, materializeMs: number | null): Reducer =>
121
+ (s) => {
122
+ const next = withEntry(s, hash, (e) => {
123
+ const prev = e.telemetry.phaseSamples.localFetch ?? [];
124
+ const telemetry: QueryTelemetry = {
125
+ ...e.telemetry,
126
+ updateCount: changed ? e.telemetry.updateCount + 1 : e.telemetry.updateCount,
127
+ phaseSamples:
128
+ materializeMs === null
129
+ ? e.telemetry.phaseSamples
130
+ : { ...e.telemetry.phaseSamples, localFetch: [...prev, materializeMs].slice(-TELEMETRY_SAMPLE_WINDOW) },
131
+ phaseLast: materializeMs === null ? e.telemetry.phaseLast : { ...e.telemetry.phaseLast, localFetch: materializeMs },
132
+ };
133
+ return {
134
+ ...e,
135
+ records: changed ? records : e.records,
136
+ telemetry,
137
+ lifecycle: transition(e.lifecycle, { type: 'notified' }),
138
+ };
139
+ });
140
+ return next === s ? s : { ...next, dirty: withoutAll(next.dirty, [hash]) };
141
+ };
142
+
143
+ export const stampUpdated =
144
+ (hash: QueryHash, now: number): Reducer =>
145
+ (s) =>
146
+ withEntry(s, hash, (e) => ({ ...e, telemetry: { ...e.telemetry, lastUpdatedAt: now } }));
147
+
148
+ export const recordPhase =
149
+ (hash: QueryHash, phase: string, ms: number): Reducer =>
150
+ (s) =>
151
+ withEntry(s, hash, (e) => {
152
+ const prev = e.telemetry.phaseSamples[phase] ?? [];
153
+ return {
154
+ ...e,
155
+ telemetry: {
156
+ ...e.telemetry,
157
+ phaseSamples: { ...e.telemetry.phaseSamples, [phase]: [...prev, ms].slice(-TELEMETRY_SAMPLE_WINDOW) },
158
+ phaseLast: { ...e.telemetry.phaseLast, [phase]: ms },
159
+ },
160
+ };
161
+ });
162
+
163
+ /** SSP ingest wall time for one update (the `ssp` phase). */
164
+ export const recordIngest =
165
+ (hash: QueryHash, ms: number): Reducer =>
166
+ (s) =>
167
+ withEntry(s, hash, (e) => ({
168
+ ...e,
169
+ telemetry: {
170
+ ...e.telemetry,
171
+ lastIngestLatencyMs: ms,
172
+ materializationSamples: [...e.telemetry.materializationSamples, ms].slice(-TELEMETRY_SAMPLE_WINDOW),
173
+ },
174
+ }));
175
+
176
+ export const recordError =
177
+ (hash: QueryHash): Reducer =>
178
+ (s) =>
179
+ withEntry(s, hash, (e) => ({ ...e, telemetry: { ...e.telemetry, errorCount: e.telemetry.errorCount + 1 } }));
180
+
181
+ export const setRegistrationTimings =
182
+ (hash: QueryHash, registrationTimings: QueryTelemetry['registrationTimings']): Reducer =>
183
+ (s) =>
184
+ withEntry(s, hash, (e) => ({ ...e, telemetry: { ...e.telemetry, registrationTimings } }));
185
+
186
+ export const bumpRegisterAttempts =
187
+ (hash: QueryHash): Reducer =>
188
+ (s) =>
189
+ withEntry(s, hash, (e) => ({ ...e, registerAttempts: e.registerAttempts + 1 }));
190
+
191
+ export const resetRegisterAttempts =
192
+ (hash: QueryHash): Reducer =>
193
+ (s) =>
194
+ withEntry(s, hash, (e) => (e.registerAttempts === 0 ? e : { ...e, registerAttempts: 0 }));
195
+
196
+ export const stampHeartbeat =
197
+ (hashes: Iterable<QueryHash>, now: number): Reducer =>
198
+ (s) => {
199
+ let next = s;
200
+ for (const hash of hashes) next = withEntry(next, hash, (e) => ({ ...e, lastHeartbeatAt: now }));
201
+ return next;
202
+ };
203
+
204
+ export const beginRegistering =
205
+ (hash: QueryHash): Reducer =>
206
+ (s) => ({ ...s, registering: addAll(s.registering, [hash]) });
207
+
208
+ export const endRegistering =
209
+ (hash: QueryHash): Reducer =>
210
+ (s) =>
211
+ s.registering.has(hash) ? { ...s, registering: withoutAll(s.registering, [hash]) } : s;
212
+
213
+ export const setMembershipReread =
214
+ (hash: QueryHash, attempt: number | null): Reducer =>
215
+ (s) => {
216
+ const membershipReread = new Map(s.membershipReread);
217
+ if (attempt === null) {
218
+ if (!membershipReread.delete(hash)) return s;
219
+ } else {
220
+ membershipReread.set(hash, attempt);
221
+ }
222
+ return { ...s, membershipReread };
223
+ };
224
+
225
+ export const stampPolled =
226
+ (hashes: Iterable<QueryHash>, now: number): Reducer =>
227
+ (s) => {
228
+ let next = s;
229
+ for (const hash of hashes) next = withEntry(next, hash, (e) => ({ ...e, lastPolledAt: now }));
230
+ return next;
231
+ };
232
+
233
+ // ---- subscribers -----------------------------------------------------------
234
+
235
+ export const subscribe =
236
+ (hash: QueryHash): Reducer =>
237
+ (s) =>
238
+ withEntry(s, hash, (e) => ({ ...e, subscribers: e.subscribers + 1, lastSubscriberLeftAt: null }));
239
+
240
+ export const unsubscribe =
241
+ (hash: QueryHash, now: number): Reducer =>
242
+ (s) =>
243
+ withEntry(s, hash, (e) => {
244
+ const subscribers = Math.max(0, e.subscribers - 1);
245
+ return { ...e, subscribers, lastSubscriberLeftAt: subscribers === 0 ? now : e.lastSubscriberLeftAt };
246
+ });
247
+
248
+ // ---- dirt ------------------------------------------------------------------
249
+
250
+ export const markDirty =
251
+ (hashes: Iterable<QueryHash>): Reducer =>
252
+ (s) => {
253
+ const dirty = addAll(s.dirty, hashes);
254
+ return dirty.size === s.dirty.size ? s : { ...s, dirty };
255
+ };
256
+
257
+ export const markTableDirty =
258
+ (table: string): Reducer =>
259
+ (s) =>
260
+ markDirty(hashesForTable(s, table))(s);
261
+
262
+ export const clearDirty =
263
+ (hash: QueryHash): Reducer =>
264
+ (s) =>
265
+ s.dirty.has(hash) ? { ...s, dirty: withoutAll(s.dirty, [hash]) } : s;
266
+
267
+ export const markMembershipDirty =
268
+ (hashes: Iterable<QueryHash>): Reducer =>
269
+ (s) => {
270
+ const live = [...hashes].filter((h) => s.queries.has(h));
271
+ if (live.length === 0) return s;
272
+ return { ...s, membershipDirty: addAll(s.membershipDirty, live) };
273
+ };
274
+
275
+ export const clearMembershipDirty =
276
+ (hashes: Iterable<QueryHash>): Reducer =>
277
+ (s) => ({ ...s, membershipDirty: withoutAll(s.membershipDirty, hashes) });
278
+
279
+ // ---- versions --------------------------------------------------------------
280
+
281
+ /** Record local body versions; dirties every query whose membership names one of them. */
282
+ export const setVersions =
283
+ (entries: ReadonlyArray<readonly [string, number]>): Reducer =>
284
+ (s) => {
285
+ if (entries.length === 0) return s;
286
+ const versions = new Map(s.versions);
287
+ const changed = new Set<string>();
288
+ for (const [id, v] of entries) {
289
+ if (versions.get(id) !== v) {
290
+ versions.set(id, v);
291
+ changed.add(id);
292
+ }
293
+ }
294
+ if (changed.size === 0) return s;
295
+ const dirty: QueryHash[] = [];
296
+ for (const [hash, entry] of s.queries) {
297
+ if (entry.remoteArray.some(([id]) => changed.has(id)) || entry.localArray.some(([id]) => changed.has(id))) {
298
+ dirty.push(hash);
299
+ }
300
+ }
301
+ return { ...s, versions, dirty: addAll(s.dirty, dirty) };
302
+ };
303
+
304
+ export const deleteVersions =
305
+ (ids: Iterable<string>): Reducer =>
306
+ (s) => {
307
+ const versions = new Map(s.versions);
308
+ let touched = false;
309
+ for (const id of ids) touched = versions.delete(id) || touched;
310
+ return touched ? { ...s, versions } : s;
311
+ };
312
+
313
+ // ---- outbox ----------------------------------------------------------------
314
+
315
+ export const outboxReplace =
316
+ (items: ReadonlyArray<OutboxItem>): Reducer =>
317
+ (s) => {
318
+ const tables = new Set([...s.outbox, ...items].map((i) => i.table));
319
+ let next: ClientState = { ...s, outbox: [...items] };
320
+ for (const table of tables) next = markTableDirty(table)(next);
321
+ return next;
322
+ };
323
+
324
+ export const outboxPush =
325
+ (item: OutboxItem): Reducer =>
326
+ (s) =>
327
+ markTableDirty(item.table)({ ...s, outbox: [...s.outbox, item] });
328
+
329
+ export const outboxAck =
330
+ (id: string, now: number): Reducer =>
331
+ (s) => {
332
+ const idx = s.outbox.findIndex((i) => i.id === id);
333
+ if (idx < 0) return s;
334
+ const outbox = [...s.outbox];
335
+ outbox[idx] = { ...outbox[idx], status: 'acked', ackedAt: now };
336
+ return { ...s, outbox };
337
+ };
338
+
339
+ export const outboxRemove =
340
+ (id: string): Reducer =>
341
+ (s) => {
342
+ const item = s.outbox.find((i) => i.id === id);
343
+ if (!item) return s;
344
+ return markTableDirty(item.table)({ ...s, outbox: s.outbox.filter((i) => i.id !== id) });
345
+ };
346
+
347
+ export const outboxBumpAttempts =
348
+ (id: string): Reducer =>
349
+ (s) => {
350
+ const idx = s.outbox.findIndex((i) => i.id === id);
351
+ if (idx < 0) return s;
352
+ const outbox = [...s.outbox];
353
+ outbox[idx] = { ...outbox[idx], attempts: outbox[idx].attempts + 1 };
354
+ return { ...s, outbox };
355
+ };
356
+
357
+ /** Drop acked items older than `graceMs` (membership never named them). */
358
+ export const outboxPruneAcked =
359
+ (now: number, graceMs: number): Reducer =>
360
+ (s) => {
361
+ const stale = s.outbox.filter((i) => i.status === 'acked' && i.ackedAt !== null && now - i.ackedAt >= graceMs);
362
+ if (stale.length === 0) return s;
363
+ let next: ClientState = { ...s, outbox: s.outbox.filter((i) => !stale.includes(i)) };
364
+ for (const table of new Set(stale.map((i) => i.table))) next = markTableDirty(table)(next);
365
+ return next;
366
+ };
367
+
368
+ /** Merge a debounced update into its pending write (first `before` wins). */
369
+ export const mergePendingWrite =
370
+ (write: PendingWrite): Reducer =>
371
+ (s) => {
372
+ const prev = s.pendingWrites.get(write.key);
373
+ const pendingWrites = new Map(s.pendingWrites);
374
+ pendingWrites.set(
375
+ write.key,
376
+ prev ? { ...prev, data: { ...prev.data, ...write.data } } : write
377
+ );
378
+ return { ...s, pendingWrites };
379
+ };
380
+
381
+ export const clearPendingWrite =
382
+ (key: string): Reducer =>
383
+ (s) => {
384
+ if (!s.pendingWrites.has(key)) return s;
385
+ const pendingWrites = new Map(s.pendingWrites);
386
+ pendingWrites.delete(key);
387
+ return { ...s, pendingWrites };
388
+ };
389
+
390
+ export const setFailedCount =
391
+ (failedCount: number): Reducer =>
392
+ (s) =>
393
+ s.failedCount === failedCount ? s : { ...s, failedCount };
394
+
395
+ // ---- identity / connection --------------------------------------------------
396
+
397
+ export const setIdentity =
398
+ (
399
+ patch: Partial<
400
+ Pick<ClientState, 'sessionId' | 'userId' | 'saltUserId' | 'pendingBucket' | 'bucketId' | 'tabRole' | 'localReady' | 'primed'>
401
+ >
402
+ ): Reducer =>
403
+ (s) => ({ ...s, ...patch });
404
+
405
+ /** Re-home a query after a bucket switch: new store, same hash, fresh sync state. */
406
+ export const rebindQuery =
407
+ (
408
+ hash: QueryHash,
409
+ next: { id: QueryEntry['def']['id']; lifecycle: QueryEntry['lifecycle']; remoteArray: RecordVersionArray; localArray: RecordVersionArray }
410
+ ): Reducer =>
411
+ (s) => {
412
+ const rebound = withEntry(s, hash, (e) => ({
413
+ ...e,
414
+ def: { ...e.def, id: next.id },
415
+ lifecycle: next.lifecycle,
416
+ remoteArray: next.remoteArray,
417
+ localArray: next.localArray,
418
+ subqueryRemoteArray: [],
419
+ records: [],
420
+ serverState: null,
421
+ lastHeartbeatAt: null,
422
+ lastPolledAt: null,
423
+ registerAttempts: 0,
424
+ }));
425
+ return rebound === s ? s : { ...rebound, dirty: addAll(rebound.dirty, [hash]) };
426
+ };
427
+
428
+ /** Everything a bucket switch invalidates in one go. */
429
+ export const clearBucketState = (): Reducer => (s) => ({
430
+ ...s,
431
+ versions: new Map(),
432
+ outbox: [],
433
+ pendingWrites: new Map(),
434
+ dirty: new Set(),
435
+ membershipDirty: new Set(),
436
+ membershipReread: new Map(),
437
+ primed: false,
438
+ });
439
+
440
+ export const setTabRole =
441
+ (tabRole: TabRole): Reducer =>
442
+ (s) =>
443
+ s.tabRole === tabRole ? s : { ...s, tabRole };
444
+
445
+ export const setConnection =
446
+ (connection: ConnectionState): Reducer =>
447
+ (s) =>
448
+ s.sync.health.connection === connection ? s : { ...s, sync: { ...s.sync, health: { ...s.sync.health, connection } } };
449
+
450
+ /**
451
+ * Shallow value equality over {@link SyncHealth}. `nextHealth` rebuilds the
452
+ * snapshot on every sync round, so identity alone would report a change each
453
+ * time; the runtime uses identity to decide whether to notify subscribers, and
454
+ * this is what keeps that identity stable while nothing actually moved.
455
+ */
456
+ export const sameHealth = (a: SyncHealth, b: SyncHealth): boolean =>
457
+ a.status === b.status &&
458
+ a.consecutiveFailures === b.consecutiveFailures &&
459
+ a.everConnected === b.everConnected &&
460
+ a.connection === b.connection &&
461
+ a.kind === b.kind &&
462
+ a.error === b.error;
463
+
464
+ export const setHealth =
465
+ (health: SyncHealth): Reducer =>
466
+ (s) => (sameHealth(s.sync.health, health) ? s : { ...s, sync: { ...s.sync, health } });
467
+
468
+ export const patchSync =
469
+ (patch: Partial<Omit<ClientState['sync'], 'health'>>): Reducer =>
470
+ (s) => ({ ...s, sync: { ...s.sync, ...patch } });
471
+
472
+ /** Compose reducers left to right. */
473
+ export const compose =
474
+ (...reducers: Reducer[]): Reducer =>
475
+ (s) =>
476
+ reducers.reduce((acc, r) => r(acc), s);
@@ -0,0 +1,149 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import * as S from './selectors';
3
+ import * as R from './reducers';
4
+ import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
5
+
6
+ const e = (hash: string, over: Parameters<typeof buildEntry>[0] = {}) => buildEntry({ ...over, def: { hash, ...over.def } });
7
+
8
+ describe('basic lookups', () => {
9
+ it('queryByHash / activeHashes / hashesForTable / queryStatus', () => {
10
+ const s = buildState([e('a', { def: { tableName: 't1' } }), e('b', { def: { tableName: 't2' } })]);
11
+ expect(S.queryByHash(s, 'a')?.def.hash).toBe('a');
12
+ expect(S.activeHashes(s)).toEqual(['a', 'b']);
13
+ expect(S.hashesForTable(s, 't2')).toEqual(['b']);
14
+ expect(S.queryStatus(s, 'a')).toBe('idle');
15
+ expect(S.queryStatus(s, 'zz')).toBeUndefined();
16
+ });
17
+ });
18
+
19
+ describe('overlay and outbox counts', () => {
20
+ it('derives writes/deletes from pending and acked items', () => {
21
+ const s = buildState(
22
+ [],
23
+ R.outboxReplace([
24
+ buildOutboxItem({ id: '1', type: 'create', recordId: 'thing:1' }),
25
+ buildOutboxItem({ id: '2', type: 'update', recordId: 'thing:2', status: 'acked', ackedAt: 1 }),
26
+ buildOutboxItem({ id: '3', type: 'delete', recordId: 'thing:3' }),
27
+ ])
28
+ );
29
+ const o = S.overlay(s);
30
+ expect([...o.writes].sort()).toEqual(['thing:1', 'thing:2']);
31
+ expect([...o.deletes]).toEqual(['thing:3']);
32
+ expect([...S.pendingDeleteIds(s)]).toEqual(['thing:3']);
33
+ expect(S.hasAckedWrites(s)).toBe(true);
34
+ expect(S.pendingMutationCount(s)).toBe(2);
35
+ });
36
+ });
37
+
38
+ describe('needed / planFetch / settled', () => {
39
+ const live = { phase: 'live' } as const;
40
+ it('needed compares membership versions against local versions and skips pending deletes', () => {
41
+ const s = buildState(
42
+ [e('a', { lifecycle: live, remoteArray: [['thing:1', 2], ['thing:2', 1], ['thing:3', 1]] })],
43
+ R.setVersions([['thing:1', 2], ['thing:2', 0]]),
44
+ R.outboxReplace([buildOutboxItem({ type: 'delete', recordId: 'thing:3' })])
45
+ );
46
+ expect(S.needed(s, 'a')).toEqual([['thing:2', 1]]);
47
+ expect(S.needed(s, 'missing')).toEqual([]);
48
+ const cached = buildState([e('c', { lifecycle: { phase: 'cached' }, remoteArray: [['thing:9', 1]] })]);
49
+ expect(S.needed(cached, 'c')).toEqual([]);
50
+ });
51
+ it('planFetch dedupes across queries (highest version wins), includes subquery children, chunks', () => {
52
+ const s = buildState([
53
+ e('a', { lifecycle: live, remoteArray: [['thing:1', 1], ['thing:2', 3]] }),
54
+ e('b', { lifecycle: live, remoteArray: [['thing:2', 1], ['thing:3', 1]], subqueryRemoteArray: [['child:1', 2]] }),
55
+ e('c', { lifecycle: live, subqueryRemoteArray: [['child:1', 1], ['child:2', 1]] }),
56
+ e('d', { lifecycle: { phase: 'cached' }, remoteArray: [['thing:9', 1]] }),
57
+ ]);
58
+ const plan = S.planFetch(s, 2);
59
+ expect(plan.hashes).toEqual(['a', 'b']);
60
+ expect(plan.chunks).toEqual([['thing:1', 'thing:2'], ['thing:3', 'child:1'], ['child:2']]);
61
+ expect(plan.versions.get('thing:2')).toBe(3);
62
+ expect(plan.versions.get('child:1')).toBe(2);
63
+ expect(S.planFetch(buildState()).chunks).toEqual([]);
64
+ expect(S.neededChildren(s, 'missing')).toEqual([]);
65
+ expect(S.neededChildren(R.setVersions([['child:1', 2]])(s), 'b')).toEqual([]);
66
+ });
67
+ it('settled requires live, complete, clean, notified', () => {
68
+ const base = e('a', { lifecycle: { ...live, notified: true }, remoteArray: [['thing:1', 1]] });
69
+ const s = { ...buildState([base], R.setVersions([['thing:1', 1]])), dirty: new Set<string>() };
70
+ expect(S.settled(s, 'a')).toBe(true);
71
+ expect(S.settled(R.markDirty(['a'])(s), 'a')).toBe(false);
72
+ expect(S.settled(R.setVersions([['thing:1', 0]])(s), 'a')).toBe(false);
73
+ expect(S.settled(buildState([e('a', { lifecycle: { phase: 'cached', notified: true } })]), 'a')).toBe(false);
74
+ expect(S.settled(buildState([e('a', { lifecycle: live })]), 'a')).toBe(false);
75
+ expect(S.settled(s, 'missing')).toBe(false);
76
+ expect(S.settleFailed(s, 'missing')).toBe(true);
77
+ expect(S.settleFailed(s, 'a')).toBe(false);
78
+ expect(S.settleFailed(R.applyLifecycle('a', { type: 'remote-failed' })(s), 'a')).toBe(true);
79
+ });
80
+ it('fetchingQueryCount counts entries with fetch depth', () => {
81
+ const s = buildState([e('a', { lifecycle: { fetchDepth: 2 } }), e('b')]);
82
+ expect(S.fetchingQueryCount(s)).toBe(1);
83
+ });
84
+ });
85
+
86
+ describe('registration / eviction / ttl', () => {
87
+ it('desiredRegistrations lists unregistered queries', () => {
88
+ const s = buildState([e('a'), e('b', { lifecycle: { remote: 'registered' } }), e('c', { lifecycle: { remote: 'registering' } })]);
89
+ expect(S.desiredRegistrations(s)).toEqual(['a']);
90
+ });
91
+ it('evictable respects subscribers and ttl', () => {
92
+ const s = buildState([
93
+ e('gone', { lastSubscriberLeftAt: 0, def: { ttlMs: 100 } }),
94
+ e('fresh', { lastSubscriberLeftAt: 950, def: { ttlMs: 100 } }),
95
+ e('watched', { subscribers: 1, lastSubscriberLeftAt: 0, def: { ttlMs: 100 } }),
96
+ e('never', { def: { ttlMs: 100 } }),
97
+ ]);
98
+ expect(S.evictable(s, 1000)).toEqual(['gone']);
99
+ });
100
+ it('shortestTtlMs', () => {
101
+ expect(S.shortestTtlMs(buildState())).toBeNull();
102
+ expect(S.shortestTtlMs(buildState([e('a', { def: { ttlMs: 500 } }), e('b', { def: { ttlMs: 100 } })]))).toBe(100);
103
+ });
104
+ });
105
+
106
+ describe('toQueryState', () => {
107
+ it('projects the legacy shape with derived flags', () => {
108
+ const entry = e('a', {
109
+ lifecycle: { phase: 'view-lost', fetchDepth: 1, notified: true },
110
+ remoteArray: [['thing:1', 1]],
111
+ subqueryRemoteArray: [['child:1', 1]],
112
+ records: [{ id: 'thing:1' }],
113
+ serverState: 'ready',
114
+ lastHeartbeatAt: 123,
115
+ });
116
+ const qs = S.toQueryState(entry);
117
+ expect(qs.config.membershipKnown).toBe(true);
118
+ expect(qs.config.membershipKey).toBe('view-a');
119
+ expect(qs.viewLost).toBe(true);
120
+ expect(qs.serverMembership).toBe(true);
121
+ expect(qs.status).toBe('fetching');
122
+ expect(qs.syncNotified).toBe(true);
123
+ expect(qs.config.subqueryRemoteArray).toEqual([['child:1', 1]]);
124
+ expect(qs.config.lastActiveAt.getTime()).toBe(123);
125
+ expect(qs.records).toEqual([{ id: 'thing:1' }]);
126
+ const cold = S.toQueryState(e('b'));
127
+ expect(cold.config.membershipKnown).toBe(false);
128
+ expect(cold.config.subqueryRemoteArray).toBeUndefined();
129
+ expect(cold.lastHeartbeatAt).toBeUndefined();
130
+ expect(cold.config.lastActiveAt.getTime()).toBe(1_700_000_000_000);
131
+ });
132
+ });
133
+
134
+ describe('phaseTimings', () => {
135
+ it('summarizes every phase, with nulls before the first sample', () => {
136
+ const cold = S.phaseTimings(e('a'));
137
+ expect(cold.ssp).toEqual({ lastMs: null, p50: null, p90: null, p99: null, count: 0 });
138
+ expect(cold.localFetch.count).toBe(0);
139
+ let s = buildState([e('a')]);
140
+ for (const ms of [5, 1, 9, 3]) s = R.recordIngest('a', ms)(s);
141
+ s = R.recordPhase('a', 'remoteFetch', 7)(s);
142
+ s = R.recordError('a')(s);
143
+ const t = S.phaseTimings(s.queries.get('a')!);
144
+ expect(t.ssp).toEqual({ lastMs: 3, p50: 5, p90: 9, p99: 9, count: 4 });
145
+ expect(t.remoteFetch).toEqual({ lastMs: 7, p50: 7, p90: 7, p99: 7, count: 1 });
146
+ expect(t.errorCount).toBe(1);
147
+ expect(t.registration.parseMs).toBeNull();
148
+ });
149
+ });