@spooky-sync/core 0.0.1-canary.20 → 0.0.1-canary.201

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