@spooky-sync/core 0.0.1-canary.22 → 0.0.1-canary.221

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 (163) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2615 -58
  3. package/dist/index.js +12714 -2408
  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 +206 -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 +1815 -151
  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.subquery.test.ts +82 -0
  77. package/src/modules/sync/sync.tabs.test.ts +249 -0
  78. package/src/modules/sync/sync.ts +1851 -98
  79. package/src/modules/sync/utils.test.ts +269 -2
  80. package/src/modules/sync/utils.ts +201 -16
  81. package/src/otel/index.ts +13 -10
  82. package/src/services/blobs/blob-cache.test.ts +359 -0
  83. package/src/services/blobs/blob-cache.ts +603 -0
  84. package/src/services/blobs/blob-manifest.ts +227 -0
  85. package/src/services/blobs/blob-store.test.ts +77 -0
  86. package/src/services/blobs/blob-store.ts +359 -0
  87. package/src/services/blobs/blob.fixture.ts +90 -0
  88. package/src/services/blobs/index.ts +70 -0
  89. package/src/services/database/cache-engine.ts +193 -0
  90. package/src/services/database/connection-supervisor.test.ts +289 -0
  91. package/src/services/database/connection-supervisor.ts +415 -0
  92. package/src/services/database/database.query-timeout.test.ts +83 -0
  93. package/src/services/database/database.ts +41 -12
  94. package/src/services/database/engine-factory.ts +33 -0
  95. package/src/services/database/errors.ts +34 -0
  96. package/src/services/database/events/index.ts +2 -1
  97. package/src/services/database/index.ts +7 -0
  98. package/src/services/database/local-migrator.ts +30 -27
  99. package/src/services/database/local.test.ts +64 -0
  100. package/src/services/database/local.ts +484 -67
  101. package/src/services/database/plan-render.test.ts +159 -0
  102. package/src/services/database/plan-render.ts +108 -0
  103. package/src/services/database/relation-resolver.test.ts +413 -0
  104. package/src/services/database/relation-resolver.ts +0 -0
  105. package/src/services/database/remote.ts +192 -15
  106. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  107. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  108. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  109. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  110. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  111. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  112. package/src/services/database/sqlite-lock-verify.ts +45 -0
  113. package/src/services/database/sqlite-open.test.ts +150 -0
  114. package/src/services/database/sqlite-open.ts +164 -0
  115. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  116. package/src/services/database/sqlite-plan-sql.ts +138 -0
  117. package/src/services/database/sqlite-projection.test.ts +99 -0
  118. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  119. package/src/services/database/sqlite-select.test.ts +246 -0
  120. package/src/services/database/sqlite-select.ts +131 -0
  121. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  122. package/src/services/database/sqlite-transport.ts +224 -0
  123. package/src/services/database/sqlite-worker.ts +437 -0
  124. package/src/services/database/surql-translate.ts +416 -0
  125. package/src/services/database/surreal-cache-engine.ts +161 -0
  126. package/src/services/logger/index.ts +3 -2
  127. package/src/services/persistence/localstorage.ts +2 -2
  128. package/src/services/persistence/resilient.ts +11 -4
  129. package/src/services/persistence/surrealdb.ts +10 -10
  130. package/src/services/stream-processor/index.ts +796 -84
  131. package/src/services/stream-processor/permissions.test.ts +47 -0
  132. package/src/services/stream-processor/permissions.ts +53 -0
  133. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  134. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  135. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  136. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  137. package/src/services/stream-processor/wasm-types.ts +59 -3
  138. package/src/services/tabs/broker-client.ts +283 -0
  139. package/src/services/tabs/broker.test.ts +327 -0
  140. package/src/services/tabs/coordinator.test.ts +365 -0
  141. package/src/services/tabs/coordinator.ts +633 -0
  142. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  143. package/src/services/tabs/leader-locks.ts +75 -0
  144. package/src/services/tabs/protocol.ts +258 -0
  145. package/src/services/tabs/support.ts +36 -0
  146. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  147. package/src/sp00ky.auth-order.test.ts +92 -0
  148. package/src/sp00ky.init-query.test.ts +183 -0
  149. package/src/sp00ky.local-first.test.ts +60 -0
  150. package/src/sp00ky.ts +1720 -0
  151. package/src/types.ts +528 -13
  152. package/src/utils/blurhash.ts +90 -0
  153. package/src/utils/error-classification.test.ts +44 -0
  154. package/src/utils/error-classification.ts +7 -0
  155. package/src/utils/index.ts +79 -13
  156. package/src/utils/parser.test.ts +49 -120
  157. package/src/utils/parser.ts +32 -2
  158. package/src/utils/semver.test.ts +32 -0
  159. package/src/utils/semver.ts +30 -0
  160. package/src/utils/surql.ts +30 -18
  161. package/src/utils/withRetry.test.ts +1 -1
  162. package/tsdown.config.ts +86 -1
  163. package/src/spooky.ts +0 -395
@@ -0,0 +1,228 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { DownQueue } from './queue-down';
3
+ import type { DownEvent } from './queue-down';
4
+ import type { LocalStore } from '../../../services/database/index';
5
+
6
+ const silentLogger = {
7
+ child: () => silentLogger,
8
+ debug: () => {},
9
+ info: () => {},
10
+ warn: () => {},
11
+ error: () => {},
12
+ } as any;
13
+
14
+ const register = (hash: string) => ({ type: 'register', payload: { hash } }) as DownEvent;
15
+ const cleanup = (hash: string) => ({ type: 'cleanup', payload: { hash } }) as DownEvent;
16
+
17
+ const hashOf = (e: DownEvent) => e.payload.hash;
18
+
19
+ function makeQueue() {
20
+ return new DownQueue({} as LocalStore, silentLogger);
21
+ }
22
+
23
+ describe('DownQueue.next failure handling', () => {
24
+ it('re-heads a failing event so a transient failure keeps its order', async () => {
25
+ const q = makeQueue();
26
+ q.push(register('a'));
27
+ q.push(register('b'));
28
+
29
+ const seen: string[] = [];
30
+ await expect(
31
+ q.next(async (e) => {
32
+ seen.push(hashOf(e));
33
+ throw new Error('503');
34
+ })
35
+ ).rejects.toThrow('503');
36
+
37
+ expect(seen).toEqual(['a']);
38
+ // 'a' is back at the head, ahead of 'b'.
39
+ await expect(q.next(async (e) => { seen.push(hashOf(e)); throw new Error('503'); })).rejects.toThrow();
40
+ expect(seen).toEqual(['a', 'a']);
41
+ });
42
+
43
+ it('rotates a persistently failing event to the back so others can proceed', async () => {
44
+ const q = makeQueue();
45
+ q.push(register('poison'));
46
+ q.push(register('healthy'));
47
+
48
+ const seen: string[] = [];
49
+ const failPoison = async (e: DownEvent) => {
50
+ seen.push(hashOf(e));
51
+ if (hashOf(e) === 'poison') throw new Error('400 rejected');
52
+ };
53
+
54
+ // Three attempts keep the head; the third rotates it behind 'healthy'.
55
+ for (let i = 0; i < 3; i++) {
56
+ await expect(q.next(failPoison)).rejects.toThrow();
57
+ }
58
+ expect(seen).toEqual(['poison', 'poison', 'poison']);
59
+
60
+ // 'healthy' is no longer starved.
61
+ await q.next(failPoison);
62
+ expect(seen).toEqual(['poison', 'poison', 'poison', 'healthy']);
63
+ expect(q.size).toBe(1); // only the poison event remains
64
+ });
65
+
66
+ it('does not rotate when nothing else is waiting', async () => {
67
+ const q = makeQueue();
68
+ q.push(register('only'));
69
+
70
+ for (let i = 0; i < 5; i++) {
71
+ await expect(
72
+ q.next(async () => {
73
+ throw new Error('boom');
74
+ })
75
+ ).rejects.toThrow();
76
+ }
77
+ expect(q.size).toBe(1);
78
+ });
79
+
80
+ it('clears the failure count once an event succeeds', async () => {
81
+ const q = makeQueue();
82
+ const event = register('a');
83
+ q.push(event);
84
+ q.push(register('b'));
85
+
86
+ await expect(
87
+ q.next(async () => {
88
+ throw new Error('boom');
89
+ })
90
+ ).rejects.toThrow();
91
+ // Succeeds on the retry, so its streak resets rather than carrying over.
92
+ await q.next(async () => {});
93
+ expect(q.size).toBe(1);
94
+
95
+ q.push(event);
96
+ // A fresh streak: it keeps the head again rather than rotating immediately.
97
+ await expect(
98
+ q.next(async () => {
99
+ throw new Error('boom');
100
+ })
101
+ ).rejects.toThrow();
102
+ const drained: string[] = [];
103
+ await q.next(async (e) => {
104
+ drained.push(hashOf(e));
105
+ });
106
+ expect(drained).toEqual(['b']);
107
+ });
108
+ });
109
+
110
+ describe('DownQueue.takeNext (per-hash ordering under concurrency)', () => {
111
+ it('hands out events for distinct hashes so they can run in parallel', () => {
112
+ const q = makeQueue();
113
+ q.push(register('a'));
114
+ q.push(register('b'));
115
+ q.push(register('c'));
116
+ const busy = new Set<string>();
117
+
118
+ const first = q.takeNext(busy)!;
119
+ busy.add(hashOf(first));
120
+ const second = q.takeNext(busy)!;
121
+ busy.add(hashOf(second));
122
+
123
+ expect([hashOf(first), hashOf(second)]).toEqual(['a', 'b']);
124
+ expect(q.size).toBe(1);
125
+ });
126
+
127
+ it('SKIPS an event whose hash is busy without reordering it', () => {
128
+ // The whole correctness argument: a `cleanup` must never overtake the
129
+ // `register` for the same query. A busy hash's event keeps its place in the
130
+ // queue and is simply passed over.
131
+ const q = makeQueue();
132
+ q.push(register('a'));
133
+ q.push(cleanup('a'));
134
+ q.push(register('b'));
135
+
136
+ const busy = new Set(['a']);
137
+ const taken = q.takeNext(busy)!;
138
+ expect(hashOf(taken)).toBe('b');
139
+
140
+ // Once 'a' frees up, its two events come back out in their original order.
141
+ const rest = [q.takeNext(new Set())!, q.takeNext(new Set())!];
142
+ expect(rest.map((e) => e.type)).toEqual(['register', 'cleanup']);
143
+ expect(q.size).toBe(0);
144
+ });
145
+
146
+ it('returns undefined when every remaining event is blocked', () => {
147
+ const q = makeQueue();
148
+ q.push(register('a'));
149
+ expect(q.takeNext(new Set(['a']))).toBeUndefined();
150
+ // Blocked, not consumed.
151
+ expect(q.size).toBe(1);
152
+ });
153
+ });
154
+
155
+ describe('DownQueue.run', () => {
156
+ it('returns the error instead of throwing, and re-heads the event', async () => {
157
+ // A concurrent drain has other work in flight when one event fails; a
158
+ // rejection here would take that work down with it.
159
+ const q = makeQueue();
160
+ const event = register('a');
161
+ q.push(event);
162
+ const taken = q.takeNext(new Set())!;
163
+
164
+ const boom = new Error('nope');
165
+ const err = await q.run(taken, async () => {
166
+ throw boom;
167
+ });
168
+
169
+ expect(err).toBe(boom);
170
+ expect(q.size).toBe(1);
171
+ expect(hashOf(q.takeNext(new Set())!)).toBe('a');
172
+ });
173
+
174
+ it('returns undefined on success', async () => {
175
+ const q = makeQueue();
176
+ q.push(register('a'));
177
+ const taken = q.takeNext(new Set())!;
178
+ await expect(q.run(taken, async () => {})).resolves.toBeUndefined();
179
+ expect(q.size).toBe(0);
180
+ });
181
+ });
182
+
183
+ describe('DownQueue.push register coalescing', () => {
184
+ it('drops a register for a hash that already has one queued', () => {
185
+ // Four paths re-enqueue `register` for every active hash (reconnect,
186
+ // self-heal, re-mount, and a re-headed failure) and they stack: one tab was
187
+ // measured issuing 84 registrations in 93 seconds for 38 hashes. A register
188
+ // carries nothing but the hash, so the second is identical work.
189
+ const q = makeQueue();
190
+ q.push(register('a'));
191
+ q.push(register('a'));
192
+ q.push(register('a'));
193
+
194
+ expect(q.size).toBe(1);
195
+ });
196
+
197
+ it('keeps registers for DIFFERENT hashes', () => {
198
+ const q = makeQueue();
199
+ q.push(register('a'));
200
+ q.push(register('b'));
201
+
202
+ expect(q.size).toBe(2);
203
+ });
204
+
205
+ it('does NOT coalesce a register queued behind a cleanup for the same hash', () => {
206
+ // Ordering is per hash: dropping this register would let the cleanup tear
207
+ // the query down with nothing left to re-establish it.
208
+ const q = makeQueue();
209
+ q.push(register('a'));
210
+ q.push(cleanup('a'));
211
+ q.push(register('a'));
212
+
213
+ expect(q.size).toBe(3);
214
+ expect([q.takeNext(new Set())!, q.takeNext(new Set())!, q.takeNext(new Set())!].map((e) => e.type)).toEqual([
215
+ 'register',
216
+ 'cleanup',
217
+ 'register',
218
+ ]);
219
+ });
220
+
221
+ it('leaves non-register events alone', () => {
222
+ const q = makeQueue();
223
+ q.push(cleanup('a'));
224
+ q.push(cleanup('a'));
225
+
226
+ expect(q.size).toBe(2);
227
+ });
228
+ });
@@ -1,10 +1,11 @@
1
- import { LocalDatabaseService } from '../../../services/database/index';
1
+ import type { LocalStore } from '../../../services/database/index';
2
+ import type {
3
+ SyncQueueEventSystem} from '../events/index';
2
4
  import {
3
5
  createSyncQueueEventSystem,
4
- SyncQueueEventSystem,
5
6
  SyncQueueEventTypes,
6
7
  } from '../events/index';
7
- import { Logger } from '../../../services/logger/index';
8
+ import type { Logger } from '../../../services/logger/index';
8
9
 
9
10
  export type RegisterEvent = {
10
11
  type: 'register';
@@ -36,17 +37,28 @@ export type CleanupEvent = {
36
37
 
37
38
  export type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
38
39
 
40
+ /**
41
+ * How many times a failing event keeps its place at the head before it is
42
+ * rotated to the back. A transient failure (the SSP still bootstrapping) clears
43
+ * well inside this, so ordering is preserved for the common case; a permanently
44
+ * rejected event (a permission the SSP refuses to lower) stops holding every
45
+ * other query hostage behind it.
46
+ */
47
+ const MAX_HEAD_RETRIES = 3;
48
+
39
49
  export class DownQueue {
40
50
  private queue: DownEvent[] = [];
41
51
  private _events: SyncQueueEventSystem;
42
52
  private logger: Logger;
53
+ /** Consecutive failures per queued event; cleared when it finally succeeds. */
54
+ private failures = new WeakMap<DownEvent, number>();
43
55
 
44
56
  get events(): SyncQueueEventSystem {
45
57
  return this._events;
46
58
  }
47
59
 
48
60
  constructor(
49
- private local: LocalDatabaseService,
61
+ private local: LocalStore,
50
62
  logger: Logger
51
63
  ) {
52
64
  this._events = createSyncQueueEventSystem();
@@ -58,10 +70,38 @@ export class DownQueue {
58
70
  }
59
71
 
60
72
  push(event: DownEvent) {
73
+ // Coalesce repeat registrations. Four separate paths re-enqueue `register`
74
+ // for every active hash — reconnect, self-heal while degraded, a
75
+ // re-mounted subscription, and a failed event re-headed by `run` — and
76
+ // they stack, so one tab was observed issuing 84 `fn::query::register`
77
+ // round trips in 93 seconds for 38 hashes. A register is idempotent and
78
+ // carries no payload beyond the hash, so a second one queued behind the
79
+ // first would re-do identical work.
80
+ //
81
+ // Only when the LAST queued event for the hash is itself a `register`.
82
+ // Ordering never mattered globally but it does per hash (see `takeNext`):
83
+ // dropping a register queued behind a `cleanup` would let the cleanup tear
84
+ // the query down with nothing to re-establish it.
85
+ if (event.type === 'register' && this.lastQueuedTypeFor(event.payload.hash) === 'register') {
86
+ this.logger.debug(
87
+ { hash: event.payload.hash, Category: 'sp00ky-client::DownQueue::push' },
88
+ 'Register already queued for this hash; coalescing'
89
+ );
90
+ return;
91
+ }
61
92
  this.queue.push(event);
62
93
  this.emitPushEvent();
63
94
  }
64
95
 
96
+ /** Type of the last queued event for `hash`, or `undefined` if none. */
97
+ private lastQueuedTypeFor(hash: string): DownEvent['type'] | undefined {
98
+ for (let i = this.queue.length - 1; i >= 0; i--) {
99
+ const queued = this.queue[i]!;
100
+ if (queued.payload.hash === hash) return queued.type;
101
+ }
102
+ return undefined;
103
+ }
104
+
65
105
  private emitPushEvent() {
66
106
  this._events.addEvent({
67
107
  type: SyncQueueEventTypes.QueryItemEnqueued,
@@ -71,19 +111,74 @@ export class DownQueue {
71
111
  });
72
112
  }
73
113
 
114
+ /** Drop all queued events (bucket switch: old-bucket register/sync work is
115
+ * re-derived after the switch; replaying it would target dead query rows). */
116
+ clear(): void {
117
+ this.queue = [];
118
+ }
119
+
74
120
  async next(fn: (event: DownEvent) => Promise<void>): Promise<void> {
75
121
  const event = this.queue.shift();
76
- if (event) {
77
- try {
78
- await fn(event);
79
- } catch (error) {
80
- this.logger.error(
81
- { error, event, Category: 'spooky-client::DownQueue::next' },
82
- 'Failed to process query'
83
- );
122
+ if (!event) return;
123
+ const error = await this.run(event, fn);
124
+ if (error !== undefined) throw error;
125
+ }
126
+
127
+ /**
128
+ * The next event whose hash is NOT already being processed, or `undefined`
129
+ * when every remaining event is blocked on a busy hash.
130
+ *
131
+ * Ordering only ever mattered PER HASH — a `cleanup` must not overtake the
132
+ * `register` for the same query — but the queue enforced it globally, so one
133
+ * registration RPC at a time was the ceiling for the whole client. An event
134
+ * for a busy hash keeps its place here (it is skipped, not reordered), so
135
+ * per-hash ordering is preserved exactly while independent hashes proceed
136
+ * concurrently.
137
+ */
138
+ takeNext(busy: ReadonlySet<string>): DownEvent | undefined {
139
+ for (let i = 0; i < this.queue.length; i++) {
140
+ const event = this.queue[i]!;
141
+ if (busy.has(event.payload.hash)) continue;
142
+ this.queue.splice(i, 1);
143
+ return event;
144
+ }
145
+ return undefined;
146
+ }
147
+
148
+ /**
149
+ * Process one event, applying the re-head / rotate failure policy.
150
+ *
151
+ * NEVER rejects: it RETURNS the error instead (`undefined` on success). A
152
+ * concurrent drain has other work in flight when one event fails, and a
153
+ * rejection would either take that work down with it or have to be caught at
154
+ * every call site. `next` reinstates the throwing contract for the serial
155
+ * callers that still want it.
156
+ */
157
+ async run(
158
+ event: DownEvent,
159
+ fn: (event: DownEvent) => Promise<void>
160
+ ): Promise<unknown | undefined> {
161
+ try {
162
+ await fn(event);
163
+ this.failures.delete(event);
164
+ return undefined;
165
+ } catch (error) {
166
+ const attempts = (this.failures.get(event) ?? 0) + 1;
167
+ this.failures.set(event, attempts);
168
+ // Re-head so a transient failure keeps its ordering, but give up the
169
+ // head once it looks permanent and there is other work waiting — one
170
+ // unregisterable query must not stall every other query's registration.
171
+ const starvingOthers = attempts >= MAX_HEAD_RETRIES && this.queue.length > 0;
172
+ if (starvingOthers) {
173
+ this.queue.push(event);
174
+ } else {
84
175
  this.queue.unshift(event);
85
- throw error;
86
176
  }
177
+ this.logger.error(
178
+ { error, event, attempts, rotated: starvingOthers, Category: 'sp00ky-client::DownQueue::next' },
179
+ 'Failed to process query'
180
+ );
181
+ return error;
87
182
  }
88
183
  }
89
184
  }
@@ -0,0 +1,164 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { UpQueue } from './queue-up';
3
+ import { translateSurql } from '../../../services/database/surql-translate';
4
+ import { surql, classifySyncError } from '../../../utils/index';
5
+
6
+ function makeLogger(): any {
7
+ const noop = () => {};
8
+ const l: any = { debug: noop, info: noop, warn: noop, error: noop, trace: noop };
9
+ l.child = () => l;
10
+ return l;
11
+ }
12
+
13
+ const ROW = {
14
+ id: '_00_pending_mutations:0001753875000000_0001_tabB',
15
+ mutationType: 'create',
16
+ recordId: 'game:g1',
17
+ data: { title: 'x' },
18
+ };
19
+
20
+ // Shared-tabs: followers commit outbox rows into the shared store and notify
21
+ // the leader by id. The notify may be REPLAYED (failover buffering), so the
22
+ // enqueue must be idempotent, and only the leader ever drains.
23
+ describe('UpQueue.enqueueFromDatabase', () => {
24
+ function makeQueue(rows: Record<string, unknown[]>) {
25
+ const query = vi.fn(async (_sql: string, vars?: Record<string, unknown>) => {
26
+ const ids = (vars?.mutation_ids as unknown[]) ?? [];
27
+ const id = String(ids[0] ?? '');
28
+ return [rows[id] ?? []];
29
+ });
30
+ const local: any = { query };
31
+ return { queue: new UpQueue(local, makeLogger()), query };
32
+ }
33
+
34
+ it('loads exactly the forwarded row and enqueues it once', async () => {
35
+ const { queue } = makeQueue({ [ROW.id]: [ROW] });
36
+ await queue.enqueueFromDatabase(ROW.id);
37
+ expect(queue.size).toBe(1);
38
+ });
39
+
40
+ it('is idempotent: a replayed notify does not double-enqueue', async () => {
41
+ const { queue, query } = makeQueue({ [ROW.id]: [ROW] });
42
+ await queue.enqueueFromDatabase(ROW.id);
43
+ await queue.enqueueFromDatabase(ROW.id);
44
+ expect(queue.size).toBe(1);
45
+ // The second call short-circuits before even touching the store.
46
+ expect(query).toHaveBeenCalledTimes(1);
47
+ });
48
+
49
+ it('a row that never committed is a silent no-op (the app promise already rejected)', async () => {
50
+ const { queue } = makeQueue({});
51
+ await queue.enqueueFromDatabase(ROW.id);
52
+ expect(queue.size).toBe(0);
53
+ });
54
+
55
+ // The mock above replaces `local.query` wholesale, so on its own it proves
56
+ // nothing about the SQLite engine actually being able to RUN the statement.
57
+ // That gap shipped a bug: the emitted `SELECT * FROM $mutation_id` passed a
58
+ // single RecordId where the engine's `selectByIds` lowering expects an array,
59
+ // so it threw, the surrounding catch swallowed it at `error` level, and every
60
+ // follower mutation was silently never pushed. Drive the real translator.
61
+ it('discards a create with no payload instead of queueing a guaranteed failure', async () => {
62
+ // `processUpEvent` does `Object.keys(event.data)`, so this row can never be
63
+ // sent. Queued, it sat at the HEAD and blocked every later mutation for the
64
+ // whole app: `next()` re-queues on failure, so the backlog never drained.
65
+ const dropped: any[] = [];
66
+ const rows: Record<string, unknown[]> = {
67
+ [ROW.id]: [{ id: ROW.id, mutationType: 'create', recordId: 'comment:c1' }],
68
+ };
69
+ const query = vi.fn(async (sql: string, vars?: Record<string, unknown>) => {
70
+ if (sql.startsWith('DELETE')) return [[]];
71
+ const ids = (vars?.mutation_ids as unknown[]) ?? [];
72
+ return [rows[String(ids[0] ?? '')] ?? []];
73
+ });
74
+ const queue = new UpQueue({ query } as any, makeLogger(), (d) => dropped.push(d));
75
+
76
+ await queue.enqueueFromDatabase(ROW.id);
77
+
78
+ expect(queue.size).toBe(0);
79
+ expect(dropped).toHaveLength(1);
80
+ // And the row is deleted, so it cannot re-poison the next boot.
81
+ expect(query.mock.calls.some(([sql]) => String(sql).startsWith('DELETE'))).toBe(true);
82
+ });
83
+
84
+ it('loadFromDatabase drains the replayable rows even when one is unsendable', async () => {
85
+ const dropped: any[] = [];
86
+ const query = vi.fn(async (sql: string) => {
87
+ if (sql.startsWith('DELETE')) return [[]];
88
+ return [
89
+ [
90
+ { id: '_00_pending_mutations:a', mutationType: 'create', recordId: 'comment:c1' },
91
+ {
92
+ id: '_00_pending_mutations:b',
93
+ mutationType: 'update',
94
+ recordId: 'game:g1',
95
+ data: { title: 'x' },
96
+ },
97
+ ],
98
+ ];
99
+ });
100
+ const queue = new UpQueue({ query } as any, makeLogger(), (d) => dropped.push(d));
101
+
102
+ await queue.loadFromDatabase();
103
+
104
+ // The good row still loads; the poison one is dropped and reported.
105
+ expect(queue.size).toBe(1);
106
+ expect(dropped).toHaveLength(1);
107
+ expect(dropped[0].mutationId).toBe('_00_pending_mutations:a');
108
+ });
109
+
110
+ it('persists the payload for a create, so it can be replayed at all', () => {
111
+ // The create branch used to accept `dataVar` and ignore it, so the outbox
112
+ // row was the ONLY copy of a pending create and it carried no data.
113
+ const stmt = surql.createMutation('create', 'mid', 'id', 'data');
114
+ expect(stmt).toContain('data = $data');
115
+ });
116
+
117
+ it('deletes the row using the STORED id, not its escaped display form', async () => {
118
+ // Outbox ids contain `_` and `-`, so the store returns them escaped:
119
+ // `_00_pending_mutations:⟨1785…_0005_c960…⟩`. Parsing that verbatim and
120
+ // re-encoding escapes the brackets AGAIN, so the DELETE targeted
121
+ // `⟨⟨…\⟩⟩` and matched nothing: a mutation replayed from the store could
122
+ // never have its row removed, even after a SUCCESSFUL push, so it was
123
+ // re-sent on every boot.
124
+ const storedId = '_00_pending_mutations:⟨1785540216679_0005_c960958c-d6ed⟩';
125
+ const deletes: any[] = [];
126
+ const query = vi.fn(async (sql: string, vars?: Record<string, unknown>) => {
127
+ if (sql.startsWith('DELETE')) {
128
+ deletes.push(vars?.mutation_id);
129
+ return [[]];
130
+ }
131
+ return [[{ id: storedId, mutationType: 'create', recordId: 'comment:c1' }]];
132
+ });
133
+ const queue = new UpQueue({ query } as any, makeLogger(), () => {});
134
+
135
+ await queue.enqueueFromDatabase(storedId);
136
+
137
+ expect(deletes).toHaveLength(1);
138
+ const rid: any = deletes[0];
139
+ expect(String(rid.table)).toBe('_00_pending_mutations');
140
+ expect(rid.id).toBe('1785540216679_0005_c960958c-d6ed');
141
+ expect(String(rid.id)).not.toContain('⟨');
142
+ });
143
+
144
+ it('a push timeout classifies as network, so it retries instead of rolling back', () => {
145
+ const err = new Error('Mutation push timed out after 30000ms (create)');
146
+ expect(classifySyncError(err)).toBe('network');
147
+ });
148
+
149
+ it('emits a statement the SQLite engine can actually translate', async () => {
150
+ const { queue, query } = makeQueue({ [ROW.id]: [ROW] });
151
+ await queue.enqueueFromDatabase(ROW.id);
152
+
153
+ const [sql, vars] = query.mock.calls[0] as [string, Record<string, unknown>];
154
+ const translated = translateSurql(sql, vars);
155
+ const op: any = translated.ops[0];
156
+
157
+ expect(op.kind).toBe('selectByIds');
158
+ // The engine does `ids.length` then `ids.map(...)`: a non-array silently
159
+ // skips the empty-guard and then throws.
160
+ expect(Array.isArray(op.ids)).toBe(true);
161
+ expect(op.ids).toHaveLength(1);
162
+ expect(() => (op.ids as unknown[]).map((x) => x)).not.toThrow();
163
+ });
164
+ });