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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2650 -58
  3. package/dist/index.js +12800 -2419
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +303 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +439 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +472 -0
  11. package/dist/types.d.ts +751 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +36 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/auth.local-first.test.ts +141 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +138 -25
  27. package/src/modules/cache/cache.relay.test.ts +95 -0
  28. package/src/modules/cache/index.ts +163 -43
  29. package/src/modules/cache/types.ts +2 -2
  30. package/src/modules/crdt/crdt-field.ts +294 -0
  31. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  32. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  33. package/src/modules/crdt/index.ts +463 -0
  34. package/src/modules/crdt/loro-loader.ts +25 -0
  35. package/src/modules/data/data.hydration.test.ts +142 -0
  36. package/src/modules/data/data.membership.test.ts +523 -0
  37. package/src/modules/data/data.notify-table.test.ts +41 -0
  38. package/src/modules/data/data.pending-ids.test.ts +199 -0
  39. package/src/modules/data/data.rebind.test.ts +170 -0
  40. package/src/modules/data/data.rematerialize.test.ts +114 -0
  41. package/src/modules/data/data.run.test.ts +113 -0
  42. package/src/modules/data/data.settled-writes.test.ts +235 -0
  43. package/src/modules/data/data.status.test.ts +249 -0
  44. package/src/modules/data/id-set-plan.test.ts +122 -0
  45. package/src/modules/data/index.ts +1861 -152
  46. package/src/modules/data/mutation-id.test.ts +25 -0
  47. package/src/modules/data/mutation-id.ts +35 -0
  48. package/src/modules/data/window-query.test.ts +52 -0
  49. package/src/modules/data/window-query.ts +194 -0
  50. package/src/modules/devtools/flags.ts +349 -0
  51. package/src/modules/devtools/index.ts +450 -46
  52. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  53. package/src/modules/devtools/state-shape.test.ts +146 -0
  54. package/src/modules/devtools/storage-info.test.ts +79 -0
  55. package/src/modules/devtools/storage-info.ts +168 -0
  56. package/src/modules/devtools/versions.test.ts +74 -0
  57. package/src/modules/devtools/versions.ts +110 -0
  58. package/src/modules/feature-flag/index.test.ts +251 -0
  59. package/src/modules/feature-flag/index.ts +308 -0
  60. package/src/modules/ref-tables.test.ts +91 -0
  61. package/src/modules/ref-tables.ts +88 -0
  62. package/src/modules/sync/engine.ts +165 -86
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  65. package/src/modules/sync/queue/queue-down.ts +108 -13
  66. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  67. package/src/modules/sync/queue/queue-up.ts +241 -57
  68. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  69. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  70. package/src/modules/sync/scheduler.ts +215 -13
  71. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  72. package/src/modules/sync/sync.health.test.ts +149 -0
  73. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  74. package/src/modules/sync/sync.live-removal.test.ts +175 -0
  75. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  76. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +93 -0
  77. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  78. package/src/modules/sync/sync.subquery.test.ts +82 -0
  79. package/src/modules/sync/sync.tabs.test.ts +249 -0
  80. package/src/modules/sync/sync.ts +1868 -98
  81. package/src/modules/sync/utils.test.ts +269 -2
  82. package/src/modules/sync/utils.ts +201 -16
  83. package/src/otel/index.ts +13 -10
  84. package/src/services/blobs/blob-cache.test.ts +359 -0
  85. package/src/services/blobs/blob-cache.ts +603 -0
  86. package/src/services/blobs/blob-manifest.ts +227 -0
  87. package/src/services/blobs/blob-store.test.ts +77 -0
  88. package/src/services/blobs/blob-store.ts +359 -0
  89. package/src/services/blobs/blob.fixture.ts +90 -0
  90. package/src/services/blobs/index.ts +70 -0
  91. package/src/services/database/cache-engine.ts +193 -0
  92. package/src/services/database/connection-supervisor.test.ts +289 -0
  93. package/src/services/database/connection-supervisor.ts +415 -0
  94. package/src/services/database/database.query-timeout.test.ts +83 -0
  95. package/src/services/database/database.ts +41 -12
  96. package/src/services/database/engine-factory.ts +33 -0
  97. package/src/services/database/errors.ts +34 -0
  98. package/src/services/database/events/index.ts +2 -1
  99. package/src/services/database/index.ts +7 -0
  100. package/src/services/database/local-migrator.ts +30 -27
  101. package/src/services/database/local.test.ts +64 -0
  102. package/src/services/database/local.ts +484 -67
  103. package/src/services/database/plan-render.test.ts +159 -0
  104. package/src/services/database/plan-render.ts +108 -0
  105. package/src/services/database/relation-resolver.test.ts +413 -0
  106. package/src/services/database/relation-resolver.ts +0 -0
  107. package/src/services/database/remote.ts +192 -15
  108. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  109. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  110. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  111. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  112. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  113. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  114. package/src/services/database/sqlite-lock-verify.ts +45 -0
  115. package/src/services/database/sqlite-open.test.ts +150 -0
  116. package/src/services/database/sqlite-open.ts +164 -0
  117. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  118. package/src/services/database/sqlite-plan-sql.ts +138 -0
  119. package/src/services/database/sqlite-projection.test.ts +99 -0
  120. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  121. package/src/services/database/sqlite-select.test.ts +246 -0
  122. package/src/services/database/sqlite-select.ts +131 -0
  123. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  124. package/src/services/database/sqlite-transport.ts +224 -0
  125. package/src/services/database/sqlite-worker.ts +437 -0
  126. package/src/services/database/surql-translate.ts +416 -0
  127. package/src/services/database/surreal-cache-engine.ts +161 -0
  128. package/src/services/logger/index.ts +3 -2
  129. package/src/services/persistence/localstorage.ts +2 -2
  130. package/src/services/persistence/resilient.ts +11 -4
  131. package/src/services/persistence/surrealdb.ts +10 -10
  132. package/src/services/stream-processor/index.ts +796 -84
  133. package/src/services/stream-processor/permissions.test.ts +47 -0
  134. package/src/services/stream-processor/permissions.ts +53 -0
  135. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  136. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  137. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  138. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  139. package/src/services/stream-processor/wasm-types.ts +59 -3
  140. package/src/services/tabs/broker-client.ts +283 -0
  141. package/src/services/tabs/broker.test.ts +327 -0
  142. package/src/services/tabs/coordinator.test.ts +365 -0
  143. package/src/services/tabs/coordinator.ts +633 -0
  144. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  145. package/src/services/tabs/leader-locks.ts +75 -0
  146. package/src/services/tabs/protocol.ts +258 -0
  147. package/src/services/tabs/support.ts +36 -0
  148. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  149. package/src/sp00ky.auth-order.test.ts +112 -0
  150. package/src/sp00ky.init-query.test.ts +183 -0
  151. package/src/sp00ky.local-first.test.ts +60 -0
  152. package/src/sp00ky.ts +1772 -0
  153. package/src/types.ts +528 -13
  154. package/src/utils/blurhash.ts +90 -0
  155. package/src/utils/error-classification.test.ts +44 -0
  156. package/src/utils/error-classification.ts +7 -0
  157. package/src/utils/index.ts +79 -13
  158. package/src/utils/parser.test.ts +49 -120
  159. package/src/utils/parser.ts +32 -2
  160. package/src/utils/semver.test.ts +32 -0
  161. package/src/utils/semver.ts +30 -0
  162. package/src/utils/surql.ts +30 -18
  163. package/src/utils/withRetry.test.ts +1 -1
  164. package/tsdown.config.ts +86 -1
  165. package/src/spooky.ts +0 -395
@@ -1,28 +1,35 @@
1
1
  import { RecordId, Duration } from 'surrealdb';
2
- import {
2
+ import type {
3
3
  SchemaStructure,
4
4
  TableNames,
5
5
  BackendNames,
6
6
  BackendRoutes,
7
7
  RoutePayload,
8
+ QueryPlan,
8
9
  } from '@spooky-sync/query-builder';
9
- import { LocalDatabaseService } from '../../services/database/index';
10
- import { CacheModule, RecordWithId } from '../cache/index';
11
- import { Logger } from '../../services/logger/index';
12
- import { StreamUpdate } from '../../services/stream-processor/index';
13
- import {
14
- MutationEvent,
10
+ import type { LocalStore } from '../../services/database/index';
11
+ import { StaleEpochError } from '../../services/database/index';
12
+ import type { CacheModule, RecordWithId, CacheRecord } from '../cache/index';
13
+ import type { Logger } from '../../services/logger/index';
14
+ import type { StreamUpdate } from '../../services/stream-processor/index';
15
+ import type {
15
16
  QueryConfig,
16
17
  QueryHash,
17
18
  QueryState,
19
+ QueryStatus,
20
+ QueryStatusCallback,
18
21
  QueryTimeToLive,
19
22
  QueryUpdateCallback,
20
23
  MutationCallback,
21
24
  RecordVersionArray,
22
25
  QueryConfigRecord,
23
26
  UpdateOptions,
27
+ QueryTimings,
28
+ PhaseStat,
29
+ RegistrationTimings,
24
30
  RunOptions,
25
31
  } from '../../types';
32
+ import { MATERIALIZATION_SAMPLE_WINDOW } from '../../types';
26
33
  import {
27
34
  parseRecordIdString,
28
35
  extractIdPart,
@@ -31,11 +38,44 @@ import {
31
38
  withRetry,
32
39
  surql,
33
40
  parseParams,
41
+ parseQueryParams,
42
+ cleanRecord,
34
43
  extractTablePart,
35
44
  generateId,
36
45
  } from '../../utils/index';
37
- import { CreateEvent, DeleteEvent, UpdateEvent } from '../sync/index';
38
- import { PushEventOptions } from '../../events/index';
46
+ import type { CreateEvent, DeleteEvent, UpdateEvent } from '../sync/index';
47
+ import type { PushEventOptions } from '../../events/index';
48
+ import {
49
+ buildIdSetPlan,
50
+ buildIdSetSurql,
51
+ buildWindowMaterialization,
52
+ buildWindowMaterializationPlan,
53
+ } from './window-query';
54
+ import { mintMutationId } from './mutation-id';
55
+
56
+ /**
57
+ * How many consecutive empty `_00_list_ref` reads it takes to believe a query
58
+ * really is empty, before any non-empty set has been seen this session. One
59
+ * read is the registration race (the SSP flushes a view's initial edges
60
+ * asynchronously); the second comes from the poll a cycle later.
61
+ */
62
+ const EMPTY_MEMBERSHIP_CONFIRMATIONS = 2;
63
+
64
+ /** Push a timing sample (ms) into a rolling window, capped at the sample window. */
65
+ function pushSample(samples: number[], ms: number): void {
66
+ samples.push(ms);
67
+ if (samples.length > MATERIALIZATION_SAMPLE_WINDOW) samples.shift();
68
+ }
69
+
70
+ /** Build a {lastMs,p50,p90,p99,count} summary from a rolling sample window. */
71
+ function phaseStatOf(samples: number[], lastMs: number | null): PhaseStat {
72
+ if (samples.length === 0) {
73
+ return { lastMs, p50: null, p90: null, p99: null, count: 0 };
74
+ }
75
+ const sorted = [...samples].sort((a, b) => a - b);
76
+ const pick = (q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]!;
77
+ return { lastMs, p50: pick(0.5), p90: pick(0.9), p99: pick(0.99), count: samples.length };
78
+ }
39
79
 
40
80
  /**
41
81
  * DataModule - Unified query and mutation management
@@ -43,26 +83,134 @@ import { PushEventOptions } from '../../events/index';
43
83
  * Merges the functionality of QueryManager and MutationManager.
44
84
  * Uses CacheModule for all storage operations.
45
85
  */
86
+ /** A `_00_window` row as read back: the id-set and whether the server vouched
87
+ * for it (which is what allows an empty set to count as known membership). */
88
+ export interface DurableMembership {
89
+ ids: RecordVersionArray;
90
+ confirmed: boolean;
91
+ }
92
+
93
+ /**
94
+ * Fraction of a query's TTL after which the client refreshes `lastActiveAt`.
95
+ *
96
+ * Must leave room for at least one retry: the server sweeps a view — and its
97
+ * `_00_list_ref` edges — the moment `lastActiveAt + ttl` passes, and the client
98
+ * is LIVE on those edges, so a swept-but-still-watched view empties the UI.
99
+ */
100
+ const TTL_HEARTBEAT_FRACTION = 0.5;
101
+
46
102
  export class DataModule<S extends SchemaStructure> {
103
+ /** Tab identity baked into mutation ids (shared-tabs rollback routing);
104
+ * undefined in solo mode, where mutation-id falls back to a session id. */
105
+ private tabId: string | undefined;
47
106
  private activeQueries: Map<QueryHash, QueryState> = new Map();
48
107
  private pendingQueries: Map<QueryHash, Promise<QueryHash>> = new Map();
49
108
  private subscriptions: Map<QueryHash, Set<QueryUpdateCallback>> = new Map();
109
+ private statusSubscriptions: Map<QueryHash, Set<QueryStatusCallback>> = new Map();
50
110
  private mutationCallbacks: Set<MutationCallback> = new Set();
51
111
  private debounceTimers: Map<QueryHash, NodeJS.Timeout> = new Map();
112
+ // The update each debounce timer would process on its trailing edge. Kept in a
113
+ // map (not just the timer closure) so `flushPendingStreamUpdate` can process
114
+ // it early — the sync engine flushes before flipping a query to `idle`, so
115
+ // subscribers never observe idle status with stale (partial-window) rows.
116
+ private pendingStreamUpdates: Map<QueryHash, StreamUpdate> = new Map();
117
+ // Refcount of in-flight fetch cycles per query (registration + concurrent
118
+ // poll/LIVE sync rounds can overlap). Status flips to `fetching` on 0→1 and
119
+ // back to `idle` only on 1→0, so an inner cycle finishing can't emit a
120
+ // premature idle mid-registration.
121
+ private fetchDepth: Map<QueryHash, number> = new Map();
52
122
  private logger: Logger;
123
+ /**
124
+ * Optional observer notified whenever a query's fetch status changes.
125
+ * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
126
+ * settable field (rather than a constructor arg) because DevTools is
127
+ * constructed after DataModule.
128
+ */
129
+ public onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
130
+ /**
131
+ * Optional observer invoked when a still-subscribed query's TTL heartbeat
132
+ * fires (~90% of the TTL). Wired by Sp00kyClient to
133
+ * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
134
+ * row's `lastActiveAt` so an actively-watched query never expires. Settable
135
+ * field (not a constructor arg) because the sync engine is wired after
136
+ * DataModule is constructed — mirrors `onQueryStatusChange`.
137
+ */
138
+ public onHeartbeat?: (hash: QueryHash) => void;
139
+ /**
140
+ * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
141
+ * viewport-windowed list cancelling an off-screen window) loses its last
142
+ * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
143
+ * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
144
+ * instead of leaving it for the TTL sweep. The local view + state are freed in
145
+ * {@link finalizeDeregister} only after that remote delete, so a fast
146
+ * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
147
+ */
148
+ public onDeregister?: (hash: QueryHash) => void;
149
+ // Salt for query-id hashing. Set from SurrealDB's session::id() so two
150
+ // browser sessions registering the same logical query (same surql + params)
151
+ // don't collide on the same `_00_query` row — each session gets its own.
152
+ // Empty string until init(sessionId) is called.
153
+ private sessionId: string = '';
154
+ // Authenticated user record id (e.g. `"user:abc"`). Updated by
155
+ // `setCurrentUserId` from the auth subscription. null when
156
+ // unauthenticated. Consulted by `Sp00kySync.listRefTable()` so the
157
+ // poll and LIVE subscription target the same per-user
158
+ // `_00_list_ref_user_<id>` table the sync engine writes to.
159
+ private currentUserId: string | null = null;
53
160
 
54
161
  constructor(
55
162
  private cache: CacheModule,
56
- private local: LocalDatabaseService,
163
+ private local: LocalStore,
57
164
  private schema: S,
58
165
  logger: Logger,
59
- private streamDebounceTime: number = 100
166
+ // Client-side SSP aggregation throttle: coalesces the in-browser
167
+ // StreamProcessor's per-record stream updates per query before notifying
168
+ // readers, so a burst of synced records repaints the UI once per window
169
+ // rather than row-by-row. 50ms keeps it responsive while still batching the
170
+ // initial-sync stream. Override via `SyncedDbConfig.streamDebounceTime`.
171
+ private streamDebounceTime: number = 50
60
172
  ) {
61
173
  this.logger = logger.child({ service: 'DataModule' });
62
174
  }
63
175
 
64
- async init(): Promise<void> {
65
- this.logger.info({ Category: 'spooky-client::DataModule::init' }, 'DataModule initialized');
176
+ async init(sessionId: string): Promise<void> {
177
+ this.sessionId = sessionId;
178
+ this.logger.info(
179
+ { sessionId, Category: 'sp00ky-client::DataModule::init' },
180
+ 'DataModule initialized'
181
+ );
182
+ }
183
+
184
+ /**
185
+ * Update the session salt used in query-id hashing. Call this when the
186
+ * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
187
+ * registered queries will get fresh, session-scoped IDs.
188
+ */
189
+ setSessionId(sessionId: string): void {
190
+ this.sessionId = sessionId;
191
+ }
192
+
193
+ /** Shared-tabs: bake this tab's identity into mutation ids so a rollback of
194
+ * a follower's mutation routes back to the tab that made it. */
195
+ setTabId(tabId: string): void {
196
+ this.tabId = tabId;
197
+ }
198
+
199
+ /**
200
+ * Update the authenticated user record id. Pass `null` on sign-out.
201
+ * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
202
+ * the poll route to the same per-user `_00_list_ref_user_<id>` the
203
+ * SSP writes to.
204
+ */
205
+ setCurrentUserId(userId: string | null): void {
206
+ this.currentUserId = userId;
207
+ }
208
+
209
+ /** Read-only view of the authenticated user id used for per-user
210
+ * `_00_list_ref` routing. Other modules consult this so they pick the
211
+ * same table name DataModule does. */
212
+ getCurrentUserId(): string | null {
213
+ return this.currentUserId;
66
214
  }
67
215
 
68
216
  // ==================== QUERY MANAGEMENT ====================
@@ -74,19 +222,22 @@ export class DataModule<S extends SchemaStructure> {
74
222
  tableName: T,
75
223
  surqlString: string,
76
224
  params: Record<string, any>,
77
- ttl: QueryTimeToLive
225
+ ttl: QueryTimeToLive,
226
+ plan?: QueryPlan
78
227
  ): Promise<QueryHash> {
79
228
  const hash = await this.calculateHash({ surql: surqlString, params });
80
229
  this.logger.debug(
81
- { hash, Category: 'spooky-client::DataModule::query' },
230
+ { hash, Category: 'sp00ky-client::DataModule::query' },
82
231
  'Query Initialization: started'
83
232
  );
84
233
 
85
- const recordId = new RecordId('_spooky_query', hash);
234
+ // `_00_query` stays the single shared registration table in both
235
+ // ref-modes; the per-user split happens only on `_00_list_ref`.
236
+ const recordId = new RecordId('_00_query', hash);
86
237
 
87
238
  if (this.activeQueries.has(hash)) {
88
239
  this.logger.debug(
89
- { hash, Category: 'spooky-client::DataModule::query' },
240
+ { hash, Category: 'sp00ky-client::DataModule::query' },
90
241
  'Query Initialization: exists, returning'
91
242
  );
92
243
  return hash;
@@ -95,7 +246,7 @@ export class DataModule<S extends SchemaStructure> {
95
246
  // Another call is already creating this query — wait for it
96
247
  if (this.pendingQueries.has(hash)) {
97
248
  this.logger.debug(
98
- { hash, Category: 'spooky-client::DataModule::query' },
249
+ { hash, Category: 'sp00ky-client::DataModule::query' },
99
250
  'Query Initialization: pending, waiting for existing creation'
100
251
  );
101
252
  await this.pendingQueries.get(hash);
@@ -103,12 +254,21 @@ export class DataModule<S extends SchemaStructure> {
103
254
  }
104
255
 
105
256
  this.logger.debug(
106
- { hash, Category: 'spooky-client::DataModule::query' },
257
+ { hash, Category: 'sp00ky-client::DataModule::query' },
107
258
  'Query Initialization: not found, creating new query'
108
259
  );
109
260
 
110
261
  // Create the query and track the pending promise
111
- const promise = this.createAndRegisterQuery<T>(hash, recordId, surqlString, params, ttl, tableName);
262
+ const promise = this.createAndRegisterQuery<T>(
263
+ hash,
264
+ recordId,
265
+ surqlString,
266
+ params,
267
+ ttl,
268
+ tableName,
269
+ plan,
270
+ await this.calculateMembershipKey({ surql: surqlString, params })
271
+ );
112
272
  this.pendingQueries.set(hash, promise);
113
273
  try {
114
274
  await promise;
@@ -147,11 +307,95 @@ export class DataModule<S extends SchemaStructure> {
147
307
  subs.delete(callback);
148
308
  if (subs.size === 0) {
149
309
  this.subscriptions.delete(queryHash);
310
+ // NOTE: intentionally do NOT tear down the query / free its in-browser
311
+ // SSP view here. The subscriber-gated heartbeat (startTTLHeartbeat)
312
+ // already self-stops once subscribers hit 0, so an abandoned query
313
+ // stops being kept alive and the server's TTL sweep removes it. Freeing
314
+ // the local view on every last-unsubscribe caused re-registration churn
315
+ // on navigation (open A → leave → open A again re-registers), which is
316
+ // a flakiness risk for no real benefit — keep the local view resident.
150
317
  }
151
318
  }
152
319
  };
153
320
  }
154
321
 
322
+ /**
323
+ * Subscribe to a query's fetch-status changes (idle/fetching).
324
+ * With `{ immediate: true }` the callback fires synchronously with the
325
+ * current status (defaults to `idle` if the query isn't registered yet).
326
+ */
327
+ subscribeStatus(
328
+ queryHash: string,
329
+ callback: QueryStatusCallback,
330
+ options: { immediate?: boolean } = {}
331
+ ): () => void {
332
+ if (!this.statusSubscriptions.has(queryHash)) {
333
+ this.statusSubscriptions.set(queryHash, new Set());
334
+ }
335
+ this.statusSubscriptions.get(queryHash)?.add(callback);
336
+
337
+ if (options.immediate) {
338
+ callback(this.activeQueries.get(queryHash)?.status ?? 'idle');
339
+ }
340
+
341
+ return () => {
342
+ const subs = this.statusSubscriptions.get(queryHash);
343
+ if (subs) {
344
+ subs.delete(callback);
345
+ if (subs.size === 0) {
346
+ this.statusSubscriptions.delete(queryHash);
347
+ }
348
+ }
349
+ };
350
+ }
351
+
352
+ /**
353
+ * Set a query's fetch status and notify status observers (DevTools +
354
+ * `subscribeStatus` listeners). No-op when the status is unchanged or the
355
+ * query is unknown.
356
+ */
357
+ setQueryStatus(queryHash: string, status: QueryStatus): void {
358
+ const queryState = this.activeQueries.get(queryHash);
359
+ if (!queryState || queryState.status === status) {
360
+ return;
361
+ }
362
+ queryState.status = status;
363
+
364
+ this.onQueryStatusChange?.(queryHash, status);
365
+
366
+ const subs = this.statusSubscriptions.get(queryHash);
367
+ if (subs) {
368
+ for (const callback of subs) {
369
+ callback(status);
370
+ }
371
+ }
372
+ }
373
+
374
+ /**
375
+ * Enter a fetch cycle for a query. Refcounted: registration and concurrent
376
+ * poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
377
+ * cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
378
+ * emits `idle`. Always pair with `endFetching` in a `finally`.
379
+ */
380
+ beginFetching(queryHash: string): void {
381
+ const depth = this.fetchDepth.get(queryHash) ?? 0;
382
+ this.fetchDepth.set(queryHash, depth + 1);
383
+ if (depth === 0) {
384
+ this.setQueryStatus(queryHash, 'fetching');
385
+ }
386
+ }
387
+
388
+ /** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
389
+ endFetching(queryHash: string): void {
390
+ const depth = this.fetchDepth.get(queryHash) ?? 0;
391
+ if (depth <= 1) {
392
+ this.fetchDepth.delete(queryHash);
393
+ this.setQueryStatus(queryHash, 'idle');
394
+ return;
395
+ }
396
+ this.fetchDepth.set(queryHash, depth - 1);
397
+ }
398
+
155
399
  /**
156
400
  * Subscribe to mutations (for sync)
157
401
  */
@@ -168,67 +412,487 @@ export class DataModule<S extends SchemaStructure> {
168
412
  async onStreamUpdate(update: StreamUpdate): Promise<void> {
169
413
  const { queryHash, op } = update;
170
414
 
171
- // Only debounce UPDATE operations
172
- // CREATE and DELETE should propagate immediately
173
- if (op === 'UPDATE') {
174
- // Clear existing timer if any
175
- if (this.debounceTimers.has(queryHash)) {
176
- clearTimeout(this.debounceTimers.get(queryHash)!);
415
+ // DELETE propagates immediately — a removed row should disappear without
416
+ // waiting on a debounce.
417
+ //
418
+ // CREATE and UPDATE are coalesced per query on a trailing timer. A list's
419
+ // rows stream in from sync as many small `_00_list_ref` diffs, each its own
420
+ // `cache.saveBatch` → one stream update per chunk. `ingestMany` only
421
+ // coalesces records ingested synchronously together, so chunks spread over
422
+ // time each re-materialize and re-notify — a 50-row window can fire 30+
423
+ // updates as it fills. Each StreamUpdate carries the full materialized
424
+ // `localArray`, so the latest one already reflects every prior chunk: keep
425
+ // only it and fire once on the trailing edge, settling the query in a couple
426
+ // of notifications instead of one per chunk.
427
+ if (op === 'DELETE') {
428
+ const existing = this.debounceTimers.get(queryHash);
429
+ if (existing) {
430
+ clearTimeout(existing);
431
+ this.debounceTimers.delete(queryHash);
177
432
  }
433
+ // The DELETE update carries the full latest localArray, so the coalesced
434
+ // CREATE/UPDATE it supersedes is already reflected — drop it.
435
+ this.pendingStreamUpdates.delete(queryHash);
436
+ await this.processStreamUpdate(update);
437
+ return;
438
+ }
178
439
 
179
- // Set new timer
180
- const timer = setTimeout(async () => {
181
- this.debounceTimers.delete(queryHash);
182
- await this.processStreamUpdate(update);
183
- }, this.streamDebounceTime);
440
+ this.queueStreamUpdate(update);
441
+ }
184
442
 
185
- this.debounceTimers.set(queryHash, timer);
186
- } else {
187
- // CREATE and DELETE - process immediately
443
+ /** Coalesce `update` onto the query's trailing timer (see onStreamUpdate). */
444
+ private queueStreamUpdate(update: StreamUpdate): void {
445
+ const { queryHash } = update;
446
+ // Clear existing timer if any
447
+ if (this.debounceTimers.has(queryHash)) {
448
+ // oxlint-disable-next-line no-non-null-assertion -- guarded by .has() check above
449
+ clearTimeout(this.debounceTimers.get(queryHash)!);
450
+ }
451
+
452
+ // Set new timer
453
+ this.pendingStreamUpdates.set(queryHash, update);
454
+ const timer = setTimeout(async () => {
455
+ this.debounceTimers.delete(queryHash);
456
+ this.pendingStreamUpdates.delete(queryHash);
188
457
  await this.processStreamUpdate(update);
458
+ }, this.streamDebounceTime);
459
+
460
+ this.debounceTimers.set(queryHash, timer);
461
+ }
462
+
463
+ /**
464
+ * Re-materialize + notify a query whose MEMBERSHIP changed without any row
465
+ * needing to be fetched, i.e. without the SSP stream update that normally
466
+ * carries the notify. That is every row this client wrote itself: the local
467
+ * CREATE memoized it at `_00_rv = 1`, the server publishes it at 1, so the
468
+ * sync engine rightly fetches nothing - and then nobody told the subscribers
469
+ * that `remoteArray` now holds the id. The row appeared on reload only.
470
+ *
471
+ * Routed through the same per-query debounce as a real stream update, so it
472
+ * cannot race one: a pending real update already materializes against the
473
+ * current `remoteArray` and wins. The synthetic update re-uses the circuit's
474
+ * last `localArray` and skips the persist/metrics that describe an ingest.
475
+ */
476
+ scheduleRematerialize(queryHash: string): void {
477
+ if (this.debounceTimers.has(queryHash)) return;
478
+ const queryState = this.activeQueries.get(queryHash);
479
+ if (!queryState) return;
480
+ this.queueStreamUpdate({
481
+ queryHash,
482
+ localArray: queryState.config.localArray ?? [],
483
+ op: 'UPDATE',
484
+ synthetic: true,
485
+ });
486
+ }
487
+
488
+ /**
489
+ * Process a query's pending (debounced) stream update NOW instead of on the
490
+ * trailing edge. Called by the sync engine before it flips a query back to
491
+ * `idle`, so the status change never races ahead of the rows it fetched.
492
+ * No-op when nothing is pending. The pending entry is removed before the
493
+ * await so a concurrently-firing timer can't process it twice.
494
+ */
495
+ async flushPendingStreamUpdate(queryHash: string): Promise<boolean> {
496
+ const timer = this.debounceTimers.get(queryHash);
497
+ if (timer) {
498
+ clearTimeout(timer);
499
+ this.debounceTimers.delete(queryHash);
500
+ }
501
+ const pending = this.pendingStreamUpdates.get(queryHash);
502
+ if (!pending) return false;
503
+ this.pendingStreamUpdates.delete(queryHash);
504
+ await this.processStreamUpdate(pending);
505
+ return true;
506
+ }
507
+
508
+ /**
509
+ * Materialize a query's result rows from the local store.
510
+ *
511
+ * A query's rows are its MEMBERSHIP — the id-set the server put in
512
+ * `_00_list_ref` (`remoteArray`) — not "every local body that matches the
513
+ * WHERE". Those two disagree, and the disagreement was the bug: when a row
514
+ * leaves a query's window but still exists upstream, `handleRemovedRecords`
515
+ * keeps its local body and never re-fetches it, so a predicate re-scan finds
516
+ * that stale body still matching and keeps rendering the row. Selecting the
517
+ * id-set directly is also the only correct thing for a windowed query, where
518
+ * re-applying `START m` against the shared local store skips the window's own
519
+ * rows entirely (sparse windowing) and returns nothing.
520
+ *
521
+ * The rendered set is:
522
+ *
523
+ * (membership ∪ (pendingWrites ∩ localArray)) − pendingDeletes
524
+ *
525
+ * The middle term keeps optimistic writes visible without re-admitting stale
526
+ * rows. Every local write is fed to the SSP (`cache.saveBatch` →
527
+ * `ingestMany`), so `localArray` answers "does this row match the predicate
528
+ * per LOCAL truth". A pending write that moves a row into the window is in
529
+ * `localArray` and shows; one that moves a row out is absent and does not; a
530
+ * stale body the server dropped has no pending write at all, so it stays out.
531
+ * `pendingDeletes` covers the reverse lag — the server still lists a row whose
532
+ * DELETE is sitting in our outbox.
533
+ *
534
+ * Falls back to the predicate scan only when membership has never been
535
+ * established (a query first run on this device), so an offline first paint
536
+ * still shows something.
537
+ */
538
+ private async materializeRecords(
539
+ queryState: QueryState,
540
+ sspArray?: Array<[string, number]>
541
+ ): Promise<Record<string, any>[]> {
542
+ const t0 = performance.now();
543
+ const records = await this.materializeFromConfig(queryState.config, sspArray);
544
+ // Local SurrealDB record-fetch time → DevTools "localFetch" phase.
545
+ this.recordPhase(queryState, 'localFetch', performance.now() - t0);
546
+ return records;
547
+ }
548
+
549
+ /**
550
+ * The materialization itself, without the DevTools timing wrapper. Split out so
551
+ * cold-start seeding can use it before a `QueryState` exists.
552
+ */
553
+ private async materializeFromConfig(
554
+ config: QueryConfig,
555
+ sspArray?: Array<[string, number]>
556
+ ): Promise<Record<string, any>[]> {
557
+ const plan = config.plan;
558
+ const membership = this.resolveMembership(config, sspArray);
559
+ let records: Record<string, any>[];
560
+
561
+ if (membership) {
562
+ const ids = await this.buildRenderIds(config, membership, sspArray);
563
+ if (plan) {
564
+ records = await this.local.select(buildIdSetPlan(plan, ids), config.params);
565
+ } else {
566
+ const idSetSurql = buildIdSetSurql(config.surql);
567
+ if (idSetSurql) {
568
+ const [rows] = await this.local.query<[Record<string, any>[]]>(idSetSurql.query, {
569
+ ...config.params,
570
+ __win: ids,
571
+ });
572
+ records = rows || [];
573
+ } else {
574
+ // Unparseable shape (no top-level FROM): the predicate scan is the
575
+ // only option left. Rare — the query-builder always supplies a plan.
576
+ const [rows] = await this.local.query<[Record<string, any>[]]>(
577
+ config.surql,
578
+ config.params
579
+ );
580
+ records = rows || [];
581
+ }
582
+ }
583
+ } else if (plan) {
584
+ records = await this.local.select(plan, config.params);
585
+ } else {
586
+ const [rows] = await this.local.query<[Record<string, any>[]]>(config.surql, config.params);
587
+ records = rows || [];
588
+ }
589
+ return records;
590
+ }
591
+
592
+ /**
593
+ * The authoritative membership list to render from, or `null` when membership
594
+ * has never been established and the caller must fall back to a scan.
595
+ *
596
+ * A windowed query has no usable fallback — re-running its `START m` locally
597
+ * returns the wrong rows — so it renders from whatever id-set is on hand
598
+ * (SSP's included) rather than degrading to a scan. That is the pre-existing
599
+ * behavior for windows and is preserved.
600
+ */
601
+ private resolveMembership(
602
+ config: QueryConfig,
603
+ sspArray?: Array<[string, number]>
604
+ ): RecordVersionArray | null {
605
+ if (config.membershipKnown) return config.remoteArray ?? [];
606
+ if (buildWindowMaterialization(config.surql) !== null) {
607
+ return (
608
+ (config.remoteArray?.length && config.remoteArray) ||
609
+ (sspArray?.length && sspArray) ||
610
+ config.localArray ||
611
+ []
612
+ );
613
+ }
614
+ return null;
615
+ }
616
+
617
+ // ---- Settled-write grace window ----------------------------------------
618
+ //
619
+ // A local write is visible because it is in the outbox: the render set is
620
+ // `(membership ∪ (pendingWrites ∩ localArray)) − pendingDeletes`. The outbox
621
+ // row is deleted the moment the remote push succeeds (see
622
+ // `UpQueue.next` / `SyncScheduler` — the delete is deliberately tied to the
623
+ // push, not to anything downstream), but the row does not enter `membership`
624
+ // until the SSP has ingested it, materialized the view and written the
625
+ // `_00_list_ref` edge, and this client has read that back.
626
+ //
627
+ // Between those two moments the row is in neither term, so it is rendered,
628
+ // then disappears, then returns — reported as "the comment shows on every
629
+ // other client but not on the one that wrote it". Other clients don't blink
630
+ // because a client that never established membership renders from the local
631
+ // predicate scan instead.
632
+ //
633
+ // So a settled write keeps its place in the union for a short grace period,
634
+ // until membership catches up or the deadline passes. Kept in memory only:
635
+ // it covers a round trip, and a reload re-derives membership anyway.
636
+ private readonly settledWrites = new Map<string, number>();
637
+ private readonly settledDeletes = new Map<string, number>();
638
+
639
+ // ---- Outbox id cache -----------------------------------------------------
640
+ //
641
+ // `getPendingRecordIds` runs a full `SELECT ... FROM _00_pending_mutations`,
642
+ // and `buildRenderIds` calls it on EVERY materialization of EVERY query. That
643
+ // is a round trip down the local engine's single-flight op queue, so with tens
644
+ // of live queries one ingest fanned out into tens of them — in a 4-second
645
+ // capture, 11 of 25 local queries were that one statement, against an outbox
646
+ // holding zero rows.
647
+ //
648
+ // Cached, and invalidated at the two points that change the outbox: enqueueing
649
+ // a mutation (below) and `noteWriteSettled` (the row is deleted before it is
650
+ // called). The TTL is a BACKSTOP, not the mechanism: should some other path
651
+ // ever remove a row without telling us, this bounds the staleness to one tick
652
+ // instead of the session. Well under the grace windows the render set already
653
+ // tolerates deliberately (SETTLED_WRITE_GRACE_MS is 10s).
654
+ private pendingIds: { writes: Set<string>; deletes: Set<string> } | null = null;
655
+ private pendingIdsAt = 0;
656
+ private pendingIdsInflight: Promise<{ writes: Set<string>; deletes: Set<string> }> | null = null;
657
+ private static readonly PENDING_IDS_TTL_MS = 250;
658
+ // Bumped by every invalidation. A read carries the generation it started
659
+ // under, and a result from an older generation is neither cached nor
660
+ // returned to a caller that asked after the invalidation: it was taken
661
+ // before the outbox row it needs existed. Without this, a materialization
662
+ // that joined a read already in flight when `create()` invalidated saw the
663
+ // pre-create set, found "no change", and skipped its notify - the one
664
+ // stream update a CREATE gets, so the row stayed invisible until reload.
665
+ private pendingIdsGen = 0;
666
+ private static readonly PENDING_IDS_MAX_REREADS = 3;
667
+
668
+ /** Drop the cached outbox ids. Cheap; call it on anything that could change
669
+ * `_00_pending_mutations`. */
670
+ private invalidatePendingIds(): void {
671
+ this.pendingIds = null;
672
+ this.pendingIdsGen++;
673
+ // The in-flight read (if any) predates this invalidation; whoever joins
674
+ // next starts a fresh one. Its own joiners re-read via the generation check.
675
+ this.pendingIdsInflight = null;
676
+ }
677
+
678
+ /**
679
+ * Grace period for a settled write. Long enough to cover an SSP round trip
680
+ * that is running slowly (seconds, not milliseconds, when the edge path is
681
+ * backed up), short enough that a write the server silently dropped cannot
682
+ * linger misleadingly.
683
+ *
684
+ * The rejection case does NOT rely on this expiring: an application error
685
+ * rolls the mutation back and never reports it settled, so it vanishes at
686
+ * once. This deadline only bounds the case where the write succeeded and its
687
+ * membership never arrived at all.
688
+ *
689
+ * 30 s, up from 10 s. At 10 s every server hiccup longer than a scheduler
690
+ * drain plus one slow database commit showed up as the user's own chat
691
+ * message vanishing and coming back a minute later. 30 s covers a drain and
692
+ * a stalled commit end to end; a membership that takes longer than that is
693
+ * a server fault the admin heartbeat reports, not something to paper over.
694
+ */
695
+ private static readonly SETTLED_WRITE_GRACE_MS = 30_000;
696
+
697
+ /**
698
+ * Whether any settled write or delete is still waiting for membership to
699
+ * catch up. The sync poll keeps its fast cadence while this is true, so a
700
+ * missed LIVE notification for the edge is picked up on the next poll tick
701
+ * rather than after the idle backoff.
702
+ */
703
+ hasSettledWritesPending(): boolean {
704
+ this.pruneSettled(Date.now());
705
+ return this.settledWrites.size > 0 || this.settledDeletes.size > 0;
706
+ }
707
+
708
+ /**
709
+ * Report that a mutation was accepted by the server and its outbox row
710
+ * removed. Called only on the SUCCESS path — a rolled-back mutation must
711
+ * disappear immediately, which is what makes this safe.
712
+ */
713
+ noteWriteSettled(recordId: string, mutationType: string): void {
714
+ // The outbox row is already gone by the time this is called — that is what
715
+ // makes it the delete-side invalidation point for the cache above.
716
+ this.invalidatePendingIds();
717
+ const until = Date.now() + DataModule.SETTLED_WRITE_GRACE_MS;
718
+ if (mutationType === 'delete') this.settledDeletes.set(recordId, until);
719
+ else this.settledWrites.set(recordId, until);
720
+ }
721
+
722
+ /** Drop entries past their deadline. */
723
+ private pruneSettled(now: number): void {
724
+ for (const [id, until] of this.settledWrites) {
725
+ if (until <= now) this.settledWrites.delete(id);
726
+ }
727
+ for (const [id, until] of this.settledDeletes) {
728
+ if (until <= now) this.settledDeletes.delete(id);
189
729
  }
190
730
  }
191
731
 
732
+ /** Apply the pending-write union and pending-delete subtraction, and map to
733
+ * RecordIds for the engines' id-set path. */
734
+ private async buildRenderIds(
735
+ config: QueryConfig,
736
+ membership: RecordVersionArray,
737
+ sspArray?: Array<[string, number]>
738
+ ): Promise<unknown[]> {
739
+ const { writes, deletes } = await this.getPendingRecordIds();
740
+ const now = Date.now();
741
+ this.pruneSettled(now);
742
+ // A settled write counts as pending until membership catches up. Merged
743
+ // into the same sets so the union/subtraction below is unchanged — the
744
+ // grace window changes WHEN an id leaves the render set, never how the
745
+ // set is composed.
746
+ if (this.settledWrites.size > 0) {
747
+ for (const id of this.settledWrites.keys()) writes.add(id);
748
+ }
749
+ if (this.settledDeletes.size > 0) {
750
+ for (const id of this.settledDeletes.keys()) deletes.add(id);
751
+ }
752
+
753
+ const ordered: string[] = [];
754
+ const seen = new Set<string>();
755
+ for (const [id] of membership) {
756
+ // Membership has caught up with this write: the grace window has done
757
+ // its job and ends here rather than at its deadline. Doing it inline
758
+ // keeps the common case (nothing settled) free of extra passes.
759
+ if (this.settledWrites.size > 0) this.settledWrites.delete(id);
760
+ if (deletes.has(id) || seen.has(id)) continue;
761
+ seen.add(id);
762
+ ordered.push(id);
763
+ }
764
+ // A settled DELETE is the mirror case: membership still lists the row
765
+ // until the SSP publishes its removal, so the id stays subtracted until
766
+ // membership stops naming it.
767
+ if (this.settledDeletes.size > 0) {
768
+ const stillListed = new Set(membership.map(([id]) => id));
769
+ for (const id of [...this.settledDeletes.keys()]) {
770
+ if (!stillListed.has(id)) this.settledDeletes.delete(id);
771
+ }
772
+ }
773
+ if (writes.size > 0) {
774
+ // Only pending writes the SSP agrees currently match this query — see the
775
+ // formula in `materializeRecords`. `sspArray` is the fresher signal when a
776
+ // stream update triggered this pass; `localArray` is the persisted one.
777
+ const localView = (sspArray?.length && sspArray) || config.localArray || [];
778
+ for (const [id] of localView) {
779
+ if (!writes.has(id) || deletes.has(id) || seen.has(id)) continue;
780
+ seen.add(id);
781
+ ordered.push(id);
782
+ }
783
+ }
784
+ // `_00_list_ref` is selected without an ORDER BY, so this id-set arrives in
785
+ // whatever order the server happened to return. For a query with its own
786
+ // ORDER BY that does not matter (the engine sorts), and for a window the
787
+ // id-set order IS the window's slice order and must be preserved. Anything
788
+ // else renders in server order while its first paint came from the local
789
+ // scan in id order — the same rows, visibly reshuffled a second later.
790
+ // Sorting here is what makes the two paints agree.
791
+ const hasExplicitOrder = (config.plan?.orderBy?.length ?? 0) > 0;
792
+ const isWindow = buildWindowMaterialization(config.surql) !== null;
793
+ if (!hasExplicitOrder && !isWindow) {
794
+ ordered.sort();
795
+ }
796
+ return ordered.map((id) => parseRecordIdString(id));
797
+ }
798
+
192
799
  private async processStreamUpdate(update: StreamUpdate): Promise<void> {
193
- const { queryHash, localArray } = update;
800
+ const { queryHash, localArray, materializationTimeMs } = update;
194
801
  const queryState = this.activeQueries.get(queryHash);
195
802
  if (!queryState) {
196
803
  this.logger.warn(
197
- { queryHash, Category: 'spooky-client::DataModule::onStreamUpdate' },
804
+ { queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
198
805
  'Received update for unknown query. Skipping...'
199
806
  );
200
807
  return;
201
808
  }
202
809
 
203
- try {
204
- // Fetch updated records
205
- const [records] = await this.local.query<[Record<string, any>[]]>(
206
- queryState.config.surql,
207
- queryState.config.params
208
- );
810
+ // Update the rolling materialization-sample window before the work that
811
+ // could throw, so the percentiles still move when the downstream local
812
+ // query fails (the materialization step itself ran).
813
+ if (typeof materializationTimeMs === 'number') {
814
+ queryState.materializationSamples.push(materializationTimeMs);
815
+ if (queryState.materializationSamples.length > MATERIALIZATION_SAMPLE_WINDOW) {
816
+ queryState.materializationSamples.shift();
817
+ }
818
+ queryState.lastIngestLatencyMs = materializationTimeMs;
819
+ }
820
+ // Record the SSP internal sub-phase timings (from the WASM binding) so
821
+ // DevTools can attribute ingest cost to store-apply vs circuit-step vs transform.
822
+ if (typeof update.storeApplyMs === 'number')
823
+ this.recordPhase(queryState, 'sspStoreApply', update.storeApplyMs);
824
+ if (typeof update.circuitStepMs === 'number')
825
+ this.recordPhase(queryState, 'sspCircuitStep', update.circuitStepMs);
826
+ if (typeof update.transformMs === 'number')
827
+ this.recordPhase(queryState, 'sspTransform', update.transformMs);
828
+ const percentiles = this.computeMaterializationPercentiles(queryState.materializationSamples);
829
+
830
+ // Fence against bucket switches: this update's `localArray` came from the
831
+ // pre-switch SSP circuit; applying it after a switch would show (and
832
+ // persist) the previous user's ids in the new bucket.
833
+ const epoch = this.local.epoch;
209
834
 
210
- // Update state
211
- const newRecords = records || [];
212
- queryState.config.localArray = localArray;
213
- await this.local.query(surql.seal(surql.updateSet('id', ['localArray'])), {
214
- id: queryState.config.id,
215
- localArray,
216
- });
835
+ try {
836
+ // Materialize the query's rows. For a windowed (offset) query, re-running
837
+ // the original surql would re-apply `START n` against the shared local DB
838
+ // and skip the window's rows entirely; instead select the SSP's
839
+ // materialized window id-set (`localArray`) directly, re-applying the
840
+ // original ORDER BY for stable display order. Non-offset queries keep the
841
+ // normal re-query path.
842
+ const newRecords = await this.materializeRecords(queryState, localArray);
843
+ if (epoch !== this.local.epoch) return;
844
+ if (!update.synthetic) queryState.config.localArray = localArray;
217
845
 
218
- // Skip notification if records haven't changed
219
846
  const prevJson = JSON.stringify(queryState.records);
220
847
  const newJson = JSON.stringify(newRecords);
221
848
  queryState.records = newRecords;
222
- if (prevJson === newJson) {
849
+ const recordsChanged = prevJson !== newJson;
850
+
851
+ // updateCount counts user-visible updates (matches the prior semantic),
852
+ // while the materialization sample/percentiles already moved above for
853
+ // every observed engine step.
854
+ if (recordsChanged) {
855
+ queryState.updateCount++;
856
+ queryState.lastUpdatedAt = Date.now();
857
+ }
858
+
859
+ // A synthetic re-materialize did not come from an ingest: nothing about
860
+ // the circuit's view changed, so there is nothing to persist for it.
861
+ if (!update.synthetic) {
862
+ await this.local.query(
863
+ surql.seal(
864
+ surql.updateSet('id', [
865
+ 'localArray',
866
+ 'rowCount',
867
+ 'updateCount',
868
+ 'lastIngestLatency',
869
+ 'materializationP55',
870
+ 'materializationP90',
871
+ 'materializationP99',
872
+ ])
873
+ ),
874
+ {
875
+ id: queryState.config.id,
876
+ localArray,
877
+ rowCount: localArray.length,
878
+ updateCount: queryState.updateCount,
879
+ lastIngestLatency: queryState.lastIngestLatencyMs,
880
+ materializationP55: percentiles.p55,
881
+ materializationP90: percentiles.p90,
882
+ materializationP99: percentiles.p99,
883
+ },
884
+ { epoch }
885
+ );
886
+ }
887
+
888
+ if (!recordsChanged) {
223
889
  this.logger.debug(
224
- { queryHash, Category: 'spooky-client::DataModule::onStreamUpdate' },
890
+ { queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
225
891
  'Query records unchanged, skipping notification'
226
892
  );
227
893
  return;
228
894
  }
229
895
 
230
- queryState.updateCount++;
231
-
232
896
  // Notify subscribers
233
897
  const subscribers = this.subscriptions.get(queryHash);
234
898
  if (subscribers) {
@@ -240,19 +904,110 @@ export class DataModule<S extends SchemaStructure> {
240
904
  this.logger.debug(
241
905
  {
242
906
  queryHash,
243
- recordCount: records?.length,
244
- Category: 'spooky-client::DataModule::onStreamUpdate',
907
+ recordCount: newRecords?.length,
908
+ Category: 'sp00ky-client::DataModule::onStreamUpdate',
245
909
  },
246
910
  'Query updated from stream'
247
911
  );
248
912
  } catch (err) {
913
+ if (err instanceof StaleEpochError) {
914
+ this.logger.debug(
915
+ { queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
916
+ 'Dropped stream update from before a bucket switch'
917
+ );
918
+ return;
919
+ }
920
+ queryState.errorCount++;
249
921
  this.logger.error(
250
- { err, queryHash, Category: 'spooky-client::DataModule::onStreamUpdate' },
922
+ { err, queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
251
923
  'Failed to fetch records for stream update'
252
924
  );
925
+ // Best-effort persist of the bumped errorCount; swallow secondary
926
+ // failures to avoid masking the original error in logs.
927
+ try {
928
+ await this.local.query(surql.seal(surql.updateSet('id', ['errorCount'])), {
929
+ id: queryState.config.id,
930
+ errorCount: queryState.errorCount,
931
+ });
932
+ } catch (persistErr) {
933
+ this.logger.warn(
934
+ {
935
+ err: persistErr,
936
+ queryHash,
937
+ Category: 'sp00ky-client::DataModule::onStreamUpdate',
938
+ },
939
+ 'Failed to persist incremented errorCount'
940
+ );
941
+ }
253
942
  }
254
943
  }
255
944
 
945
+ /**
946
+ * Compute p55/p90/p99 from a rolling window of materialization samples.
947
+ * Returns nulls for any percentile that has no samples yet so SurrealDB
948
+ * `option<float>` columns stay NONE rather than 0 before the first ingest.
949
+ */
950
+ private computeMaterializationPercentiles(samples: number[]): {
951
+ p55: number | null;
952
+ p90: number | null;
953
+ p99: number | null;
954
+ } {
955
+ if (samples.length === 0) {
956
+ return { p55: null, p90: null, p99: null };
957
+ }
958
+ const sorted = [...samples].sort((a, b) => a - b);
959
+ const pick = (q: number) => {
960
+ const idx = Math.min(sorted.length - 1, Math.floor(q * sorted.length));
961
+ return sorted[idx]!;
962
+ };
963
+ return { p55: pick(0.55), p90: pick(0.9), p99: pick(0.99) };
964
+ }
965
+
966
+ /** Record a per-phase timing sample (ms) on a query's rolling window. */
967
+ private recordPhase(qs: QueryState, phase: string, ms: number): void {
968
+ if (!Number.isFinite(ms)) return;
969
+ const arr = qs.phaseSamples[phase] ?? (qs.phaseSamples[phase] = []);
970
+ pushSample(arr, ms);
971
+ qs.phaseLast[phase] = ms;
972
+ }
973
+
974
+ /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
975
+ recordRemoteFetch(hash: string, ms: number): void {
976
+ const qs = this.activeQueries.get(hash);
977
+ if (qs) this.recordPhase(qs, 'remoteFetch', ms);
978
+ }
979
+
980
+ /**
981
+ * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
982
+ * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
983
+ */
984
+ recordFrontendTiming(hash: string, ms: number): void {
985
+ const qs = this.activeQueries.get(hash);
986
+ if (qs) this.recordPhase(qs, 'frontend', ms);
987
+ }
988
+
989
+ /**
990
+ * Build the per-query processing-time breakdown surfaced to the DevTools panel
991
+ * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
992
+ * the rest come from the per-phase rolling windows + one-shot registration timings.
993
+ */
994
+ phaseTimings(q: QueryState): QueryTimings {
995
+ const stat = (phase: string) =>
996
+ phaseStatOf(q.phaseSamples[phase] ?? [], q.phaseLast[phase] ?? null);
997
+ return {
998
+ ssp: phaseStatOf(q.materializationSamples, q.lastIngestLatencyMs),
999
+ sspStoreApply: stat('sspStoreApply'),
1000
+ sspCircuitStep: stat('sspCircuitStep'),
1001
+ sspTransform: stat('sspTransform'),
1002
+ localFetch: stat('localFetch'),
1003
+ remoteFetch: stat('remoteFetch'),
1004
+ frontend: stat('frontend'),
1005
+ registration: q.registrationTimings,
1006
+ updateCount: q.updateCount,
1007
+ errorCount: q.errorCount,
1008
+ };
1009
+ }
1010
+
256
1011
  /**
257
1012
  * Get query state (for sync and devtools)
258
1013
  */
@@ -260,6 +1015,417 @@ export class DataModule<S extends SchemaStructure> {
260
1015
  return this.activeQueries.get(hash);
261
1016
  }
262
1017
 
1018
+ /**
1019
+ * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
1020
+ * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
1021
+ * We gate on `remoteArray`, not local `records`: a windowed query is often
1022
+ * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
1023
+ * but it still hasn't loaded its own full window from the server — so it should
1024
+ * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
1025
+ */
1026
+ isCold(hash: string): boolean {
1027
+ const qs = this.activeQueries.get(hash);
1028
+ return !!qs && !qs.hydrated && (qs.config.remoteArray?.length ?? 0) === 0;
1029
+ }
1030
+
1031
+ /**
1032
+ * Walk a hydrated record's fields and append any EMBEDDED child records to
1033
+ * `batch` (recursing for nested related fields). An embedded child is a
1034
+ * value that is itself a record — a non-null object whose `id` is a
1035
+ * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
1036
+ * bare `RecordId` (a foreign-key reference) or any other value is skipped,
1037
+ * so this never mistakes a FK column for an embedded body. Children are
1038
+ * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
1039
+ * to their table's real columns (which strips the alias/related fields).
1040
+ * `seen` dedupes within the batch.
1041
+ */
1042
+ private collectEmbeddedChildren(
1043
+ record: Record<string, any>,
1044
+ batch: CacheRecord[],
1045
+ seen: Set<string>
1046
+ ): void {
1047
+ const isEmbeddedRecord = (v: unknown): v is RecordWithId =>
1048
+ !!v &&
1049
+ typeof v === 'object' &&
1050
+ !(v instanceof RecordId) &&
1051
+ (v as { id?: unknown }).id instanceof RecordId;
1052
+
1053
+ for (const value of Object.values(record)) {
1054
+ const children = Array.isArray(value)
1055
+ ? value.filter(isEmbeddedRecord)
1056
+ : isEmbeddedRecord(value)
1057
+ ? [value]
1058
+ : [];
1059
+ for (const child of children) {
1060
+ const key = encodeRecordId(child.id);
1061
+ if (seen.has(key)) continue;
1062
+ seen.add(key);
1063
+ // Recurse FIRST so nested grandchildren are captured before `cleanRecord`
1064
+ // strips this child's alias fields.
1065
+ this.collectEmbeddedChildren(child, batch, seen);
1066
+ const table = child.id.table.toString();
1067
+ const tableSchema = this.schema.tables.find((t) => t.name === table);
1068
+ batch.push({
1069
+ table,
1070
+ op: 'CREATE',
1071
+ // Flatten the child too: a nested comment carries its own embedded
1072
+ // `author` object which the schemafull `record<user>` field would
1073
+ // reject. (Its author is captured as a separate row by the recursion
1074
+ // above.)
1075
+ record: this.flattenRelationsForStorage(child, tableSchema),
1076
+ version: (child._00_rv as number) || 1,
1077
+ });
1078
+ }
1079
+ }
1080
+ }
1081
+
1082
+ /**
1083
+ * Prepare a subquery-bearing row (preload / hydration) for the schemafull
1084
+ * local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
1085
+ * with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
1086
+ * ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
1087
+ * own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
1088
+ * with relations already RecordIds — passes through unchanged.
1089
+ */
1090
+ private flattenRelationsForStorage(
1091
+ record: Record<string, any>,
1092
+ tableSchema?: { columns: Record<string, any> }
1093
+ ): RecordWithId {
1094
+ const isEmbeddedRecord = (v: unknown): boolean =>
1095
+ !!v &&
1096
+ typeof v === 'object' &&
1097
+ !(v instanceof RecordId) &&
1098
+ (v as { id?: unknown }).id instanceof RecordId;
1099
+ const flat: Record<string, any> = {};
1100
+ for (const [k, v] of Object.entries(record)) {
1101
+ if (isEmbeddedRecord(v)) {
1102
+ flat[k] = (v as { id: unknown }).id;
1103
+ } else if (Array.isArray(v) && v.some(isEmbeddedRecord)) {
1104
+ continue;
1105
+ } else {
1106
+ flat[k] = v;
1107
+ }
1108
+ }
1109
+ return (tableSchema ? cleanRecord(tableSchema.columns, flat) : flat) as RecordWithId;
1110
+ }
1111
+
1112
+ /**
1113
+ * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
1114
+ * surql run directly) so the query DISPLAYS immediately, while the full realtime
1115
+ * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
1116
+ * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
1117
+ * `remoteArray` so windowed queries materialize the correct window (no sparse
1118
+ * local-circuit issue). Runs at most once per query (the `hydrated` flag).
1119
+ */
1120
+ async applyHydration(hash: string, rows: RecordWithId[]): Promise<void> {
1121
+ const queryState = this.activeQueries.get(hash);
1122
+ if (!queryState) return;
1123
+ queryState.hydrated = true; // run-once, even when the remote returns nothing
1124
+ if (rows.length === 0) return;
1125
+
1126
+ const epoch = this.local.epoch;
1127
+ const tableName = queryState.config.tableName;
1128
+ await this.buildAndSaveCacheBatch(tableName, rows);
1129
+ // Bucket switched while we persisted: these rows were fetched under the
1130
+ // previous auth context — don't let them prime the new bucket's query
1131
+ // state; the rebind's re-registration refills it. (saveBatch's own epoch
1132
+ // fence usually catches this, but the switch can land between it and here.)
1133
+ if (epoch !== this.local.epoch) return;
1134
+
1135
+ // Prime remoteArray from the hydrated id+version pairs: `materializeRecords`
1136
+ // renders from it and it feeds the version dedup. Registration later
1137
+ // overwrites it with the authoritative `_00_list_ref`.
1138
+ queryState.config.remoteArray = rows.map(
1139
+ (r) => [encodeRecordId(r.id), (r._00_rv as number) || 1] as [string, number]
1140
+ );
1141
+ // These rows ARE the server's answer to this query, so membership is now
1142
+ // known and rendering can stop falling back to a predicate scan. The durable
1143
+ // `_00_window` mirror is deliberately left to `updateQueryRemoteArray` (the
1144
+ // single write point) — the registration that follows lands there anyway.
1145
+ queryState.config.membershipKnown = true;
1146
+
1147
+ queryState.records = await this.materializeRecords(queryState);
1148
+ const subscribers = this.subscriptions.get(hash);
1149
+ if (subscribers) {
1150
+ for (const cb of subscribers) cb(queryState.records);
1151
+ }
1152
+ }
1153
+
1154
+ /**
1155
+ * Build the cache batch for a set of one-shot rows and persist it to the
1156
+ * local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
1157
+ * and extracts EMBEDDED related children (any nesting depth) as their own
1158
+ * records — a `.related()` query returns its children embedded, and a later
1159
+ * correlated re-materialization needs them present as standalone rows.
1160
+ * Shared by `applyHydration` (live registration) and `persistSnapshot`
1161
+ * (preload).
1162
+ */
1163
+ private async buildAndSaveCacheBatch(tableName: string, rows: RecordWithId[]): Promise<void> {
1164
+ const tableSchema = this.schema.tables.find((t) => t.name === tableName);
1165
+ const batch: CacheRecord[] = rows.map((record) => ({
1166
+ table: tableName,
1167
+ op: 'CREATE' as const,
1168
+ // Flatten embedded relations first: a preload/hydration row can carry a
1169
+ // forward relation as a full nested OBJECT (`author = { id, … }`) and a
1170
+ // reverse subquery as an array of objects (`comments = [ … ]`). The
1171
+ // schemafull local field is `record<user>`, which rejects an object
1172
+ // (`Couldn't coerce … found { id: …, username: … }`) and would throw the
1173
+ // WHOLE batch. Store the parent with `author` as its RecordId and drop the
1174
+ // subquery arrays — the children are cached as their own rows below.
1175
+ record: this.flattenRelationsForStorage(record, tableSchema),
1176
+ version: (record._00_rv as number) || 1,
1177
+ }));
1178
+
1179
+ const seen = new Set<string>(rows.map((r) => encodeRecordId(r.id)));
1180
+ for (const record of rows) {
1181
+ this.collectEmbeddedChildren(record, batch, seen);
1182
+ }
1183
+
1184
+ await this.cache.saveBatch(batch);
1185
+ }
1186
+
1187
+ /**
1188
+ * Preload/prewarm: persist one-shot rows (and their embedded related children)
1189
+ * into the local cache WITHOUT registering a query — no `activeQueries` entry,
1190
+ * no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
1191
+ * ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
1192
+ * first paint from them instantly, then registers a live view to freshen.
1193
+ */
1194
+ async persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void> {
1195
+ if (rows.length === 0) return;
1196
+ await this.buildAndSaveCacheBatch(tableName, rows);
1197
+ }
1198
+
1199
+ /**
1200
+ * Read the durable preload freshness marker for a query hash, or null if this
1201
+ * query was never preloaded in the current bucket. Co-located with the cached
1202
+ * rows (per-bucket `_00_preload` table) so a bucket switch that clears the
1203
+ * data also clears the marker — a stale marker can't claim "warm" when the
1204
+ * rows are gone. Any read error is treated as cold.
1205
+ */
1206
+ async getPreloadMarker(hash: string): Promise<{ fetchedAt: number; rowCount: number } | null> {
1207
+ try {
1208
+ // Pass a real RecordId: a bare string id hits the SurrealDB engine's
1209
+ // `FROM ONLY $__id` as a plain string, which "selects" the string itself
1210
+ // (a truthy non-row) instead of the record — misread as a warm marker.
1211
+ const row = await this.local.getById('_00_preload', new RecordId('_00_preload', hash));
1212
+ if (!row || typeof row !== 'object') return null;
1213
+ return {
1214
+ fetchedAt: Number((row as any).fetchedAt) || 0,
1215
+ rowCount: Number((row as any).rowCount) || 0,
1216
+ };
1217
+ } catch {
1218
+ return null;
1219
+ }
1220
+ }
1221
+
1222
+ /** Stamp the preload freshness marker after a successful snapshot fetch. */
1223
+ async writePreloadMarker(hash: string, rowCount: number): Promise<void> {
1224
+ // RecordId, not a bare string: the SurrealDB engine binds the id verbatim,
1225
+ // and `UPSERT <string>` is an InternalError — the marker silently never
1226
+ // landed (the write is awaited inside preload's best-effort catch).
1227
+ await this.local.upsert(
1228
+ '_00_preload',
1229
+ new RecordId('_00_preload', hash),
1230
+ { fetchedAt: Date.now(), rowCount },
1231
+ 'replace'
1232
+ );
1233
+ }
1234
+
1235
+ // ---- Durable membership (`_00_window`) ---------------------------------
1236
+ //
1237
+ // A query's authoritative membership is the id-set the server put in
1238
+ // `_00_list_ref` — `config.remoteArray`. It is persisted on the `_00_query`
1239
+ // row, but that row's id is salted with `session::id()`, which is new on every
1240
+ // page load (and `''` offline), and `doSwitchBucket` wipes the table outright.
1241
+ // So membership never survived a reload: the first paint fell back to a
1242
+ // predicate scan over whatever bodies were still cached, which re-included
1243
+ // rows the server had already dropped from the window.
1244
+ //
1245
+ // `_00_window` fixes that: same data, keyed by a session-independent hash, in
1246
+ // a table nothing wipes. Mirrors the durable `_00_preload` marker above.
1247
+ //
1248
+ // Row shape: `{ ids, confirmed, updatedAt }`. `confirmed` is the one bit that
1249
+ // lets an EMPTY row be trusted on the next boot (see `getWindowMembership`).
1250
+
1251
+ /**
1252
+ * Read the durable membership row, or `null` if this query has never had
1253
+ * authoritative membership on this device. Any read error is treated as
1254
+ * "unknown" so a broken row degrades to the predicate scan rather than
1255
+ * rendering an empty list.
1256
+ *
1257
+ * `confirmed` is true only for rows written after the server itself vouched
1258
+ * for the set (a non-empty id-set, or an empty one it reported a row count of
1259
+ * zero for, or an empty one that followed a non-empty one in the same
1260
+ * session). Rows written before the marker existed, including the `[]` rows a
1261
+ * pre-`ea56f50e` client mirrored from an unflushed read, read as unconfirmed.
1262
+ */
1263
+ async getWindowMembership(key: string): Promise<DurableMembership | null> {
1264
+ try {
1265
+ const row = await this.local.getById('_00_window', new RecordId('_00_window', key));
1266
+ if (!row || typeof row !== 'object') return null;
1267
+ const ids = (row as any).ids;
1268
+ if (!Array.isArray(ids)) return null;
1269
+ return { ids: ids as RecordVersionArray, confirmed: (row as any).confirmed === true };
1270
+ } catch {
1271
+ return null;
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ * Persist the durable membership row. Best-effort: callers must not fail a
1277
+ * sync round because the mirror write failed.
1278
+ *
1279
+ * `confirmed` says whether a cold start may trust this row even when it is
1280
+ * empty. A confirmed empty is a real answer ("the server says this query has
1281
+ * no rows") and stays empty across a reload; an unconfirmed empty is the
1282
+ * retry budget's guess and falls back to the predicate scan on the next boot,
1283
+ * exactly as every empty row did before the marker existed.
1284
+ */
1285
+ async writeWindowMembership(
1286
+ key: string,
1287
+ ids: RecordVersionArray,
1288
+ confirmed: boolean
1289
+ ): Promise<void> {
1290
+ try {
1291
+ await this.local.upsert(
1292
+ '_00_window',
1293
+ new RecordId('_00_window', key),
1294
+ { ids, confirmed, updatedAt: Date.now() },
1295
+ 'replace'
1296
+ );
1297
+ } catch (err) {
1298
+ this.logger.debug(
1299
+ { err, key, Category: 'sp00ky-client::DataModule::writeWindowMembership' },
1300
+ 'Failed to persist window membership; it will be re-derived on next register'
1301
+ );
1302
+ }
1303
+ }
1304
+
1305
+ /**
1306
+ * Record ids with a mutation still in the outbox, split by direction.
1307
+ *
1308
+ * Both halves feed {@link materializeRecords}: `writes` keeps optimistic
1309
+ * creates/updates visible before the server has acknowledged them, and
1310
+ * `deletes` suppresses rows the server still lists because our DELETE hasn't
1311
+ * been processed yet. Reading `_00_pending_mutations` (rather than tracking
1312
+ * ids in memory) is what makes both survive a reload.
1313
+ *
1314
+ * On failure returns empty sets: membership alone then decides, which can
1315
+ * briefly hide an optimistic write but never resurrects a deleted row.
1316
+ */
1317
+ async getPendingRecordIds(): Promise<{ writes: Set<string>; deletes: Set<string> }> {
1318
+ const now = Date.now();
1319
+ const cached = this.pendingIds;
1320
+ if (cached && now - this.pendingIdsAt < DataModule.PENDING_IDS_TTL_MS) {
1321
+ // COPIES: `buildRenderIds` merges the settled-write ids into these sets,
1322
+ // and handing out the cached instances would let it grow them permanently.
1323
+ return { writes: new Set(cached.writes), deletes: new Set(cached.deletes) };
1324
+ }
1325
+ // Single-flight: one ingest fans out to many queries materializing at once,
1326
+ // and without this they all queue their own identical read behind each other.
1327
+ // Bounded re-read: a result from a generation older than the one current
1328
+ // by the time it lands was taken before some outbox row existed, so it is
1329
+ // re-issued rather than returned. Bounded, because a write on every tick
1330
+ // must not spin this forever - the last read is returned then.
1331
+ let fresh: { writes: Set<string>; deletes: Set<string> } | null = null;
1332
+ for (let attempt = 0; attempt < DataModule.PENDING_IDS_MAX_REREADS; attempt++) {
1333
+ const gen = this.pendingIdsGen;
1334
+ if (!this.pendingIdsInflight) {
1335
+ const read = this.readPendingRecordIds(gen).finally(() => {
1336
+ // Only clear the slot this read still owns; an invalidation in the
1337
+ // meantime has replaced it (with null) for a newer read to fill.
1338
+ if (this.pendingIdsInflight === read) this.pendingIdsInflight = null;
1339
+ });
1340
+ this.pendingIdsInflight = read;
1341
+ }
1342
+ fresh = await this.pendingIdsInflight;
1343
+ if (gen === this.pendingIdsGen) break;
1344
+ }
1345
+ // oxlint-disable-next-line no-non-null-assertion -- the loop runs at least once
1346
+ return { writes: new Set(fresh!.writes), deletes: new Set(fresh!.deletes) };
1347
+ }
1348
+
1349
+ /** The uncached read. Also the reload path after an invalidation, so the ids
1350
+ * still survive a reload exactly as before. `gen` is the generation the read
1351
+ * was issued under; the result is cached only if it is still current. */
1352
+ private async readPendingRecordIds(gen: number): Promise<{
1353
+ writes: Set<string>;
1354
+ deletes: Set<string>;
1355
+ }> {
1356
+ const writes = new Set<string>();
1357
+ const deletes = new Set<string>();
1358
+ try {
1359
+ const [rows] = await this.local.query<
1360
+ [{ recordId: RecordId<string>; mutationType: string }[]]
1361
+ >('SELECT recordId, mutationType FROM _00_pending_mutations');
1362
+ for (const row of rows ?? []) {
1363
+ if (!row?.recordId) continue;
1364
+ const id = encodeRecordId(row.recordId);
1365
+ if (row.mutationType === 'delete') deletes.add(id);
1366
+ else writes.add(id);
1367
+ }
1368
+ } catch (err) {
1369
+ this.logger.warn(
1370
+ { err, Category: 'sp00ky-client::DataModule::getPendingRecordIds' },
1371
+ 'Failed to read pending mutations; optimistic writes may be briefly hidden'
1372
+ );
1373
+ // Do NOT cache a failed read: the empty sets are a fallback for this call,
1374
+ // not a statement that the outbox is empty.
1375
+ return { writes, deletes };
1376
+ }
1377
+ if (gen === this.pendingIdsGen) {
1378
+ this.pendingIds = { writes, deletes };
1379
+ this.pendingIdsAt = Date.now();
1380
+ }
1381
+ return { writes, deletes };
1382
+ }
1383
+
1384
+ /** True while ≥1 live subscriber is watching this query (refcount guard). */
1385
+ hasSubscribers(hash: string): boolean {
1386
+ return (this.subscriptions.get(hash)?.size ?? 0) > 0;
1387
+ }
1388
+
1389
+ /**
1390
+ * Opt-in eager teardown for a query whose LAST subscriber just left — used by
1391
+ * viewport-windowed lists to cancel off-screen windows instead of leaving
1392
+ * their remote views to expire on the TTL sweep. No-op while any subscriber
1393
+ * remains (refcount). Only enqueues the remote cleanup here; the local WASM
1394
+ * view + in-memory state are freed in {@link finalizeDeregister} after the
1395
+ * remote delete completes, so a re-subscribe in between aborts/heals it.
1396
+ *
1397
+ * NOTE: most queries should NOT use this — the default keep-alive on
1398
+ * unsubscribe avoids re-registration churn on navigation.
1399
+ */
1400
+ deregisterQuery(hash: string): void {
1401
+ if (this.hasSubscribers(hash)) return;
1402
+ if (!this.activeQueries.has(hash)) return;
1403
+ this.onDeregister?.(hash);
1404
+ }
1405
+
1406
+ /**
1407
+ * Final local teardown after the remote `_00_query` row was deleted: free the
1408
+ * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
1409
+ * (`cleanupQuery`) guarantees no subscriber remains.
1410
+ */
1411
+ finalizeDeregister(hash: string): void {
1412
+ const qs = this.activeQueries.get(hash);
1413
+ if (qs?.ttlTimer) {
1414
+ clearTimeout(qs.ttlTimer);
1415
+ qs.ttlTimer = null;
1416
+ }
1417
+ const debounce = this.debounceTimers.get(hash);
1418
+ if (debounce) {
1419
+ clearTimeout(debounce);
1420
+ this.debounceTimers.delete(hash);
1421
+ }
1422
+ this.pendingStreamUpdates.delete(hash);
1423
+ this.fetchDepth.delete(hash);
1424
+ this.cache.unregisterQuery(hash);
1425
+ this.activeQueries.delete(hash);
1426
+ this.subscriptions.delete(hash);
1427
+ }
1428
+
263
1429
  /**
264
1430
  * Get query state by id (for sync and devtools)
265
1431
  */
@@ -274,36 +1440,259 @@ export class DataModule<S extends SchemaStructure> {
274
1440
  return Array.from(this.activeQueries.values());
275
1441
  }
276
1442
 
1443
+ getActiveQueryHashes(): QueryHash[] {
1444
+ return Array.from(this.activeQueries.keys());
1445
+ }
1446
+
277
1447
  async updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void> {
278
1448
  const queryState = this.activeQueries.get(id);
279
1449
  if (!queryState) {
280
1450
  this.logger.warn(
281
- { id, Category: 'spooky-client::DataModule::updateQueryLocalArray' },
1451
+ { id, Category: 'sp00ky-client::DataModule::updateQueryLocalArray' },
282
1452
  'Query to update local array not found'
283
1453
  );
284
1454
  return;
285
1455
  }
1456
+ const epoch = this.local.epoch;
286
1457
  queryState.config.localArray = localArray;
287
- await this.local.query(surql.seal(surql.updateSet('id', ['localArray'])), {
288
- id: queryState.config.id,
289
- localArray,
290
- });
1458
+ try {
1459
+ await this.local.query(
1460
+ surql.seal(surql.updateSet('id', ['localArray'])),
1461
+ {
1462
+ id: queryState.config.id,
1463
+ localArray,
1464
+ },
1465
+ { epoch }
1466
+ );
1467
+ } catch (err) {
1468
+ if (err instanceof StaleEpochError) return;
1469
+ throw err;
1470
+ }
291
1471
  }
292
1472
 
293
- async updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void> {
1473
+ async updateQueryRemoteArray(
1474
+ hash: string,
1475
+ remoteArray: RecordVersionArray,
1476
+ opts?: {
1477
+ /** `_00_query.rowCount` read in the same round trip; `null` = unknown. */
1478
+ serverRowCount?: number | null;
1479
+ }
1480
+ ): Promise<void> {
294
1481
  const queryState = this.getQueryByHash(hash);
295
1482
  if (!queryState) {
296
1483
  this.logger.warn(
297
- { hash, Category: 'spooky-client::DataModule::updateQueryRemoteArray' },
1484
+ { hash, Category: 'sp00ky-client::DataModule::updateQueryRemoteArray' },
298
1485
  'Query to update remote array not found'
299
1486
  );
300
1487
  return;
301
1488
  }
1489
+ // An empty id-set is only believable once a real one has arrived in this
1490
+ // session. `_00_list_ref` is published asynchronously — the SSP queues a
1491
+ // view's initial edges to a coalescing flusher and returns from
1492
+ // `fn::query::register` before they land — so an empty read right after
1493
+ // registration is routinely just "not flushed yet", for a query that has
1494
+ // rows. Taking it at face value latched `membershipKnown` on an empty set,
1495
+ // which renders nothing (no scan fallback), and mirrored `[]` into the
1496
+ // durable `_00_window` row, which kept the list blank across reloads.
1497
+ //
1498
+ // Ignoring it entirely (rather than storing `[]` with the latch withheld)
1499
+ // is deliberate: on a cold start `remoteArray` is seeded from the durable
1500
+ // row, and overwriting that with `[]` would blank the very rows the seed
1501
+ // exists to paint. The `_00_list_ref` poll re-reads within ~500ms and
1502
+ // delivers the real set.
1503
+ // `serverRowCount` is what makes the two cases separable. The SSP writes it
1504
+ // onto the `_00_query` row in the same statement that registers the view,
1505
+ // before it queues the view's initial edges — so `> 0` with no edges is the
1506
+ // flush window and `=== 0` is a genuinely empty query. `null`/undefined
1507
+ // means we could not read it (older server, row not visible yet).
1508
+ //
1509
+ // Retry counting cannot substitute for this: the poll runs 500ms after
1510
+ // registration, well inside the flush window for a real collection, so
1511
+ // "believe it the second time" blanked exactly the lists this guard exists
1512
+ // to protect — reported as rows vanishing ~2s after a page load.
1513
+ // Whether this write may be trusted by the NEXT session. Non-empty sets
1514
+ // always; an empty set only when the server stood behind it (a zero row
1515
+ // count, or a real set was seen this session and it is now gone). The
1516
+ // retry-budget path below accepts an empty without that backing and must
1517
+ // stay non-durable, or the poisoned-device self-heal is lost.
1518
+ let confirmed = remoteArray.length > 0 || queryState.config.remoteSeen === true;
1519
+ if (remoteArray.length === 0 && !queryState.config.remoteSeen) {
1520
+ const serverRowCount = opts?.serverRowCount;
1521
+ const knownEmpty = serverRowCount === 0;
1522
+ confirmed = knownEmpty;
1523
+ if (!knownEmpty) {
1524
+ // Unknown row count still gets a bounded escape hatch, so a server that
1525
+ // cannot report one never strands a device on a durable seed forever.
1526
+ const emptyReads = (queryState.config.emptyReads ?? 0) + 1;
1527
+ queryState.config.emptyReads = emptyReads;
1528
+ const exhausted =
1529
+ serverRowCount === null || serverRowCount === undefined
1530
+ ? emptyReads >= EMPTY_MEMBERSHIP_CONFIRMATIONS
1531
+ : false; // a positive row count is never "confirmed empty"
1532
+ if (!exhausted) {
1533
+ this.logger.debug(
1534
+ {
1535
+ hash,
1536
+ emptyReads,
1537
+ serverRowCount,
1538
+ Category: 'sp00ky-client::DataModule::updateQueryRemoteArray',
1539
+ },
1540
+ 'Ignoring empty membership: the server still reports rows for this query'
1541
+ );
1542
+ return;
1543
+ }
1544
+ }
1545
+ }
1546
+
1547
+ const epoch = this.local.epoch;
302
1548
  queryState.config.remoteArray = remoteArray;
303
- await this.local.query(surql.seal(surql.updateSet('id', ['remoteArray'])), {
304
- id: queryState.config.id,
305
- remoteArray,
306
- });
1549
+ // The single point where authoritative membership arrives (registration and
1550
+ // the `_00_list_ref` poll both land here), so it is where "we now know the
1551
+ // membership" is latched and where the durable mirror is written.
1552
+ queryState.config.membershipKnown = true;
1553
+ if (remoteArray.length > 0) {
1554
+ // Earns the right to believe a later empty set — that transition is a
1555
+ // genuine removal and must be honoured, or removed rows resurrect.
1556
+ queryState.config.remoteSeen = true;
1557
+ queryState.config.emptyReads = 0;
1558
+ }
1559
+ if (queryState.config.membershipKey) {
1560
+ await this.writeWindowMembership(queryState.config.membershipKey, remoteArray, confirmed);
1561
+ }
1562
+ try {
1563
+ await this.local.query(
1564
+ surql.seal(surql.updateSet('id', ['remoteArray'])),
1565
+ {
1566
+ id: queryState.config.id,
1567
+ remoteArray,
1568
+ },
1569
+ { epoch }
1570
+ );
1571
+ } catch (err) {
1572
+ if (err instanceof StaleEpochError) return;
1573
+ throw err;
1574
+ }
1575
+ }
1576
+
1577
+ /**
1578
+ * Cancel every armed timer ahead of a local-bucket switch: stream-update
1579
+ * debounce timers (their pending updates carry the OLD bucket's id-sets) and
1580
+ * per-query TTL heartbeats (they'd refresh the previous user's remote
1581
+ * `_00_query` rows under the new session). The rebind re-arms heartbeats.
1582
+ */
1583
+ quiesce(): void {
1584
+ for (const timer of this.debounceTimers.values()) {
1585
+ clearTimeout(timer);
1586
+ }
1587
+ this.debounceTimers.clear();
1588
+ this.pendingStreamUpdates.clear();
1589
+ this.fetchDepth.clear();
1590
+ for (const queryState of this.activeQueries.values()) {
1591
+ if (queryState.ttlTimer) {
1592
+ clearTimeout(queryState.ttlTimer);
1593
+ queryState.ttlTimer = null;
1594
+ }
1595
+ }
1596
+ }
1597
+
1598
+ /**
1599
+ * Re-home every active query in a freshly-opened bucket, KEEPING its hash —
1600
+ * `useQuery` subscriptions are keyed by hash and don't re-register on auth
1601
+ * changes, so the hooks must stay attached. Per query:
1602
+ * 1. reset the sync arrays + hydration flag and drop the previous user's
1603
+ * records, notifying subscribers with the new-bucket materialization
1604
+ * (usually empty) so their rows leave the UI immediately;
1605
+ * 2. recreate the `_00_query` row in the new bucket;
1606
+ * 3. re-register the SSP view on the (fresh, post-reset) processor — this
1607
+ * also rebinds the view to the NEW `$auth` context;
1608
+ * 4. restart the TTL heartbeat.
1609
+ * Returns the hashes so the caller can enqueue remote re-registration, which
1610
+ * refills records from the server via the normal register→sync→notify path.
1611
+ */
1612
+ async rebindAfterBucketSwitch(): Promise<QueryHash[]> {
1613
+ const hashes: QueryHash[] = [];
1614
+ for (const [hash, queryState] of this.activeQueries.entries()) {
1615
+ const config = queryState.config;
1616
+ config.localArray = [];
1617
+ config.remoteArray = [];
1618
+ config.subqueryRemoteArray = undefined;
1619
+ // Membership belongs to the bucket we just left. Re-seed from the NEW
1620
+ // bucket's durable row if it has one (a returning user), otherwise mark it
1621
+ // unknown so the first paint falls back to a scan instead of rendering an
1622
+ // empty list until the server answers.
1623
+ config.membershipKnown = false;
1624
+ // The new bucket's server sets have not been seen yet — an empty read
1625
+ // must be re-confirmed there too.
1626
+ config.remoteSeen = false;
1627
+ config.emptyReads = 0;
1628
+ if (config.membershipKey) {
1629
+ const durable = await this.getWindowMembership(config.membershipKey);
1630
+ // Same rule as the cold-start read: a non-empty row, or an empty one
1631
+ // the server confirmed, is membership; an unmarked empty row is not.
1632
+ if (durable && (durable.ids.length > 0 || durable.confirmed)) {
1633
+ config.remoteArray = durable.ids;
1634
+ config.membershipKnown = true;
1635
+ }
1636
+ }
1637
+ queryState.hydrated = false;
1638
+ queryState.syncNotified = false;
1639
+ queryState.records = [];
1640
+ // Via setQueryStatus (not a bare assignment) so status observers see the
1641
+ // flip back to a loading state.
1642
+ this.setQueryStatus(hash, 'fetching');
1643
+
1644
+ try {
1645
+ await withRetry(this.logger, () =>
1646
+ this.local.query<[QueryConfigRecord]>(surql.seal(surql.create('id', 'data')), {
1647
+ id: config.id,
1648
+ data: {
1649
+ surql: config.surql,
1650
+ params: config.params,
1651
+ localArray: [],
1652
+ remoteArray: [],
1653
+ lastActiveAt: new Date(),
1654
+ createdAt: new Date(),
1655
+ ttl: config.ttl,
1656
+ tableName: config.tableName,
1657
+ updateCount: queryState.updateCount,
1658
+ rowCount: 0,
1659
+ errorCount: queryState.errorCount,
1660
+ },
1661
+ })
1662
+ );
1663
+
1664
+ const { localArray } = this.cache.registerQuery({
1665
+ queryHash: hash,
1666
+ surql: config.surql,
1667
+ params: config.params,
1668
+ ttl: new Duration(config.ttl),
1669
+ lastActiveAt: new Date(),
1670
+ });
1671
+ config.localArray = localArray;
1672
+ await this.local.query(surql.seal(surql.updateSet('id', ['localArray', 'rowCount'])), {
1673
+ id: config.id,
1674
+ localArray,
1675
+ rowCount: localArray.length,
1676
+ });
1677
+ } catch (err) {
1678
+ this.logger.error(
1679
+ { err, hash, Category: 'sp00ky-client::DataModule::rebindAfterBucketSwitch' },
1680
+ 'Failed to rebind query after bucket switch; remote re-registration will retry'
1681
+ );
1682
+ }
1683
+
1684
+ // Notify AFTER the SSP re-registration so a subscriber that re-reads
1685
+ // synchronously sees consistent (empty) state.
1686
+ const subscribers = this.subscriptions.get(hash);
1687
+ if (subscribers) {
1688
+ for (const callback of subscribers) {
1689
+ callback(queryState.records);
1690
+ }
1691
+ }
1692
+ this.startTTLHeartbeat(queryState, hash);
1693
+ hashes.push(hash);
1694
+ }
1695
+ return hashes;
307
1696
  }
308
1697
 
309
1698
  /**
@@ -313,20 +1702,29 @@ export class DataModule<S extends SchemaStructure> {
313
1702
  async notifyQuerySynced(queryHash: string): Promise<void> {
314
1703
  const queryState = this.activeQueries.get(queryHash);
315
1704
  if (!queryState) return;
316
-
317
- // Re-query local DB for latest data
318
- const [records] = await this.local.query<[Record<string, any>[]]>(
319
- queryState.config.surql,
320
- queryState.config.params
321
- );
322
- const newRecords = records || [];
1705
+ const epoch = this.local.epoch;
1706
+
1707
+ // Re-query local DB for latest data (windowed queries materialize from the
1708
+ // list_ref window so they resolve even if the in-browser SSP never emits —
1709
+ // it can't compute a high offset whose preceding rows aren't resident).
1710
+ const newRecords = await this.materializeRecords(queryState);
1711
+ // Bucket switched while we materialized: these rows mix old-bucket reads
1712
+ // with new-bucket state — drop them; the rebind/re-registration re-emits.
1713
+ if (epoch !== this.local.epoch) return;
323
1714
  const changed = JSON.stringify(queryState.records) !== JSON.stringify(newRecords);
324
1715
  queryState.records = newRecords;
325
1716
 
326
- // Notify if data changed OR if this is the first sync (updateCount === 0)
327
- // The latter handles "query truly has no results" so UI can stop loading
328
- if (changed || queryState.updateCount === 0) {
1717
+ // Notify if data changed OR if this registration lifetime hasn't emitted a
1718
+ // post-sync notification yet. The latter handles "query truly has no
1719
+ // results" so the UI can stop loading — gated on the in-memory
1720
+ // `syncNotified` flag rather than `updateCount === 0`, because updateCount
1721
+ // is PERSISTED across deregister/re-register: a re-registered empty window
1722
+ // (updateCount > 0, records unchanged) would otherwise never emit and its
1723
+ // subscribers would show a loading state forever.
1724
+ if (changed || !queryState.syncNotified) {
1725
+ queryState.syncNotified = true;
329
1726
  queryState.updateCount++;
1727
+ queryState.lastUpdatedAt = Date.now();
330
1728
  const subscribers = this.subscriptions.get(queryHash);
331
1729
  if (subscribers) {
332
1730
  for (const callback of subscribers) {
@@ -344,6 +1742,24 @@ export class DataModule<S extends SchemaStructure> {
344
1742
  data: RoutePayload<S, B, R>,
345
1743
  options?: RunOptions
346
1744
  ): Promise<void> {
1745
+ const { tableName, record } = this.buildJobRecord(backend, path, data, options);
1746
+ const recordId = `${tableName}:${generateId()}`;
1747
+ await this.create(recordId, record);
1748
+ }
1749
+
1750
+ /**
1751
+ * Build the outbox job record + resolve its table for a backend route.
1752
+ *
1753
+ * Every job is a single execution. Recurring work is declared server-side
1754
+ * (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
1755
+ * so nothing here needs to know about schedules.
1756
+ */
1757
+ private buildJobRecord<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(
1758
+ backend: B,
1759
+ path: R,
1760
+ data: RoutePayload<S, B, R>,
1761
+ options?: RunOptions
1762
+ ): { tableName: string; record: Record<string, unknown> } {
347
1763
  const route = this.schema.backends?.[backend]?.routes?.[path];
348
1764
  if (!route) {
349
1765
  throw new Error(`Route ${backend}.${path} not found`);
@@ -366,16 +1782,28 @@ export class DataModule<S extends SchemaStructure> {
366
1782
  const record: Record<string, unknown> = {
367
1783
  path,
368
1784
  payload: JSON.stringify(payload),
1785
+ // Set explicitly: the schema's DEFAULT ALWAYS "pending" is server-side
1786
+ // only. An optimistic local create without it surfaces with status
1787
+ // undefined, so in-flight indicators keyed on pending/processing stay
1788
+ // off until the first server echo (seconds on a delayed job).
1789
+ status: 'pending',
369
1790
  max_retries: options?.max_retries ?? 3,
370
1791
  retry_strategy: options?.retry_strategy ?? 'linear',
371
1792
  };
372
1793
 
1794
+ if (options?.timeout != null) {
1795
+ record.timeout = options.timeout;
1796
+ }
1797
+
1798
+ if (options?.delay != null) {
1799
+ record.delay = options.delay;
1800
+ }
1801
+
373
1802
  if (options?.assignedTo) {
374
1803
  record.assigned_to = options.assignedTo;
375
1804
  }
376
1805
 
377
- const recordId = `${tableName}:${generateId()}`;
378
- await this.create(recordId, record);
1806
+ return { tableName, record };
379
1807
  }
380
1808
 
381
1809
  // ==================== MUTATION MANAGEMENT ====================
@@ -392,7 +1820,7 @@ export class DataModule<S extends SchemaStructure> {
392
1820
 
393
1821
  const rid = parseRecordIdString(id);
394
1822
  const params = parseParams(tableSchema.columns, data);
395
- const mutationId = parseRecordIdString(`_spooky_pending_mutations:${Date.now()}`);
1823
+ const mutationId = parseRecordIdString(mintMutationId(this.tabId));
396
1824
 
397
1825
  const dataKeys = Object.keys(params).map((key) => ({ key, variable: `data_${key}` }));
398
1826
  const prefixedParams = Object.fromEntries(
@@ -410,22 +1838,46 @@ export class DataModule<S extends SchemaStructure> {
410
1838
  this.local.execute(query, {
411
1839
  id: rid,
412
1840
  mid: mutationId,
1841
+ // The record itself is written with per-key `data_<field>` vars
1842
+ // (`createSet`), but the OUTBOX row needs the whole payload in one
1843
+ // `data` field so the mutation can be replayed later. Without this the
1844
+ // row is written with `data` unbound: the create becomes unsendable and
1845
+ // blocks the queue behind it.
1846
+ data: params,
413
1847
  ...prefixedParams,
414
1848
  })
415
1849
  );
416
1850
 
1851
+ // The local tx has committed: the row and its outbox entry exist. The
1852
+ // cached pending-id sets no longer describe the outbox, so drop them HERE,
1853
+ // before the ingest below fans out to every view's materialization (which
1854
+ // is exactly when they are read).
1855
+ this.invalidatePendingIds();
1856
+
417
1857
  const parsedRecord = parseParams(tableSchema.columns, target) as RecordWithId;
418
1858
 
419
- // Save to cache (which handles DBSP ingestion)
420
- await this.cache.save(
421
- {
422
- table: tableName,
423
- op: 'CREATE',
424
- record: parsedRecord,
425
- version: 1,
426
- },
427
- true
428
- );
1859
+ // Save to cache (which handles DBSP ingestion). Best-effort, like
1860
+ // `delete()`: the local write is durable and the outbox row exists, so a
1861
+ // throw from the in-browser ingest must not abort the rest of this method -
1862
+ // it used to, and then the mutation was never handed to sync, the row sat
1863
+ // in the outbox until the next leader promotion re-scanned it, and the
1864
+ // caller's promise rejected after the write had already happened.
1865
+ try {
1866
+ await this.cache.save(
1867
+ {
1868
+ table: tableName,
1869
+ op: 'CREATE',
1870
+ record: parsedRecord,
1871
+ version: 1,
1872
+ },
1873
+ true
1874
+ );
1875
+ } catch (err) {
1876
+ this.logger.error(
1877
+ { err, id, Category: 'sp00ky-client::DataModule::create' },
1878
+ 'SSP create-ingest failed; the row is written and queued, but views only see it once membership arrives'
1879
+ );
1880
+ }
429
1881
 
430
1882
  // Emit mutation event for sync
431
1883
  const mutationEvent: CreateEvent = {
@@ -441,7 +1893,7 @@ export class DataModule<S extends SchemaStructure> {
441
1893
  callback([mutationEvent]);
442
1894
  }
443
1895
 
444
- this.logger.debug({ id, Category: 'spooky-client::DataModule::create' }, 'Record created');
1896
+ this.logger.debug({ id, Category: 'sp00ky-client::DataModule::create' }, 'Record created');
445
1897
 
446
1898
  return target;
447
1899
  }
@@ -463,7 +1915,10 @@ export class DataModule<S extends SchemaStructure> {
463
1915
 
464
1916
  const rid = parseRecordIdString(id);
465
1917
  const params = parseParams(tableSchema.columns, data);
466
- const mutationId = parseRecordIdString(`_spooky_pending_mutations:${Date.now()}`);
1918
+ const mutationId = parseRecordIdString(mintMutationId(this.tabId));
1919
+
1920
+ // Note: CRDT state is pushed directly to the _00_crdt table by CrdtField.pushToRemote(),
1921
+ // NOT through the record update pipeline. This keeps the record data clean.
467
1922
 
468
1923
  // Capture current record state before mutation for rollback support
469
1924
  const [beforeRecord] = await withRetry(this.logger, () =>
@@ -472,7 +1927,7 @@ export class DataModule<S extends SchemaStructure> {
472
1927
 
473
1928
  const query = surql.seal<{ target: T }>(
474
1929
  surql.tx([
475
- surql.updateSet('id', [{ statement: 'spooky_rv += 1' }]),
1930
+ surql.updateSet('id', [{ statement: '_00_rv += 1' }]),
476
1931
  surql.let('updated', surql.updateMerge('id', 'data')),
477
1932
  surql.createMutation('update', 'mid', 'id', 'data'),
478
1933
  surql.returnObject([{ key: 'target', variable: 'updated' }]),
@@ -496,23 +1951,33 @@ export class DataModule<S extends SchemaStructure> {
496
1951
  updatedFields[key] = (target as Record<string, any>)[key];
497
1952
  }
498
1953
  }
499
- if ('spooky_rv' in (target as Record<string, any>)) {
500
- updatedFields.spooky_rv = (target as Record<string, any>).spooky_rv;
1954
+ if ('_00_rv' in (target as Record<string, any>)) {
1955
+ updatedFields._00_rv = (target as Record<string, any>)._00_rv;
501
1956
  }
502
1957
  this.replaceRecordInQueries(updatedFields);
503
1958
 
1959
+ // Committed: see create() for why this precedes the ingest.
1960
+ this.invalidatePendingIds();
1961
+
504
1962
  const parsedRecord = parseParams(tableSchema.columns, target) as RecordWithId;
505
1963
 
506
- // Save to cache
507
- await this.cache.save(
508
- {
509
- table: table,
510
- op: 'UPDATE',
511
- record: parsedRecord,
512
- version: target.spooky_rv as number,
513
- },
514
- true
515
- );
1964
+ // Save to cache. Best-effort for the same reason as in create().
1965
+ try {
1966
+ await this.cache.save(
1967
+ {
1968
+ table: table,
1969
+ op: 'UPDATE',
1970
+ record: parsedRecord,
1971
+ version: target._00_rv as number,
1972
+ },
1973
+ true
1974
+ );
1975
+ } catch (err) {
1976
+ this.logger.error(
1977
+ { err, id, Category: 'sp00ky-client::DataModule::update' },
1978
+ 'SSP update-ingest failed; the row is written and queued'
1979
+ );
1980
+ }
516
1981
 
517
1982
  const pushEventOptions = parseUpdateOptions(id, data, options);
518
1983
 
@@ -531,7 +1996,7 @@ export class DataModule<S extends SchemaStructure> {
531
1996
  callback([mutationEvent]);
532
1997
  }
533
1998
 
534
- this.logger.debug({ id, Category: 'spooky-client::DataModule::update' }, 'Record updated');
1999
+ this.logger.debug({ id, Category: 'sp00ky-client::DataModule::update' }, 'Record updated');
535
2000
 
536
2001
  return target;
537
2002
  }
@@ -547,14 +2012,45 @@ export class DataModule<S extends SchemaStructure> {
547
2012
  }
548
2013
 
549
2014
  const rid = parseRecordIdString(id);
550
- const mutationId = parseRecordIdString(`_spooky_pending_mutations:${Date.now()}`);
2015
+ const mutationId = parseRecordIdString(mintMutationId(this.tabId));
2016
+
2017
+ // Fetch the record before deleting so DBSP can match it against query predicates
2018
+ const [beforeRecords] = await this.local.query<[Record<string, any>[]]>(
2019
+ 'SELECT * FROM ONLY $id',
2020
+ { id: rid }
2021
+ );
2022
+ const beforeRecord = beforeRecords ?? {};
551
2023
 
552
2024
  const query = surql.seal<void>(
553
2025
  surql.tx([surql.delete('id'), surql.createMutation('delete', 'mid', 'id')])
554
2026
  );
555
2027
 
556
2028
  await withRetry(this.logger, () => this.local.execute(query, { id: rid, mid: mutationId }));
557
- await this.cache.delete(table, id, true);
2029
+
2030
+ // Committed: the outbox row exists, drop the cached pending-id sets before
2031
+ // the re-materialize below reads them (see create()).
2032
+ this.invalidatePendingIds();
2033
+
2034
+ // The local DELETE has now committed. Everything below must reflect that in
2035
+ // active live queries — so the deleted row disappears optimistically without
2036
+ // a reload — even if the optimistic SSP-view ingest below fails. Previously a
2037
+ // throw from `cache.delete` (the WASM ingest) aborted `delete()` after the
2038
+ // commit, so the manual notify loop never ran and the row lingered on screen
2039
+ // until reload. Ingesting the delete into the in-browser SSP view is
2040
+ // best-effort: the manual re-materialize reads the local DB (which already
2041
+ // excludes the row), so the result is correct regardless.
2042
+ try {
2043
+ await this.cache.delete(table, id, true, beforeRecord);
2044
+ } catch (err) {
2045
+ this.logger.error(
2046
+ { err, id, Category: 'sp00ky-client::DataModule::delete' },
2047
+ 'SSP delete-ingest failed; relying on query re-materialize to reflect the delete'
2048
+ );
2049
+ }
2050
+
2051
+ // DBSP may not emit view updates for DELETE ops — manually notify all queries
2052
+ // that reference this table.
2053
+ await this.notifyTableQueries(tableName);
558
2054
 
559
2055
  // Emit mutation event
560
2056
  const mutationEvent: DeleteEvent = {
@@ -567,7 +2063,7 @@ export class DataModule<S extends SchemaStructure> {
567
2063
  callback([mutationEvent]);
568
2064
  }
569
2065
 
570
- this.logger.debug({ id, Category: 'spooky-client::DataModule::delete' }, 'Record deleted');
2066
+ this.logger.debug({ id, Category: 'sp00ky-client::DataModule::delete' }, 'Record deleted');
571
2067
  }
572
2068
 
573
2069
  // ==================== ROLLBACK METHODS ====================
@@ -579,19 +2075,17 @@ export class DataModule<S extends SchemaStructure> {
579
2075
  const id = encodeRecordId(recordId);
580
2076
 
581
2077
  try {
582
- await withRetry(this.logger, () =>
583
- this.local.query('DELETE $id', { id: recordId })
584
- );
2078
+ await withRetry(this.logger, () => this.local.query('DELETE $id', { id: recordId }));
585
2079
  await this.cache.delete(tableName, id, true);
586
2080
  this.removeRecordFromQueries(recordId);
587
2081
 
588
2082
  this.logger.info(
589
- { id, tableName, Category: 'spooky-client::DataModule::rollbackCreate' },
2083
+ { id, tableName, Category: 'sp00ky-client::DataModule::rollbackCreate' },
590
2084
  'Rolled back optimistic create'
591
2085
  );
592
2086
  } catch (err) {
593
2087
  this.logger.error(
594
- { err, id, tableName, Category: 'spooky-client::DataModule::rollbackCreate' },
2088
+ { err, id, tableName, Category: 'sp00ky-client::DataModule::rollbackCreate' },
595
2089
  'Failed to rollback create'
596
2090
  );
597
2091
  }
@@ -626,7 +2120,7 @@ export class DataModule<S extends SchemaStructure> {
626
2120
  table: tableName,
627
2121
  op: 'UPDATE',
628
2122
  record: parsedRecord,
629
- version: (beforeRecord.spooky_rv as number) || 1,
2123
+ version: (beforeRecord._00_rv as number) || 1,
630
2124
  },
631
2125
  true
632
2126
  );
@@ -635,17 +2129,40 @@ export class DataModule<S extends SchemaStructure> {
635
2129
  await this.replaceRecordInQueries(beforeRecord);
636
2130
 
637
2131
  this.logger.info(
638
- { id, tableName, Category: 'spooky-client::DataModule::rollbackUpdate' },
2132
+ { id, tableName, Category: 'sp00ky-client::DataModule::rollbackUpdate' },
639
2133
  'Rolled back optimistic update'
640
2134
  );
641
2135
  } catch (err) {
642
2136
  this.logger.error(
643
- { err, id, tableName, Category: 'spooky-client::DataModule::rollbackUpdate' },
2137
+ { err, id, tableName, Category: 'sp00ky-client::DataModule::rollbackUpdate' },
644
2138
  'Failed to rollback update'
645
2139
  );
646
2140
  }
647
2141
  }
648
2142
 
2143
+ /**
2144
+ * Force a re-materialize + notify of every active query on `tableName`.
2145
+ * Used after a DELETE landed in the local store (this tab's own, or one
2146
+ * relayed from another tab): the SSP may not emit a view update for a
2147
+ * DELETE ingest, and the re-materialize reads the store, which already
2148
+ * excludes the row. Each query is isolated so one failing re-materialize
2149
+ * can't stop the others.
2150
+ */
2151
+ async notifyTableQueries(tableName: string): Promise<void> {
2152
+ for (const [queryHash, queryState] of this.activeQueries) {
2153
+ if (queryState.config.tableName === tableName) {
2154
+ try {
2155
+ await this.notifyQuerySynced(queryHash);
2156
+ } catch (err) {
2157
+ this.logger.error(
2158
+ { err, queryHash, tableName, Category: 'sp00ky-client::DataModule::notifyTableQueries' },
2159
+ 'notifyQuerySynced failed after delete'
2160
+ );
2161
+ }
2162
+ }
2163
+ }
2164
+ }
2165
+
649
2166
  /**
650
2167
  * Remove a record from all active query states and notify subscribers
651
2168
  */
@@ -678,7 +2195,9 @@ export class DataModule<S extends SchemaStructure> {
678
2195
  surqlString: string,
679
2196
  params: Record<string, any>,
680
2197
  ttl: QueryTimeToLive,
681
- tableName: T
2198
+ tableName: T,
2199
+ plan?: QueryPlan,
2200
+ membershipKey?: string
682
2201
  ): Promise<QueryHash> {
683
2202
  const queryState = await this.createNewQuery<T>({
684
2203
  recordId,
@@ -686,31 +2205,77 @@ export class DataModule<S extends SchemaStructure> {
686
2205
  params,
687
2206
  ttl,
688
2207
  tableName,
2208
+ plan,
2209
+ membershipKey,
689
2210
  });
690
2211
 
691
- const { localArray } = this.cache.registerQuery({
2212
+ const t0 = performance.now();
2213
+ const { localArray, registrationTimings } = this.cache.registerQuery({
692
2214
  queryHash: hash,
693
2215
  surql: surqlString,
694
2216
  params,
695
2217
  ttl: new Duration(ttl),
696
2218
  lastActiveAt: new Date(),
697
2219
  });
2220
+ const registrationTime = performance.now() - t0;
2221
+
2222
+ // Record the one-shot SSP registration timings (parse/plan/snapshot from the
2223
+ // WASM binding) + the register_view wall time for DevTools.
2224
+ queryState.registrationTimings = {
2225
+ parseMs: registrationTimings?.parseMs ?? null,
2226
+ planMs: registrationTimings?.planMs ?? null,
2227
+ snapshotMs: registrationTimings?.snapshotMs ?? null,
2228
+ wallMs: registrationTime,
2229
+ };
698
2230
 
699
2231
  await withRetry(this.logger, () =>
700
- this.local.query(surql.seal(surql.updateSet('id', ['localArray'])), {
701
- id: recordId,
702
- localArray,
703
- })
2232
+ this.local.query(
2233
+ surql.seal(surql.updateSet('id', ['localArray', 'registrationTime', 'rowCount'])),
2234
+ {
2235
+ id: recordId,
2236
+ localArray,
2237
+ registrationTime,
2238
+ rowCount: localArray.length,
2239
+ }
2240
+ )
704
2241
  );
705
2242
 
2243
+ // Windowed (`START n`) queries skipped the raw initial load in
2244
+ // createNewQuery (O(offset) + wrong rows for sparse windows). Seed the
2245
+ // initial rows now from the SSP's window id-set (`localArray`) via the same
2246
+ // window-materialization path the stream updates use — O(window), and the
2247
+ // ids are already the correct window — so the first paint isn't empty while
2248
+ // the remote `_00_list_ref` syncs in.
2249
+ const windowMat = buildWindowMaterialization(surqlString);
2250
+ if (windowMat && localArray.length > 0) {
2251
+ try {
2252
+ const winIds = localArray.map(([id]) => parseRecordIdString(id));
2253
+ if (plan) {
2254
+ const winPlan = buildWindowMaterializationPlan(plan, winIds) ?? { ...plan, ids: winIds };
2255
+ queryState.records = await this.local.select(winPlan, params);
2256
+ } else {
2257
+ const [seeded] = await this.local.query<[Record<string, any>[]]>(windowMat.query, {
2258
+ ...params,
2259
+ __win: winIds,
2260
+ });
2261
+ queryState.records = seeded || [];
2262
+ }
2263
+ } catch (err) {
2264
+ this.logger.warn(
2265
+ { err, hash, Category: 'sp00ky-client::DataModule::createAndRegisterQuery' },
2266
+ 'Failed to seed windowed initial records from localArray'
2267
+ );
2268
+ }
2269
+ }
2270
+
706
2271
  this.activeQueries.set(hash, queryState);
707
- this.startTTLHeartbeat(queryState);
2272
+ this.startTTLHeartbeat(queryState, hash);
708
2273
  this.logger.debug(
709
2274
  {
710
2275
  hash,
711
2276
  tableName,
712
2277
  recordCount: queryState.records.length,
713
- Category: 'spooky-client::DataModule::query',
2278
+ Category: 'sp00ky-client::DataModule::query',
714
2279
  },
715
2280
  'Query registered'
716
2281
  );
@@ -724,14 +2289,27 @@ export class DataModule<S extends SchemaStructure> {
724
2289
  params,
725
2290
  ttl,
726
2291
  tableName,
2292
+ plan,
2293
+ membershipKey,
727
2294
  }: {
728
2295
  recordId: RecordId;
729
2296
  surql: string;
730
2297
  params: Record<string, any>;
731
2298
  ttl: QueryTimeToLive;
732
2299
  tableName: T;
2300
+ plan?: QueryPlan;
2301
+ membershipKey?: string;
733
2302
  }): Promise<QueryState> {
734
- const tableSchema = this.schema.tables.find((t) => t.name === tableName);
2303
+ // `_00_*` meta tables (feature flags, app releases) are framework-owned:
2304
+ // they exist in the client db schema by construction but are never part of
2305
+ // the app's generated `schema.tables`, so give them an empty column map
2306
+ // instead of the not-found error (which silently broke every meta-table
2307
+ // live query, e.g. feature flags never updating on this path).
2308
+ const tableSchema =
2309
+ this.schema.tables.find((t) => t.name === tableName) ??
2310
+ (String(tableName).startsWith('_00_')
2311
+ ? ({ name: tableName, columns: {} } as any)
2312
+ : undefined);
735
2313
  if (!tableSchema) {
736
2314
  throw new Error(`Table ${tableName} not found`);
737
2315
  }
@@ -752,8 +2330,12 @@ export class DataModule<S extends SchemaStructure> {
752
2330
  localArray: [],
753
2331
  remoteArray: [],
754
2332
  lastActiveAt: new Date(),
2333
+ createdAt: new Date(),
755
2334
  ttl,
756
2335
  tableName,
2336
+ updateCount: 0,
2337
+ rowCount: 0,
2338
+ errorCount: 0,
757
2339
  },
758
2340
  })
759
2341
  );
@@ -763,62 +2345,189 @@ export class DataModule<S extends SchemaStructure> {
763
2345
  const config: QueryConfig = {
764
2346
  ...configRecord,
765
2347
  id: recordId,
766
- params: parseParams(tableSchema.columns, configRecord.params),
2348
+ // In-memory only — carries the engine-neutral plan so non-SurrealQL local
2349
+ // engines materialize via `select(plan)` instead of parsing `surql`.
2350
+ plan,
2351
+ // The CALLER's params, not the ones read back out of the local store: the
2352
+ // store returns a RecordId as a plain `'table:id'` string, and
2353
+ // `parseQueryParams` can only turn it back into a RecordId for a column
2354
+ // the schema marks `recordId`. A union column (`string | record<x>`)
2355
+ // codegens as a plain string, so its param stayed a string and the view
2356
+ // compared a string against a record and matched nothing. The record id is
2357
+ // the same query either way - `recordId` is the hash of surql + vars - so
2358
+ // the in-memory value is the same one, with its types intact.
2359
+ params: parseQueryParams(tableSchema.columns, params ?? configRecord.params),
2360
+ membershipKey,
767
2361
  };
768
2362
 
2363
+ // The `_00_query` row we just read is session-salted, so on a reload it is
2364
+ // always a fresh row with empty arrays. Recover the last authoritative
2365
+ // membership from the durable `_00_window` row instead — this is what stops a
2366
+ // removed row reappearing after a reload, and it works with no network.
2367
+ if (membershipKey && !config.remoteArray?.length) {
2368
+ const durable = await this.getWindowMembership(membershipKey);
2369
+ // An empty durable row is trusted only when it carries the `confirmed`
2370
+ // marker, i.e. the server itself reported the query empty. Without it an
2371
+ // empty row cannot be told apart from one written before this device ever
2372
+ // saw a real id-set (or by the pre-`ea56f50e` client that mirrored
2373
+ // unflushed reads), and treating it as known would paint an empty list
2374
+ // with no scan fallback. A confirmed empty is the opposite case: the
2375
+ // server said "no rows", so a reload must stay empty rather than re-admit
2376
+ // every cached body until the next poll blanks it again.
2377
+ if (durable && (durable.ids.length > 0 || durable.confirmed)) {
2378
+ config.remoteArray = durable.ids;
2379
+ config.membershipKnown = true;
2380
+ }
2381
+ } else if (config.remoteArray?.length) {
2382
+ config.membershipKnown = true;
2383
+ }
2384
+
769
2385
  let records: Record<string, any>[] = [];
770
- try {
771
- const [result] = await this.local.query<[Record<string, any>[]]>(surqlString, params);
772
- records = result || [];
773
- } catch (err) {
774
- this.logger.warn(
775
- { err, Category: 'spooky-client::DataModule::createNewQuery' },
776
- 'Failed to load initial cached records'
777
- );
2386
+ // Windowed (`START n`) queries: do NOT seed from the raw surql here. Running
2387
+ // `… LIMIT n START m` against the shared local store is O(m) — it sorts and
2388
+ // skips m rows on every window open — AND returns the wrong rows for sparse
2389
+ // windows (the reason `buildWindowMaterialization` exists). Those windows are
2390
+ // seeded from the SSP `localArray` in `createAndRegisterQuery` instead.
2391
+ //
2392
+ // With known membership the same reasoning applies to EVERY query, windowed
2393
+ // or not: the predicate scan below would re-admit rows the server has already
2394
+ // dropped from the window (their bodies are still cached and still match the
2395
+ // WHERE). Seed from membership instead.
2396
+ if (config.membershipKnown) {
2397
+ try {
2398
+ records = await this.materializeFromConfig(config);
2399
+ } catch (err) {
2400
+ this.logger.warn(
2401
+ { err, Category: 'sp00ky-client::DataModule::createNewQuery' },
2402
+ 'Failed to seed records from durable membership'
2403
+ );
2404
+ }
2405
+ } else if (buildWindowMaterialization(surqlString) === null) {
2406
+ try {
2407
+ // Prefer the engine-neutral plan (required for non-SurrealQL engines);
2408
+ // fall back to running the raw surql on the SurrealDB engine.
2409
+ const result = plan
2410
+ ? await this.local.select(plan, params)
2411
+ : (await this.local.query<[Record<string, any>[]]>(surqlString, params))[0];
2412
+ records = result || [];
2413
+ } catch (err) {
2414
+ this.logger.warn(
2415
+ { err, Category: 'sp00ky-client::DataModule::createNewQuery' },
2416
+ 'Failed to load initial cached records'
2417
+ );
2418
+ }
778
2419
  }
779
2420
 
2421
+ // Persisted counters survive a restart even though the rolling
2422
+ // sample window is rebuilt from scratch in memory.
2423
+ const persistedUpdateCount =
2424
+ typeof (configRecord as any)?.updateCount === 'number'
2425
+ ? (configRecord as any).updateCount
2426
+ : 0;
2427
+ const persistedErrorCount =
2428
+ typeof (configRecord as any)?.errorCount === 'number' ? (configRecord as any).errorCount : 0;
2429
+
780
2430
  return {
781
2431
  config,
782
2432
  records,
783
2433
  ttlTimer: null,
784
2434
  ttlDurationMs: parseDuration(ttl),
785
- updateCount: 0,
2435
+ updateCount: persistedUpdateCount,
2436
+ lastUpdatedAt: null,
2437
+ materializationSamples: [],
2438
+ lastIngestLatencyMs: null,
2439
+ errorCount: persistedErrorCount,
2440
+ // Born `fetching`, not `idle`: every cold registration is followed by a
2441
+ // `register` down-event whose lifecycle (Sp00kySync.registerQuery) resolves
2442
+ // the status to `idle` once the initial sync completed. Starting idle left
2443
+ // a gap where a fresh windowed query looked settled while still empty.
2444
+ status: 'fetching',
2445
+ phaseSamples: {},
2446
+ phaseLast: {},
2447
+ registrationTimings: { parseMs: null, planMs: null, snapshotMs: null, wallMs: null },
786
2448
  };
787
2449
  }
788
2450
 
789
2451
  private async calculateHash(data: any): Promise<string> {
790
- const content = JSON.stringify(data);
2452
+ // sessionId is part of the hash so the same logical query from two
2453
+ // sessions (e.g. two browser tabs of the same user) lands on different
2454
+ // `_00_query` rows and doesn't fight over a shared one.
2455
+ return this.sha256(JSON.stringify({ ...data, sessionId: this.sessionId }));
2456
+ }
2457
+
2458
+ /**
2459
+ * Session-independent counterpart of {@link calculateHash}: the key for a
2460
+ * query's durable `_00_window` membership row.
2461
+ *
2462
+ * Deliberately the SAME inputs minus the `session::id()` salt, so the two keys
2463
+ * can never drift apart. The salt is right for `_00_query` (two tabs must not
2464
+ * fight over one row) and wrong for membership, which has to be recognizable
2465
+ * after a reload — a reload mints a new session id, and offline the salt is
2466
+ * `''`, so a salted key can never match what the previous session wrote.
2467
+ */
2468
+ private async calculateMembershipKey(data: any): Promise<string> {
2469
+ return this.sha256(JSON.stringify(data));
2470
+ }
2471
+
2472
+ private async sha256(content: string): Promise<string> {
791
2473
  const msgBuffer = new TextEncoder().encode(content);
792
2474
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
793
2475
  const hashArray = Array.from(new Uint8Array(hashBuffer));
794
2476
  return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
795
2477
  }
796
2478
 
797
- private startTTLHeartbeat(queryState: QueryState): void {
2479
+ private startTTLHeartbeat(queryState: QueryState, hash: QueryHash): void {
798
2480
  if (queryState.ttlTimer) return;
799
2481
 
800
- const heartbeatTime = Math.floor(queryState.ttlDurationMs * 0.9);
2482
+ // Half the TTL, not 0.9 of it, so ONE failed beat is survivable.
2483
+ //
2484
+ // The timer re-arms after each beat, so expiry sits a full TTL after the
2485
+ // last SUCCESSFUL refresh. At 0.9 a beat that fails — the SSP restarting,
2486
+ // a reconnect, a slow database — left 10% of the TTL before the sweep
2487
+ // deleted the row AND its `_00_list_ref` edges, with no second attempt in
2488
+ // between. On a 10m TTL that is 60 seconds of slack against an SSP
2489
+ // bootstrap that takes ~2 minutes on a large tenant, so the view lost a
2490
+ // race it could not win.
2491
+ //
2492
+ // The user-visible form is content vanishing and coming back: the client
2493
+ // is LIVE on those edges, so it sees the sweep's deletes immediately, and
2494
+ // only restores them once its heartbeat notices the row is gone and
2495
+ // re-registers. Reported as chat messages disappearing for 10+ seconds.
2496
+ //
2497
+ // At 0.5 a single failure still leaves another attempt and half the TTL.
2498
+ // The cost is one extra beat per view per TTL, which is a single
2499
+ // `UPDATE ... SET lastActiveAt`.
2500
+ const heartbeatTime = Math.floor(queryState.ttlDurationMs * TTL_HEARTBEAT_FRACTION);
801
2501
 
802
2502
  queryState.ttlTimer = setTimeout(() => {
803
- // TODO: Emit heartbeat event for sync
2503
+ queryState.ttlTimer = null;
2504
+ // Only keep the remote query alive while something is actually watching
2505
+ // it. With the server now sweeping ALL expired views (not just in-circuit
2506
+ // ones), an un-refreshed query WOULD be swept after its TTL — so a live
2507
+ // subscriber must heartbeat. An abandoned query (no subscribers) is left
2508
+ // to expire and get swept; its local view was already torn down at the
2509
+ // last unsubscribe, so we just stop the timer here.
2510
+ const subscriberCount = this.subscriptions.get(hash)?.size ?? 0;
2511
+ if (subscriberCount === 0) {
2512
+ this.logger.debug(
2513
+ { hash, Category: 'sp00ky-client::DataModule::startTTLHeartbeat' },
2514
+ 'TTL heartbeat: no subscribers, stopping'
2515
+ );
2516
+ return;
2517
+ }
2518
+ this.onHeartbeat?.(hash);
804
2519
  this.logger.debug(
805
2520
  {
2521
+ hash,
806
2522
  id: encodeRecordId(queryState.config.id),
807
- Category: 'spooky-client::DataModule::startTTLHeartbeat',
2523
+ Category: 'sp00ky-client::DataModule::startTTLHeartbeat',
808
2524
  },
809
- 'TTL heartbeat'
2525
+ 'TTL heartbeat sent'
810
2526
  );
811
- this.startTTLHeartbeat(queryState);
2527
+ this.startTTLHeartbeat(queryState, hash);
812
2528
  }, heartbeatTime);
813
2529
  }
814
2530
 
815
- private stopTTLHeartbeat(queryState: QueryState): void {
816
- if (queryState.ttlTimer) {
817
- clearTimeout(queryState.ttlTimer);
818
- queryState.ttlTimer = null;
819
- }
820
- }
821
-
822
2531
  private async replaceRecordInQueries(record: Record<string, any>): Promise<void> {
823
2532
  for (const [queryHash, queryState] of this.activeQueries.entries()) {
824
2533
  const index = queryState.records.findIndex((r) => r.id === record.id);
@@ -851,7 +2560,7 @@ export function parseUpdateOptions(
851
2560
  const delay = options.debounced !== true ? (options.debounced?.delay ?? 200) : 200;
852
2561
  const keyType = options.debounced !== true ? (options.debounced?.key ?? id) : id;
853
2562
  const key =
854
- keyType === 'recordId_x_fields' ? `${id}::${Object.keys(data).sort().join('#')}` : id;
2563
+ keyType === 'recordId_x_fields' ? `${id}::${Object.keys(data).toSorted().join('#')}` : id;
855
2564
 
856
2565
  pushEventOptions = {
857
2566
  debounced: {