@spooky-sync/core 0.0.1-canary.30 → 0.0.1-canary.301

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 (257) hide show
  1. package/AGENTS.md +81 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2026 -137
  4. package/dist/index.js +14939 -2432
  5. package/dist/live.d.ts +141 -0
  6. package/dist/live.js +709 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/otel/index.js +3 -3
  9. package/dist/pure.d.ts +329 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +358 -0
  12. package/dist/sqlite-worker.d.ts +1 -0
  13. package/dist/sqlite-worker.js +439 -0
  14. package/dist/sw.d.ts +207 -0
  15. package/dist/sw.js +393 -0
  16. package/dist/tabs-broker-worker.d.ts +8 -0
  17. package/dist/tabs-broker-worker.js +472 -0
  18. package/dist/types.d.ts +1765 -38
  19. package/dist/worker-edges.js +423 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +46 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +27 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +172 -0
  27. package/skills/sp00ky-core/SKILL.md +31 -6
  28. package/skills/sp00ky-core/references/config.md +6 -0
  29. package/src/boot/auth-flip.saga.test.ts +82 -0
  30. package/src/boot/auth-flip.saga.ts +62 -0
  31. package/src/boot/boot.saga.test.ts +158 -0
  32. package/src/boot/boot.saga.ts +131 -0
  33. package/src/boot/bucket-switch.saga.test.ts +187 -0
  34. package/src/boot/bucket-switch.saga.ts +133 -0
  35. package/src/boot/preload.saga.test.ts +51 -0
  36. package/src/boot/preload.saga.ts +31 -0
  37. package/src/bucket-blurhash.test.ts +148 -0
  38. package/src/build-globals.d.ts +12 -0
  39. package/src/client/bucket-handle.test.ts +117 -0
  40. package/src/client/bucket-handle.ts +227 -0
  41. package/src/client/router.test.ts +58 -0
  42. package/src/client/router.ts +100 -0
  43. package/src/client/runtime.test.ts +195 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.ts +370 -0
  46. package/src/client/sp00ky-client.test.ts +303 -0
  47. package/src/client/sp00ky-client.ts +586 -0
  48. package/src/events/events.test.ts +2 -1
  49. package/src/events/index.ts +3 -0
  50. package/src/index.ts +69 -1
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +80 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +161 -0
  55. package/src/kernel/events.ts +57 -0
  56. package/src/kernel/interpreter.test.ts +116 -0
  57. package/src/kernel/interpreter.ts +148 -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 +478 -0
  61. package/src/live/index.ts +1013 -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 +141 -0
  65. package/src/modules/auth/events/index.ts +9 -2
  66. package/src/modules/auth/impersonation-banner.ts +443 -0
  67. package/src/modules/auth/impersonation.test.ts +355 -0
  68. package/src/modules/auth/impersonation.ts +179 -0
  69. package/src/modules/auth/index.ts +386 -17
  70. package/src/modules/crdt/crdt-field.ts +294 -0
  71. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  72. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  73. package/src/modules/crdt/index.ts +463 -0
  74. package/src/modules/crdt/loro-loader.ts +25 -0
  75. package/src/modules/devtools/flags.ts +349 -0
  76. package/src/modules/devtools/index.ts +746 -95
  77. package/src/modules/devtools/mutations.test.ts +92 -0
  78. package/src/modules/devtools/mutations.ts +160 -0
  79. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  80. package/src/modules/devtools/state-shape.test.ts +263 -0
  81. package/src/modules/devtools/storage-info.test.ts +79 -0
  82. package/src/modules/devtools/storage-info.ts +168 -0
  83. package/src/modules/devtools/versions.test.ts +74 -0
  84. package/src/modules/devtools/versions.ts +110 -0
  85. package/src/modules/feature-flag/index.test.ts +251 -0
  86. package/src/modules/feature-flag/index.ts +316 -0
  87. package/src/modules/ref-tables.test.ts +91 -0
  88. package/src/modules/ref-tables.ts +88 -0
  89. package/src/modules/web-push/index.test.ts +824 -0
  90. package/src/modules/web-push/index.ts +1027 -0
  91. package/src/mutation/jobs.test.ts +25 -0
  92. package/src/mutation/jobs.ts +41 -0
  93. package/src/mutation/mutation-id.test.ts +37 -0
  94. package/src/mutation/mutation-id.ts +35 -0
  95. package/src/mutation/pending-writes.integration.test.ts +175 -0
  96. package/src/mutation/push.saga.test.ts +285 -0
  97. package/src/mutation/push.saga.ts +217 -0
  98. package/src/mutation/rows.test.ts +231 -0
  99. package/src/mutation/rows.ts +427 -0
  100. package/src/mutation/tray.saga.test.ts +63 -0
  101. package/src/mutation/tray.saga.ts +48 -0
  102. package/src/mutation/write.saga.test.ts +316 -0
  103. package/src/mutation/write.saga.ts +268 -0
  104. package/src/otel/index.ts +10 -7
  105. package/src/pure.ts +65 -0
  106. package/src/push/types.ts +174 -0
  107. package/src/query/env.test.ts +23 -0
  108. package/src/query/env.ts +56 -0
  109. package/src/query/fetch.saga.test.ts +199 -0
  110. package/src/query/fetch.saga.ts +120 -0
  111. package/src/query/hash.test.ts +14 -0
  112. package/src/query/hash.ts +18 -0
  113. package/src/query/id-set-plan.test.ts +132 -0
  114. package/src/query/lifecycle.saga.test.ts +274 -0
  115. package/src/query/lifecycle.saga.ts +159 -0
  116. package/src/query/materialize.saga.test.ts +115 -0
  117. package/src/query/materialize.saga.ts +84 -0
  118. package/src/query/materialize.test.ts +58 -0
  119. package/src/query/materialize.ts +57 -0
  120. package/src/query/membership.saga.test.ts +350 -0
  121. package/src/query/membership.saga.ts +278 -0
  122. package/src/query/membership.test.ts +118 -0
  123. package/src/query/membership.ts +201 -0
  124. package/src/query/register.saga.test.ts +293 -0
  125. package/src/query/register.saga.ts +226 -0
  126. package/src/query/render-set.test.ts +47 -0
  127. package/src/query/render-set.ts +71 -0
  128. package/src/query/sql.test.ts +63 -0
  129. package/src/query/sql.ts +93 -0
  130. package/src/query/window-query.test.ts +70 -0
  131. package/src/query/window-query.ts +195 -0
  132. package/src/services/blobs/blob-cache.test.ts +359 -0
  133. package/src/services/blobs/blob-cache.ts +603 -0
  134. package/src/services/blobs/blob-manifest.ts +227 -0
  135. package/src/services/blobs/blob-store.test.ts +77 -0
  136. package/src/services/blobs/blob-store.ts +359 -0
  137. package/src/services/blobs/blob.fixture.ts +90 -0
  138. package/src/services/blobs/index.ts +70 -0
  139. package/src/services/database/cache-engine.ts +199 -0
  140. package/src/services/database/connection-supervisor.test.ts +318 -0
  141. package/src/services/database/connection-supervisor.ts +422 -0
  142. package/src/services/database/database.query-timeout.test.ts +140 -0
  143. package/src/services/database/database.responses.test.ts +43 -0
  144. package/src/services/database/database.ts +146 -61
  145. package/src/services/database/engine-factory.ts +33 -0
  146. package/src/services/database/errors.ts +34 -0
  147. package/src/services/database/events/index.ts +2 -1
  148. package/src/services/database/index.ts +7 -0
  149. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  150. package/src/services/database/local-migrator.integration.test.ts +110 -0
  151. package/src/services/database/local-migrator.ts +59 -16
  152. package/src/services/database/local.test.ts +64 -0
  153. package/src/services/database/local.ts +487 -63
  154. package/src/services/database/plan-render.test.ts +159 -0
  155. package/src/services/database/plan-render.ts +108 -0
  156. package/src/services/database/relation-resolver.test.ts +467 -0
  157. package/src/services/database/relation-resolver.ts +0 -0
  158. package/src/services/database/remote.ts +213 -6
  159. package/src/services/database/sqlite-cache-engine.test.ts +617 -0
  160. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  161. package/src/services/database/sqlite-cache-engine.ts +1372 -0
  162. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  163. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  164. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  165. package/src/services/database/sqlite-lock-verify.ts +45 -0
  166. package/src/services/database/sqlite-open.test.ts +150 -0
  167. package/src/services/database/sqlite-open.ts +164 -0
  168. package/src/services/database/sqlite-plan-sql.test.ts +139 -0
  169. package/src/services/database/sqlite-plan-sql.ts +179 -0
  170. package/src/services/database/sqlite-projection.test.ts +121 -0
  171. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  172. package/src/services/database/sqlite-select.test.ts +246 -0
  173. package/src/services/database/sqlite-select.ts +131 -0
  174. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  175. package/src/services/database/sqlite-transport.ts +224 -0
  176. package/src/services/database/sqlite-worker.ts +437 -0
  177. package/src/services/database/surql-translate.ts +416 -0
  178. package/src/services/database/surreal-cache-engine.ts +161 -0
  179. package/src/services/logger/index.test.ts +132 -0
  180. package/src/services/logger/index.ts +189 -7
  181. package/src/services/persistence/localstorage.ts +2 -2
  182. package/src/services/persistence/resilient.ts +10 -3
  183. package/src/services/persistence/surrealdb.ts +4 -4
  184. package/src/services/stream-processor/index.ts +779 -67
  185. package/src/services/stream-processor/permissions.test.ts +47 -0
  186. package/src/services/stream-processor/permissions.ts +53 -0
  187. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  188. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  189. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  190. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  191. package/src/services/stream-processor/wasm-types.ts +58 -2
  192. package/src/services/tabs/broker-client.ts +283 -0
  193. package/src/services/tabs/broker.test.ts +327 -0
  194. package/src/services/tabs/coordinator.test.ts +386 -0
  195. package/src/services/tabs/coordinator.ts +638 -0
  196. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  197. package/src/services/tabs/leader-locks.ts +75 -0
  198. package/src/services/tabs/protocol.ts +262 -0
  199. package/src/services/tabs/support.ts +36 -0
  200. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  201. package/src/sp00ky.ts +5 -395
  202. package/src/state/client-state.ts +200 -0
  203. package/src/state/lifecycle.test.ts +118 -0
  204. package/src/state/lifecycle.ts +86 -0
  205. package/src/state/reducers.test.ts +304 -0
  206. package/src/state/reducers.ts +526 -0
  207. package/src/state/selectors.test.ts +167 -0
  208. package/src/state/selectors.ts +216 -0
  209. package/src/sw/index.test.ts +582 -0
  210. package/src/sw/index.ts +607 -0
  211. package/src/sw/store.ts +96 -0
  212. package/src/sync/connection.saga.test.ts +86 -0
  213. package/src/sync/connection.saga.ts +85 -0
  214. package/src/sync/live.saga.test.ts +178 -0
  215. package/src/sync/live.saga.ts +107 -0
  216. package/src/sync/policy.health.test.ts +56 -0
  217. package/src/sync/policy.test.ts +659 -0
  218. package/src/sync/policy.ts +502 -0
  219. package/src/sync/poll.saga.test.ts +51 -0
  220. package/src/sync/poll.saga.ts +36 -0
  221. package/src/sync/tabs.saga.test.ts +78 -0
  222. package/src/sync/tabs.saga.ts +96 -0
  223. package/src/testing/adapters.ts +133 -0
  224. package/src/testing/build.ts +63 -0
  225. package/src/testing/fake-services.ts +48 -0
  226. package/src/testing/run-pure.test.ts +92 -0
  227. package/src/testing/run-pure.ts +128 -0
  228. package/src/testing/services.ts +17 -0
  229. package/src/types.ts +624 -10
  230. package/src/utils/blurhash.ts +90 -0
  231. package/src/utils/edges.ts +39 -0
  232. package/src/utils/error-classification.test.ts +54 -0
  233. package/src/utils/error-classification.ts +25 -0
  234. package/src/utils/index.ts +75 -9
  235. package/src/utils/parser.test.ts +67 -102
  236. package/src/utils/parser.ts +64 -2
  237. package/src/utils/semver.test.ts +32 -0
  238. package/src/utils/semver.ts +30 -0
  239. package/src/utils/sha256.ts +15 -0
  240. package/src/utils/surql.ts +30 -18
  241. package/src/utils/utils.test.ts +2 -1
  242. package/tsdown.config.ts +117 -3
  243. package/vitest.config.ts +48 -0
  244. package/src/modules/cache/index.ts +0 -241
  245. package/src/modules/cache/types.ts +0 -19
  246. package/src/modules/data/data.test.ts +0 -58
  247. package/src/modules/data/index.ts +0 -879
  248. package/src/modules/sync/engine.ts +0 -173
  249. package/src/modules/sync/events/index.ts +0 -77
  250. package/src/modules/sync/index.ts +0 -3
  251. package/src/modules/sync/queue/index.ts +0 -2
  252. package/src/modules/sync/queue/queue-down.ts +0 -89
  253. package/src/modules/sync/queue/queue-up.ts +0 -223
  254. package/src/modules/sync/scheduler.ts +0 -84
  255. package/src/modules/sync/sync.ts +0 -421
  256. package/src/modules/sync/utils.test.ts +0 -311
  257. package/src/modules/sync/utils.ts +0 -167
@@ -0,0 +1,502 @@
1
+ import type { RecordId } from 'surrealdb';
2
+ import type { RecordVersionArray, RecordVersionDiff } from '../types';
3
+ import { parseRecordIdString, encodeRecordId } from '../utils/index';
4
+ import type { SyncHealth } from '../types';
5
+ import { classifySyncError } from '../utils/error-classification';
6
+ import { SELF_HEAL_BASE_MS, SELF_HEAL_MAX_MS } from '../kernel/constants';
7
+
8
+ export class ArraySyncer {
9
+ private localArray: RecordVersionArray;
10
+ private remoteArray: RecordVersionArray;
11
+ private needsSort = false;
12
+
13
+ constructor(localArray: RecordVersionArray, remoteArray: RecordVersionArray) {
14
+ this.remoteArray = remoteArray.toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
15
+ this.localArray = localArray.toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
16
+ }
17
+
18
+ /**
19
+ * Inserts an item into the local array
20
+ */
21
+ insert(recordId: string, version: number) {
22
+ this.localArray.push([recordId, version]);
23
+ this.needsSort = true;
24
+ }
25
+
26
+ /**
27
+ * Updates the current local RecordVersionArray state.
28
+ */
29
+ update(recordId: string, version: number) {
30
+ this.localArray = this.localArray.map((record) => {
31
+ if (record[0] === recordId) {
32
+ this.needsSort = true;
33
+ return [recordId, version];
34
+ }
35
+ return record;
36
+ });
37
+ }
38
+
39
+ /**
40
+ * Deletes an item from the local array
41
+ */
42
+ delete(recordId: string) {
43
+ this.localArray = this.localArray.filter((record) => record[0] !== recordId);
44
+ }
45
+
46
+ /**
47
+ * Returns the difference between the local and remote arrays.
48
+ * Includes sets of added, updated, and removed records.
49
+ */
50
+ nextSet(): RecordVersionDiff | null {
51
+ if (this.needsSort) {
52
+ this.localArray.sort((a, b) => a[0].localeCompare(b[0]));
53
+ this.needsSort = false;
54
+ }
55
+ const diff = diffRecordVersionArray(this.localArray, this.remoteArray);
56
+ return diff;
57
+ }
58
+ }
59
+
60
+ export function diffRecordVersionArray(
61
+ local: RecordVersionArray | null,
62
+ remote: RecordVersionArray | null
63
+ ): RecordVersionDiff {
64
+ const localArray = local || [];
65
+ const remoteArray = remote || [];
66
+
67
+ // Convert arrays to Maps for O(1) lookup
68
+ const localMap = new Map<string, number>(localArray);
69
+ const remoteMap = new Map<string, number>(remoteArray);
70
+
71
+ const added: string[] = [];
72
+ const updated: string[] = [];
73
+ const removed: string[] = [];
74
+
75
+ // Find added and updated records
76
+ for (const [recordId, remoteVersion] of remoteMap) {
77
+ const localVersion = localMap.get(recordId);
78
+
79
+ if (localVersion === undefined) {
80
+ // Record exists in remote but not in local
81
+ added.push(recordId);
82
+ } else if (localVersion < remoteVersion) {
83
+ // Record exists in both but remote has newer version
84
+ updated.push(recordId);
85
+ }
86
+ }
87
+
88
+ // Find removed records
89
+ for (const [recordId] of localMap) {
90
+ if (!remoteMap.has(recordId)) {
91
+ removed.push(recordId);
92
+ }
93
+ }
94
+
95
+ return {
96
+ added: added.map((id) => ({
97
+ id: parseRecordIdString(id),
98
+ // oxlint-disable-next-line no-non-null-assertion
99
+ version: remoteMap.get(id)!,
100
+ })),
101
+ updated: updated.map((id) => ({
102
+ id: parseRecordIdString(id),
103
+ // oxlint-disable-next-line no-non-null-assertion
104
+ version: remoteMap.get(id)!,
105
+ })),
106
+ removed: removed.map(parseRecordIdString),
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Applies a RecordVersionDiff to a RecordVersionArray and returns a new sorted array.
112
+ */
113
+ export function applyRecordVersionDiff(
114
+ current: RecordVersionArray,
115
+ diff: RecordVersionDiff
116
+ ): RecordVersionArray {
117
+ const currentMap = new Map(current);
118
+
119
+ // Apply removals
120
+ for (const id of diff.removed) {
121
+ currentMap.delete(encodeRecordId(id));
122
+ }
123
+
124
+ // Apply additions
125
+ for (const item of diff.added) {
126
+ currentMap.set(encodeRecordId(item.id), item.version);
127
+ }
128
+
129
+ // Apply updates
130
+ for (const item of diff.updated) {
131
+ currentMap.set(encodeRecordId(item.id), item.version);
132
+ }
133
+
134
+ return Array.from(currentMap).toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
135
+ }
136
+
137
+ export function createDiffFromDbOp(
138
+ op: 'CREATE' | 'UPDATE' | 'DELETE',
139
+ recordId: RecordId,
140
+ version: number,
141
+ versions?: RecordVersionArray
142
+ ): RecordVersionDiff {
143
+ const old = versions?.find((record) => record[0] === encodeRecordId(recordId));
144
+
145
+ if (old && old[1] >= version) {
146
+ return {
147
+ added: [],
148
+ updated: [],
149
+ removed: [],
150
+ };
151
+ }
152
+
153
+ if (op === 'CREATE') {
154
+ return {
155
+ added: [{ id: recordId, version }],
156
+ updated: [],
157
+ removed: [],
158
+ };
159
+ } else if (op === 'UPDATE') {
160
+ return {
161
+ added: [],
162
+ updated: [{ id: recordId, version }],
163
+ removed: [],
164
+ };
165
+ } else {
166
+ return {
167
+ added: [],
168
+ updated: [],
169
+ removed: [recordId],
170
+ };
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Default cadence for the `_00_list_ref_user_<id>` poll fallback. The
176
+ * poll is the safety net for SurrealDB v3's occasionally-dropped LIVE
177
+ * deliveries; 500ms is aggressive enough to feel real-time on the
178
+ * happy path while keeping the per-session query load bounded.
179
+ */
180
+ export const DEFAULT_LIST_REF_POLL_INTERVAL_MS = 500;
181
+
182
+ /**
183
+ * Build the SurrealQL select that powers both the initial-fetch and
184
+ * the periodic poll of `_00_list_ref[_user_<id>]`. The `parent IS NONE`
185
+ * predicate excludes subquery entries (rows with `parent_rel` set)
186
+ * because the client's `RecordVersionArray` only tracks primary rows;
187
+ * including subquery rows would surface them as spurious "added"
188
+ * diffs every tick.
189
+ */
190
+ export function buildListRefSelect(table: string): string {
191
+ return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NONE`;
192
+ }
193
+
194
+ /**
195
+ * Build the select that says whether an EMPTY id-set means "this query has no
196
+ * rows" or "the server has not published them yet".
197
+ *
198
+ * The SSP writes `rowCount` onto the `_00_query` row in the same statement that
199
+ * registers the view — synchronously, and BEFORE it hands the view's initial
200
+ * edges to the coalescing edge flusher. So the two are not interchangeable:
201
+ * `rowCount > 0` with no edges is the flush window, and only `rowCount === 0`
202
+ * is a genuinely empty query. Polling the edges alone cannot tell those apart
203
+ * no matter how long it waits, which is why this is read alongside them rather
204
+ * than a retry counter.
205
+ *
206
+ * `state` rides along: the SSP writes `materializing` when it hands a full
207
+ * publish to its edge flusher and flips it to `ready` INSIDE the transaction
208
+ * that writes the edges. So `ready` + no edges + `rowCount 0` is a real empty
209
+ * result, `materializing` + no edges is "still publishing", and a missing row
210
+ * (the whole object is `NONE`) is "the server no longer has this view". A
211
+ * server that predates the marker returns `state: NONE` and callers fall back
212
+ * to `rowCount` alone.
213
+ *
214
+ * Returns `NONE` (→ null) when the row is not readable or does not exist yet;
215
+ * callers must treat that as "unknown", not as zero.
216
+ */
217
+ export function buildQueryRowCountSelect(): string {
218
+ return 'SELECT VALUE { rowCount: rowCount, state: state } FROM ONLY $in';
219
+ }
220
+
221
+ /**
222
+ * Build the SurrealQL select for a query's SUBQUERY child edges — the
223
+ * mirror of {@link buildListRefSelect}. `.related()` queries register a
224
+ * correlated subquery; the SSP materializes each matched child as a
225
+ * `_00_list_ref` edge tagged with `parent`/`parent_rel` (see
226
+ * `apps/ssp` edge writer). `parent IS NONE` (the primary select) drops
227
+ * these, so their bodies never reach the local cache and a cold-reload
228
+ * re-materialization of the correlated surql yields empty related
229
+ * fields. This `parent IS NOT NONE` variant pulls the child `out`+`version`
230
+ * pairs (any nesting depth) so we can sync their bodies into the local
231
+ * store SEPARATELY from the primary window array.
232
+ */
233
+ export function buildSubqueryListRefSelect(table: string): string {
234
+ return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NOT NONE`;
235
+ }
236
+
237
+ /**
238
+ * One round trip for the edges of MANY queries: primary and subquery rows
239
+ * together, split client-side on `parent`. Replaces two selects per query per
240
+ * poll tick, which on a page with 20+ live queries was ~50 serialized round
241
+ * trips per cycle and kept the remote busy full-time.
242
+ */
243
+ export function buildListRefBatchSelect(table: string): string {
244
+ return `SELECT in, out, version, parent FROM ${table} WHERE in IN $ins`;
245
+ }
246
+
247
+ /**
248
+ * `rowCount` for many `_00_query` rows at once, keyed by id so the caller does
249
+ * not depend on the array order. Same semantics as
250
+ * {@link buildQueryRowCountSelect}: a row the session cannot read comes back
251
+ * without an id and must be treated as "unknown".
252
+ */
253
+ export function buildQueryRowCountBatchSelect(): string {
254
+ return 'SELECT VALUE { id: id, rowCount: rowCount, state: state } FROM $ins';
255
+ }
256
+
257
+ /** Known edges one poll round trip may carry before the cycle is split. */
258
+ export const LIST_REF_POLL_ROW_BUDGET = 1_500;
259
+ /** A view at or past this many edges is "large": it rides on LIVE and is only
260
+ * re-polled every {@link LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS}. */
261
+ export const LIST_REF_POLL_LARGE_VIEW_ROWS = 1_000;
262
+ export const LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS = 15_000;
263
+
264
+ export interface ListRefPollCandidate {
265
+ hash: string;
266
+ /** Edges the client currently holds for the query (`remoteArray.length`). */
267
+ rows: number;
268
+ /** When the query was last refreshed by the poll; `0` = never. */
269
+ lastPolledAt: number;
270
+ }
271
+
272
+ /**
273
+ * Split the active queries into the round trips of one poll cycle.
274
+ *
275
+ * Every query that is due is refreshed once per cycle, oldest refresh first,
276
+ * packed greedily into chunks of at most `rowBudget` known edges so one
277
+ * response never carries a whole page's worth of ids at once. A view with
278
+ * `largeViewRows` or more edges is only due once `largeViewMinAgeMs` has
279
+ * passed since its last refresh (LIVE remains its primary path); a chunk
280
+ * always holds at least one query, so a single huge view still refreshes.
281
+ */
282
+ export function planListRefPollChunks(
283
+ candidates: ListRefPollCandidate[],
284
+ opts: { now: number; rowBudget?: number; largeViewRows?: number; largeViewMinAgeMs?: number }
285
+ ): string[][] {
286
+ const {
287
+ now,
288
+ rowBudget = LIST_REF_POLL_ROW_BUDGET,
289
+ largeViewRows = LIST_REF_POLL_LARGE_VIEW_ROWS,
290
+ largeViewMinAgeMs = LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS,
291
+ } = opts;
292
+ const due = candidates
293
+ .filter((c) => c.rows < largeViewRows || now - c.lastPolledAt >= largeViewMinAgeMs)
294
+ .sort(
295
+ (a, b) => a.lastPolledAt - b.lastPolledAt || (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0)
296
+ );
297
+ const chunks: string[][] = [];
298
+ let current: string[] = [];
299
+ let currentRows = 0;
300
+ for (const c of due) {
301
+ const cost = Math.max(1, c.rows);
302
+ if (current.length > 0 && currentRows + cost > rowBudget) {
303
+ chunks.push(current);
304
+ current = [];
305
+ currentRows = 0;
306
+ }
307
+ current.push(c.hash);
308
+ currentRows += cost;
309
+ }
310
+ if (current.length > 0) chunks.push(current);
311
+ return chunks;
312
+ }
313
+
314
+ /**
315
+ * Resolve the effective list-ref poll interval. Negative or zero
316
+ * values fall back to the default — accepting them would either
317
+ * disable polling silently or busy-loop the event loop.
318
+ */
319
+ export function resolveListRefPollInterval(opt?: number): number {
320
+ if (typeof opt !== 'number' || !Number.isFinite(opt) || opt <= 0) {
321
+ return DEFAULT_LIST_REF_POLL_INTERVAL_MS;
322
+ }
323
+ return opt;
324
+ }
325
+
326
+ /**
327
+ * When the LIVE feed has delivered an event within this window, treat
328
+ * the LIVE subscription as healthy and back the poll off to
329
+ * {@link LIVE_HEALTHY_POLL_INTERVAL_MS}. As soon as LIVE quiets for
330
+ * longer than this, the poll snaps back to the aggressive default.
331
+ */
332
+ export const LIVE_HEALTHY_COOLDOWN_MS = 5_000;
333
+
334
+ /**
335
+ * Poll interval while LIVE is delivering events. The aggressive
336
+ * default 500ms costs ~120 queries / minute / session — wasted work
337
+ * when LIVE is already covering us. 5s keeps the safety net in place
338
+ * at 1/10th the load.
339
+ */
340
+ export const LIVE_HEALTHY_POLL_INTERVAL_MS = 5_000;
341
+
342
+ /**
343
+ * Pick the next poll delay based on whether LIVE has been healthy
344
+ * recently. If a LIVE event fired within `cooldownMs`, use the slow
345
+ * (`healthyIntervalMs`) cadence; otherwise the fast (`baseIntervalMs`)
346
+ * cadence. Pure so it's unit-testable; `Sp00kySync.startListRefPoll`
347
+ * calls it from a self-rescheduling timer.
348
+ *
349
+ * The healthy interval is clamped to at least `baseIntervalMs` so
350
+ * configuring an aggressive base (e.g. 100ms) never gets implicitly
351
+ * widened by this helper.
352
+ *
353
+ * @deprecated Superseded by {@link listRefPollDelayMs}, which backs the
354
+ * poll off based on observed change activity (LIVE *or* poll-detected)
355
+ * rather than LIVE liveness alone — the cross-session LIVE-permission gap
356
+ * means LIVE often never fires, so this helper would keep the poll pinned
357
+ * at the aggressive base forever even on a fully idle page. Kept (and
358
+ * tested) for reference.
359
+ */
360
+ export function nextPollDelayMs(args: {
361
+ now: number;
362
+ lastLiveEventAt: number | null;
363
+ baseIntervalMs: number;
364
+ cooldownMs?: number;
365
+ healthyIntervalMs?: number;
366
+ }): number {
367
+ const {
368
+ now,
369
+ lastLiveEventAt,
370
+ baseIntervalMs,
371
+ cooldownMs = LIVE_HEALTHY_COOLDOWN_MS,
372
+ healthyIntervalMs = LIVE_HEALTHY_POLL_INTERVAL_MS,
373
+ } = args;
374
+ if (lastLiveEventAt === null) return baseIntervalMs;
375
+ const sinceLive = now - lastLiveEventAt;
376
+ if (sinceLive < 0 || sinceLive >= cooldownMs) return baseIntervalMs;
377
+ return Math.max(healthyIntervalMs, baseIntervalMs);
378
+ }
379
+
380
+ /**
381
+ * Ceiling for the adaptive list_ref poll backoff. An idle page (no LIVE
382
+ * events, no poll-detected list_ref changes) coasts up to this cadence;
383
+ * the existing healthy-LIVE safety net runs at the same 5s, so this keeps
384
+ * the worst-case catch-up latency for a missed cross-session change at the
385
+ * cadence the codebase already treats as acceptable.
386
+ */
387
+ export const LIST_REF_POLL_MAX_INTERVAL_MS = 5_000;
388
+
389
+ /**
390
+ * Adaptive poll delay: stay at the responsive `baseIntervalMs` while
391
+ * changes are arriving, and exponentially back off toward `maxIntervalMs`
392
+ * while the `_00_list_ref` is quiet.
393
+ *
394
+ * `idleStreak` is the count of consecutive poll cycles that observed *no*
395
+ * change. `Sp00kySync` resets it to 0 whenever a poll detects a real
396
+ * remoteArray change OR a LIVE event lands, so any activity snaps the poll
397
+ * straight back to `baseIntervalMs`. A streak of 0 (something just
398
+ * happened) → base; otherwise `base * 2^streak` capped at `maxIntervalMs`.
399
+ *
400
+ * This replaces {@link nextPollDelayMs}: the old helper slowed the poll
401
+ * only while LIVE was *delivering*, but the cross-session LIVE-permission
402
+ * gap means LIVE frequently never fires here, so it left a fully idle page
403
+ * polling every `base` ms forever (the "continuous queries while idle"
404
+ * symptom). Backing off on observed idleness instead covers the
405
+ * LIVE-healthy case for free (LIVE applies the change → the next poll sees
406
+ * nothing new → the streak grows → it backs off).
407
+ */
408
+ export function listRefPollDelayMs(args: {
409
+ idleStreak: number;
410
+ baseIntervalMs: number;
411
+ maxIntervalMs?: number;
412
+ }): number {
413
+ const { idleStreak, baseIntervalMs, maxIntervalMs = LIST_REF_POLL_MAX_INTERVAL_MS } = args;
414
+ const cap = Math.max(baseIntervalMs, maxIntervalMs);
415
+ if (idleStreak <= 0) return baseIntervalMs;
416
+ // 2^streak grows fast; clamp the exponent so it can't overflow on a
417
+ // page left idle for a very long time.
418
+ const exponent = Math.min(idleStreak, 30);
419
+ return Math.min(baseIntervalMs * 2 ** exponent, cap);
420
+ }
421
+
422
+ /**
423
+ * Order-insensitive equality for two `RecordVersionArray`s (each a list of
424
+ * `[recordIdString, version]`). The `_00_list_ref` SELECT has no `ORDER
425
+ * BY`, so row order can differ between polls without anything having
426
+ * actually changed — comparing as an id→version map avoids false
427
+ * "changed" verdicts that would defeat the idle backoff. Record ids are
428
+ * unique within a query's list_ref, so a map is a faithful representation.
429
+ */
430
+ export function recordVersionArraysEqual(
431
+ a: RecordVersionArray,
432
+ b: RecordVersionArray
433
+ ): boolean {
434
+ if (a === b) return true;
435
+ if (a.length !== b.length) return false;
436
+ const byId = new Map<string, number>();
437
+ for (const [id, version] of a) byId.set(id, version);
438
+ for (const [id, version] of b) {
439
+ // `get` returns undefined for a missing id, which never === a number.
440
+ if (byId.get(id) !== version) return false;
441
+ }
442
+ return true;
443
+ }
444
+
445
+ // ---- health ------------------------------------------------------------------
446
+
447
+
448
+ export interface HealthInput {
449
+ health: SyncHealth;
450
+ consecutiveFailures: number;
451
+ hasSyncedOnce: boolean;
452
+ }
453
+
454
+ export interface HealthOutput extends HealthInput {
455
+ /** Crossed into degraded on this outcome: start self-heal. */
456
+ degradedNow: boolean;
457
+ /** Left degraded on this outcome: stop self-heal. */
458
+ recoveredNow: boolean;
459
+ }
460
+
461
+ /**
462
+ * Fold one sync round's outcome into health. A single failure is absorbed;
463
+ * `degradeAfter` consecutive ones flip to degraded, the next success flips
464
+ * back. `degradeAfter <= 0` disables reporting.
465
+ */
466
+ export function nextHealth(input: HealthInput, ok: boolean, error: unknown, degradeAfter: number): HealthOutput {
467
+ const base = { ...input, degradedNow: false, recoveredNow: false };
468
+ if (degradeAfter <= 0) return base;
469
+ if (ok) {
470
+ const everConnected = true;
471
+ if (input.consecutiveFailures === 0) {
472
+ return { ...base, hasSyncedOnce: true, health: { ...input.health, everConnected } };
473
+ }
474
+ const recovered = input.health.status === 'degraded';
475
+ return {
476
+ ...base,
477
+ hasSyncedOnce: true,
478
+ consecutiveFailures: 0,
479
+ health: { ...input.health, status: 'healthy', kind: undefined, error: undefined, everConnected },
480
+ recoveredNow: recovered,
481
+ };
482
+ }
483
+ const consecutiveFailures = input.consecutiveFailures + 1;
484
+ const kind = classifySyncError(error);
485
+ const message = error instanceof Error ? error.message : String(error);
486
+ if (input.health.status !== 'degraded' && consecutiveFailures >= degradeAfter) {
487
+ return {
488
+ ...base,
489
+ consecutiveFailures,
490
+ health: { ...input.health, status: 'degraded', consecutiveFailures, kind, error: message },
491
+ degradedNow: true,
492
+ };
493
+ }
494
+ return {
495
+ ...base,
496
+ consecutiveFailures,
497
+ health: { ...input.health, consecutiveFailures, kind, error: message },
498
+ };
499
+ }
500
+
501
+ export const selfHealDelayMs = (attempt: number): number =>
502
+ Math.min(SELF_HEAL_MAX_MS, SELF_HEAL_BASE_MS * 2 ** Math.min(attempt, 30));
@@ -0,0 +1,51 @@
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 { defaultEnv } from '../query/env';
7
+ import { pollTick } from './poll.saga';
8
+
9
+ const env = defaultEnv({ tables: [] } as any);
10
+ const ok = (result: unknown) => ({ status: 'OK', result });
11
+
12
+ describe('pollTick', () => {
13
+ it('with no queries: probes connectivity, backs off while idle', async () => {
14
+ const out = await runPure(pollTick(env), { state: R.patchSync({ pollIdleStreak: 2 })(buildState()), handlers: { 'remote.query': () => [ok(true)] } });
15
+ expect(out.dispatched).toEqual([{ type: 'SyncOutcome', ok: true }]);
16
+ expect(out.state.sync.pollIdleStreak).toBe(3);
17
+ expect(out.timers.get('poll')).toEqual({ ms: 4000, event: { type: 'PollTick' } });
18
+ const failed = await runPure(pollTick(env), {
19
+ state: buildState(),
20
+ handlers: {
21
+ 'remote.query': () => {
22
+ throw new Error('offline');
23
+ },
24
+ },
25
+ });
26
+ expect(failed.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('offline') }]);
27
+ });
28
+ it('with queries: reads membership; a change or an acked write resets the streak', async () => {
29
+ const entry = buildEntry({ def: { hash: 'a', id: new RecordId('_00_query', 'a') }, lifecycle: { phase: 'live' }, serverState: 'ready' });
30
+ const changed = await runPure(pollTick(env), {
31
+ state: R.patchSync({ pollIdleStreak: 5 })(buildState([entry])),
32
+ handlers: {
33
+ 'remote.query': () => [ok([{ out: new RecordId('thing', '1'), version: 1 }]), ok({ rowCount: 1, state: 'ready' }), ok([])],
34
+ 'local.upsert': () => undefined,
35
+ },
36
+ });
37
+ expect(changed.state.sync.pollIdleStreak).toBe(0);
38
+ expect(changed.timers.get('poll')!.ms).toBe(500);
39
+ const quiet = await runPure(pollTick(env), {
40
+ state: R.patchSync({ pollIdleStreak: 1 })(buildState([entry])),
41
+ handlers: { 'remote.query': () => [ok([]), ok({ rowCount: 0, state: 'ready' }), ok([])], 'local.upsert': () => undefined },
42
+ });
43
+ expect(quiet.state.sync.pollIdleStreak).toBe(2);
44
+ expect(quiet.timers.get('poll')!.ms).toBe(2000);
45
+ const acked = await runPure(pollTick(env), {
46
+ state: buildState([entry], R.patchSync({ pollIdleStreak: 4 }), R.outboxReplace([buildOutboxItem({ status: 'acked', ackedAt: 1 })])),
47
+ handlers: { 'remote.query': () => [ok([]), ok({ rowCount: 0, state: 'ready' }), ok([])], 'local.upsert': () => undefined },
48
+ });
49
+ expect(acked.state.sync.pollIdleStreak).toBe(0);
50
+ });
51
+ });
@@ -0,0 +1,36 @@
1
+ import type { Saga } from '../kernel/saga';
2
+ import { fx } from '../kernel/effects';
3
+ import * as R from '../state/reducers';
4
+ import { activeHashes, hasAckedWrites } from '../state/selectors';
5
+ import type { SagaEnv } from '../query/env';
6
+ import { readMembership } from '../query/membership.saga';
7
+ import { listRefPollDelayMs } from './policy';
8
+
9
+ /**
10
+ * The `_00_list_ref` poll: the safety net under LIVE. Reads every active
11
+ * query's membership on a backoff that snaps to the base cadence whenever
12
+ * something changed (or an acked write still waits for membership) and
13
+ * coasts up to the cap while quiet. With no queries it probes connectivity.
14
+ */
15
+ export function* pollTick(env: SagaEnv): Saga<void> {
16
+ const [hashes, streak, acked] = (yield fx.state.read((s) => [activeHashes(s), s.sync.pollIdleStreak, hasAckedWrites(s)])) as [
17
+ string[],
18
+ number,
19
+ boolean,
20
+ ];
21
+ let changed = false;
22
+ if (hashes.length === 0) {
23
+ try {
24
+ yield fx.remote.query('RETURN true', undefined, env.remoteTimeoutMs);
25
+ yield fx.dispatch({ type: 'SyncOutcome', ok: true });
26
+ } catch (error) {
27
+ yield fx.dispatch({ type: 'SyncOutcome', ok: false, error });
28
+ }
29
+ } else {
30
+ const result = yield* readMembership(env, hashes);
31
+ changed = result.changed;
32
+ }
33
+ const idleStreak = changed || acked ? 0 : streak + 1;
34
+ yield fx.state.update(R.patchSync({ pollIdleStreak: idleStreak }));
35
+ yield fx.timer.set('poll', listRefPollDelayMs({ idleStreak, baseIntervalMs: env.pollBaseMs }), { type: 'PollTick' });
36
+ }
@@ -0,0 +1,78 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { runPure } from '../testing/run-pure';
3
+ import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
4
+ import * as R from '../state/reducers';
5
+ import { defaultEnv } from '../query/env';
6
+ import { setRole, tabMessage } from './tabs.saga';
7
+
8
+ const env = defaultEnv({ tables: [] } as any);
9
+
10
+ describe('setRole', () => {
11
+ it('leader: loads the outbox and starts live/poll/registrations; follower: stops its timers; same role is a no-op', async () => {
12
+ const leader = await runPure(setRole(env, 'leader'), { state: buildState(), handlers: { 'local.query': () => [] } });
13
+ expect(leader.state.tabRole).toBe('leader');
14
+ expect(leader.dispatched).toEqual([{ type: 'AdoptPendingWrites' }, { type: 'LiveStart' }, { type: 'PollTick' }, { type: 'EnsureRegistered' }]);
15
+ const follower = await runPure(setRole(env, 'follower'), { state: R.patchSync({ liveUuid: 'u' })(buildState()) });
16
+ expect(follower.state.tabRole).toBe('follower');
17
+ expect(follower.state.sync.liveUuid).toBeNull();
18
+ expect(follower.log.filter((e) => e.kind === 'timer.clear').map((e) => (e as any).key)).toEqual(['poll', 'outbox']);
19
+ const same = await runPure(setRole(env, 'solo'), { state: buildState() });
20
+ expect(same.log).toHaveLength(1);
21
+ });
22
+ });
23
+
24
+ describe('tabMessage', () => {
25
+ const s = () => buildState([buildEntry({ def: { hash: 'a', tableName: 'thing' } })], R.outboxReplace([buildOutboxItem({ id: 'm1', recordId: 'thing:1' })]));
26
+ it('ignores junk', async () => {
27
+ for (const junk of [null, 'x', {}, { type: 'weird' }, { type: 'ingest', records: [] }, { type: 'membership-dirty' }, { type: 'failed-mutations-changed' }]) {
28
+ const out = await runPure(tabMessage(env, junk), { state: s() });
29
+ expect(out.emitted).toEqual([]);
30
+ }
31
+ });
32
+ it('ingest: feeds the circuit, tracks versions, dirties tables; a failing ingest is logged', async () => {
33
+ const msg = {
34
+ type: 'ingest',
35
+ records: [
36
+ { table: 'thing', op: 'CREATE', id: 'thing:2', record: { _00_rv: 3 } },
37
+ { table: 'thing', op: 'DELETE', id: 'thing:1', record: {} },
38
+ { table: 'other', op: 'UPDATE', id: 'other:1', record: {} },
39
+ ],
40
+ };
41
+ const out = await runPure(tabMessage(env, msg), { state: R.setVersions([['thing:1', 1]])(s()), handlers: { 'ssp.ingest': () => undefined } });
42
+ expect(out.state.versions.get('thing:2')).toBe(3);
43
+ expect(out.state.versions.get('other:1')).toBe(0);
44
+ expect(out.state.versions.has('thing:1')).toBe(false);
45
+ expect(out.state.dirty.has('a')).toBe(true);
46
+ // A relayed delete (another tab's GC) may drop a body this tab names: the fetch plan decides.
47
+ expect(out.dispatched).toEqual([{ type: 'FetchRows' }]);
48
+ const writesOnly = await runPure(tabMessage(env, { ...msg, records: msg.records.filter((r) => r.op !== 'DELETE') }), { state: s(), handlers: { 'ssp.ingest': () => undefined } });
49
+ expect(writesOnly.dispatched).toEqual([]);
50
+ const failing = await runPure(tabMessage(env, msg), {
51
+ state: s(),
52
+ handlers: {
53
+ 'ssp.ingest': () => {
54
+ throw new Error('wasm');
55
+ },
56
+ },
57
+ });
58
+ expect(failing.emitted).toEqual([expect.objectContaining({ level: 'warn' })]);
59
+ });
60
+ it('membership-dirty, outbox-changed (leader only), settled, rolled-back, tray count', async () => {
61
+ const dirty = await runPure(tabMessage(env, { type: 'membership-dirty', hashes: ['a'] }), { state: { ...s(), tabRole: 'follower' } });
62
+ expect(dirty.state.membershipDirty.has('a')).toBe(true);
63
+ const ob = await runPure(tabMessage(env, { type: 'outbox-changed', mutationId: 'm' }), { state: { ...s(), tabRole: 'leader' }, handlers: { 'local.query': () => [] } });
64
+ expect(ob.log.some((e) => e.kind === 'local.query')).toBe(true);
65
+ const obFollower = await runPure(tabMessage(env, { type: 'outbox-changed', mutationId: 'm' }), { state: { ...s(), tabRole: 'follower' } });
66
+ expect(obFollower.log.some((e) => e.kind === 'local.query')).toBe(false);
67
+ const settled = await runPure(tabMessage(env, { type: 'mutation-settled', mutationId: 'm1', recordId: 'thing:1', eventType: 'create' }), { state: s(), now: 9 });
68
+ expect(settled.state.outbox[0]).toMatchObject({ status: 'acked', ackedAt: 9 });
69
+ expect(settled.emitted).toEqual([{ type: 'mutation:settled', mutationId: 'm1', recordId: 'thing:1', eventType: 'create' }]);
70
+ const rolled = await runPure(tabMessage(env, { type: 'mutation-rolled-back', mutationId: 'm1', recordId: 'thing:1', eventType: 'create', error: 'denied' }), { state: s() });
71
+ expect(rolled.state.outbox).toEqual([]);
72
+ expect(rolled.state.dirty.has('a')).toBe(true);
73
+ expect(rolled.emitted[0]).toMatchObject({ type: 'mutation:rolled-back', error: 'denied' });
74
+ const tray = await runPure(tabMessage(env, { type: 'failed-mutations-changed', count: 4 }), { state: s() });
75
+ expect(tray.state.failedCount).toBe(4);
76
+ expect(tray.emitted).toEqual([{ type: 'tray:changed', count: 4 }]);
77
+ });
78
+ });