@spooky-sync/core 0.0.1-canary.23 → 0.0.1-canary.230

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 (165) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2650 -58
  3. package/dist/index.js +12800 -2419
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +303 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +439 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +472 -0
  11. package/dist/types.d.ts +751 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +36 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/auth.local-first.test.ts +141 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +138 -25
  27. package/src/modules/cache/cache.relay.test.ts +95 -0
  28. package/src/modules/cache/index.ts +163 -43
  29. package/src/modules/cache/types.ts +2 -2
  30. package/src/modules/crdt/crdt-field.ts +294 -0
  31. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  32. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  33. package/src/modules/crdt/index.ts +463 -0
  34. package/src/modules/crdt/loro-loader.ts +25 -0
  35. package/src/modules/data/data.hydration.test.ts +142 -0
  36. package/src/modules/data/data.membership.test.ts +523 -0
  37. package/src/modules/data/data.notify-table.test.ts +41 -0
  38. package/src/modules/data/data.pending-ids.test.ts +199 -0
  39. package/src/modules/data/data.rebind.test.ts +170 -0
  40. package/src/modules/data/data.rematerialize.test.ts +114 -0
  41. package/src/modules/data/data.run.test.ts +113 -0
  42. package/src/modules/data/data.settled-writes.test.ts +235 -0
  43. package/src/modules/data/data.status.test.ts +249 -0
  44. package/src/modules/data/id-set-plan.test.ts +122 -0
  45. package/src/modules/data/index.ts +1861 -152
  46. package/src/modules/data/mutation-id.test.ts +25 -0
  47. package/src/modules/data/mutation-id.ts +35 -0
  48. package/src/modules/data/window-query.test.ts +52 -0
  49. package/src/modules/data/window-query.ts +194 -0
  50. package/src/modules/devtools/flags.ts +349 -0
  51. package/src/modules/devtools/index.ts +450 -46
  52. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  53. package/src/modules/devtools/state-shape.test.ts +146 -0
  54. package/src/modules/devtools/storage-info.test.ts +79 -0
  55. package/src/modules/devtools/storage-info.ts +168 -0
  56. package/src/modules/devtools/versions.test.ts +74 -0
  57. package/src/modules/devtools/versions.ts +110 -0
  58. package/src/modules/feature-flag/index.test.ts +251 -0
  59. package/src/modules/feature-flag/index.ts +308 -0
  60. package/src/modules/ref-tables.test.ts +91 -0
  61. package/src/modules/ref-tables.ts +88 -0
  62. package/src/modules/sync/engine.ts +165 -86
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  65. package/src/modules/sync/queue/queue-down.ts +108 -13
  66. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  67. package/src/modules/sync/queue/queue-up.ts +241 -57
  68. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  69. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  70. package/src/modules/sync/scheduler.ts +215 -13
  71. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  72. package/src/modules/sync/sync.health.test.ts +149 -0
  73. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  74. package/src/modules/sync/sync.live-removal.test.ts +175 -0
  75. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  76. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +93 -0
  77. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  78. package/src/modules/sync/sync.subquery.test.ts +82 -0
  79. package/src/modules/sync/sync.tabs.test.ts +249 -0
  80. package/src/modules/sync/sync.ts +1868 -98
  81. package/src/modules/sync/utils.test.ts +269 -2
  82. package/src/modules/sync/utils.ts +201 -16
  83. package/src/otel/index.ts +13 -10
  84. package/src/services/blobs/blob-cache.test.ts +359 -0
  85. package/src/services/blobs/blob-cache.ts +603 -0
  86. package/src/services/blobs/blob-manifest.ts +227 -0
  87. package/src/services/blobs/blob-store.test.ts +77 -0
  88. package/src/services/blobs/blob-store.ts +359 -0
  89. package/src/services/blobs/blob.fixture.ts +90 -0
  90. package/src/services/blobs/index.ts +70 -0
  91. package/src/services/database/cache-engine.ts +193 -0
  92. package/src/services/database/connection-supervisor.test.ts +289 -0
  93. package/src/services/database/connection-supervisor.ts +415 -0
  94. package/src/services/database/database.query-timeout.test.ts +83 -0
  95. package/src/services/database/database.ts +41 -12
  96. package/src/services/database/engine-factory.ts +33 -0
  97. package/src/services/database/errors.ts +34 -0
  98. package/src/services/database/events/index.ts +2 -1
  99. package/src/services/database/index.ts +7 -0
  100. package/src/services/database/local-migrator.ts +30 -27
  101. package/src/services/database/local.test.ts +64 -0
  102. package/src/services/database/local.ts +484 -67
  103. package/src/services/database/plan-render.test.ts +159 -0
  104. package/src/services/database/plan-render.ts +108 -0
  105. package/src/services/database/relation-resolver.test.ts +413 -0
  106. package/src/services/database/relation-resolver.ts +0 -0
  107. package/src/services/database/remote.ts +192 -15
  108. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  109. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  110. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  111. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  112. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  113. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  114. package/src/services/database/sqlite-lock-verify.ts +45 -0
  115. package/src/services/database/sqlite-open.test.ts +150 -0
  116. package/src/services/database/sqlite-open.ts +164 -0
  117. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  118. package/src/services/database/sqlite-plan-sql.ts +138 -0
  119. package/src/services/database/sqlite-projection.test.ts +99 -0
  120. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  121. package/src/services/database/sqlite-select.test.ts +246 -0
  122. package/src/services/database/sqlite-select.ts +131 -0
  123. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  124. package/src/services/database/sqlite-transport.ts +224 -0
  125. package/src/services/database/sqlite-worker.ts +437 -0
  126. package/src/services/database/surql-translate.ts +416 -0
  127. package/src/services/database/surreal-cache-engine.ts +161 -0
  128. package/src/services/logger/index.ts +3 -2
  129. package/src/services/persistence/localstorage.ts +2 -2
  130. package/src/services/persistence/resilient.ts +11 -4
  131. package/src/services/persistence/surrealdb.ts +10 -10
  132. package/src/services/stream-processor/index.ts +796 -84
  133. package/src/services/stream-processor/permissions.test.ts +47 -0
  134. package/src/services/stream-processor/permissions.ts +53 -0
  135. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  136. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  137. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  138. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  139. package/src/services/stream-processor/wasm-types.ts +59 -3
  140. package/src/services/tabs/broker-client.ts +283 -0
  141. package/src/services/tabs/broker.test.ts +327 -0
  142. package/src/services/tabs/coordinator.test.ts +365 -0
  143. package/src/services/tabs/coordinator.ts +633 -0
  144. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  145. package/src/services/tabs/leader-locks.ts +75 -0
  146. package/src/services/tabs/protocol.ts +258 -0
  147. package/src/services/tabs/support.ts +36 -0
  148. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  149. package/src/sp00ky.auth-order.test.ts +112 -0
  150. package/src/sp00ky.init-query.test.ts +183 -0
  151. package/src/sp00ky.local-first.test.ts +60 -0
  152. package/src/sp00ky.ts +1772 -0
  153. package/src/types.ts +528 -13
  154. package/src/utils/blurhash.ts +90 -0
  155. package/src/utils/error-classification.test.ts +44 -0
  156. package/src/utils/error-classification.ts +7 -0
  157. package/src/utils/index.ts +79 -13
  158. package/src/utils/parser.test.ts +49 -120
  159. package/src/utils/parser.ts +32 -2
  160. package/src/utils/semver.test.ts +32 -0
  161. package/src/utils/semver.ts +30 -0
  162. package/src/utils/surql.ts +30 -18
  163. package/src/utils/withRetry.test.ts +1 -1
  164. package/tsdown.config.ts +86 -1
  165. package/src/spooky.ts +0 -395
@@ -1,33 +1,217 @@
1
- import { LocalDatabaseService, RemoteDatabaseService } from '../../services/database/index';
2
- import { MutationEvent, RecordVersionArray } from '../../types';
1
+ import type {
2
+ ConnectionSupervisor,
3
+ LocalStore,
4
+ RemoteDatabaseService,
5
+ } from '../../services/database/index';
6
+ import type {
7
+ ConnectionState,
8
+ RecordVersionArray,
9
+ RecordVersionDiff,
10
+ SyncHealth,
11
+ SyncHealthStatus,
12
+ } from '../../types';
3
13
  import { createSyncEventSystem, SyncEventTypes, SyncQueueEventTypes } from './events/index';
4
- import { Logger } from '../../services/logger/index';
5
- import { DownEvent, DownQueue, UpEvent, UpQueue } from './queue/index';
6
- import { RecordId, Uuid } from 'surrealdb';
7
- import { ArraySyncer, createDiffFromDbOp } from './utils';
14
+ import type { Logger } from '../../services/logger/index';
15
+ import type { DownEvent, UpEvent } from './queue/index';
16
+ import { DownQueue, UpQueue } from './queue/index';
17
+ import type { RecordId, Uuid } from 'surrealdb';
18
+ import {
19
+ applyRecordVersionDiff,
20
+ ArraySyncer,
21
+ buildListRefSelect,
22
+ buildQueryRowCountSelect,
23
+ buildSubqueryListRefSelect,
24
+ createDiffFromDbOp,
25
+ diffRecordVersionArray,
26
+ listRefPollDelayMs,
27
+ recordVersionArraysEqual,
28
+ resolveListRefPollInterval,
29
+ } from './utils';
8
30
  import { SyncEngine } from './engine';
9
31
  import { SyncScheduler } from './scheduler';
10
- import { SchemaStructure } from '@spooky-sync/query-builder';
11
- import { CacheModule } from '../cache/index';
12
- import { DataModule } from '../data/index';
13
- import { encodeRecordId, extractTablePart, parseDuration, surql } from '../../utils/index';
32
+ import type { SchemaStructure } from '@spooky-sync/query-builder';
33
+ import type { CacheModule } from '../cache/index';
34
+ import type { DataModule } from '../data/index';
35
+ import {
36
+ classifySyncError,
37
+ encodeRecordId,
38
+ extractIdPart,
39
+ extractTablePart,
40
+ surql,
41
+ withTimeout,
42
+ } from '../../utils/index';
43
+ import { ANON_USER_ID, DEFAULT_REF_MODE, listRefTableFor, RefMode } from '../ref-tables';
44
+ import { mutationOwnerTabId } from '../data/mutation-id';
45
+ import type { LeaderSyncHub, SyncForwarder } from '../../services/tabs/coordinator';
46
+ import type { IngestTuple } from '../../services/tabs/protocol';
47
+ import { parseRecordIdString } from '../../utils/index';
14
48
 
15
49
  /**
16
- * The main synchronization engine for Spooky.
50
+ * Tunables for `Sp00kySync` construction.
51
+ */
52
+ export interface Sp00kySyncOptions {
53
+ /**
54
+ * Cadence (ms) for the `_00_list_ref` poll fallback that catches
55
+ * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
56
+ * values fall back to the default; see
57
+ * {@link resolveListRefPollInterval}.
58
+ */
59
+ refSyncIntervalMs?: number;
60
+ /**
61
+ * Enable realtime sync for unauthenticated clients against the shared
62
+ * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
63
+ * Defaults to `false`.
64
+ */
65
+ anonymousLiveQueries?: boolean;
66
+ /**
67
+ * Consecutive failed sync rounds before sync health flips to `degraded`.
68
+ * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
69
+ * Defaults to `3`.
70
+ */
71
+ degradeAfterConsecutiveFailures?: number;
72
+ /**
73
+ * Max time a single mutation push may take before it is treated as a network
74
+ * failure and retried. Guards against an RPC that never settles wedging the
75
+ * up-queue for the session. Defaults to 30000; `0` disables the timeout.
76
+ */
77
+ pushTimeoutMs?: number;
78
+ /**
79
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
80
+ * it is treated as a network failure and retried. The mirror of
81
+ * {@link pushTimeoutMs} for the read side, which had no such guard: a
82
+ * `fn::query::register` that never settled held its slot in the down drain,
83
+ * and every later registration behind it, for the rest of the session.
84
+ * Defaults to 30000; `0` disables the timeout.
85
+ */
86
+ downTimeoutMs?: number;
87
+ /**
88
+ * Transport supervisor. Sync reads its state to report `connection` in
89
+ * {@link SyncHealth} so a UI can show "reconnecting…" the instant the socket
90
+ * drops, without waiting for the degrade threshold. Optional: omitted in
91
+ * tests, where `connection` then reports `connected`.
92
+ */
93
+ connectionSupervisor?: ConnectionSupervisor;
94
+ }
95
+
96
+ /**
97
+ * The main synchronization engine for Sp00ky.
17
98
  * Handles the bidirectional synchronization between the local database and the remote backend.
18
99
  * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
19
100
  * @template S The schema structure type.
20
101
  */
21
- export class SpookySync<S extends SchemaStructure> {
22
- private clientId: string = '';
102
+ export class Sp00kySync<S extends SchemaStructure> {
23
103
  private upQueue: UpQueue;
24
104
  private downQueue: DownQueue;
25
105
  private isInit: boolean = false;
26
106
  private logger: Logger;
27
107
  private syncEngine: SyncEngine;
108
+ /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
109
+ * from `this.events`, which carries Sp00kySync-level events like
110
+ * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
111
+ public get engineEvents() {
112
+ return this.syncEngine.events;
113
+ }
28
114
  private scheduler: SyncScheduler;
115
+ /**
116
+ * Set by any event that means the socket we registered on is gone, so the
117
+ * next `connected` knows it must re-subscribe rather than treat itself as the
118
+ * initial connect. See {@link subscribeToReconnect}.
119
+ */
120
+ private needsResubscribe: boolean = false;
121
+ /** When the last reconnect-driven full refetch ran, for burst coalescing. */
122
+ private lastReconnectRefetchAt = 0;
123
+ /**
124
+ * Minimum gap between reconnect-driven full refetches. Long enough to absorb
125
+ * a flapping socket (the SDK reconnect ladder starts at 1s), short enough
126
+ * that a genuine drop minutes later still refetches.
127
+ */
128
+ private static readonly RECONNECT_REFETCH_COOLDOWN_MS = 10_000;
129
+ /** Poll interval while waiting for a reconnected session to re-authenticate. */
130
+ private static readonly AUTH_READY_RETRY_MS = 500;
131
+ /** Attempts before giving up on re-auth and skipping the refetch entirely. */
132
+ private static readonly AUTH_READY_MAX_ATTEMPTS = 10;
29
133
  public events = createSyncEventSystem();
30
134
 
135
+ // Auth identity that drives per-user `_00_list_ref_user_<id>` routing
136
+ // in `RefMode.Dedicated`. Updated by `setCurrentUserId` from the auth
137
+ // subscription in `Sp00kyClient`; null when unauthenticated.
138
+ private currentUserId: string | null = null;
139
+
140
+ // ---- shared-tabs role state ----
141
+ // Followers keep their own remote WS (registration, per-query sync, poll)
142
+ // but must never drain the shared outbox or hold a second list_ref LIVE.
143
+ // The leader relays its LIVE events and routes rollbacks by mutation owner.
144
+ private tabRole: 'solo' | 'leader' | 'follower' = 'solo';
145
+ private tabId: string | null = null;
146
+ private hub: LeaderSyncHub | null = null;
147
+ private forwarder: SyncForwarder | null = null;
148
+
149
+ private refMode: RefMode = DEFAULT_REF_MODE;
150
+
151
+ // When true, an unauthenticated client still runs the `_00_list_ref` poll
152
+ // and LIVE subscription, routed to the shared `_00_list_ref_anon` table, so
153
+ // a logged-out page gets realtime `useQuery` updates. Off by default.
154
+ private readonly anonLiveEnabled: boolean;
155
+
156
+ // Bookkeeping for the LIVE subscription on `_00_list_ref[_user_*]`.
157
+ // SurrealDB binds the permission context at LIVE-registration time and
158
+ // the table name in dedicated mode depends on the authenticated user,
159
+ // so we have to re-register whenever auth state flips.
160
+ private currentLiveQueryUuid: Uuid | null = null;
161
+ private liveQueryUnsubscribe: (() => void) | null = null;
162
+
163
+ // Periodic re-poll of `_00_list_ref` as a safety net for missed LIVE
164
+ // notifications. SurrealDB v3 occasionally drops LIVE deliveries
165
+ // across sessions even when the row matches the permission rule;
166
+ // this catches those without requiring users to reload. The
167
+ // interval is configurable via the constructor; see
168
+ // `resolveListRefPollInterval` for fallback semantics.
169
+ //
170
+ // Self-rescheduling rather than setInterval so each tick can pick
171
+ // its own delay via `nextPollDelayMs` — slows the poll down when
172
+ // LIVE is delivering events and speeds it back up when LIVE quiets.
173
+ private listRefPollTimer: ReturnType<typeof setTimeout> | null = null;
174
+ private listRefPollRunning: boolean = false;
175
+ // The currently-executing poll tick, if any. `stopListRefPoll` only stops
176
+ // future ticks; a bucket switch must also AWAIT the in-flight one so its
177
+ // local writes land in the store it started against.
178
+ private listRefPollInFlight: Promise<void> | null = null;
179
+ public readonly refSyncIntervalMs: number;
180
+
181
+ // Consecutive poll cycles that observed NO list_ref change. Drives the
182
+ // adaptive backoff in `startListRefPoll` via `listRefPollDelayMs`: an idle
183
+ // page coasts from the fast base cadence toward the 5s cap, and any activity
184
+ // (a poll-detected change or a LIVE event) resets it to 0 so the poll snaps
185
+ // back to responsive. Replaces the old LIVE-liveness backoff, which kept the
186
+ // poll pinned at 500ms forever whenever LIVE wasn't firing (the common case
187
+ // on a quiet page, thanks to the cross-session LIVE-permission gap).
188
+ private listRefIdleStreak: number = 0;
189
+
190
+ // `${queryHash}:${recordId}` -> consecutive rounds the id has been "still
191
+ // remote" (left the query's list_ref but still exists upstream). Used to
192
+ // distinguish a PERSISTENT view-membership disagreement (the `job:` churn,
193
+ // converged once it crosses the threshold) from a record that's merely
194
+ // mid-deletion (still-remote for ~one round, then gone) — which must NOT be
195
+ // converged, or it gets stranded in this window before its delete is observed.
196
+ private stillRemoteStreaks: Map<string, number> = new Map();
197
+
198
+ // Wall-clock timestamp (ms) of the most recent LIVE event delivered
199
+ // through `handleRemoteListRefChange`. Kept as a diagnostic / liveness
200
+ // signal; the poll cadence is now driven by `listRefIdleStreak`.
201
+ private lastLiveEventAt: number | null = null;
202
+
203
+ // Number of times the initial `_00_list_ref[_user_*]` LIVE subscription
204
+ // had to retry on `setCurrentUserId`. Stays at 0 when the SSP has
205
+ // pre-emptively created the user's dedicated tables; otherwise
206
+ // increments on each retry attempt until LIVE succeeds or attempts
207
+ // are exhausted. Surfaced as a diagnostic so the e2e suite can prove
208
+ // the pre-emptive table-creation path is keeping the first sign-in
209
+ // off the lazy-creation race.
210
+ private _liveRetryCount: number = 0;
211
+ public get liveRetryCount(): number {
212
+ return this._liveRetryCount;
213
+ }
214
+
31
215
  get isSyncing() {
32
216
  return this.scheduler.isSyncing;
33
217
  }
@@ -37,13 +221,11 @@ export class SpookySync<S extends SchemaStructure> {
37
221
  }
38
222
 
39
223
  subscribeToPendingMutations(cb: (count: number) => void): () => void {
40
- const id1 = this.upQueue.events.subscribe(
41
- SyncQueueEventTypes.MutationEnqueued,
42
- (event) => cb(event.payload.queueSize)
224
+ const id1 = this.upQueue.events.subscribe(SyncQueueEventTypes.MutationEnqueued, (event) =>
225
+ cb(event.payload.queueSize)
43
226
  );
44
- const id2 = this.upQueue.events.subscribe(
45
- SyncQueueEventTypes.MutationDequeued,
46
- (event) => cb(event.payload.queueSize)
227
+ const id2 = this.upQueue.events.subscribe(SyncQueueEventTypes.MutationDequeued, (event) =>
228
+ cb(event.payload.queueSize)
47
229
  );
48
230
  return () => {
49
231
  this.upQueue.events.unsubscribe(id1);
@@ -51,16 +233,239 @@ export class SpookySync<S extends SchemaStructure> {
51
233
  };
52
234
  }
53
235
 
236
+ // ---- Sync health -------------------------------------------------------
237
+ // `0` disables degraded reporting (config `syncHealth: false`). Resolved
238
+ // from config in Sp00kyClient and passed through the constructor options.
239
+ private readonly degradeAfterFailures: number;
240
+ /** Per-push RPC deadline; see {@link withPushTimeout}. */
241
+ private readonly pushTimeoutMs: number;
242
+ private readonly downTimeoutMs: number;
243
+ private consecutiveSyncFailures = 0;
244
+ private syncHealthStatus: SyncHealthStatus = 'healthy';
245
+ private lastSyncErrorKind: 'network' | 'application' | undefined;
246
+ private lastSyncErrorMessage: string | undefined;
247
+ // Latched `true` on the first successful sync round; never reset. Lets a UI
248
+ // tell a cold-start "connecting" phase (never reached the server) apart from
249
+ // a real lost connection after a working session.
250
+ private hasSyncedOnce = false;
251
+
252
+ // Self-heal: while degraded, re-drive sync on an exponential backoff so the
253
+ // app recovers on its own — even when the socket never actually dropped (in
254
+ // that case no `connected` event fires, so this re-registration is the ONLY
255
+ // thing that re-probes the server). Started on the degrade transition,
256
+ // cleared on recovery. Capped cadence so a long outage doesn't busy-loop.
257
+ private selfHealTimer: ReturnType<typeof setTimeout> | null = null;
258
+ private selfHealAttempts = 0;
259
+ private static readonly SELF_HEAL_BASE_MS = 2_000;
260
+ private static readonly SELF_HEAL_MAX_MS = 30_000;
261
+
262
+ /**
263
+ * Transport supervisor, when one was supplied. Sync only reads state from it;
264
+ * it never drives reconnects itself.
265
+ */
266
+ private readonly connectionSupervisor?: ConnectionSupervisor;
267
+ /**
268
+ * Mirror of the supervisor's state. Defaults to `connected` so a client
269
+ * constructed without a supervisor (tests, embedders) reports the same health
270
+ * shape it always has rather than a permanent false "disconnected".
271
+ */
272
+ private connectionState: ConnectionState = 'connected';
273
+
274
+ /** Current sync-health snapshot. */
275
+ get syncHealth(): SyncHealth {
276
+ return {
277
+ status: this.syncHealthStatus,
278
+ consecutiveFailures: this.consecutiveSyncFailures,
279
+ kind: this.syncHealthStatus === 'degraded' ? this.lastSyncErrorKind : undefined,
280
+ error: this.syncHealthStatus === 'degraded' ? this.lastSyncErrorMessage : undefined,
281
+ everConnected: this.hasSyncedOnce,
282
+ connection: this.connectionState,
283
+ };
284
+ }
285
+
286
+ /**
287
+ * Observe sync health. The callback fires immediately with the current
288
+ * status and again on every healthy↔degraded transition. Returns an
289
+ * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
290
+ */
291
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {
292
+ cb(this.syncHealth);
293
+ const id = this.events.subscribe(SyncEventTypes.SyncHealthChanged, (event) =>
294
+ cb(event.payload)
295
+ );
296
+ return () => this.events.unsubscribe(id);
297
+ }
298
+
299
+ private emitSyncHealth(): void {
300
+ this.events.emit(SyncEventTypes.SyncHealthChanged, this.syncHealth);
301
+ }
302
+
303
+ /**
304
+ * Mirror the supervisor's transport state into {@link SyncHealth} and emit on
305
+ * every change, so a UI can react to a dropped socket immediately instead of
306
+ * waiting for `degradeAfterFailures` failed rounds. `status` is untouched:
307
+ * a brief reconnect is not a degradation.
308
+ *
309
+ * No explicit unsubscribe: the supervisor is owned by the same client and
310
+ * drops all subscribers in its own `dispose()`, which `Sp00kyClient.close()`
311
+ * calls first.
312
+ */
313
+ private subscribeToConnectionState(): void {
314
+ if (!this.connectionSupervisor) return;
315
+ this.connectionSupervisor.subscribe((state) => {
316
+ if (this.connectionState === state) return;
317
+ this.connectionState = state;
318
+ this.emitSyncHealth();
319
+ });
320
+ }
321
+
322
+ /**
323
+ * Fed by the scheduler once per drained sync round. Individual failures are
324
+ * absorbed by the queue's retry; only a run of `degradeAfterFailures`
325
+ * consecutive failures flips the status to `degraded`, and the next clean
326
+ * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
327
+ * is 0).
328
+ */
329
+ private recordSyncOutcome(ok: boolean, error?: unknown): void {
330
+ if (this.degradeAfterFailures <= 0) return;
331
+ if (ok) {
332
+ // Latch first-ever success so a UI can drop the connecting phase. Set
333
+ // before the early return so a clean cold start (0 prior failures) counts.
334
+ this.hasSyncedOnce = true;
335
+ if (this.consecutiveSyncFailures === 0) return;
336
+ this.consecutiveSyncFailures = 0;
337
+ if (this.syncHealthStatus !== 'healthy') {
338
+ this.syncHealthStatus = 'healthy';
339
+ this.lastSyncErrorKind = undefined;
340
+ this.lastSyncErrorMessage = undefined;
341
+ this.stopSelfHeal();
342
+ this.logger.info(
343
+ { Category: 'sp00ky-client::Sp00kySync::syncHealth' },
344
+ 'Sync recovered; health back to healthy'
345
+ );
346
+ this.emitSyncHealth();
347
+ }
348
+ return;
349
+ }
350
+ this.consecutiveSyncFailures++;
351
+ this.lastSyncErrorKind = classifySyncError(error);
352
+ this.lastSyncErrorMessage = error instanceof Error ? error.message : String(error);
353
+ if (
354
+ this.syncHealthStatus !== 'degraded' &&
355
+ this.consecutiveSyncFailures >= this.degradeAfterFailures
356
+ ) {
357
+ this.syncHealthStatus = 'degraded';
358
+ this.logger.warn(
359
+ {
360
+ consecutiveFailures: this.consecutiveSyncFailures,
361
+ kind: this.lastSyncErrorKind,
362
+ error,
363
+ Category: 'sp00ky-client::Sp00kySync::syncHealth',
364
+ },
365
+ 'Sync degraded after sustained failures'
366
+ );
367
+ this.emitSyncHealth();
368
+ this.startSelfHeal();
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Begin self-heal retries (no-op if already running). Started on the
374
+ * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
375
+ */
376
+ private startSelfHeal(): void {
377
+ if (this.selfHealTimer !== null) return;
378
+ this.selfHealAttempts = 0;
379
+ this.scheduleSelfHeal();
380
+ }
381
+
382
+ private scheduleSelfHeal(): void {
383
+ const delay = Math.min(
384
+ Sp00kySync.SELF_HEAL_MAX_MS,
385
+ Sp00kySync.SELF_HEAL_BASE_MS * 2 ** this.selfHealAttempts
386
+ );
387
+ this.selfHealTimer = setTimeout(async () => {
388
+ this.selfHealTimer = null;
389
+ if (this.syncHealthStatus !== 'degraded') return;
390
+ this.selfHealAttempts++;
391
+ this.logger.debug(
392
+ {
393
+ attempt: this.selfHealAttempts,
394
+ delayMs: delay,
395
+ Category: 'sp00ky-client::Sp00kySync::selfHeal',
396
+ },
397
+ 'Self-heal: re-driving sync while degraded'
398
+ );
399
+ try {
400
+ // Retry whatever is still queued first; the failing op (register or
401
+ // mutation) was re-queued by the queue, so this re-probes the server
402
+ // and reports the outcome through the scheduler → recordSyncOutcome.
403
+ if (this.upQueue.size > 0) {
404
+ await this.scheduler.syncUp();
405
+ } else if (this.downQueue.size > 0) {
406
+ await this.scheduler.syncDown();
407
+ } else {
408
+ // Nothing queued (e.g. the failing op was rolled back + dropped):
409
+ // re-register active queries — mirroring the reconnect handler — so
410
+ // there's a concrete op whose success flips health. If there are no
411
+ // active queries either, probe connectivity directly.
412
+ // Same identity gate as the reconnect path: self-heal fires while
413
+ // sync is degraded, which is exactly when a session is most likely
414
+ // to have lost its `$auth`, and a register issued there stamps the
415
+ // view with an empty identity permanently. See
416
+ // `remoteAuthEstablished`.
417
+ const hashes = this.dataModule.getActiveQueryHashes();
418
+ const canRegister = hashes.length > 0 && (await this.remoteAuthEstablished());
419
+ if (canRegister) {
420
+ for (const hash of hashes) {
421
+ this.scheduler.enqueueDownEvent({ type: 'register', payload: { hash } });
422
+ }
423
+ await this.scheduler.syncDown();
424
+ } else {
425
+ await this.remote.query('RETURN true');
426
+ this.recordSyncOutcome(true);
427
+ }
428
+ }
429
+ } catch (err) {
430
+ // Only the direct connectivity probe can throw here (syncUp/syncDown
431
+ // swallow + self-report); treat a probe failure as another failed round.
432
+ this.recordSyncOutcome(false, err);
433
+ }
434
+ // Keep retrying until recovery. recordSyncOutcome(true) calls stopSelfHeal
435
+ // (clearing any pending timer), so only continue while still degraded.
436
+ if (this.syncHealthStatus === 'degraded') this.scheduleSelfHeal();
437
+ }, delay);
438
+ }
439
+
440
+ private stopSelfHeal(): void {
441
+ if (this.selfHealTimer !== null) {
442
+ clearTimeout(this.selfHealTimer);
443
+ this.selfHealTimer = null;
444
+ }
445
+ this.selfHealAttempts = 0;
446
+ }
447
+
448
+ /**
449
+ * Release a deregistered query's remote view immediately instead of leaving
450
+ * it to the TTL sweep. Off by default; see the reasoning in
451
+ * {@link cleanupQuery}. Kept as a field rather than deleted so the eager path
452
+ * can be re-enabled in a test once the subquery-body repair path exists.
453
+ */
454
+ private readonly releaseQueriesEagerly = false;
455
+
54
456
  constructor(
55
- private local: LocalDatabaseService,
457
+ private local: LocalStore,
56
458
  private remote: RemoteDatabaseService,
57
459
  private cache: CacheModule,
58
460
  private dataModule: DataModule<S>,
59
461
  private schema: S,
60
- logger: Logger
462
+ logger: Logger,
463
+ options?: Sp00kySyncOptions
61
464
  ) {
62
- this.logger = logger.child({ service: 'SpookySync' });
63
- this.upQueue = new UpQueue(this.local, this.logger);
465
+ this.logger = logger.child({ service: 'Sp00kySync' });
466
+ this.upQueue = new UpQueue(this.local, this.logger, (dropped) =>
467
+ this.onMutationDropped(dropped)
468
+ );
64
469
  this.downQueue = new DownQueue(this.local, this.logger);
65
470
  this.syncEngine = new SyncEngine(this.remote, this.cache, this.schema, this.logger);
66
471
  this.scheduler = new SyncScheduler(
@@ -69,43 +474,848 @@ export class SpookySync<S extends SchemaStructure> {
69
474
  this.processUpEvent.bind(this),
70
475
  this.processDownEvent.bind(this),
71
476
  this.logger,
72
- this.handleRollback.bind(this)
477
+ this.handleRollback.bind(this),
478
+ this.recordSyncOutcome.bind(this),
479
+ this.handleMutationSettled.bind(this)
73
480
  );
481
+ this.refSyncIntervalMs = resolveListRefPollInterval(options?.refSyncIntervalMs);
482
+ this.anonLiveEnabled = options?.anonymousLiveQueries ?? false;
483
+ this.degradeAfterFailures = Math.max(0, options?.degradeAfterConsecutiveFailures ?? 3);
484
+ this.pushTimeoutMs = Math.max(0, options?.pushTimeoutMs ?? 30_000);
485
+ this.downTimeoutMs = Math.max(0, options?.downTimeoutMs ?? 30_000);
486
+ this.connectionSupervisor = options?.connectionSupervisor;
74
487
  }
75
488
 
76
489
  /**
77
490
  * Initializes the synchronization system.
78
491
  * Starts the scheduler and initiates the initial sync cycles.
79
- * @param clientId The unique identifier for this client instance.
80
492
  * @throws Error if already initialized.
81
493
  */
82
- public async init(clientId: string) {
83
- if (this.isInit) throw new Error('SpookySync is already initialized');
84
- this.clientId = clientId;
494
+ public async init() {
495
+ if (this.isInit) throw new Error('Sp00kySync is already initialized');
85
496
  this.isInit = true;
86
- await this.scheduler.init();
87
- void this.scheduler.syncUp();
497
+ await this.scheduler.init({ loadOutbox: this.tabRole !== 'follower' });
498
+ // Boot is local-first now, so init() routinely runs BEFORE the socket is
499
+ // up. Treat that as "the socket we registered on is gone": otherwise the
500
+ // first `connected` takes the initial-connect branch, returns early, and
501
+ // never re-enqueues `register` for queries that registered while offline.
502
+ // They would still heal via the down-queue backoff, but slowly and only
503
+ // because every query happens to enqueue its own register.
504
+ if (this.remote.getStatus() !== 'connected') this.needsResubscribe = true;
505
+ this.subscribeToReconnect();
506
+ this.subscribeToConnectionState();
88
507
  void this.scheduler.syncUp();
89
508
  void this.scheduler.syncDown();
90
- void this.startRefLiveQueries();
509
+ // No initial LIVE subscription — wait for `setCurrentUserId` to fire
510
+ // from the auth subscription. In dedicated mode the table name
511
+ // depends on the authenticated user, and an unauthenticated
512
+ // subscription wouldn't match any of the per-user tables anyway.
513
+ //
514
+ // Exception: when anonymous live queries are enabled, start realtime now
515
+ // against the shared `_00_list_ref_anon` table so a logged-out client
516
+ // syncs immediately. `setCurrentUserId` re-points LIVE to the per-user
517
+ // table on sign-in. Guard on `currentUserId` because the auth callback can
518
+ // fire (and authenticate) before `init()` runs — don't clobber that back
519
+ // to the anon table. `setCurrentUserId(null)` is a no-op on first load
520
+ // (it's already null), so this is the only place anon realtime starts.
521
+ if (this.anonLiveEnabled && !this.currentUserId) {
522
+ this.startListRefPoll();
523
+ this.restartRefLiveQuery().catch((err) => {
524
+ this.logger.debug(
525
+ { err, Category: 'sp00ky-client::Sp00kySync::init' },
526
+ 'Anonymous ref LIVE start failed; relying on periodic poll fallback'
527
+ );
528
+ });
529
+ }
530
+ }
531
+
532
+ // ---- shared-tabs roles ------------------------------------------------------
533
+
534
+ /** Set BEFORE init(): shapes what init boots (a follower loads no outbox and
535
+ * never starts LIVE; its own registration/poll paths stay untouched). */
536
+ public setTabContext(role: 'solo' | 'leader' | 'follower', tabId: string | null): void {
537
+ this.tabRole = role;
538
+ this.tabId = tabId;
539
+ }
540
+
541
+ /** In-flight {@link resumeLeaderDuties}, so a second call joins the first
542
+ * instead of double-draining the outbox. */
543
+ private leaderDutiesInFlight: Promise<void> | null = null;
544
+
545
+ /** Resolves once the in-browser circuit has been primed from the local
546
+ * store. Every sync diff waits on it: diffing against an empty circuit
547
+ * classifies the whole working set as missing and re-downloads it. */
548
+ private primeGate: () => Promise<void> = () => Promise.resolve();
549
+ /** The prime we last waited on. `whenPrimed` hands out one promise per
550
+ * prime, so a new identity means a new prime (boot, bucket switch) ran. */
551
+ private settledPrime: Promise<void> | null = null;
552
+
553
+ setPrimeGate(gate: () => Promise<void>): void {
554
+ this.primeGate = gate;
555
+ this.settledPrime = null;
556
+ }
557
+
558
+ /**
559
+ * Leader WIRING only, and deliberately synchronous.
560
+ *
561
+ * The coordinator publishes the leader role and tells the broker
562
+ * `leader-ready` the moment the store is adopted, and the broker can mint a
563
+ * follower's ports on the very next tick. So the follower-message handler
564
+ * has to be live before this returns, or a mutation forwarded in that window
565
+ * is dropped. Everything that can block (outbox reload, LIVE restart) moved
566
+ * to {@link resumeLeaderDuties}: a promotion that waits on the network holds
567
+ * `leader-ready` back, and a broker whose leader never reports ready serves
568
+ * no follower ports and re-elects no one, which wedges the whole namespace.
569
+ */
570
+ public promoteToLeader(hub: LeaderSyncHub): void {
571
+ this.tabRole = 'leader';
572
+ this.hub = hub;
573
+ this.forwarder = null;
574
+ this.leaderDutiesInFlight = null;
575
+ hub.onFollowerMessage = (tabId, msg) => {
576
+ switch (msg.type) {
577
+ case 'sync-hello':
578
+ break;
579
+ case 'mutation-enqueued':
580
+ // A write is activity: snap the poll back to its base cadence so the
581
+ // membership for it lands fast even if LIVE drops the event.
582
+ this.listRefIdleStreak = 0;
583
+ void this.enqueueForwardedMutation(msg.mutationId);
584
+ break;
585
+ case 'ingest':
586
+ // A follower's optimistic write. The row is already in the shared
587
+ // store; feed this tab's circuit and fan it out to every OTHER
588
+ // follower, so the write shows up everywhere in one hop instead of
589
+ // after the server round-trip (which also depends on LIVE delivery).
590
+ this.applyRelayedIngest(msg.tuples);
591
+ hub.relayIngest(msg.tuples, tabId);
592
+ this.listRefIdleStreak = 0;
593
+ break;
594
+ case 'request-poll':
595
+ this.listRefIdleStreak = 0;
596
+ break;
597
+ }
598
+ };
599
+ }
600
+
601
+ /** Leader duties: drain the shared outbox, own the single list_ref LIVE,
602
+ * relay LIVE events and rollbacks to followers. Idempotent for a boot-time
603
+ * leader; a runtime promotion (failover) reloads the outbox, which now
604
+ * holds EVERY tab's rows, and restarts LIVE under this session. Runs in the
605
+ * background off the promotion path, so however long it takes (or if it
606
+ * never finishes) the tab is already a working leader. */
607
+ public resumeLeaderDuties(): Promise<void> {
608
+ if (this.leaderDutiesInFlight) return this.leaderDutiesInFlight;
609
+ const run = (async () => {
610
+ if (!this.isInit || this.tabRole !== 'leader') return;
611
+ await this.upQueue.loadFromDatabase();
612
+ void this.scheduler.syncUp();
613
+ if (this.currentUserId || this.anonLiveEnabled) {
614
+ this.startListRefPoll();
615
+ await this.restartRefLiveQuery().catch((err) => {
616
+ this.logger.warn(
617
+ { err, Category: 'sp00ky-client::Sp00kySync::resumeLeaderDuties' },
618
+ 'LIVE restart failed on promotion; poll fallback covers it'
619
+ );
620
+ });
621
+ }
622
+ })();
623
+ this.leaderDutiesInFlight = run;
624
+ return run.finally(() => {
625
+ if (this.leaderDutiesInFlight === run) this.leaderDutiesInFlight = null;
626
+ });
627
+ }
628
+
629
+ /** Follower duties: no outbox drain, no LIVE. Mutations forward to the
630
+ * leader; everything else (registration, per-query sync, poll) runs
631
+ * against this tab's own remote session as usual. */
632
+ public demoteToFollower(forwarder: SyncForwarder): void {
633
+ this.tabRole = 'follower';
634
+ this.hub = null;
635
+ this.forwarder = forwarder;
636
+ // A still-running resumeLeaderDuties self-cancels on its `tabRole` guard;
637
+ // drop the handle so a later re-promotion starts a fresh drain.
638
+ this.leaderDutiesInFlight = null;
639
+ void this.killRefLiveQuery();
640
+ forwarder.onLeaderMessage = (msg) => {
641
+ switch (msg.type) {
642
+ case 'ingest-relay':
643
+ this.applyRelayedIngest(msg.tuples);
644
+ break;
645
+ case 'mutation-settled':
646
+ // The leader pushed a write and deleted its outbox row from the
647
+ // shared store. Without this the row would leave this tab's render
648
+ // set (it is in neither membership nor pending writes) until the
649
+ // relayed `_00_list_ref` event lands: the blink the leader itself
650
+ // is already protected from by `handleMutationSettled`.
651
+ this.dataModule.noteWriteSettled(msg.recordId, msg.eventType);
652
+ break;
653
+ case 'list-ref-change':
654
+ void this.applyRelayedListRefChange(msg).catch((err) => {
655
+ this.logger.error(
656
+ { err, Category: 'sp00ky-client::Sp00kySync::relay' },
657
+ 'Relayed list_ref change failed'
658
+ );
659
+ });
660
+ break;
661
+ case 'mutation-rolled-back':
662
+ this.events.emit(SyncEventTypes.MutationRolledBack, {
663
+ eventType: msg.eventType,
664
+ recordId: msg.recordId,
665
+ error: msg.error,
666
+ });
667
+ break;
668
+ default:
669
+ // db-ready is consumed by the coordinator's attach handshake before
670
+ // the sync handler is installed.
671
+ break;
672
+ }
673
+ };
674
+ }
675
+
676
+ /**
677
+ * A pending mutation was discarded because it can never be sent.
678
+ *
679
+ * This is a lost write, so it must not stay invisible. Every failure in this
680
+ * chain used to be a `logger.error` an app running `logLevel: 'fatal'` never
681
+ * shows, which is how an outbox could sit undrained for hours with the UI
682
+ * reporting nothing. Surfaces as a rollback event (the mutation will never
683
+ * apply, which is what a subscriber needs to know) and degrades sync health.
684
+ */
685
+ private onMutationDropped(dropped: {
686
+ mutationId: string;
687
+ recordId?: string;
688
+ mutationType?: string;
689
+ reason: string;
690
+ }): void {
691
+ this.logger.error(
692
+ { ...dropped, Category: 'sp00ky-client::Sp00kySync::onMutationDropped' },
693
+ 'Dropped a pending mutation that can never be sent'
694
+ );
695
+ this.recordSyncOutcome(false, new Error(`dropped mutation: ${dropped.reason}`));
696
+ this.events.emit(SyncEventTypes.MutationRolledBack, {
697
+ eventType: (dropped.mutationType as 'create' | 'update' | 'delete') ?? 'update',
698
+ recordId: dropped.recordId ?? dropped.mutationId,
699
+ error: `dropped: ${dropped.reason}`,
700
+ });
701
+ }
702
+
703
+ /** A forwarded outbox row from a follower: load + drain it. Idempotent. */
704
+ public async enqueueForwardedMutation(mutationId: string): Promise<void> {
705
+ if (this.tabRole !== 'leader') return;
706
+ await this.upQueue.enqueueFromDatabase(mutationId);
707
+ }
708
+
709
+ /**
710
+ * Tuples another tab already committed to the shared store: feed them to
711
+ * THIS tab's circuit (no local write). A DELETE additionally forces a
712
+ * re-materialize of the table's queries, exactly as the writing tab does
713
+ * for itself, because the SSP may not emit a view update for it.
714
+ */
715
+ private applyRelayedIngest(tuples: IngestTuple[]): void {
716
+ this.cache.applyRelayedIngest(tuples);
717
+ const deletedTables = new Set<string>();
718
+ for (const t of tuples) if (t.op === 'DELETE') deletedTables.add(t.table);
719
+ for (const table of deletedTables) {
720
+ void this.dataModule.notifyTableQueries(table).catch((err) => {
721
+ this.logger.warn(
722
+ { err, table, Category: 'sp00ky-client::Sp00kySync::applyRelayedIngest' },
723
+ 'Re-materialize after relayed delete failed'
724
+ );
725
+ });
726
+ }
727
+ }
728
+
729
+ /** A relayed `_00_list_ref` LIVE event: resolve against THIS tab's queries
730
+ * and run the exact same handling the LIVE subscription would have. */
731
+ private async applyRelayedListRefChange(msg: {
732
+ action: 'CREATE' | 'UPDATE' | 'DELETE';
733
+ queryId: string;
734
+ recordId: string;
735
+ version: number;
736
+ parent: boolean;
737
+ }): Promise<void> {
738
+ const queryId = parseRecordIdString(msg.queryId);
739
+ // Foreign query (another tab's session-salted hash): not ours, ignore.
740
+ if (!this.dataModule.getQueryById(queryId)) return;
741
+ const recordId = parseRecordIdString(msg.recordId);
742
+ if (msg.parent) {
743
+ await this.handleRemoteSubqueryChange(msg.action, queryId, recordId, msg.version);
744
+ } else {
745
+ await this.handleRemoteListRefChange(msg.action, queryId, recordId, msg.version);
746
+ }
747
+ }
748
+
749
+ /** One immediate poll cycle (failover convergence). */
750
+ public async forcePollRound(): Promise<void> {
751
+ this.listRefIdleStreak = 0;
752
+ await this.pollListRefForActiveQueries().catch(() => false);
753
+ }
754
+
755
+ /**
756
+ * Quiesce all sync activity ahead of a local-bucket switch. After this
757
+ * resolves, nothing in the sync module writes to the local store: the poll
758
+ * loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
759
+ * timers are cancelled (their outbox rows are already persisted), and the
760
+ * scheduler has drained its in-flight queue item — including that item's
761
+ * outbox-row delete, which must land in the OLD bucket. Queued down-events
762
+ * are dropped (they reference old-bucket query rows; the post-switch rebind
763
+ * re-enqueues registrations). The old user's un-pushed outbox is deliberately
764
+ * NOT drained: the remote session already belongs to the next user.
765
+ */
766
+ public async prepareBucketSwitch(): Promise<void> {
767
+ this.stopSelfHeal();
768
+ this.stopListRefPoll();
769
+ if (this.listRefPollInFlight) await this.listRefPollInFlight;
770
+ await this.killRefLiveQuery();
771
+ this.upQueue.clearDebounceTimers();
772
+ await this.scheduler.pause();
773
+ this.downQueue.clear();
774
+ this.stillRemoteStreaks.clear();
775
+ this.logger.info(
776
+ { Category: 'sp00ky-client::Sp00kySync::prepareBucketSwitch' },
777
+ 'Sync quiesced for bucket switch'
778
+ );
779
+ }
780
+
781
+ /**
782
+ * Resume syncing against the freshly-opened bucket: reload the mutation
783
+ * outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
784
+ * offline work) and restart the scheduler. LIVE + the list_ref poll restart
785
+ * via the `setCurrentUserId` call that follows in the auth listener.
786
+ */
787
+ public async completeBucketSwitch(): Promise<void> {
788
+ await this.upQueue.loadFromDatabase();
789
+ this.scheduler.resume();
790
+ this.logger.info(
791
+ { Category: 'sp00ky-client::Sp00kySync::completeBucketSwitch' },
792
+ 'Sync resumed after bucket switch'
793
+ );
794
+ }
795
+
796
+ /**
797
+ * Push the authenticated user's record id from the parent client's
798
+ * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
799
+ * any) and re-registers it under the new user's dedicated table so
800
+ * SurrealDB binds the permission rule under the post-flip auth
801
+ * context. Pass `null` on sign-out.
802
+ *
803
+ * The dedicated `_00_list_ref_user_<id>` table is created lazily by
804
+ * the SSP when the first query registration arrives, which may be
805
+ * concurrent with this call. We retry the LIVE registration with a
806
+ * short backoff so a "table not found" race resolves without
807
+ * surfacing as a permanent auth-loading hang.
808
+ */
809
+ public async setCurrentUserId(userId: string | null): Promise<void> {
810
+ if (this.currentUserId === userId) return;
811
+ this.currentUserId = userId;
812
+ if (!userId) {
813
+ if (this.anonLiveEnabled) {
814
+ // Signed out but anonymous realtime is on: keep the poll running and
815
+ // re-point LIVE from the (now stale) per-user table to the shared
816
+ // `_00_list_ref_anon`. `startListRefPoll` is idempotent; the poll
817
+ // re-resolves `listRefTable()` each tick so it follows automatically.
818
+ this.startListRefPoll();
819
+ await this.restartRefLiveQuery().catch((err) => {
820
+ this.logger.debug(
821
+ { err, Category: 'sp00ky-client::Sp00kySync::setCurrentUserId' },
822
+ 'Anonymous ref LIVE restart failed; relying on periodic poll fallback'
823
+ );
824
+ });
825
+ return;
826
+ }
827
+ await this.killRefLiveQuery();
828
+ this.stopListRefPoll();
829
+ return;
830
+ }
831
+ // Start periodic polling FIRST so we have a deterministic fallback
832
+ // even when LIVE registration fails or SurrealDB drops a delivery.
833
+ this.startListRefPoll();
834
+ // Try to start LIVE with backoff for low-latency delivery on the
835
+ // happy path; the poll handles the rest.
836
+ const attemptDelays = [0, 250, 500, 1000, 2000];
837
+ for (let i = 0; i < attemptDelays.length; i++) {
838
+ if (attemptDelays[i] > 0) {
839
+ this._liveRetryCount++;
840
+ await new Promise((r) => setTimeout(r, attemptDelays[i]));
841
+ }
842
+ try {
843
+ await this.restartRefLiveQuery();
844
+ return;
845
+ } catch (err) {
846
+ this.logger.debug(
847
+ { err, attempt: i + 1, Category: 'sp00ky-client::Sp00kySync::setCurrentUserId' },
848
+ 'Ref LIVE start failed; relying on periodic poll fallback'
849
+ );
850
+ }
851
+ }
852
+ }
853
+
854
+ private startListRefPoll(): void {
855
+ if (this.listRefPollRunning) return;
856
+ this.listRefPollRunning = true;
857
+ this.logger.debug(
858
+ {
859
+ intervalMs: this.refSyncIntervalMs,
860
+ Category: 'sp00ky-client::Sp00kySync::startListRefPoll',
861
+ },
862
+ 'list_ref poll loop started'
863
+ );
864
+ const schedule = (delayMs: number) => {
865
+ this.listRefPollTimer = setTimeout(async () => {
866
+ if (!this.listRefPollRunning) return;
867
+ let changed = false;
868
+ const tick = (async () => {
869
+ changed = await this.pollListRefForActiveQueries();
870
+ })();
871
+ this.listRefPollInFlight = tick.catch(() => {});
872
+ try {
873
+ await tick;
874
+ } finally {
875
+ this.listRefPollInFlight = null;
876
+ if (!this.listRefPollRunning) return;
877
+ // Reset the idle streak on any observed change so the poll snaps
878
+ // back to the fast base cadence; otherwise grow it so a quiet page
879
+ // backs off toward the cap. (`handleRemoteListRefChange` also resets
880
+ // it when a LIVE event lands.) A settled write still waiting for its
881
+ // membership also pins the fast cadence: the row is on borrowed time
882
+ // (the settled-write grace), so the edge must be found on the first
883
+ // poll after it lands, not after the backoff has grown to the cap.
884
+ const awaitingMembership = this.dataModule.hasSettledWritesPending();
885
+ this.listRefIdleStreak = changed || awaitingMembership ? 0 : this.listRefIdleStreak + 1;
886
+ const next = listRefPollDelayMs({
887
+ idleStreak: this.listRefIdleStreak,
888
+ baseIntervalMs: this.refSyncIntervalMs,
889
+ });
890
+ schedule(next);
891
+ }
892
+ }, delayMs);
893
+ };
894
+ schedule(this.refSyncIntervalMs);
895
+ }
896
+
897
+ private stopListRefPoll(): void {
898
+ this.listRefPollRunning = false;
899
+ if (this.listRefPollTimer !== null) {
900
+ clearTimeout(this.listRefPollTimer);
901
+ this.listRefPollTimer = null;
902
+ }
903
+ }
904
+
905
+ /**
906
+ * One poll cycle: refetch `_00_list_ref` for every active query. Returns
907
+ * whether ANY query's remoteArray actually changed — the scheduler uses this
908
+ * to drive the adaptive idle backoff.
909
+ *
910
+ * Also the ONLY health signal that runs while the page is idle. Sync health is
911
+ * otherwise activity-driven (mutations/registrations via the scheduler,
912
+ * reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
913
+ * would linger until the next mutation and a genuine idle drop would be
914
+ * invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
915
+ * so idle health self-recovers (and self-degrades) with no user action. A clean
916
+ * cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
917
+ * `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
918
+ */
919
+ private async pollListRefForActiveQueries(): Promise<boolean> {
920
+ const hashes = this.dataModule.getActiveQueryHashes();
921
+ if (hashes.length === 0) {
922
+ // No active queries to piggyback on, but health still needs a heartbeat —
923
+ // probe connectivity directly so an idle page with no live queries doesn't
924
+ // go blind. Cheap, and gated by the same adaptive backoff (≤5s idle cap).
925
+ try {
926
+ await this.remote.query('RETURN true');
927
+ this.recordSyncOutcome(true);
928
+ } catch (err) {
929
+ this.recordSyncOutcome(false, err);
930
+ }
931
+ return false;
932
+ }
933
+ let anyChanged = false;
934
+ // `reached` = the server answered at least once this cycle (a success, or an
935
+ // *application* error, which still proves reachability). `firstNetworkErr`
936
+ // holds the first network-classified failure. A cycle that only produced
937
+ // network errors reports the outcome as a down round; a mixed/app cycle counts
938
+ // as reached; an all-application cycle reports nothing (that's a query-shape
939
+ // fault owned by the registration path, not a reachability signal).
940
+ let reached = false;
941
+ let firstNetworkErr: unknown;
942
+ for (const hash of hashes) {
943
+ try {
944
+ if (await this.refetchListRefForQuery(hash)) anyChanged = true;
945
+ reached = true;
946
+ } catch (err) {
947
+ if (classifySyncError(err) === 'network') {
948
+ if (firstNetworkErr === undefined) firstNetworkErr = err;
949
+ } else {
950
+ reached = true;
951
+ }
952
+ this.logger.debug(
953
+ {
954
+ err: (err as Error)?.message ?? err,
955
+ hash,
956
+ Category: 'sp00ky-client::Sp00kySync::pollListRefForActiveQueries',
957
+ },
958
+ 'Per-query list_ref poll failed'
959
+ );
960
+ }
961
+ }
962
+ // Call the private outcome recorder directly rather than routing through the
963
+ // scheduler — the scheduler only reports on rounds that drained ≥1 queue item
964
+ // (`processedAny`), and this isn't a queue round.
965
+ if (reached) {
966
+ this.recordSyncOutcome(true);
967
+ } else if (firstNetworkErr !== undefined) {
968
+ this.recordSyncOutcome(false, firstNetworkErr);
969
+ }
970
+ return anyChanged;
971
+ }
972
+
973
+ /**
974
+ * Pull the upstream list_ref entries for `queryHash`, diff them
975
+ * against the local `remoteArray` cache, sync any added/updated rows
976
+ * through the SyncEngine, then persist the new remoteArray. This is
977
+ * the same shape `createRemoteQuery` does for its initial fetch and
978
+ * what `handleRemoteListRefChange` does per-LIVE-event — we reuse
979
+ * it on a timer as a fallback for missed LIVE notifications.
980
+ */
981
+ private async refetchListRefForQuery(queryHash: string): Promise<boolean> {
982
+ const queryState = this.dataModule.getQueryByHash(queryHash);
983
+ if (!queryState) return false;
984
+ const listRefTbl = this.listRefTable();
985
+ const [items, serverRowCount] = await this.remote.query<
986
+ [{ out: RecordId<string>; version: number }[], number | null]
987
+ >(`${buildListRefSelect(listRefTbl)};\n${buildQueryRowCountSelect()}`, {
988
+ in: queryState.config.id,
989
+ });
990
+ if (!Array.isArray(items)) return false;
991
+ const fresh: RecordVersionArray = items.map((item) => [encodeRecordId(item.out), item.version]);
992
+ // Capture which ids LEFT the query's window (present in the cached
993
+ // remoteArray, absent from `fresh`) BEFORE we overwrite remoteArray — these
994
+ // are cross-window deletes (or rows that scrolled out). They drive the
995
+ // forced re-render below.
996
+ const prevRemote = queryState.config.remoteArray ?? [];
997
+ const freshIds = new Set(fresh.map(([id]) => id));
998
+ const removedIds = prevRemote.filter(([id]) => !freshIds.has(id)).map(([id]) => id);
999
+ // Idempotent poll: only persist the remoteArray when it actually changed.
1000
+ // The poll runs continuously as a LIVE fallback, so on a quiet page `fresh`
1001
+ // equals the cached array every tick — re-writing it (an `UPDATE _00_query`
1002
+ // each cycle, per active query) was pure churn and the bulk of the idle
1003
+ // traffic. `recordVersionArraysEqual` is order-insensitive because the
1004
+ // list_ref SELECT has no `ORDER BY`.
1005
+ const changed = !recordVersionArraysEqual(fresh, queryState.config.remoteArray);
1006
+ if (changed) {
1007
+ // Update the cached remoteArray so the next diff/sync sees the new state.
1008
+ // `syncQuery` (below) then writes through `cache.saveBatch`, which UPSERTs
1009
+ // the local DB row and ingests it into the in-browser SSP — the SSP's
1010
+ // stream updates run `processStreamUpdate`, which re-queries the local DB
1011
+ // and notifies subscribers. We skip an explicit `notifyQuerySynced`
1012
+ // because that path races the stream-update path (can notify with stale
1013
+ // records).
1014
+ await this.dataModule.updateQueryRemoteArray(queryHash, fresh, { serverRowCount });
1015
+ }
1016
+ // Run `syncQuery` every tick regardless: it's a no-op when localArray has
1017
+ // caught up to remoteArray (`if (!diff) return`, issues no query), but it
1018
+ // covers the rare case where remoteArray is stable yet localArray is behind
1019
+ // (a prior record fetch failed) — so a missed row still gets retried.
1020
+ // For REMOVALS it runs the ids through `handleRemovedRecords`, which deletes
1021
+ // confirmed-gone records from the local DB.
1022
+ try {
1023
+ await this.syncQuery(queryHash);
1024
+ } catch (err) {
1025
+ this.logger.info(
1026
+ {
1027
+ err: (err as Error)?.message ?? err,
1028
+ queryHash,
1029
+ Category: 'sp00ky-client::Sp00kySync::refetchListRefForQuery',
1030
+ },
1031
+ 'syncQuery failed during poll'
1032
+ );
1033
+ }
1034
+ // Membership moved but a row may have needed no fetch (this client wrote
1035
+ // it, so the engine already holds it at the published version): nothing
1036
+ // then re-materializes the query. Ask for one; it is a no-op behind a
1037
+ // stream update that a fetch above already queued.
1038
+ if (changed) this.dataModule.scheduleRematerialize(queryHash);
1039
+ // Cross-session fallback for `.related()` child rows: the LIVE-permission
1040
+ // gap can drop child-edge notifications, so converge their bodies on the
1041
+ // poll too (idempotent — no-op when nothing changed).
1042
+ await this.syncSubqueryChildren(queryHash).catch((err) => {
1043
+ this.logger.info(
1044
+ {
1045
+ err: (err as Error)?.message ?? err,
1046
+ queryHash,
1047
+ Category: 'sp00ky-client::Sp00kySync::refetchListRefForQuery',
1048
+ },
1049
+ 'Subquery child sync failed during poll'
1050
+ );
1051
+ });
1052
+ // A REMOVAL needs no record fetch, so unlike the added-row path it doesn't
1053
+ // get a re-render from the SSP stream on this code path reliably (and the
1054
+ // non-windowed window-0 query re-queries the local DB rather than the id-set).
1055
+ // Force a re-materialize + notify so the deleted row drops from the list in
1056
+ // this (second) window — the reliable, LIVE-independent cross-window path.
1057
+ if (removedIds.length > 0) {
1058
+ try {
1059
+ await this.dataModule.notifyQuerySynced(queryHash);
1060
+ } catch (err) {
1061
+ this.logger.info(
1062
+ {
1063
+ err: (err as Error)?.message ?? err,
1064
+ queryHash,
1065
+ Category: 'sp00ky-client::Sp00kySync::refetchListRefForQuery',
1066
+ },
1067
+ 'notifyQuerySynced failed during poll-removal re-render'
1068
+ );
1069
+ }
1070
+ }
1071
+ return changed;
1072
+ }
1073
+
1074
+ /**
1075
+ * Resolve the current `_00_list_ref` table name for the active auth
1076
+ * context. Public so the `createRemoteQuery` initial-fetch path can
1077
+ * read from the right per-user table.
1078
+ *
1079
+ * Reads the user id from `DataModule` rather than the local mirror,
1080
+ * because `DataModule.setCurrentUserId` runs synchronously from the
1081
+ * auth callback (before any `await`), whereas `sync.setCurrentUserId`
1082
+ * is async — the userQuery's initial fetch can fire between those
1083
+ * two points and we need the correct table name immediately.
1084
+ */
1085
+ public listRefTable(): string {
1086
+ const userId = this.dataModule.getCurrentUserId();
1087
+ // Unauthenticated with the flag on → the shared `_00_list_ref_anon` table.
1088
+ if (userId == null && this.anonLiveEnabled) {
1089
+ return listRefTableFor(this.refMode, ANON_USER_ID);
1090
+ }
1091
+ return listRefTableFor(this.refMode, userId);
1092
+ }
1093
+
1094
+ private async killRefLiveQuery(): Promise<void> {
1095
+ if (this.liveQueryUnsubscribe) {
1096
+ try {
1097
+ this.liveQueryUnsubscribe();
1098
+ } catch {
1099
+ /* ignore */
1100
+ }
1101
+ this.liveQueryUnsubscribe = null;
1102
+ }
1103
+ if (this.currentLiveQueryUuid !== null) {
1104
+ // A LIVE subscription is scoped to its WebSocket session, so after a
1105
+ // reconnect the server-side one is already gone and there is nothing to
1106
+ // KILL. Sending it anyway either fails (no connection) or races the fresh
1107
+ // socket's readiness while holding up the restart behind it. Local
1108
+ // bookkeeping is cleared either way.
1109
+ if (this.remote.getStatus() === 'connected') {
1110
+ try {
1111
+ await this.remote.query('KILL $u', { u: this.currentLiveQueryUuid });
1112
+ } catch (err) {
1113
+ this.logger.debug(
1114
+ { err, Category: 'sp00ky-client::Sp00kySync::killRefLiveQuery' },
1115
+ 'Prior LIVE KILL failed; continuing'
1116
+ );
1117
+ }
1118
+ }
1119
+ this.currentLiveQueryUuid = null;
1120
+ }
1121
+ }
1122
+
1123
+ private async restartRefLiveQuery(): Promise<void> {
1124
+ await this.killRefLiveQuery();
1125
+ await this.startRefLiveQueries();
1126
+ }
1127
+
1128
+ /**
1129
+ * Drop local LIVE bookkeeping without issuing a `KILL`.
1130
+ *
1131
+ * Called when the socket dies. The server-side subscription is scoped to that
1132
+ * WebSocket session and died with it, so there is nothing left to kill — and
1133
+ * by the time the reconnect handler runs, the client reports `connected`
1134
+ * again, which would otherwise send a `KILL` for a stale uuid on the *new*
1135
+ * session and hold up the restart queued behind it.
1136
+ */
1137
+ private invalidateRefLiveQuery(): void {
1138
+ if (this.liveQueryUnsubscribe) {
1139
+ try {
1140
+ this.liveQueryUnsubscribe();
1141
+ } catch {
1142
+ /* ignore */
1143
+ }
1144
+ this.liveQueryUnsubscribe = null;
1145
+ }
1146
+ this.currentLiveQueryUuid = null;
1147
+ }
1148
+
1149
+ // Only the connect that follows a prior drop counts as a reconnect; the
1150
+ // initial connect after init() must not trigger a refetch storm.
1151
+ //
1152
+ // Both drop events have to be watched. The SDK publishes `disconnected` ONLY
1153
+ // when it has given up entirely (attempts exhausted, or the engine
1154
+ // terminated); an ordinary recovered drop goes `error` -> `reconnecting` ->
1155
+ // `connected` and never touches `disconnected`. Listening for `disconnected`
1156
+ // alone therefore misses every successful reconnect — the exact case this
1157
+ // handler exists for — and leaves the dead server-side LIVE in place with the
1158
+ // poll as the only sync path.
1159
+ private subscribeToReconnect() {
1160
+ const client = this.remote.getClient();
1161
+ client.subscribe('disconnected', () => {
1162
+ this.needsResubscribe = true;
1163
+ this.invalidateRefLiveQuery();
1164
+ this.logger.info(
1165
+ { Category: 'sp00ky-client::Sp00kySync::onDisconnect' },
1166
+ 'Remote disconnected'
1167
+ );
1168
+ });
1169
+ client.subscribe('reconnecting', () => {
1170
+ this.needsResubscribe = true;
1171
+ this.invalidateRefLiveQuery();
1172
+ this.logger.info(
1173
+ { Category: 'sp00ky-client::Sp00kySync::onReconnecting' },
1174
+ 'Remote socket dropped; awaiting reconnect'
1175
+ );
1176
+ });
1177
+ client.subscribe('connected', () => {
1178
+ if (!this.needsResubscribe) return;
1179
+ this.needsResubscribe = false;
1180
+ // A flapping socket produces reconnecting -> connected repeatedly, and
1181
+ // each cycle used to re-register EVERY active query (a busy app has
1182
+ // dozens). That is the "everything reloads about a second after a blip"
1183
+ // symptom: the SDK's retryDelay is 1s, so the refetch lands right after
1184
+ // the drop the user never saw. Collapse bursts into one refetch.
1185
+ const sinceLast = Date.now() - this.lastReconnectRefetchAt;
1186
+ if (sinceLast < Sp00kySync.RECONNECT_REFETCH_COOLDOWN_MS) {
1187
+ this.logger.debug(
1188
+ { sinceLast, Category: 'sp00ky-client::Sp00kySync::onReconnect' },
1189
+ 'Reconnected again within the cooldown; skipping duplicate refetch'
1190
+ );
1191
+ return;
1192
+ }
1193
+ this.lastReconnectRefetchAt = Date.now();
1194
+ void this.refetchAfterReconnect();
1195
+ });
1196
+ }
1197
+
1198
+ /**
1199
+ * Whether the REMOTE SESSION currently carries `$auth.id`.
1200
+ *
1201
+ * Not the same question as `currentUserId`, and that gap is the whole point:
1202
+ * `currentUserId` is this client's own record of who signed in and survives a
1203
+ * socket drop untouched, while `$auth` lives on the WebSocket session and has
1204
+ * to be re-applied after every reconnect. Registering in the window between
1205
+ * the two is silently destructive, because `fn::query::register` sends
1206
+ * `<string>($auth.id OR '')` and the SSP stores that value write-once: the
1207
+ * view's edges then route to the global `_00_list_ref` stamped `auth_id = ''`,
1208
+ * which that table's own permission rule (`auth_id = $auth.id`) makes
1209
+ * unreadable to the very user who registered it.
1210
+ *
1211
+ * Signed-out clients answer `true`: `''` is the honest identity there, not a
1212
+ * race.
1213
+ */
1214
+ private async remoteAuthEstablished(): Promise<boolean> {
1215
+ if (!this.currentUserId) return true;
1216
+ try {
1217
+ const result = await this.remote.query<[string]>("RETURN <string>($auth.id OR '')");
1218
+ const authId = Array.isArray(result) ? result[0] : undefined;
1219
+ return typeof authId === 'string' && authId.length > 0;
1220
+ } catch (err) {
1221
+ this.logger.debug(
1222
+ { err, Category: 'sp00ky-client::Sp00kySync::remoteAuthEstablished' },
1223
+ 'Auth probe failed; treating the session as not yet authenticated'
1224
+ );
1225
+ return false;
1226
+ }
1227
+ }
1228
+
1229
+ /**
1230
+ * Wait for the reconnected session to carry an identity again, then
1231
+ * re-register every active query and re-bind LIVE.
1232
+ *
1233
+ * Giving up without registering is deliberately better than registering
1234
+ * anyway: a registration made with no `$auth.id` produces a view its own
1235
+ * owner cannot read, and it is write-once, so it stays that way. Skipping
1236
+ * leaves the query unregistered and visibly loading, which the next
1237
+ * reconnect or heartbeat retries.
1238
+ */
1239
+ private async refetchAfterReconnect(): Promise<void> {
1240
+ for (let attempt = 1; attempt <= Sp00kySync.AUTH_READY_MAX_ATTEMPTS; attempt++) {
1241
+ if (await this.remoteAuthEstablished()) break;
1242
+ if (attempt === Sp00kySync.AUTH_READY_MAX_ATTEMPTS) {
1243
+ this.logger.warn(
1244
+ {
1245
+ attempts: attempt,
1246
+ Category: 'sp00ky-client::Sp00kySync::onReconnect',
1247
+ },
1248
+ 'Reconnected but the session still carries no $auth.id; not re-registering (a registration now would stamp every view with an empty identity)'
1249
+ );
1250
+ return;
1251
+ }
1252
+ await new Promise((resolve) => setTimeout(resolve, Sp00kySync.AUTH_READY_RETRY_MS));
1253
+ }
1254
+
1255
+ const hashes = this.dataModule.getActiveQueryHashes();
1256
+ this.logger.info(
1257
+ { queries: hashes.length, Category: 'sp00ky-client::Sp00kySync::onReconnect' },
1258
+ 'Remote reconnected, refetching active queries'
1259
+ );
1260
+ for (const hash of hashes) {
1261
+ this.scheduler.enqueueDownEvent({ type: 'register', payload: { hash } });
1262
+ }
1263
+ // The WS reconnect leaves the server-side LIVE subscription dead — the
1264
+ // re-enqueued `register` events only re-fetch initial state, they don't
1265
+ // re-subscribe. Without this, LIVE never recovers after a reconnect and
1266
+ // the poll silently becomes the sole sync path (and never backs off).
1267
+ // Authenticated → per-user table; signed-out with anon live enabled →
1268
+ // the shared `_00_list_ref_anon`. Otherwise there's no table to re-bind.
1269
+ if (this.currentUserId || this.anonLiveEnabled) {
1270
+ this.restartRefLiveQuery().catch((err) => {
1271
+ this.logger.debug(
1272
+ { err, Category: 'sp00ky-client::Sp00kySync::onReconnect' },
1273
+ 'LIVE restart after reconnect failed; relying on poll fallback'
1274
+ );
1275
+ });
1276
+ }
91
1277
  }
92
1278
 
93
1279
  private async startRefLiveQueries() {
1280
+ // Shared-tabs follower: exactly one LIVE per user exists, on the leader;
1281
+ // its events reach this tab through the relay.
1282
+ if (this.tabRole === 'follower') return;
1283
+ const tableName = this.listRefTable();
94
1284
  this.logger.debug(
95
- { clientId: this.clientId, Category: 'spooky-client::SpookySync::startRefLiveQueries' },
1285
+ { tableName, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
96
1286
  'Starting ref live queries'
97
1287
  );
98
1288
 
99
- const [queryUuid] = await this.remote.query<[Uuid]>(
100
- 'LIVE SELECT * FROM _spooky_list_ref'
101
- );
1289
+ const [queryUuid] = await this.remote.query<[Uuid]>(`LIVE SELECT * FROM ${tableName}`);
1290
+ this.currentLiveQueryUuid = queryUuid;
102
1291
 
103
- (await this.remote.getClient().liveOf(queryUuid)).subscribe((message) => {
1292
+ const live = await this.remote.getClient().liveOf(queryUuid);
1293
+ this.liveQueryUnsubscribe = live.subscribe((message) => {
104
1294
  this.logger.debug(
105
- { message, Category: 'spooky-client::SpookySync::startRefLiveQueries' },
1295
+ { message, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
106
1296
  'Live update received'
107
1297
  );
108
1298
  if (message.action === 'KILLED') return;
1299
+ // Subquery child edges (rows with `parent` set) are NOT primary window
1300
+ // rows — the client's `RecordVersionArray` only tracks primary rows, so
1301
+ // routing them through `handleRemoteListRefChange` would surface them as
1302
+ // spurious "added" diffs and pollute the window. Instead route them to
1303
+ // the dedicated child-body sync so `.related()` data stays realtime
1304
+ // cross-session (the LIVE-permission gap otherwise leaves it to the poll).
1305
+ if ((message.value as { parent?: unknown }).parent != null) {
1306
+ this.handleRemoteSubqueryChange(
1307
+ message.action,
1308
+ message.value.in as RecordId<string>,
1309
+ message.value.out as RecordId<string>,
1310
+ message.value.version as number
1311
+ ).catch((err) => {
1312
+ this.logger.error(
1313
+ { err, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
1314
+ 'Error handling remote subquery change'
1315
+ );
1316
+ });
1317
+ return;
1318
+ }
109
1319
  this.handleRemoteListRefChange(
110
1320
  message.action,
111
1321
  message.value.in as RecordId<string>,
@@ -113,7 +1323,7 @@ export class SpookySync<S extends SchemaStructure> {
113
1323
  message.value.version as number
114
1324
  ).catch((err) => {
115
1325
  this.logger.error(
116
- { err, Category: 'spooky-client::SpookySync::startRefLiveQueries' },
1326
+ { err, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
117
1327
  'Error handling remote list ref change'
118
1328
  );
119
1329
  });
@@ -126,16 +1336,47 @@ export class SpookySync<S extends SchemaStructure> {
126
1336
  recordId: RecordId,
127
1337
  version: number
128
1338
  ) {
1339
+ // Any LIVE delivery is evidence of activity — a CREATE/UPDATE/DELETE on a
1340
+ // query's window, or a notification for an unknown local query. Reset the
1341
+ // poll's idle streak so it snaps back to the fast base cadence (the page
1342
+ // is clearly not idle), and record the timestamp as a liveness diagnostic.
1343
+ this.lastLiveEventAt = Date.now();
1344
+ this.listRefIdleStreak = 0;
1345
+
1346
+ // Shared-tabs leader: the list_ref table is USER-scoped, so this LIVE also
1347
+ // carries events for FOLLOWER tabs' queries (their own session-salted
1348
+ // hashes). Relay every primary event; each follower resolves the queryId
1349
+ // against its own DataModule and ignores foreign ones. Then continue with
1350
+ // this tab's own handling below.
1351
+ this.hub?.broadcast({
1352
+ type: 'list-ref-change',
1353
+ action,
1354
+ queryId: encodeRecordId(queryId),
1355
+ recordId: encodeRecordId(recordId),
1356
+ version,
1357
+ parent: false,
1358
+ });
1359
+
1360
+ // NOTE: DELETE is handled like CREATE/UPDATE below. When another window (or
1361
+ // this one) deletes a record, the server's SSP removes it from `_00_list_ref`
1362
+ // and the LIVE subscription delivers a DELETE here — `createDiffFromDbOp`
1363
+ // turns it into a `removed: [recordId]` diff so the row drops from the window
1364
+ // in realtime. (It was previously ignored, so other windows only caught up on
1365
+ // reload / the slow poll.)
129
1366
  const existing = this.dataModule.getQueryById(queryId);
130
1367
 
131
1368
  if (!existing) {
132
- this.logger.warn(
133
- {
134
- queryId: queryId.toString(),
135
- Category: 'spooky-client::SpookySync::handleRemoteListRefChange',
136
- },
137
- 'Received remote update for unknown local query'
138
- );
1369
+ // With a hub attached, an unknown query is the NORMAL case (it belongs
1370
+ // to a follower tab); without one it still warrants the warning.
1371
+ if (!this.hub) {
1372
+ this.logger.warn(
1373
+ {
1374
+ queryId: queryId.toString(),
1375
+ Category: 'sp00ky-client::Sp00kySync::handleRemoteListRefChange',
1376
+ },
1377
+ 'Received remote update for unknown local query'
1378
+ );
1379
+ }
139
1380
  return;
140
1381
  }
141
1382
 
@@ -148,12 +1389,103 @@ export class SpookySync<S extends SchemaStructure> {
148
1389
  recordId,
149
1390
  version,
150
1391
  localArray,
151
- Category: 'spooky-client::SpookySync::handleRemoteListRefChange',
1392
+ Category: 'sp00ky-client::Sp00kySync::handleRemoteListRefChange',
152
1393
  },
153
1394
  'Live update is being processed'
154
1395
  );
155
1396
  const diff = createDiffFromDbOp(action, recordId, version, localArray);
156
- await this.syncEngine.syncRecords(diff);
1397
+ // `config.id` is `_00_query:<hash>`, so its id-part IS the query hash
1398
+ // (a SHA-256 over query content + sessionId) — the key DataModule uses.
1399
+ const hash = extractIdPart(existing.config.id);
1400
+
1401
+ // Apply the event to `remoteArray` — the authoritative membership rows are
1402
+ // now rendered FROM. Only registration and the poll used to write it, so a
1403
+ // LIVE removal left the departed id in the list (in memory and persisted)
1404
+ // until the next poll tick, which is up to 5s of showing a deleted row. This
1405
+ // also persists the durable `_00_window` mirror, so the removal survives a
1406
+ // reload with no network.
1407
+ //
1408
+ // Derived from the raw action, NOT from `diff`: `createDiffFromDbOp` is
1409
+ // empty when the circuit already holds the row at this version, which is
1410
+ // every tab that ingested the write optimistically (its own, or one
1411
+ // relayed from another tab). The fetch is rightly skipped then, but the
1412
+ // membership still has to be recorded, or the row lives on the
1413
+ // settled-write grace alone until the poll catches it.
1414
+ if (existing.config.membershipKnown) {
1415
+ const membershipDiff: RecordVersionDiff =
1416
+ action === 'DELETE'
1417
+ ? { added: [], updated: [], removed: [recordId] }
1418
+ : { added: [{ id: recordId, version }], updated: [], removed: [] };
1419
+ const next = applyRecordVersionDiff(existing.config.remoteArray ?? [], membershipDiff);
1420
+ if (!recordVersionArraysEqual(next, existing.config.remoteArray ?? [])) {
1421
+ await this.dataModule.updateQueryRemoteArray(hash, next);
1422
+ }
1423
+ }
1424
+
1425
+ await this.runSyncForQuery(hash, diff);
1426
+
1427
+ // A removal-only diff sets `fetching` false in `runSyncForQuery`, so it gets
1428
+ // no `flushPendingStreamUpdate`/`endFetching` re-render — and a removal needs
1429
+ // no record fetch to trigger one either. Force it, mirroring what the poll
1430
+ // path already does for its own removals (`refetchListRefForQuery`).
1431
+ if (diff.removed.length > 0 && diff.added.length === 0 && diff.updated.length === 0) {
1432
+ await this.dataModule.notifyQuerySynced(hash);
1433
+ } else if (diff.added.length === 0 && diff.updated.length === 0) {
1434
+ // Empty diff: the circuit already holds the row at this version (this
1435
+ // tab wrote it), so no fetch and no stream update - but the membership
1436
+ // recorded above is new, and the subscribers have to hear about it.
1437
+ this.dataModule.scheduleRematerialize(hash);
1438
+ }
1439
+ }
1440
+
1441
+ /**
1442
+ * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
1443
+ * `parent` set) for a `.related()` query. Unlike primary rows, child rows
1444
+ * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
1445
+ * keep the child BODY fresh in the local cache so the in-browser SSP's
1446
+ * subquery-table dependency re-materializes the parent view.
1447
+ *
1448
+ * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
1449
+ * no-op: a child leaving this query's set must not delete a body another
1450
+ * query may still show (see `syncSubqueryChildren` deletion-safety note);
1451
+ * a genuine record delete propagates via the normal delete path.
1452
+ */
1453
+ private async handleRemoteSubqueryChange(
1454
+ action: 'CREATE' | 'UPDATE' | 'DELETE',
1455
+ queryId: RecordId,
1456
+ childId: RecordId,
1457
+ version: number
1458
+ ) {
1459
+ this.lastLiveEventAt = Date.now();
1460
+ this.listRefIdleStreak = 0;
1461
+
1462
+ if (action === 'DELETE') return;
1463
+
1464
+ // Relay child-edge events too (see handleRemoteListRefChange).
1465
+ this.hub?.broadcast({
1466
+ type: 'list-ref-change',
1467
+ action,
1468
+ queryId: encodeRecordId(queryId),
1469
+ recordId: encodeRecordId(childId),
1470
+ version,
1471
+ parent: true,
1472
+ });
1473
+
1474
+ const existing = this.dataModule.getQueryById(queryId);
1475
+ if (!existing) return;
1476
+
1477
+ const item = { id: childId, version };
1478
+ await this.syncEngine.syncRecords(
1479
+ action === 'CREATE'
1480
+ ? { added: [item], updated: [], removed: [] }
1481
+ : { added: [], updated: [item], removed: [] }
1482
+ );
1483
+
1484
+ // Keep the in-memory child array in step so the poll's idempotent diff
1485
+ // doesn't re-fetch this body on the next tick.
1486
+ const key = encodeRecordId(childId);
1487
+ const prev = existing.config.subqueryRemoteArray ?? [];
1488
+ existing.config.subqueryRemoteArray = [...prev.filter(([id]) => id !== key), [key, version]];
157
1489
  }
158
1490
 
159
1491
  /**
@@ -164,49 +1496,103 @@ export class SpookySync<S extends SchemaStructure> {
164
1496
  this.scheduler.enqueueDownEvent(event);
165
1497
  }
166
1498
 
1499
+ /**
1500
+ * Bound a mutation push so it always settles.
1501
+ *
1502
+ * `SyncScheduler.syncUp` early-returns while `isSyncingUp` is true, and that
1503
+ * flag only clears in the `finally` of the drain loop. A push whose RPC never
1504
+ * settles (socket dropped mid-flight, response lost) therefore wedges the
1505
+ * up-queue for the rest of the session: no retry, no error, no further
1506
+ * mutation ever sent. A timeout turns that into an ordinary network failure,
1507
+ * which `UpQueue.next` re-queues for the next trigger. The message deliberately
1508
+ * contains "timed out" so `classifySyncError` treats it as `network` and
1509
+ * retries rather than rolling the mutation back.
1510
+ */
1511
+ private withPushTimeout<T>(promise: Promise<T>, label: string): Promise<T> {
1512
+ return withTimeout(
1513
+ promise,
1514
+ this.pushTimeoutMs,
1515
+ `Mutation push timed out after ${this.pushTimeoutMs}ms (${label})`
1516
+ );
1517
+ }
1518
+
167
1519
  private async processUpEvent(event: UpEvent) {
168
1520
  this.logger.debug(
169
- { event, Category: 'spooky-client::SpookySync::processUpEvent' },
1521
+ { event, Category: 'sp00ky-client::Sp00kySync::processUpEvent' },
170
1522
  'Processing up event'
171
1523
  );
172
1524
  switch (event.type) {
173
- case 'create':
1525
+ case 'create': {
174
1526
  const dataKeys = Object.keys(event.data).map((key) => ({ key, variable: `data_${key}` }));
175
1527
  const prefixedParams = Object.fromEntries(
176
1528
  dataKeys.map(({ key, variable }) => [variable, event.data[key]])
177
1529
  );
178
1530
  const query = surql.seal(surql.createSet('id', dataKeys));
179
- await this.remote.query(query, {
180
- id: event.record_id,
181
- ...prefixedParams,
182
- });
1531
+ await this.withPushTimeout(
1532
+ this.remote.query(query, {
1533
+ id: event.record_id,
1534
+ ...prefixedParams,
1535
+ }),
1536
+ 'create'
1537
+ );
183
1538
  break;
1539
+ }
184
1540
  case 'update':
185
- await this.remote.query(`UPDATE $id MERGE $data`, {
186
- id: event.record_id,
187
- data: event.data,
188
- });
1541
+ await this.withPushTimeout(
1542
+ this.remote.query(`UPDATE $id MERGE $data`, {
1543
+ id: event.record_id,
1544
+ data: event.data,
1545
+ }),
1546
+ 'update'
1547
+ );
189
1548
  break;
190
1549
  case 'delete':
191
- await this.remote.query(`DELETE $id`, {
192
- id: event.record_id,
193
- });
1550
+ await this.withPushTimeout(
1551
+ this.remote.query(`DELETE $id`, {
1552
+ id: event.record_id,
1553
+ }),
1554
+ 'delete'
1555
+ );
194
1556
  break;
195
1557
  default:
196
1558
  this.logger.error(
197
- { event, Category: 'spooky-client::SpookySync::processUpEvent' },
1559
+ { event, Category: 'sp00ky-client::Sp00kySync::processUpEvent' },
198
1560
  'processUpEvent unknown event type'
199
1561
  );
200
1562
  return;
201
1563
  }
202
1564
  }
203
1565
 
1566
+ /**
1567
+ * A mutation the server accepted, reported once its outbox row is gone.
1568
+ *
1569
+ * Keeps the written row in the render set until its membership arrives.
1570
+ * Without this the row is briefly in neither term of
1571
+ * `(membership ∪ pendingWrites) − pendingDeletes` — the outbox delete is
1572
+ * tied to the push, while membership waits on the SSP ingesting the row,
1573
+ * materializing the view, writing the `_00_list_ref` edge and this client
1574
+ * reading it back. The writer therefore watched its own comment appear,
1575
+ * vanish, and return, while every other client showed it throughout.
1576
+ */
1577
+ private handleMutationSettled(event: UpEvent): void {
1578
+ const recordId = encodeRecordId(event.record_id);
1579
+ this.dataModule.noteWriteSettled(recordId, event.type);
1580
+ // Shared-tabs: the outbox row just left the SHARED store, so every
1581
+ // follower rendering the row as a pending write has the same gap. All of
1582
+ // them, not just the owner: any tab whose query matched the row was
1583
+ // showing it through `pendingWrites`.
1584
+ this.hub?.broadcast({
1585
+ type: 'mutation-settled',
1586
+ mutationId: encodeRecordId(event.mutation_id),
1587
+ recordId,
1588
+ eventType: event.type,
1589
+ });
1590
+ }
1591
+
204
1592
  private async handleRollback(event: UpEvent, error: Error): Promise<void> {
205
1593
  const recordId = encodeRecordId(event.record_id);
206
1594
  const tableName =
207
- event.type === 'create' && event.tableName
208
- ? event.tableName
209
- : extractTablePart(recordId);
1595
+ event.type === 'create' && event.tableName ? event.tableName : extractTablePart(recordId);
210
1596
 
211
1597
  this.logger.warn(
212
1598
  {
@@ -214,7 +1600,7 @@ export class SpookySync<S extends SchemaStructure> {
214
1600
  recordId,
215
1601
  tableName,
216
1602
  error: error.message,
217
- Category: 'spooky-client::SpookySync::handleRollback',
1603
+ Category: 'sp00ky-client::Sp00kySync::handleRollback',
218
1604
  },
219
1605
  'Rolling back failed mutation'
220
1606
  );
@@ -230,7 +1616,7 @@ export class SpookySync<S extends SchemaStructure> {
230
1616
  this.logger.warn(
231
1617
  {
232
1618
  recordId,
233
- Category: 'spooky-client::SpookySync::handleRollback',
1619
+ Category: 'sp00ky-client::Sp00kySync::handleRollback',
234
1620
  },
235
1621
  'Cannot rollback update: no beforeRecord available. Down-sync will reconcile.'
236
1622
  );
@@ -240,7 +1626,7 @@ export class SpookySync<S extends SchemaStructure> {
240
1626
  this.logger.warn(
241
1627
  {
242
1628
  recordId,
243
- Category: 'spooky-client::SpookySync::handleRollback',
1629
+ Category: 'sp00ky-client::Sp00kySync::handleRollback',
244
1630
  },
245
1631
  'Delete rollback not implemented. Down-sync will reconcile.'
246
1632
  );
@@ -252,13 +1638,46 @@ export class SpookySync<S extends SchemaStructure> {
252
1638
  recordId,
253
1639
  error: error.message,
254
1640
  });
1641
+
1642
+ // Shared-tabs: the store rollback above already propagated to every tab
1643
+ // via the ingest relay; additionally deliver the EVENT to the tab that
1644
+ // owns the mutation so its UI (toasts, subscribeToRollbacks) fires there.
1645
+ const mutationId = encodeRecordId(event.mutation_id);
1646
+ const owner = mutationOwnerTabId(mutationId);
1647
+ if (this.hub && owner && this.tabId && owner !== this.tabId) {
1648
+ this.hub.sendTo(owner, {
1649
+ type: 'mutation-rolled-back',
1650
+ mutationId,
1651
+ recordId,
1652
+ eventType: event.type,
1653
+ error: error.message,
1654
+ });
1655
+ }
255
1656
  }
256
1657
 
257
1658
  private async processDownEvent(event: DownEvent) {
258
1659
  this.logger.debug(
259
- { event, Category: 'spooky-client::SpookySync::processDownEvent' },
1660
+ { event, Category: 'sp00ky-client::Sp00kySync::processDownEvent' },
260
1661
  'Processing down event'
261
1662
  );
1663
+ // Bounded for the same reason a push is (see withPushTimeout): an RPC that
1664
+ // never settles would otherwise hold its slot in the concurrent down drain
1665
+ // — and, before that drain existed, the WHOLE queue — for the rest of the
1666
+ // session, with no retry, no error, and every dependent `useQuery` stuck
1667
+ // loading. "timed out" in the message keeps `classifySyncError` treating it
1668
+ // as a network failure, so `DownQueue.run` re-heads it for the next pass.
1669
+ return this.withDownTimeout(this.runDownEvent(event), `${event.type} ${event.payload.hash}`);
1670
+ }
1671
+
1672
+ private withDownTimeout<T>(promise: Promise<T>, label: string): Promise<T> {
1673
+ return withTimeout(
1674
+ promise,
1675
+ this.downTimeoutMs,
1676
+ `Down event timed out after ${this.downTimeoutMs}ms (${label})`
1677
+ );
1678
+ }
1679
+
1680
+ private async runDownEvent(event: DownEvent): Promise<void> {
262
1681
  switch (event.type) {
263
1682
  case 'register':
264
1683
  return this.registerQuery(event.payload.hash);
@@ -280,7 +1699,7 @@ export class SpookySync<S extends SchemaStructure> {
280
1699
  const queryState = this.dataModule.getQueryByHash(hash);
281
1700
  if (!queryState) {
282
1701
  this.logger.warn(
283
- { hash, Category: 'spooky-client::SpookySync::syncQuery' },
1702
+ { hash, Category: 'sp00ky-client::Sp00kySync::syncQuery' },
284
1703
  'Query not found'
285
1704
  );
286
1705
  return;
@@ -294,7 +1713,133 @@ export class SpookySync<S extends SchemaStructure> {
294
1713
  if (!diff) {
295
1714
  return;
296
1715
  }
297
- return this.syncEngine.syncRecords(diff);
1716
+ return this.runSyncForQuery(hash, diff);
1717
+ }
1718
+
1719
+ /**
1720
+ * Run a sync for a single query while reflecting its fetch status. Marks the
1721
+ * query `fetching` for the duration when the diff actually pulls records
1722
+ * (added/updated), then resets to `idle` in a `finally` so a failed sync
1723
+ * never leaves a query stuck `fetching`. Part A's notification coalescing
1724
+ * means the single resulting UI update lands after this completes.
1725
+ */
1726
+ private async runSyncForQuery(hash: string, diff: RecordVersionDiff): Promise<void> {
1727
+ // The diff was computed against whatever the circuit held at call time; if
1728
+ // the boot prime is still filling it, wait and recompute from the primed
1729
+ // `localArray` so the delta is real rather than "everything".
1730
+ const prime = this.primeGate();
1731
+ if (prime !== this.settledPrime) {
1732
+ await prime;
1733
+ this.settledPrime = prime;
1734
+ const fresh = this.dataModule.getQueryByHash(hash);
1735
+ if (!fresh) return;
1736
+ const recomputed = new ArraySyncer(fresh.config.localArray, fresh.config.remoteArray).nextSet();
1737
+ if (!recomputed) return;
1738
+ diff = recomputed;
1739
+ }
1740
+ // Don't let sync re-add a record the user just deleted locally. The remote
1741
+ // delete is queued in the outbox, so until it's processed the server's
1742
+ // `_00_list_ref` still lists the record — the diff then classifies it as
1743
+ // `added` (present remotely, absent locally) and `syncRecords` re-fetches +
1744
+ // re-inserts it, so a deleted database reappears a few seconds later. Drop
1745
+ // any id with a pending local DELETE from the re-add paths. Once the remote
1746
+ // delete lands, the pending row clears and the server drops it from
1747
+ // `_00_list_ref`, so this guard naturally stops applying.
1748
+ if (diff.added.length > 0 || diff.updated.length > 0) {
1749
+ const pendingDeletes = await this.getPendingDeleteIds();
1750
+ if (pendingDeletes.size > 0) {
1751
+ diff = {
1752
+ added: diff.added.filter((r) => !pendingDeletes.has(encodeRecordId(r.id))),
1753
+ updated: diff.updated.filter((r) => !pendingDeletes.has(encodeRecordId(r.id))),
1754
+ removed: diff.removed,
1755
+ };
1756
+ }
1757
+ }
1758
+
1759
+ const fetching = diff.added.length + diff.updated.length > 0;
1760
+ if (fetching) {
1761
+ this.dataModule.beginFetching(hash);
1762
+ }
1763
+ try {
1764
+ const { remoteFetchMs, stillRemoteIds } = await this.syncEngine.syncRecords(diff);
1765
+ if (fetching) {
1766
+ this.dataModule.recordRemoteFetch(hash, remoteFetchMs);
1767
+ }
1768
+ // Converge localArray to the authoritative remoteArray for ids that left
1769
+ // the server's list_ref but still exist — a view-membership change, not a
1770
+ // delete — so the poll's diff stops re-flagging them every tick (the `job:`
1771
+ // churn). CRUCIAL: only converge after the id has been still-remote for
1772
+ // several CONSECUTIVE rounds. A record that's merely mid-deletion is
1773
+ // still-remote for ~one round (its delete hasn't committed when our
1774
+ // existence check races it) and is gone the next round → it never reaches
1775
+ // the threshold, so it's deleted normally instead of being stranded here.
1776
+ if (stillRemoteIds.length > 0) {
1777
+ const CONVERGE_AFTER = 3;
1778
+ const toConverge: string[] = [];
1779
+ for (const id of stillRemoteIds) {
1780
+ const key = `${hash}:${id}`;
1781
+ const n = (this.stillRemoteStreaks.get(key) ?? 0) + 1;
1782
+ if (n >= CONVERGE_AFTER) {
1783
+ this.stillRemoteStreaks.delete(key);
1784
+ toConverge.push(id);
1785
+ } else {
1786
+ this.stillRemoteStreaks.set(key, n);
1787
+ }
1788
+ }
1789
+ if (toConverge.length > 0) {
1790
+ const qs = this.dataModule.getQueryByHash(hash);
1791
+ const local = qs?.config.localArray;
1792
+ if (local && local.length > 0) {
1793
+ const drop = new Set(toConverge);
1794
+ const next = local.filter(([id]) => !drop.has(id));
1795
+ if (next.length !== local.length) {
1796
+ await this.dataModule.updateQueryLocalArray(hash, next);
1797
+ }
1798
+ }
1799
+ }
1800
+ }
1801
+ } finally {
1802
+ if (fetching) {
1803
+ // Land the coalesced result BEFORE flipping to idle: the final stream
1804
+ // update sits on a debounce timer, and an `idle` that races ahead of it
1805
+ // would let consumers treat a partially-filled window as authoritative.
1806
+ //
1807
+ // A fetch that changed a row already in membership can come with no
1808
+ // stream update at all: the body lands in the local store, but the
1809
+ // circuit sees the same id-set and stays silent (measured: a peer's
1810
+ // UPDATE to a `conversation` row reached the store at `_00_rv` 8 while
1811
+ // the query kept rendering version 2 indefinitely). Nothing else
1812
+ // re-reads the query then, so ask for a synthetic re-materialize and
1813
+ // land it here too. It is one local select, and a no-op when a real
1814
+ // update was pending, which the first flush already processed.
1815
+ try {
1816
+ const landed = await this.dataModule.flushPendingStreamUpdate(hash);
1817
+ if (!landed) {
1818
+ this.dataModule.scheduleRematerialize(hash);
1819
+ await this.dataModule.flushPendingStreamUpdate(hash);
1820
+ }
1821
+ } catch (err) {
1822
+ this.logger.warn(
1823
+ { err, hash, Category: 'sp00ky-client::Sp00kySync::runSyncForQuery' },
1824
+ 'Failed to flush pending stream update before idle'
1825
+ );
1826
+ }
1827
+ this.dataModule.endFetching(hash);
1828
+ }
1829
+ }
1830
+ }
1831
+
1832
+ /**
1833
+ * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
1834
+ * Sync must not re-fetch/re-insert these — the remote delete is async, so the
1835
+ * server's `_00_list_ref` still lists them until it's processed, and the diff
1836
+ * would otherwise resurrect a just-deleted record.
1837
+ */
1838
+ private async getPendingDeleteIds(): Promise<Set<string>> {
1839
+ // Single implementation, shared with the render path: `materializeRecords`
1840
+ // subtracts the same set so a row whose DELETE is still in the outbox is
1841
+ // neither re-fetched here nor rendered there.
1842
+ return (await this.dataModule.getPendingRecordIds()).deletes;
298
1843
  }
299
1844
 
300
1845
  /**
@@ -302,26 +1847,101 @@ export class SpookySync<S extends SchemaStructure> {
302
1847
  * @param mutations Array of UpEvents (create/update/delete) to enqueue.
303
1848
  */
304
1849
  public async enqueueMutation(mutations: UpEvent[]) {
1850
+ // Follower: the outbox rows are already committed in the SHARED store (the
1851
+ // mutation tx went through the leader's worker); only the leader drains,
1852
+ // so hand over the ids instead of queueing locally. A notify lost in a
1853
+ // failover window is covered by the new leader's loadFromDatabase.
1854
+ if (this.tabRole === 'follower') {
1855
+ for (const m of mutations) {
1856
+ this.forwarder?.mutationEnqueued(encodeRecordId(m.mutation_id));
1857
+ }
1858
+ return;
1859
+ }
305
1860
  this.scheduler.enqueueMutation(mutations);
306
1861
  }
307
1862
 
1863
+ /**
1864
+ * Best-effort release of THIS tab's views as the page goes away.
1865
+ *
1866
+ * Without it a closed tab's views stay materialized on the SSP for a full
1867
+ * TTL (10 minutes by default), because nothing else tears them down:
1868
+ * `releaseQueriesEagerly` is off, so the TTL sweep is the only reclaim path.
1869
+ * On a busy tenant that is a generation of live views per reload, each still
1870
+ * being stepped by every ingest, for ten minutes after the last human left.
1871
+ *
1872
+ * This is NOT `releaseQueriesEagerly` re-enabled. That released views
1873
+ * mid-session on a viewport change and tore the window out from under a live
1874
+ * page (see `cleanupQuery`); this runs only when the page itself is going
1875
+ * away and nothing is left to render.
1876
+ *
1877
+ * Safe against other tabs by construction: `fn::query::unsubscribe` drops
1878
+ * only this session from `subscribers` and deletes the row solely when it
1879
+ * was the last one, so a second tab of the same user keeps its view.
1880
+ *
1881
+ * One statement, not one per id: an unload handler gets a few milliseconds,
1882
+ * and N round trips would not survive it. Fire-and-forget — if the frame
1883
+ * does not make it out, the TTL sweep still reclaims exactly as before, so
1884
+ * the worst case is today's behaviour.
1885
+ */
1886
+ releaseViewsOnUnload(): void {
1887
+ let ids: unknown[];
1888
+ try {
1889
+ ids = this.dataModule
1890
+ .getActiveQueryHashes()
1891
+ .map((hash) => this.dataModule.getQueryByHash(hash)?.config.id)
1892
+ .filter((id): id is NonNullable<typeof id> => id != null);
1893
+ } catch {
1894
+ return;
1895
+ }
1896
+ if (ids.length === 0) return;
1897
+
1898
+ // Over HTTP with `keepalive`, NOT the live socket. A WebSocket send during
1899
+ // `pagehide` is not guaranteed to flush — the browser may tear the socket
1900
+ // down first and the frame is lost. Measured on staging: releasing over the
1901
+ // socket reached the server zero times; `fetch`/`keepalive` is the only
1902
+ // primitive the platform promises to finish after the page is gone.
1903
+ //
1904
+ // Ids are inlined rather than bound because this is a bare statement, not
1905
+ // an RPC call with a params channel. They are `_00_query:<sha256>` record
1906
+ // ids the client itself derived, so the only interpolation is a hex digest.
1907
+ const list = ids
1908
+ .map((id) => String(id))
1909
+ .filter((id) => /^_00_query:[0-9a-f]{64}$/.test(id))
1910
+ .join(', ');
1911
+ if (!list) return;
1912
+
1913
+ this.remote.beaconSql(
1914
+ `FOR $id IN [${list}] { LET $_released = fn::query::unsubscribe($id); };`
1915
+ );
1916
+ }
1917
+
308
1918
  private async registerQuery(queryHash: string) {
1919
+ // Hold `fetching` across the WHOLE registration (remote view creation +
1920
+ // initial sync + post-sync notify). A query is born `fetching` in
1921
+ // createNewQuery; this refcounted cycle is what resolves it to `idle` — so
1922
+ // consumers (e.g. useQuery's `isSettled`) never see an idle query whose
1923
+ // window is still empty/partially materialized.
1924
+ this.dataModule.beginFetching(queryHash);
309
1925
  try {
310
1926
  this.logger.debug(
311
- { queryHash, Category: 'spooky-client::SpookySync::registerQuery' },
1927
+ { queryHash, Category: 'sp00ky-client::Sp00kySync::registerQuery' },
312
1928
  'Register Query state'
313
1929
  );
314
1930
  await this.createRemoteQuery(queryHash);
315
1931
  await this.syncQuery(queryHash);
316
- // Always notify after sync completes — handles empty result sets
317
- // where no stream updates fire but the UI needs to stop loading
1932
+ // Land any still-debounced stream result, then always notify — handles
1933
+ // empty result sets where no stream updates fire but the UI needs to
1934
+ // stop loading.
1935
+ await this.dataModule.flushPendingStreamUpdate(queryHash);
318
1936
  await this.dataModule.notifyQuerySynced(queryHash);
319
1937
  } catch (e) {
320
1938
  this.logger.error(
321
- { err: e, Category: 'spooky-client::SpookySync::registerQuery' },
1939
+ { err: e, Category: 'sp00ky-client::Sp00kySync::registerQuery' },
322
1940
  'registerQuery error'
323
1941
  );
324
1942
  throw e;
1943
+ } finally {
1944
+ this.dataModule.endFetching(queryHash);
325
1945
  }
326
1946
  }
327
1947
 
@@ -330,15 +1950,15 @@ export class SpookySync<S extends SchemaStructure> {
330
1950
 
331
1951
  if (!queryState) {
332
1952
  this.logger.warn(
333
- { queryHash, Category: 'spooky-client::SpookySync::createRemoteQuery' },
1953
+ { queryHash, Category: 'sp00ky-client::Sp00kySync::createRemoteQuery' },
334
1954
  'Query to register not found'
335
1955
  );
336
1956
  throw new Error('Query to register not found');
337
1957
  }
338
- // Delegate to remote function which handles DBSP registration & persistence
1958
+ // Delegate to remote function which handles DBSP registration & persistence.
1959
+ // clientId is set server-side from session::id() — see fn::query::register.
339
1960
  await this.remote.query('fn::query::register($config)', {
340
1961
  config: {
341
- clientId: this.clientId,
342
1962
  id: queryState.config.id,
343
1963
  surql: queryState.config.surql,
344
1964
  params: queryState.config.params,
@@ -346,18 +1966,26 @@ export class SpookySync<S extends SchemaStructure> {
346
1966
  },
347
1967
  });
348
1968
 
349
- const [items] = await this.remote.query<[{ out: RecordId<string>; version: number }[]]>(
350
- surql.selectByFieldsAnd('_spooky_list_ref', ['in'], ['out', 'version']),
351
- {
352
- in: queryState.config.id,
353
- }
354
- );
1969
+ // Initial materialized-view fetch — pull from the same per-user
1970
+ // `_00_list_ref_user_<id>` (or global `_00_list_ref` in single
1971
+ // mode) that the LIVE subscription listens on, so the two stay in
1972
+ // sync. `parent IS NONE` excludes subquery entries; the
1973
+ // `localArray` cache only tracks primary records.
1974
+ const listRefTbl = this.listRefTable();
1975
+ // `rowCount` rides along: it is written by the SSP in the same statement
1976
+ // that registers the view, BEFORE the edges are flushed, so it is the only
1977
+ // way to tell "this query is empty" from "its edges have not landed yet".
1978
+ const [items, serverRowCount] = await this.remote.query<
1979
+ [{ out: RecordId<string>; version: number }[], number | null]
1980
+ >(`${buildListRefSelect(listRefTbl)};\n${buildQueryRowCountSelect()}`, {
1981
+ in: queryState.config.id,
1982
+ });
355
1983
 
356
1984
  this.logger.trace(
357
1985
  {
358
1986
  queryId: encodeRecordId(queryState.config.id),
359
1987
  items,
360
- Category: 'spooky-client::SpookySync::createRemoteQuery',
1988
+ Category: 'sp00ky-client::Sp00kySync::createRemoteQuery',
361
1989
  },
362
1990
  'Got query record version array from remote'
363
1991
  );
@@ -368,42 +1996,184 @@ export class SpookySync<S extends SchemaStructure> {
368
1996
  {
369
1997
  queryId: encodeRecordId(queryState.config.id),
370
1998
  array,
371
- Category: 'spooky-client::SpookySync::createRemoteQuery',
1999
+ Category: 'sp00ky-client::Sp00kySync::createRemoteQuery',
372
2000
  },
373
2001
  'createdRemoteQuery'
374
2002
  );
375
2003
 
376
2004
  if (array) {
377
2005
  /// Incantation existed already
378
- await this.dataModule.updateQueryRemoteArray(queryHash, array);
2006
+ await this.dataModule.updateQueryRemoteArray(queryHash, array, { serverRowCount });
379
2007
  }
2008
+
2009
+ // Pull the bodies of any `.related()` subquery children into the local
2010
+ // cache. The primary fetch above (`parent IS NONE`) tracks only window
2011
+ // rows, so without this a cold-reload re-materialization of the
2012
+ // correlated surql finds no child rows and related fields come back
2013
+ // empty. Best-effort: never fail registration over it.
2014
+ await this.syncSubqueryChildren(queryHash).catch((err) => {
2015
+ this.logger.info(
2016
+ {
2017
+ err: (err as Error)?.message ?? err,
2018
+ queryHash,
2019
+ Category: 'sp00ky-client::Sp00kySync::createRemoteQuery',
2020
+ },
2021
+ 'Subquery child sync failed during registration; poll will retry'
2022
+ );
2023
+ });
380
2024
  }
381
2025
 
382
- private async heartbeatQuery(queryHash: string) {
2026
+ /**
2027
+ * Sync the BODIES of a `.related()` query's subquery child rows into the
2028
+ * local cache, separately from the primary window array. The SSP writes
2029
+ * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
2030
+ * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
2031
+ * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
2032
+ * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
2033
+ * them into the local DB AND the in-browser SSP, whose subquery-table
2034
+ * dependency then re-materializes the parent view (no explicit notify).
2035
+ *
2036
+ * Deletion safety: we pass `removed: []` deliberately. A child body can be
2037
+ * shared by other queries; letting `handleRemovedRecords` delete one that
2038
+ * merely left THIS query's child set would clobber data another query still
2039
+ * shows. Genuine record deletes flow through the normal delete path; a
2040
+ * lingering orphan body is invisible (the correlated WHERE stops matching).
2041
+ *
2042
+ * Kept off `runSyncForQuery` on purpose so child fetches never flip the
2043
+ * query to `fetching` or skew its DevTools timings.
2044
+ */
2045
+ private async syncSubqueryChildren(queryHash: string): Promise<void> {
2046
+ const queryState = this.dataModule.getQueryByHash(queryHash);
2047
+ if (!queryState) return;
2048
+
2049
+ const listRefTbl = this.listRefTable();
2050
+ const [items] = await this.remote.query<[{ out: RecordId<string>; version: number }[]]>(
2051
+ buildSubqueryListRefSelect(listRefTbl),
2052
+ { in: queryState.config.id }
2053
+ );
2054
+ if (!Array.isArray(items)) return;
2055
+
2056
+ const fresh: RecordVersionArray = items.map((item) => [encodeRecordId(item.out), item.version]);
2057
+ const prev = queryState.config.subqueryRemoteArray ?? [];
2058
+ if (recordVersionArraysEqual(fresh, prev)) return; // idempotent: nothing new
2059
+
2060
+ const diff = diffRecordVersionArray(prev, fresh);
2061
+ if (diff.added.length > 0 || diff.updated.length > 0) {
2062
+ await this.syncEngine.syncRecords({
2063
+ added: diff.added,
2064
+ updated: diff.updated,
2065
+ removed: [], // never delete child bodies here — see method doc
2066
+ });
2067
+ }
2068
+ // In-memory only — child rows must never enter the persisted primary array.
2069
+ queryState.config.subqueryRemoteArray = fresh;
2070
+ }
2071
+
2072
+ public async heartbeatQuery(queryHash: string) {
383
2073
  const queryState = this.dataModule.getQueryByHash(queryHash);
384
2074
  if (!queryState) {
385
2075
  this.logger.warn(
386
- { queryHash, Category: 'spooky-client::SpookySync::heartbeatQuery' },
2076
+ { queryHash, Category: 'sp00ky-client::Sp00kySync::heartbeatQuery' },
387
2077
  'Query to register not found'
388
2078
  );
389
2079
  throw new Error('Query to register not found');
390
2080
  }
391
- await this.remote.query('fn::query::heartbeat($id)', {
2081
+ // `fn::query::heartbeat` is an `UPDATE $id SET ...`. On a record that no
2082
+ // longer exists that matches nothing and returns an empty array — it does
2083
+ // NOT recreate the row. So an unchecked heartbeat is indistinguishable from
2084
+ // a successful one, and a client whose row was reclaimed keeps beating
2085
+ // against nothing forever: no membership, no edges, no re-registration.
2086
+ // The page renders as if the data were deleted ("Game not found").
2087
+ //
2088
+ // A live query's row is reclaimed more easily than it looks. The sweep
2089
+ // expires on `lastActiveAt + ttl`, and this heartbeat runs on a timer that
2090
+ // browsers throttle hard in background tabs — so a second window left idle
2091
+ // past its TTL is the ordinary way to get here, not an edge case. Until
2092
+ // canary.194 the sweep could not actually remove the in-memory view (it
2093
+ // looked it up under the other of the two query-id spellings), which masked
2094
+ // this: the view survived its own row. Now reclamation is real, so the
2095
+ // client has to notice and rebuild.
2096
+ const result = await this.remote.query('fn::query::heartbeat($id)', {
392
2097
  id: queryState.config.id,
393
2098
  });
2099
+ const updated = Array.isArray(result) ? result[0] : undefined;
2100
+ const rowGone = Array.isArray(updated) && updated.length === 0;
2101
+ if (!rowGone) return;
2102
+
2103
+ this.logger.warn(
2104
+ {
2105
+ queryHash,
2106
+ id: String(queryState.config.id),
2107
+ Category: 'sp00ky-client::Sp00kySync::heartbeatQuery',
2108
+ },
2109
+ 'Query row was reclaimed while still in use; re-registering'
2110
+ );
2111
+ // Re-register rather than recreate the row here: the row alone is useless
2112
+ // without the SSP view behind it, and only registration rebuilds the view,
2113
+ // republishes `_00_list_ref` and writes `rowCount`.
2114
+ this.enqueueDownEvent({ type: 'register', payload: { hash: queryHash } });
394
2115
  }
395
2116
 
2117
+ // Eager teardown of a deregistered query's remote `_00_query` view (opt-in,
2118
+ // e.g. a viewport-windowed list cancelling an off-screen window). Query ids
2119
+ // are a deterministic hash of (surql+params), so a release racing a
2120
+ // scroll-back re-register (same id) could nuke a freshly-recreated view —
2121
+ // hence two guards: abort if a subscriber reappeared BEFORE the release;
2122
+ // re-register if one reappears DURING the release's network await. Tolerant
2123
+ // of a missing/already-gone query (no throw).
2124
+ //
2125
+ // Releases via `fn::query::unsubscribe` rather than deleting the row
2126
+ // outright. A `_00_query` row can be shared by several sessions of the same
2127
+ // user, so a bare `DELETE` would tear the view — and every `_00_list_ref`
2128
+ // edge hanging off it — out from under other live tabs. The function drops
2129
+ // only this session from `subscribers` and deletes the row when it was the
2130
+ // last one. (The old `DELETE $id` was harmless in practice only because the
2131
+ // table granted no delete permission and it silently affected zero rows.)
396
2132
  private async cleanupQuery(queryHash: string) {
397
2133
  const queryState = this.dataModule.getQueryByHash(queryHash);
398
- if (!queryState) {
399
- this.logger.warn(
400
- { queryHash, Category: 'spooky-client::SpookySync::cleanupQuery' },
401
- 'Query to register not found'
402
- );
403
- throw new Error('Query to register not found');
2134
+ if (!queryState) return; // already torn down / never registered
2135
+
2136
+ // Re-subscribed before the queued cleanup ran → keep everything as-is.
2137
+ if (this.dataModule.hasSubscribers(queryHash)) return;
2138
+
2139
+ // EAGER REMOTE RELEASE IS DISABLED. Deliberate, and not a leak: the TTL
2140
+ // sweep reclaims the row and its edges on `lastActiveAt + ttl`, which is the
2141
+ // ONLY reclamation that has ever actually run in production.
2142
+ //
2143
+ // Until canary.190 `_00_query` granted no delete permission, so the bare
2144
+ // `DELETE $id` this used to issue affected zero rows. .190 granted delete
2145
+ // and .191 wired `fn::query::unsubscribe`, which made teardown real for the
2146
+ // first time -- and the guards above are best-effort by construction
2147
+ // (`hasSubscribers` can be momentarily false during a rebind or a windowed
2148
+ // list re-flow). Every misfire that had been silently inert for months
2149
+ // became a live delete of the row AND every `_00_list_ref` edge on it.
2150
+ //
2151
+ // That matches a report of chat suddenly rendering raw record ids instead
2152
+ // of users, with the message list re-flowing underneath. Server state was
2153
+ // measured intact at the time (`rowCount` equalled the actual edge count on
2154
+ // every row), so the damage is on the client side of a teardown, not in the
2155
+ // materialization.
2156
+ //
2157
+ // Re-enable only together with a repair path that can re-fetch subquery
2158
+ // child bodies whose `subqueryRemoteArray` entry claims they are already
2159
+ // synced -- otherwise a torn-down-and-recreated view never restores the
2160
+ // related records it dropped, because the idempotence check skips them.
2161
+ if (this.releaseQueriesEagerly) {
2162
+ await this.remote.query('fn::query::unsubscribe($id)', {
2163
+ id: queryState.config.id,
2164
+ });
2165
+
2166
+ // Re-subscribed while we awaited the release → re-register. Covers both
2167
+ // outcomes: if we were the last subscriber the remote view is gone and
2168
+ // this recreates it, and if it survived for other sessions this re-adds
2169
+ // us to `subscribers` so our heartbeats keep counting.
2170
+ if (this.dataModule.hasSubscribers(queryHash)) {
2171
+ this.enqueueDownEvent({ type: 'register', payload: { hash: queryHash } });
2172
+ return;
2173
+ }
404
2174
  }
405
- await this.remote.query(`DELETE $id`, {
406
- id: queryState.config.id,
407
- });
2175
+
2176
+ // No subscribers throughout → safe to free the local view + state.
2177
+ this.dataModule.finalizeDeregister(queryHash);
408
2178
  }
409
2179
  }