@terreno/syncdb 56.0.0-beta.0

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 (317) hide show
  1. package/README.md +419 -0
  2. package/dist/auth/betterAuthAdapter.d.ts +22 -0
  3. package/dist/auth/betterAuthAdapter.d.ts.map +1 -0
  4. package/dist/auth/betterAuthAdapter.js +181 -0
  5. package/dist/auth/betterAuthAdapter.js.map +1 -0
  6. package/dist/auth/betterAuthAdapter.test.d.ts +2 -0
  7. package/dist/auth/betterAuthAdapter.test.d.ts.map +1 -0
  8. package/dist/auth/betterAuthAdapter.test.js +350 -0
  9. package/dist/auth/betterAuthAdapter.test.js.map +1 -0
  10. package/dist/auth/types.d.ts +42 -0
  11. package/dist/auth/types.d.ts.map +1 -0
  12. package/dist/auth/types.js +9 -0
  13. package/dist/auth/types.js.map +1 -0
  14. package/dist/client.d.ts +246 -0
  15. package/dist/client.d.ts.map +1 -0
  16. package/dist/client.js +1415 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/client.test.d.ts +2 -0
  19. package/dist/client.test.d.ts.map +1 -0
  20. package/dist/client.test.js +2310 -0
  21. package/dist/client.test.js.map +1 -0
  22. package/dist/crypto/aesGcmCodec.d.ts +33 -0
  23. package/dist/crypto/aesGcmCodec.d.ts.map +1 -0
  24. package/dist/crypto/aesGcmCodec.js +80 -0
  25. package/dist/crypto/aesGcmCodec.js.map +1 -0
  26. package/dist/crypto/aesGcmCodec.test.d.ts +2 -0
  27. package/dist/crypto/aesGcmCodec.test.d.ts.map +1 -0
  28. package/dist/crypto/aesGcmCodec.test.js +83 -0
  29. package/dist/crypto/aesGcmCodec.test.js.map +1 -0
  30. package/dist/crypto/identityCodec.d.ts +7 -0
  31. package/dist/crypto/identityCodec.d.ts.map +1 -0
  32. package/dist/crypto/identityCodec.js +9 -0
  33. package/dist/crypto/identityCodec.js.map +1 -0
  34. package/dist/crypto/keyProviders.d.ts +34 -0
  35. package/dist/crypto/keyProviders.d.ts.map +1 -0
  36. package/dist/crypto/keyProviders.js +102 -0
  37. package/dist/crypto/keyProviders.js.map +1 -0
  38. package/dist/crypto/keyProviders.test.d.ts +2 -0
  39. package/dist/crypto/keyProviders.test.d.ts.map +1 -0
  40. package/dist/crypto/keyProviders.test.js +189 -0
  41. package/dist/crypto/keyProviders.test.js.map +1 -0
  42. package/dist/crypto/types.d.ts +24 -0
  43. package/dist/crypto/types.d.ts.map +1 -0
  44. package/dist/crypto/types.js +8 -0
  45. package/dist/crypto/types.js.map +1 -0
  46. package/dist/debug/debugChannel.d.ts +52 -0
  47. package/dist/debug/debugChannel.d.ts.map +1 -0
  48. package/dist/debug/debugChannel.js +73 -0
  49. package/dist/debug/debugChannel.js.map +1 -0
  50. package/dist/debug/debugChannel.test.d.ts +2 -0
  51. package/dist/debug/debugChannel.test.d.ts.map +1 -0
  52. package/dist/debug/debugChannel.test.js +105 -0
  53. package/dist/debug/debugChannel.test.js.map +1 -0
  54. package/dist/debug/debugLog.d.ts +111 -0
  55. package/dist/debug/debugLog.d.ts.map +1 -0
  56. package/dist/debug/debugLog.js +150 -0
  57. package/dist/debug/debugLog.js.map +1 -0
  58. package/dist/debug/debugLog.test.d.ts +2 -0
  59. package/dist/debug/debugLog.test.d.ts.map +1 -0
  60. package/dist/debug/debugLog.test.js +121 -0
  61. package/dist/debug/debugLog.test.js.map +1 -0
  62. package/dist/index.d.ts +46 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +51 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts +2 -0
  67. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts.map +1 -0
  68. package/dist/isolated/defaultPersisterFactoryNative.isolated.js +38 -0
  69. package/dist/isolated/defaultPersisterFactoryNative.isolated.js.map +1 -0
  70. package/dist/mutations/conflicts.d.ts +31 -0
  71. package/dist/mutations/conflicts.d.ts.map +1 -0
  72. package/dist/mutations/conflicts.js +73 -0
  73. package/dist/mutations/conflicts.js.map +1 -0
  74. package/dist/mutations/outbox.d.ts +174 -0
  75. package/dist/mutations/outbox.d.ts.map +1 -0
  76. package/dist/mutations/outbox.js +385 -0
  77. package/dist/mutations/outbox.js.map +1 -0
  78. package/dist/mutations/outbox.test.d.ts +2 -0
  79. package/dist/mutations/outbox.test.d.ts.map +1 -0
  80. package/dist/mutations/outbox.test.js +643 -0
  81. package/dist/mutations/outbox.test.js.map +1 -0
  82. package/dist/mutations/resolveConflict.d.ts +32 -0
  83. package/dist/mutations/resolveConflict.d.ts.map +1 -0
  84. package/dist/mutations/resolveConflict.js +101 -0
  85. package/dist/mutations/resolveConflict.js.map +1 -0
  86. package/dist/mutations/resolveConflict.test.d.ts +2 -0
  87. package/dist/mutations/resolveConflict.test.d.ts.map +1 -0
  88. package/dist/mutations/resolveConflict.test.js +282 -0
  89. package/dist/mutations/resolveConflict.test.js.map +1 -0
  90. package/dist/persisters/defaultPersisterFactory.d.ts +9 -0
  91. package/dist/persisters/defaultPersisterFactory.d.ts.map +1 -0
  92. package/dist/persisters/defaultPersisterFactory.js +9 -0
  93. package/dist/persisters/defaultPersisterFactory.js.map +1 -0
  94. package/dist/persisters/defaultPersisterFactory.native.d.ts +10 -0
  95. package/dist/persisters/defaultPersisterFactory.native.d.ts.map +1 -0
  96. package/dist/persisters/defaultPersisterFactory.native.js +44 -0
  97. package/dist/persisters/defaultPersisterFactory.native.js.map +1 -0
  98. package/dist/persisters/defaultPersisterFactory.test.d.ts +2 -0
  99. package/dist/persisters/defaultPersisterFactory.test.d.ts.map +1 -0
  100. package/dist/persisters/defaultPersisterFactory.test.js +177 -0
  101. package/dist/persisters/defaultPersisterFactory.test.js.map +1 -0
  102. package/dist/persisters/defaultPersisterFactory.web.d.ts +17 -0
  103. package/dist/persisters/defaultPersisterFactory.web.d.ts.map +1 -0
  104. package/dist/persisters/defaultPersisterFactory.web.js +65 -0
  105. package/dist/persisters/defaultPersisterFactory.web.js.map +1 -0
  106. package/dist/persisters/encryptedIndexedDbPersister.d.ts +46 -0
  107. package/dist/persisters/encryptedIndexedDbPersister.d.ts.map +1 -0
  108. package/dist/persisters/encryptedIndexedDbPersister.js +171 -0
  109. package/dist/persisters/encryptedIndexedDbPersister.js.map +1 -0
  110. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts +2 -0
  111. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts.map +1 -0
  112. package/dist/persisters/encryptedIndexedDbPersister.test.js +352 -0
  113. package/dist/persisters/encryptedIndexedDbPersister.test.js.map +1 -0
  114. package/dist/persisters/memoryPersister.d.ts +19 -0
  115. package/dist/persisters/memoryPersister.d.ts.map +1 -0
  116. package/dist/persisters/memoryPersister.js +31 -0
  117. package/dist/persisters/memoryPersister.js.map +1 -0
  118. package/dist/persisters/memoryPersister.test.d.ts +2 -0
  119. package/dist/persisters/memoryPersister.test.d.ts.map +1 -0
  120. package/dist/persisters/memoryPersister.test.js +113 -0
  121. package/dist/persisters/memoryPersister.test.js.map +1 -0
  122. package/dist/persisters/types.d.ts +65 -0
  123. package/dist/persisters/types.d.ts.map +1 -0
  124. package/dist/persisters/types.js +2 -0
  125. package/dist/persisters/types.js.map +1 -0
  126. package/dist/react/hooks.d.ts +132 -0
  127. package/dist/react/hooks.d.ts.map +1 -0
  128. package/dist/react/hooks.js +269 -0
  129. package/dist/react/hooks.js.map +1 -0
  130. package/dist/react/hooks.test.d.ts +2 -0
  131. package/dist/react/hooks.test.d.ts.map +1 -0
  132. package/dist/react/hooks.test.js +645 -0
  133. package/dist/react/hooks.test.js.map +1 -0
  134. package/dist/react/index.d.ts +11 -0
  135. package/dist/react/index.d.ts.map +1 -0
  136. package/dist/react/index.js +11 -0
  137. package/dist/react/index.js.map +1 -0
  138. package/dist/react/provider.d.ts +11 -0
  139. package/dist/react/provider.d.ts.map +1 -0
  140. package/dist/react/provider.js +17 -0
  141. package/dist/react/provider.js.map +1 -0
  142. package/dist/storage/idb.d.ts +27 -0
  143. package/dist/storage/idb.d.ts.map +1 -0
  144. package/dist/storage/idb.js +72 -0
  145. package/dist/storage/idb.js.map +1 -0
  146. package/dist/storage/idb.test.d.ts +2 -0
  147. package/dist/storage/idb.test.d.ts.map +1 -0
  148. package/dist/storage/idb.test.js +100 -0
  149. package/dist/storage/idb.test.js.map +1 -0
  150. package/dist/storage/purgeUnknownStream.test.d.ts +2 -0
  151. package/dist/storage/purgeUnknownStream.test.d.ts.map +1 -0
  152. package/dist/storage/purgeUnknownStream.test.js +64 -0
  153. package/dist/storage/purgeUnknownStream.test.js.map +1 -0
  154. package/dist/storage/schema.d.ts +33 -0
  155. package/dist/storage/schema.d.ts.map +1 -0
  156. package/dist/storage/schema.js +92 -0
  157. package/dist/storage/schema.js.map +1 -0
  158. package/dist/storage/store.d.ts +136 -0
  159. package/dist/storage/store.d.ts.map +1 -0
  160. package/dist/storage/store.js +275 -0
  161. package/dist/storage/store.js.map +1 -0
  162. package/dist/storage/store.test.d.ts +2 -0
  163. package/dist/storage/store.test.d.ts.map +1 -0
  164. package/dist/storage/store.test.js +357 -0
  165. package/dist/storage/store.test.js.map +1 -0
  166. package/dist/storage/types.d.ts +146 -0
  167. package/dist/storage/types.d.ts.map +1 -0
  168. package/dist/storage/types.js +32 -0
  169. package/dist/storage/types.js.map +1 -0
  170. package/dist/storage/wipe.d.ts +22 -0
  171. package/dist/storage/wipe.d.ts.map +1 -0
  172. package/dist/storage/wipe.js +43 -0
  173. package/dist/storage/wipe.js.map +1 -0
  174. package/dist/storage/wipe.test.d.ts +2 -0
  175. package/dist/storage/wipe.test.d.ts.map +1 -0
  176. package/dist/storage/wipe.test.js +95 -0
  177. package/dist/storage/wipe.test.js.map +1 -0
  178. package/dist/sync/bootstrap.d.ts +64 -0
  179. package/dist/sync/bootstrap.d.ts.map +1 -0
  180. package/dist/sync/bootstrap.js +160 -0
  181. package/dist/sync/bootstrap.js.map +1 -0
  182. package/dist/sync/bootstrap.test.d.ts +2 -0
  183. package/dist/sync/bootstrap.test.d.ts.map +1 -0
  184. package/dist/sync/bootstrap.test.js +447 -0
  185. package/dist/sync/bootstrap.test.js.map +1 -0
  186. package/dist/sync/cursor.d.ts +67 -0
  187. package/dist/sync/cursor.d.ts.map +1 -0
  188. package/dist/sync/cursor.js +74 -0
  189. package/dist/sync/cursor.js.map +1 -0
  190. package/dist/sync/cursor.test.d.ts +2 -0
  191. package/dist/sync/cursor.test.d.ts.map +1 -0
  192. package/dist/sync/cursor.test.js +73 -0
  193. package/dist/sync/cursor.test.js.map +1 -0
  194. package/dist/sync/deltaApplier.d.ts +30 -0
  195. package/dist/sync/deltaApplier.d.ts.map +1 -0
  196. package/dist/sync/deltaApplier.js +61 -0
  197. package/dist/sync/deltaApplier.js.map +1 -0
  198. package/dist/sync/deltaApplier.test.d.ts +2 -0
  199. package/dist/sync/deltaApplier.test.d.ts.map +1 -0
  200. package/dist/sync/deltaApplier.test.js +212 -0
  201. package/dist/sync/deltaApplier.test.js.map +1 -0
  202. package/dist/sync/entityRepair.d.ts +45 -0
  203. package/dist/sync/entityRepair.d.ts.map +1 -0
  204. package/dist/sync/entityRepair.js +91 -0
  205. package/dist/sync/entityRepair.js.map +1 -0
  206. package/dist/sync/entityRepair.test.d.ts +2 -0
  207. package/dist/sync/entityRepair.test.d.ts.map +1 -0
  208. package/dist/sync/entityRepair.test.js +146 -0
  209. package/dist/sync/entityRepair.test.js.map +1 -0
  210. package/dist/sync/httpChannel.d.ts +74 -0
  211. package/dist/sync/httpChannel.d.ts.map +1 -0
  212. package/dist/sync/httpChannel.js +123 -0
  213. package/dist/sync/httpChannel.js.map +1 -0
  214. package/dist/sync/httpChannel.test.d.ts +2 -0
  215. package/dist/sync/httpChannel.test.d.ts.map +1 -0
  216. package/dist/sync/httpChannel.test.js +215 -0
  217. package/dist/sync/httpChannel.test.js.map +1 -0
  218. package/dist/sync/replayCoordinator.d.ts +212 -0
  219. package/dist/sync/replayCoordinator.d.ts.map +1 -0
  220. package/dist/sync/replayCoordinator.js +1110 -0
  221. package/dist/sync/replayCoordinator.js.map +1 -0
  222. package/dist/sync/replayCoordinator.test.d.ts +2 -0
  223. package/dist/sync/replayCoordinator.test.d.ts.map +1 -0
  224. package/dist/sync/replayCoordinator.test.js +1496 -0
  225. package/dist/sync/replayCoordinator.test.js.map +1 -0
  226. package/dist/sync/socketTransport.d.ts +56 -0
  227. package/dist/sync/socketTransport.d.ts.map +1 -0
  228. package/dist/sync/socketTransport.js +292 -0
  229. package/dist/sync/socketTransport.js.map +1 -0
  230. package/dist/sync/socketTransport.test.d.ts +2 -0
  231. package/dist/sync/socketTransport.test.d.ts.map +1 -0
  232. package/dist/sync/socketTransport.test.js +346 -0
  233. package/dist/sync/socketTransport.test.js.map +1 -0
  234. package/dist/sync/transport.d.ts +80 -0
  235. package/dist/sync/transport.d.ts.map +1 -0
  236. package/dist/sync/transport.js +5 -0
  237. package/dist/sync/transport.js.map +1 -0
  238. package/dist/testing/fakeTransport.d.ts +55 -0
  239. package/dist/testing/fakeTransport.d.ts.map +1 -0
  240. package/dist/testing/fakeTransport.js +139 -0
  241. package/dist/testing/fakeTransport.js.map +1 -0
  242. package/dist/testing/fakeTransport.test.d.ts +2 -0
  243. package/dist/testing/fakeTransport.test.d.ts.map +1 -0
  244. package/dist/testing/fakeTransport.test.js +112 -0
  245. package/dist/testing/fakeTransport.test.js.map +1 -0
  246. package/dist/testing/index.d.ts +13 -0
  247. package/dist/testing/index.d.ts.map +1 -0
  248. package/dist/testing/index.js +13 -0
  249. package/dist/testing/index.js.map +1 -0
  250. package/dist/types.d.ts +271 -0
  251. package/dist/types.d.ts.map +1 -0
  252. package/dist/types.js +9 -0
  253. package/dist/types.js.map +1 -0
  254. package/package.json +71 -0
  255. package/src/auth/betterAuthAdapter.test.ts +455 -0
  256. package/src/auth/betterAuthAdapter.ts +214 -0
  257. package/src/auth/types.ts +49 -0
  258. package/src/client.test.ts +2670 -0
  259. package/src/client.ts +1748 -0
  260. package/src/crypto/aesGcmCodec.test.ts +103 -0
  261. package/src/crypto/aesGcmCodec.ts +98 -0
  262. package/src/crypto/identityCodec.ts +10 -0
  263. package/src/crypto/keyProviders.test.ts +228 -0
  264. package/src/crypto/keyProviders.ts +153 -0
  265. package/src/crypto/types.ts +23 -0
  266. package/src/debug/debugChannel.test.ts +121 -0
  267. package/src/debug/debugChannel.ts +112 -0
  268. package/src/debug/debugLog.test.ts +139 -0
  269. package/src/debug/debugLog.ts +272 -0
  270. package/src/index.ts +157 -0
  271. package/src/isolated/defaultPersisterFactoryNative.isolated.ts +45 -0
  272. package/src/mutations/conflicts.ts +108 -0
  273. package/src/mutations/outbox.test.ts +754 -0
  274. package/src/mutations/outbox.ts +585 -0
  275. package/src/mutations/resolveConflict.test.ts +338 -0
  276. package/src/mutations/resolveConflict.ts +115 -0
  277. package/src/persisters/defaultPersisterFactory.native.ts +53 -0
  278. package/src/persisters/defaultPersisterFactory.test.ts +207 -0
  279. package/src/persisters/defaultPersisterFactory.ts +12 -0
  280. package/src/persisters/defaultPersisterFactory.web.ts +78 -0
  281. package/src/persisters/encryptedIndexedDbPersister.test.ts +381 -0
  282. package/src/persisters/encryptedIndexedDbPersister.ts +218 -0
  283. package/src/persisters/memoryPersister.test.ts +136 -0
  284. package/src/persisters/memoryPersister.ts +52 -0
  285. package/src/persisters/types.ts +71 -0
  286. package/src/react/hooks.test.tsx +761 -0
  287. package/src/react/hooks.ts +409 -0
  288. package/src/react/index.ts +11 -0
  289. package/src/react/provider.tsx +27 -0
  290. package/src/storage/idb.test.ts +116 -0
  291. package/src/storage/idb.ts +112 -0
  292. package/src/storage/purgeUnknownStream.test.ts +74 -0
  293. package/src/storage/schema.ts +103 -0
  294. package/src/storage/store.test.ts +424 -0
  295. package/src/storage/store.ts +461 -0
  296. package/src/storage/types.ts +159 -0
  297. package/src/storage/wipe.test.ts +111 -0
  298. package/src/storage/wipe.ts +58 -0
  299. package/src/sync/bootstrap.test.ts +486 -0
  300. package/src/sync/bootstrap.ts +217 -0
  301. package/src/sync/cursor.test.ts +84 -0
  302. package/src/sync/cursor.ts +113 -0
  303. package/src/sync/deltaApplier.test.ts +237 -0
  304. package/src/sync/deltaApplier.ts +84 -0
  305. package/src/sync/entityRepair.test.ts +161 -0
  306. package/src/sync/entityRepair.ts +124 -0
  307. package/src/sync/httpChannel.test.ts +265 -0
  308. package/src/sync/httpChannel.ts +220 -0
  309. package/src/sync/replayCoordinator.test.ts +1709 -0
  310. package/src/sync/replayCoordinator.ts +1370 -0
  311. package/src/sync/socketTransport.test.ts +413 -0
  312. package/src/sync/socketTransport.ts +379 -0
  313. package/src/sync/transport.ts +76 -0
  314. package/src/testing/fakeTransport.test.ts +125 -0
  315. package/src/testing/fakeTransport.ts +206 -0
  316. package/src/testing/index.ts +18 -0
  317. package/src/types.ts +284 -0
@@ -0,0 +1,1709 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {getConflict} from "../mutations/conflicts";
4
+ import {createOutbox, type Outbox} from "../mutations/outbox";
5
+ import {createSyncStore, type SyncStore} from "../storage/store";
6
+ import {createFakeTransport, type FakeTransport} from "../testing/fakeTransport";
7
+ import type {SyncMutateRequest} from "../types";
8
+ import {AuthRequiredError} from "./httpChannel";
9
+ import {
10
+ BATCH_UNSUPPORTED_REPROBE_INTERVAL_MS,
11
+ type CreateReplayCoordinatorArgs,
12
+ createReplayCoordinator,
13
+ ERROR_NACK_BASE_BACKOFF_MS,
14
+ MAX_BACKOFF_MS,
15
+ MAX_ERROR_NACK_ATTEMPTS,
16
+ type ReplayCoordinator,
17
+ } from "./replayCoordinator";
18
+
19
+ const USER = "user-1";
20
+
21
+ interface Harness {
22
+ store: SyncStore;
23
+ outbox: Outbox;
24
+ transport: FakeTransport;
25
+ coordinator: ReplayCoordinator;
26
+ clock: {value: number};
27
+ }
28
+
29
+ const makeHarness = (): Harness => {
30
+ const store = createSyncStore({collections: ["notes", "todos"]});
31
+ const outbox = createOutbox({store});
32
+ const transport = createFakeTransport();
33
+ const clock = {value: 1_000_000};
34
+ const coordinator = createReplayCoordinator({
35
+ now: () => clock.value,
36
+ outbox,
37
+ sendMutation: transport.sendMutation,
38
+ store,
39
+ });
40
+ return {clock, coordinator, outbox, store, transport};
41
+ };
42
+
43
+ /** Harness variant with the batch transport wired in (B3), plus optional overrides. */
44
+ const makeBatchHarness = (overrides: Partial<CreateReplayCoordinatorArgs> = {}): Harness => {
45
+ const store = createSyncStore({collections: ["notes", "todos"]});
46
+ const outbox = createOutbox({store});
47
+ const transport = createFakeTransport();
48
+ const clock = {value: 1_000_000};
49
+ const coordinator = createReplayCoordinator({
50
+ now: () => clock.value,
51
+ outbox,
52
+ sendMutation: transport.sendMutation,
53
+ sendMutationBatch: transport.sendMutationBatch,
54
+ store,
55
+ ...overrides,
56
+ });
57
+ return {clock, coordinator, outbox, store, transport};
58
+ };
59
+
60
+ /** A fake, controllable timer queue: setTimeoutFn/clearTimeoutFn injectable into the coordinator. */
61
+ interface FakeTimers {
62
+ /** Fire every timer whose delay has elapsed at the current clock value, in schedule order. */
63
+ flush: () => void;
64
+ /** Number of currently armed (not yet fired/cleared) timers. */
65
+ armedCount: () => number;
66
+ }
67
+
68
+ const makeFakeTimers = (clock: {
69
+ value: number;
70
+ }): {timers: FakeTimers} & Pick<CreateReplayCoordinatorArgs, "setTimeoutFn" | "clearTimeoutFn"> => {
71
+ interface Entry {
72
+ id: number;
73
+ handler: () => void;
74
+ dueAt: number;
75
+ cleared: boolean;
76
+ }
77
+ const entries = new Map<number, Entry>();
78
+ let nextId = 1;
79
+ const setTimeoutFn = (handler: () => void, ms: number): unknown => {
80
+ const id = nextId++;
81
+ entries.set(id, {cleared: false, dueAt: clock.value + ms, handler, id});
82
+ return id;
83
+ };
84
+ const clearTimeoutFn = (handle: unknown): void => {
85
+ const entry = entries.get(handle as number);
86
+ if (entry) {
87
+ entry.cleared = true;
88
+ entries.delete(handle as number);
89
+ }
90
+ };
91
+ const flush = (): void => {
92
+ const due = [...entries.values()]
93
+ .filter((entry) => !entry.cleared && entry.dueAt <= clock.value)
94
+ .sort((a, b) => a.dueAt - b.dueAt || a.id - b.id);
95
+ for (const entry of due) {
96
+ if (entries.get(entry.id)?.cleared) {
97
+ continue;
98
+ }
99
+ entries.delete(entry.id);
100
+ entry.handler();
101
+ }
102
+ };
103
+ return {
104
+ clearTimeoutFn,
105
+ setTimeoutFn,
106
+ timers: {
107
+ armedCount: () => entries.size,
108
+ flush,
109
+ },
110
+ };
111
+ };
112
+
113
+ /** Enqueue a mutation plus its optimistic entity state, mirroring client.mutate. */
114
+ const enqueue = (
115
+ harness: Harness,
116
+ {
117
+ collection = "todos",
118
+ entityId,
119
+ mutationId,
120
+ data = {title: entityId},
121
+ baseVersion,
122
+ operation = "create" as const,
123
+ userId = USER,
124
+ }: {
125
+ collection?: string;
126
+ entityId: string;
127
+ mutationId: string;
128
+ data?: Record<string, unknown>;
129
+ baseVersion?: number;
130
+ operation?: "create" | "update" | "delete";
131
+ userId?: string;
132
+ }
133
+ ): void => {
134
+ harness.store.upsertEntity({
135
+ collection,
136
+ data,
137
+ id: entityId,
138
+ pendingMutationId: mutationId,
139
+ seq: baseVersion,
140
+ });
141
+ harness.outbox.enqueue({
142
+ args: data,
143
+ baseVersion,
144
+ collection,
145
+ entityId,
146
+ mutationId,
147
+ operation,
148
+ userId,
149
+ });
150
+ };
151
+
152
+ describe("createReplayCoordinator", () => {
153
+ it("acks finalize the mutation, clear pendingMutationId, and stamp the server seq", async () => {
154
+ const harness = makeHarness();
155
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
156
+ harness.transport.respondWithAck({seq: 42});
157
+
158
+ const result = await harness.coordinator.replay({userId: USER});
159
+ expect(result).toEqual({});
160
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
161
+ const entity = harness.store.getEntity({collection: "todos", id: "t1"});
162
+ expect(entity?.pendingMutationId).toBeUndefined();
163
+ expect(entity?.seq).toBe(42);
164
+ expect(entity?.data).toEqual({title: "t1"});
165
+ });
166
+
167
+ it("does not clear a pendingMutationId owned by a newer mutation", async () => {
168
+ const harness = makeHarness();
169
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
170
+ // A second optimistic edit re-protects the entity before m1 resolves.
171
+ harness.store.upsertEntity({
172
+ collection: "todos",
173
+ data: {title: "newer"},
174
+ id: "t1",
175
+ pendingMutationId: "m2",
176
+ });
177
+ harness.transport.respondWithAck({seq: 5});
178
+
179
+ await harness.coordinator.replay({userId: USER});
180
+ const entity = harness.store.getEntity({collection: "todos", id: "t1"});
181
+ expect(entity?.pendingMutationId).toBe("m2");
182
+ expect(entity?.seq).toBe(5);
183
+ });
184
+
185
+ it("sends mutations with parsed data, baseVersion, and no data for deletes", async () => {
186
+ const harness = makeHarness();
187
+ enqueue(harness, {
188
+ baseVersion: 3,
189
+ data: {title: "hello"},
190
+ entityId: "t1",
191
+ mutationId: "m1",
192
+ operation: "update",
193
+ });
194
+ enqueue(harness, {baseVersion: 4, entityId: "t2", mutationId: "m2", operation: "delete"});
195
+
196
+ await harness.coordinator.replay({userId: USER});
197
+ const [first, second] = harness.transport.sentMutations;
198
+ expect(first).toEqual({
199
+ baseVersion: 3,
200
+ collection: "todos",
201
+ data: {title: "hello"},
202
+ id: "t1",
203
+ mutationId: "m1",
204
+ operation: "update",
205
+ });
206
+ expect(second).toEqual({
207
+ baseVersion: 4,
208
+ collection: "todos",
209
+ id: "t2",
210
+ mutationId: "m2",
211
+ operation: "delete",
212
+ });
213
+ });
214
+
215
+ describe("send-time baseVersion refresh (A2)", () => {
216
+ it("chains a create + update to the same entity through one queue with no self-conflict", async () => {
217
+ const harness = makeHarness();
218
+ // create: no baseVersion (new entity).
219
+ enqueue(harness, {
220
+ data: {title: "v1"},
221
+ entityId: "t1",
222
+ mutationId: "m1",
223
+ operation: "create",
224
+ });
225
+ // update enqueued offline BEFORE the create acked: captured baseVersion
226
+ // is still the stale 0/undefined floor.
227
+ harness.store.upsertEntity({collection: "todos", data: {title: "v2"}, id: "t1"});
228
+ harness.outbox.enqueue({
229
+ args: {title: "v2"},
230
+ collection: "todos",
231
+ entityId: "t1",
232
+ mutationId: "m2",
233
+ operation: "update",
234
+ userId: USER,
235
+ });
236
+
237
+ await harness.coordinator.replay({userId: USER});
238
+ const [createReq, updateReq] = harness.transport.sentMutations;
239
+ expect(createReq.baseVersion).toBeUndefined();
240
+ // The create's ack (seq 1) stamped the entity's seq before the update's
241
+ // request was built — the update carries the FRESH seq, not the stale
242
+ // enqueue-time floor, so it never manufactures a conflict.
243
+ expect(updateReq.baseVersion).toBe(1);
244
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
245
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
246
+ });
247
+
248
+ it("chains update + update through one queue: the second request carries the first's acked seq", async () => {
249
+ const harness = makeHarness();
250
+ harness.store.upsertEntity({collection: "todos", data: {title: "v0"}, id: "t1", seq: 5});
251
+ harness.outbox.enqueue({
252
+ args: {title: "v1"},
253
+ baseVersion: 5,
254
+ collection: "todos",
255
+ entityId: "t1",
256
+ mutationId: "m1",
257
+ operation: "update",
258
+ userId: USER,
259
+ });
260
+ harness.outbox.enqueue({
261
+ // Enqueued while m1 is still unacked: same stale baseVersion captured.
262
+ args: {title: "v2"},
263
+ baseVersion: 5,
264
+ collection: "todos",
265
+ entityId: "t1",
266
+ mutationId: "m2",
267
+ operation: "update",
268
+ userId: USER,
269
+ });
270
+ harness.transport.respondWithAck({seq: 6});
271
+
272
+ await harness.coordinator.replay({userId: USER});
273
+ const [firstReq, secondReq] = harness.transport.sentMutations;
274
+ expect(firstReq.baseVersion).toBe(5);
275
+ // m1's ack (seq 6) stamped the entity's seq before m2's request was
276
+ // built — m2 carries that fresh seq, not the stale enqueue-time floor.
277
+ expect(secondReq.baseVersion).toBe(6);
278
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
279
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
280
+ });
281
+
282
+ it("never sends a baseVersion lower than the one stored at enqueue time (floor)", async () => {
283
+ const harness = makeHarness();
284
+ // The entity's live seq (2) is BELOW the stored baseVersion (5) — e.g. a
285
+ // stale local write raced a delta application. The stored value is the
286
+ // floor and must win.
287
+ harness.store.upsertEntity({collection: "todos", data: {title: "v1"}, id: "t1", seq: 2});
288
+ harness.outbox.enqueue({
289
+ args: {title: "v1"},
290
+ baseVersion: 5,
291
+ collection: "todos",
292
+ entityId: "t1",
293
+ mutationId: "m1",
294
+ operation: "update",
295
+ userId: USER,
296
+ });
297
+
298
+ await harness.coordinator.replay({userId: USER});
299
+ expect(harness.transport.sentMutations[0]?.baseVersion).toBe(5);
300
+ });
301
+
302
+ it("regression: a genuinely stale base (server changed underneath) still conflicts", async () => {
303
+ const harness = makeHarness();
304
+ enqueue(harness, {
305
+ baseVersion: 2,
306
+ data: {title: "local"},
307
+ entityId: "t1",
308
+ mutationId: "m1",
309
+ operation: "update",
310
+ });
311
+ harness.transport.respondWithNack({
312
+ code: "conflict",
313
+ serverDoc: {title: "server wins"},
314
+ serverSeq: 9,
315
+ });
316
+
317
+ await harness.coordinator.replay({userId: USER});
318
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("conflicted");
319
+ expect(getConflict({mutationId: "m1", store: harness.store})?.serverSeq).toBe(9);
320
+ });
321
+ });
322
+
323
+ it("drains FIFO within a collection", async () => {
324
+ const harness = makeHarness();
325
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
326
+ enqueue(harness, {entityId: "t2", mutationId: "m2"});
327
+ enqueue(harness, {entityId: "t3", mutationId: "m3"});
328
+
329
+ await harness.coordinator.replay({userId: USER});
330
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["m1", "m2", "m3"]);
331
+ });
332
+
333
+ it("a transport rejection halts the ENTIRE global drain (INV-1), not just its collection", async () => {
334
+ const harness = makeHarness();
335
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
336
+ enqueue(harness, {entityId: "t2", mutationId: "m2"});
337
+ enqueue(harness, {collection: "notes", entityId: "n1", mutationId: "m3"});
338
+ harness.transport.setDefaultResponder((request) => {
339
+ if (request.collection === "todos") {
340
+ throw new Error("timeout");
341
+ }
342
+ return {ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1}, type: "ack"};
343
+ });
344
+
345
+ await harness.coordinator.replay({userId: USER});
346
+ // m1 (head of the global FIFO) failed to send and went back to queued;
347
+ // the drain stops the line — m2 AND m3 (a different collection) are never
348
+ // attempted, even though m3's transport would have acked it.
349
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
350
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("queued");
351
+ expect(harness.outbox.getMutation({mutationId: "m3"})?.status).toBe("queued");
352
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["m1"]);
353
+
354
+ // The next replay resumes the whole queue once the transport recovers and
355
+ // the jittered backoff has elapsed.
356
+ harness.transport.setDefaultResponder();
357
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 30;
358
+ await harness.coordinator.replay({userId: USER});
359
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
360
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
361
+ expect(harness.outbox.getMutation({mutationId: "m3"})?.status).toBe("acked");
362
+ });
363
+
364
+ it("conflict nacks record a _conflicts row and leave the optimistic entity in place", async () => {
365
+ const harness = makeHarness();
366
+ enqueue(harness, {
367
+ baseVersion: 2,
368
+ data: {title: "local"},
369
+ entityId: "t1",
370
+ mutationId: "m1",
371
+ operation: "update",
372
+ });
373
+ harness.transport.respondWithNack({
374
+ code: "conflict",
375
+ serverDoc: {title: "server"},
376
+ serverSeq: 9,
377
+ });
378
+
379
+ await harness.coordinator.replay({userId: USER});
380
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("conflicted");
381
+ expect(getConflict({mutationId: "m1", store: harness.store})).toEqual({
382
+ collection: "todos",
383
+ dismissed: false,
384
+ entityId: "t1",
385
+ localData: JSON.stringify({title: "local"}),
386
+ mutationId: "m1",
387
+ serverData: JSON.stringify({title: "server"}),
388
+ serverDeleted: false,
389
+ serverSeq: 9,
390
+ });
391
+ const entity = harness.store.getEntity({collection: "todos", id: "t1"});
392
+ expect(entity?.data).toEqual({title: "local"});
393
+ expect(entity?.pendingMutationId).toBe("m1");
394
+ });
395
+
396
+ // Task 9.12: the flag has to survive onto the `_conflicts` row, since that is
397
+ // all `resolveConflict` sees when the user eventually picks a side.
398
+ it("records a conflict nack's serverDeleted flag on the conflict row (9.12)", async () => {
399
+ const harness = makeHarness();
400
+ enqueue(harness, {
401
+ baseVersion: 2,
402
+ data: {title: "local"},
403
+ entityId: "t1",
404
+ mutationId: "m1",
405
+ operation: "update",
406
+ });
407
+ harness.transport.respondWithNack({code: "conflict", serverDeleted: true, serverSeq: 9});
408
+
409
+ await harness.coordinator.replay({userId: USER});
410
+ expect(getConflict({mutationId: "m1", store: harness.store})?.serverDeleted).toBe(true);
411
+ });
412
+
413
+ it("unauthorized nacks requeue, pause replay for the user, and resume on the next call", async () => {
414
+ const harness = makeHarness();
415
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
416
+ enqueue(harness, {entityId: "t2", mutationId: "m2"});
417
+ enqueue(harness, {collection: "notes", entityId: "n1", mutationId: "m3"});
418
+ harness.transport.setDefaultResponder((request) => ({
419
+ nack: {code: "unauthorized", mutationId: request.mutationId},
420
+ type: "nack",
421
+ }));
422
+
423
+ const result = await harness.coordinator.replay({userId: USER});
424
+ expect(result).toEqual({paused: "auth"});
425
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
426
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("queued");
427
+
428
+ // Resumable: after auth is restored the next replay drains everything.
429
+ harness.transport.setDefaultResponder();
430
+ const resumed = await harness.coordinator.replay({userId: USER});
431
+ expect(resumed).toEqual({});
432
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
433
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
434
+ expect(harness.outbox.getMutation({mutationId: "m3"})?.status).toBe("acked");
435
+ });
436
+
437
+ it("AuthRequiredError thrown by the send channel (A4) is treated exactly like an unauthorized nack: requeue, pause, zero budget burn", async () => {
438
+ const harness = makeHarness();
439
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
440
+ enqueue(harness, {entityId: "t2", mutationId: "m2"});
441
+ harness.transport.respondWith(() => {
442
+ throw new AuthRequiredError();
443
+ });
444
+
445
+ const result = await harness.coordinator.replay({userId: USER});
446
+ expect(result).toEqual({paused: "auth"});
447
+ const mutation = harness.outbox.getMutation({mutationId: "m1"});
448
+ expect(mutation?.status).toBe("queued");
449
+ // No budget consumed at all: neither the diagnostic attemptCount (beyond
450
+ // the single send attempt already counted by markInFlight) nor the
451
+ // error-nack terminality counter.
452
+ expect(mutation?.errorNackCount).toBe(0);
453
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("queued");
454
+
455
+ // Resumable exactly like an unauthorized nack.
456
+ harness.transport.setDefaultResponder();
457
+ const resumed = await harness.coordinator.replay({userId: USER});
458
+ expect(resumed).toEqual({});
459
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
460
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
461
+ });
462
+
463
+ it("validation nacks are terminal failures that release the entity", async () => {
464
+ const harness = makeHarness();
465
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
466
+ harness.transport.respondWithNack({code: "validation", message: "title required"});
467
+
468
+ await harness.coordinator.replay({userId: USER});
469
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
470
+ // pendingMutationId is released so future server deltas can apply.
471
+ expect(
472
+ harness.store.getEntity({collection: "todos", id: "t1"})?.pendingMutationId
473
+ ).toBeUndefined();
474
+ });
475
+
476
+ // Task 9.11a: a terminal nack means the server never accepted the optimistic
477
+ // payload, and (absent a concurrent server write) the entity's seq never
478
+ // moves, so snapshot reconcile skips it forever. Marking needs-repair in the
479
+ // terminal path is what makes the rejected data converge back to the server.
480
+ it("marks the entity needs-repair on a terminal validation nack (9.11a)", async () => {
481
+ const harness = makeHarness();
482
+ harness.store.upsertEntity({
483
+ collection: "todos",
484
+ data: {title: "server"},
485
+ id: "t1",
486
+ seq: 7,
487
+ stream: "todos|owner:u1",
488
+ });
489
+ enqueue(harness, {
490
+ baseVersion: 7,
491
+ data: {title: "rejected"},
492
+ entityId: "t1",
493
+ mutationId: "m1",
494
+ operation: "update",
495
+ });
496
+ harness.transport.respondWithNack({code: "validation", message: "title required"});
497
+
498
+ await harness.coordinator.replay({userId: USER});
499
+ expect(harness.store.listNeedsRepair()).toEqual([
500
+ {collection: "todos", entityId: "t1", missedSeq: 7, stream: "todos|owner:u1"},
501
+ ]);
502
+ });
503
+
504
+ it("marks the entity needs-repair when the error-nack budget is exhausted (9.11a)", async () => {
505
+ const harness = makeHarness();
506
+ harness.store.upsertEntity({
507
+ collection: "todos",
508
+ data: {title: "server"},
509
+ id: "t1",
510
+ seq: 2,
511
+ stream: "todos|owner:u1",
512
+ });
513
+ enqueue(harness, {
514
+ baseVersion: 2,
515
+ entityId: "t1",
516
+ mutationId: "m1",
517
+ operation: "update",
518
+ });
519
+ harness.transport.setDefaultResponder((request) => ({
520
+ nack: {code: "error", mutationId: request.mutationId},
521
+ type: "nack",
522
+ }));
523
+
524
+ for (let attempt = 1; attempt <= MAX_ERROR_NACK_ATTEMPTS; attempt += 1) {
525
+ harness.clock.value += MAX_BACKOFF_MS;
526
+ await harness.coordinator.replay({userId: USER});
527
+ }
528
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
529
+ expect(harness.store.hasNeedsRepair({collection: "todos", entityId: "t1"})).toBe(true);
530
+ });
531
+
532
+ it("passes the released entity to the repair hook with its needs-repair mark already set (9.11a)", async () => {
533
+ const store = createSyncStore({collections: ["notes", "todos"]});
534
+ const outbox = createOutbox({store});
535
+ const transport = createFakeTransport();
536
+ const markedWhenNotified: boolean[] = [];
537
+ const coordinator = createReplayCoordinator({
538
+ onEntityReleasedWithoutServerAck: (mutation) => {
539
+ markedWhenNotified.push(
540
+ store.hasNeedsRepair({collection: mutation.collection, entityId: mutation.entityId})
541
+ );
542
+ },
543
+ outbox,
544
+ sendMutation: transport.sendMutation,
545
+ store,
546
+ });
547
+ const harness: Harness = {clock: {value: 0}, coordinator, outbox, store, transport};
548
+ enqueue(harness, {entityId: "t1", mutationId: "m1", operation: "update"});
549
+ transport.respondWithNack({code: "validation"});
550
+
551
+ await coordinator.replay({userId: USER});
552
+ expect(markedWhenNotified).toEqual([true]);
553
+ });
554
+
555
+ it("error nacks requeue with exponential backoff and block the collection head", async () => {
556
+ const harness = makeHarness();
557
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
558
+ enqueue(harness, {entityId: "t2", mutationId: "m2"});
559
+ harness.transport.respondWithNack({code: "error"});
560
+
561
+ await harness.coordinator.replay({userId: USER});
562
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
563
+ // FIFO: m2 is not sent while the head is backing off.
564
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["m1"]);
565
+
566
+ // Within the backoff window nothing is retried.
567
+ await harness.coordinator.replay({userId: USER});
568
+ expect(harness.transport.sentMutations).toHaveLength(1);
569
+
570
+ // After the first backoff delay elapses, the head retries and the queue drains.
571
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS;
572
+ await harness.coordinator.replay({userId: USER});
573
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["m1", "m1", "m2"]);
574
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
575
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
576
+ });
577
+
578
+ it(`marks failed after ${MAX_ERROR_NACK_ATTEMPTS} error-nack attempts`, async () => {
579
+ const harness = makeHarness();
580
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
581
+ harness.transport.setDefaultResponder((request) => ({
582
+ nack: {code: "error", mutationId: request.mutationId},
583
+ type: "nack",
584
+ }));
585
+
586
+ for (let attempt = 1; attempt <= MAX_ERROR_NACK_ATTEMPTS; attempt += 1) {
587
+ await harness.coordinator.replay({userId: USER});
588
+ // Jump past any backoff so the next attempt is eligible.
589
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 2 ** attempt;
590
+ }
591
+ expect(harness.transport.sentMutations).toHaveLength(MAX_ERROR_NACK_ATTEMPTS);
592
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
593
+ expect(
594
+ harness.store.getEntity({collection: "todos", id: "t1"})?.pendingMutationId
595
+ ).toBeUndefined();
596
+
597
+ // Terminal: further replays never resend it.
598
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 100;
599
+ await harness.coordinator.replay({userId: USER});
600
+ expect(harness.transport.sentMutations).toHaveLength(MAX_ERROR_NACK_ATTEMPTS);
601
+ });
602
+
603
+ it("a concurrent replay for the same user returns the in-flight promise", async () => {
604
+ const harness = makeHarness();
605
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
606
+ let release: (() => void) | undefined;
607
+ harness.transport.respondWith(async (request: SyncMutateRequest) => {
608
+ await new Promise<void>((resolve) => {
609
+ release = resolve;
610
+ });
611
+ return {ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1}, type: "ack"};
612
+ });
613
+
614
+ const first = harness.coordinator.replay({userId: USER});
615
+ const second = harness.coordinator.replay({userId: USER});
616
+ expect(second).toBe(first);
617
+ release?.();
618
+ await first;
619
+ expect(harness.transport.sentMutations).toHaveLength(1);
620
+
621
+ // After completion a new replay starts fresh.
622
+ const third = harness.coordinator.replay({userId: USER});
623
+ expect(third).not.toBe(first);
624
+ await third;
625
+ });
626
+
627
+ it("only replays mutations belonging to the requested user", async () => {
628
+ const harness = makeHarness();
629
+ enqueue(harness, {entityId: "t1", mutationId: "m1", userId: "someone-else"});
630
+ enqueue(harness, {entityId: "t2", mutationId: "m2"});
631
+
632
+ await harness.coordinator.replay({userId: USER});
633
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["m2"]);
634
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
635
+ });
636
+
637
+ it("tolerates unparseable stored args by sending empty data", async () => {
638
+ const harness = makeHarness();
639
+ harness.store.upsertEntity({
640
+ collection: "todos",
641
+ data: null,
642
+ id: "t1",
643
+ pendingMutationId: "m1",
644
+ });
645
+ harness.outbox.enqueue({
646
+ args: {},
647
+ collection: "todos",
648
+ entityId: "t1",
649
+ mutationId: "m1",
650
+ operation: "create",
651
+ userId: USER,
652
+ });
653
+ harness.store.raw.setCell("_outbox", "m1", "args", "{not json");
654
+
655
+ await harness.coordinator.replay({userId: USER});
656
+ expect(harness.transport.sentMutations[0]?.data).toEqual({});
657
+ });
658
+
659
+ describe("real scheduler: drain-until-empty + timed wake-ups + jittered backoff (A3)", () => {
660
+ it("sends a mutation enqueued during an active drain, within the same replay() call", async () => {
661
+ const store = createSyncStore({collections: ["todos"]});
662
+ const outbox = createOutbox({store});
663
+ const transport = createFakeTransport();
664
+ let armedSecond = false;
665
+ transport.respondWith(async (request) => {
666
+ // Enqueue m2 WHILE m1's send is in flight — before the drain loop's
667
+ // "is the queue now empty" recheck runs.
668
+ if (!armedSecond) {
669
+ armedSecond = true;
670
+ outbox.enqueue({
671
+ args: {title: "t2"},
672
+ collection: "todos",
673
+ entityId: "t2",
674
+ mutationId: "m2",
675
+ operation: "create",
676
+ userId: USER,
677
+ });
678
+ }
679
+ return {ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1}, type: "ack"};
680
+ });
681
+ const coordinator = createReplayCoordinator({
682
+ outbox,
683
+ sendMutation: transport.sendMutation,
684
+ store,
685
+ });
686
+ outbox.enqueue({
687
+ args: {title: "t1"},
688
+ collection: "todos",
689
+ entityId: "t1",
690
+ mutationId: "m1",
691
+ operation: "create",
692
+ userId: USER,
693
+ });
694
+
695
+ await coordinator.replay({userId: USER});
696
+ expect(transport.sentMutations.map((m) => m.mutationId)).toEqual(["m1", "m2"]);
697
+ expect(outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
698
+ });
699
+
700
+ it("an error-nack backoff elapsing fires the retry from the armed timer alone (no external trigger)", async () => {
701
+ const store = createSyncStore({collections: ["todos"]});
702
+ const outbox = createOutbox({store});
703
+ const transport = createFakeTransport();
704
+ const clock = {value: 1_000_000};
705
+ const {timers, ...timerArgs} = makeFakeTimers(clock);
706
+ const coordinator = createReplayCoordinator({
707
+ ...timerArgs,
708
+ now: () => clock.value,
709
+ outbox,
710
+ random: () => 0.999999, // near-max jitter for a deterministic wake delay
711
+ sendMutation: transport.sendMutation,
712
+ store,
713
+ });
714
+ outbox.enqueue({
715
+ args: {title: "t1"},
716
+ collection: "todos",
717
+ entityId: "t1",
718
+ mutationId: "m1",
719
+ operation: "create",
720
+ userId: USER,
721
+ });
722
+ transport.respondWithNack({code: "error"});
723
+
724
+ await coordinator.replay({userId: USER});
725
+ expect(outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
726
+ expect(transport.sentMutations).toHaveLength(1);
727
+ expect(timers.armedCount()).toBe(1);
728
+
729
+ // Advance the clock past the backoff and fire the armed timer directly —
730
+ // no replay()/replayOutbox() call from the test.
731
+ clock.value += ERROR_NACK_BASE_BACKOFF_MS;
732
+ timers.flush();
733
+ await Promise.resolve();
734
+ await Promise.resolve();
735
+ expect(transport.sentMutations.map((m) => m.mutationId)).toEqual(["m1", "m1"]);
736
+ expect(outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
737
+ });
738
+
739
+ it("transport failures get unlimited retries (never terminal) and don't burn the error-nack budget; a subsequent error-nack budget starts at 1", async () => {
740
+ const harness = makeHarness();
741
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
742
+ harness.transport.setDefaultResponder(() => {
743
+ throw new Error("network down");
744
+ });
745
+
746
+ // Ten transport failures — still queued, never terminal, attemptCount
747
+ // climbs but errorNackCount (the terminality budget) stays at 0.
748
+ for (let i = 0; i < 10; i += 1) {
749
+ await harness.coordinator.replay({userId: USER});
750
+ harness.clock.value += MAX_BACKOFF_MS;
751
+ }
752
+ const afterTransportFailures = harness.outbox.getMutation({mutationId: "m1"});
753
+ expect(afterTransportFailures?.status).toBe("queued");
754
+ expect(afterTransportFailures?.errorNackCount).toBe(0);
755
+ expect(afterTransportFailures?.attemptCount).toBe(10);
756
+
757
+ // Now the server responds with a real error-nack: its budget starts at 1,
758
+ // not at 10 (proving the two counters are tracked separately).
759
+ harness.transport.setDefaultResponder((request) => ({
760
+ nack: {code: "error", mutationId: request.mutationId},
761
+ type: "nack",
762
+ }));
763
+ await harness.coordinator.replay({userId: USER});
764
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.errorNackCount).toBe(1);
765
+ });
766
+
767
+ it("rate_limited nacks are treated exactly like a transport failure: unlimited retries, zero errorNackCount burn (FIX 1)", async () => {
768
+ const harness = makeHarness();
769
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
770
+ harness.transport.setDefaultResponder((request) => ({
771
+ nack: {code: "rate_limited", mutationId: request.mutationId, retryAfterMs: 500},
772
+ type: "nack",
773
+ }));
774
+
775
+ // Five-plus rate-limit nacks — more than MAX_ERROR_NACK_ATTEMPTS would
776
+ // ever tolerate for a real error-nack — must never go terminal.
777
+ for (let i = 0; i < 6; i += 1) {
778
+ const result = await harness.coordinator.replay({userId: USER});
779
+ expect(result).toEqual({});
780
+ harness.clock.value += MAX_BACKOFF_MS;
781
+ }
782
+ const mutation = harness.outbox.getMutation({mutationId: "m1"});
783
+ expect(mutation?.status).toBe("queued");
784
+ expect(mutation?.errorNackCount).toBe(0);
785
+
786
+ // Once the server allows it through, the mutation drains successfully.
787
+ harness.transport.setDefaultResponder();
788
+ await harness.coordinator.replay({userId: USER});
789
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
790
+ });
791
+
792
+ it("rate_limited respects retryAfterMs as a backoff floor — no retry before the server's window clears", async () => {
793
+ const harness = makeHarness();
794
+ enqueue(harness, {entityId: "t1", mutationId: "m1"});
795
+ harness.transport.respondWithNack({code: "rate_limited", retryAfterMs: 10_000});
796
+
797
+ await harness.coordinator.replay({userId: USER});
798
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
799
+ expect(harness.transport.sentMutations).toHaveLength(1);
800
+
801
+ // A jittered backoff well under the server's floor must not fire yet.
802
+ harness.transport.setDefaultResponder();
803
+ harness.clock.value += 1_000;
804
+ await harness.coordinator.replay({userId: USER});
805
+ expect(harness.transport.sentMutations).toHaveLength(1);
806
+
807
+ // Past the 10s floor, the armed wake-up (or an explicit replay) retries.
808
+ harness.clock.value += 10_000;
809
+ await harness.coordinator.replay({userId: USER});
810
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
811
+ });
812
+
813
+ it("a rate_limited chunk response requeues the WHOLE batch untouched and halts the drain (FIX 1, batch path)", async () => {
814
+ const harness = makeBatchHarness();
815
+ enqueue(harness, {entityId: "e1", mutationId: "m1"});
816
+ enqueue(harness, {entityId: "e2", mutationId: "m2"});
817
+ harness.transport.setBatchResponder((request) => ({
818
+ results: request.mutations.map((mutation) => ({
819
+ nack: {code: "rate_limited" as const, mutationId: mutation.mutationId, retryAfterMs: 200},
820
+ type: "nack" as const,
821
+ })),
822
+ type: "results",
823
+ }));
824
+
825
+ await harness.coordinator.replay({userId: USER});
826
+ for (const id of ["m1", "m2"]) {
827
+ const mutation = harness.outbox.getMutation({mutationId: id});
828
+ expect(mutation?.status).toBe("queued");
829
+ expect(mutation?.errorNackCount).toBe(0);
830
+ }
831
+
832
+ harness.transport.setBatchResponder();
833
+ harness.clock.value += 1_000;
834
+ await harness.coordinator.replay({userId: USER});
835
+ for (const id of ["m1", "m2"]) {
836
+ expect(harness.outbox.getMutation({mutationId: id})?.status).toBe("acked");
837
+ }
838
+ });
839
+
840
+ it("jitter: two backoffs for the same attempt differ under an injected seeded random source", async () => {
841
+ const seeds = [0.1, 0.9];
842
+ let call = 0;
843
+ const transport = createFakeTransport();
844
+ const clock = {value: 1_000_000};
845
+ const delays: number[] = [];
846
+
847
+ // A fresh store/outbox/coordinator per mutation isolates each one's
848
+ // "attempt 1" backoff so both draw from the seeded random source below.
849
+ for (const id of ["m1", "m2"]) {
850
+ const store = createSyncStore({collections: ["todos"]});
851
+ const outbox = createOutbox({store});
852
+ const coordinator = createReplayCoordinator({
853
+ now: () => clock.value,
854
+ outbox,
855
+ random: () => seeds[call++] ?? 0.5,
856
+ sendMutation: transport.sendMutation,
857
+ setTimeoutFn: (_handler, ms) => {
858
+ delays.push(ms);
859
+ return 0;
860
+ },
861
+ store,
862
+ });
863
+ outbox.enqueue({
864
+ args: {},
865
+ collection: "todos",
866
+ entityId: id,
867
+ mutationId: id,
868
+ operation: "create",
869
+ userId: USER,
870
+ });
871
+ transport.respondWithNack({code: "error"});
872
+ await coordinator.replay({userId: USER});
873
+ }
874
+ expect(delays).toHaveLength(2);
875
+ expect(delays[0]).not.toBe(delays[1]);
876
+ });
877
+
878
+ it("global order: mutations across two collections replay strictly in enqueue order", async () => {
879
+ const harness = makeHarness();
880
+ enqueue(harness, {collection: "todos", entityId: "t1", mutationId: "m1"});
881
+ enqueue(harness, {collection: "notes", entityId: "n1", mutationId: "m2"});
882
+ enqueue(harness, {collection: "todos", entityId: "t2", mutationId: "m3"});
883
+ enqueue(harness, {collection: "notes", entityId: "n2", mutationId: "m4"});
884
+
885
+ await harness.coordinator.replay({userId: USER});
886
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual([
887
+ "m1",
888
+ "m2",
889
+ "m3",
890
+ "m4",
891
+ ]);
892
+ });
893
+
894
+ it("dispose() clears armed timers so nothing sends after stop", async () => {
895
+ const store = createSyncStore({collections: ["todos"]});
896
+ const outbox = createOutbox({store});
897
+ const transport = createFakeTransport();
898
+ const clock = {value: 1_000_000};
899
+ const {timers, ...timerArgs} = makeFakeTimers(clock);
900
+ const coordinator = createReplayCoordinator({
901
+ ...timerArgs,
902
+ now: () => clock.value,
903
+ outbox,
904
+ sendMutation: transport.sendMutation,
905
+ store,
906
+ });
907
+ outbox.enqueue({
908
+ args: {},
909
+ collection: "todos",
910
+ entityId: "t1",
911
+ mutationId: "m1",
912
+ operation: "create",
913
+ userId: USER,
914
+ });
915
+ transport.respondWithNack({code: "error"});
916
+
917
+ await coordinator.replay({userId: USER});
918
+ expect(timers.armedCount()).toBe(1);
919
+
920
+ coordinator.dispose({userId: USER});
921
+ expect(timers.armedCount()).toBe(0);
922
+
923
+ // Even if the clock advances past the backoff, nothing fires — the
924
+ // timer was cleared, not just superseded.
925
+ clock.value += ERROR_NACK_BASE_BACKOFF_MS * 10;
926
+ timers.flush();
927
+ await Promise.resolve();
928
+ expect(transport.sentMutations).toHaveLength(1);
929
+ });
930
+
931
+ it("skips the debug-only listQueued scan when debug logging is disabled", async () => {
932
+ const harness = makeHarness();
933
+ expect(harness.coordinator).toBeDefined();
934
+ // No debug log was configured for this harness; replay must not throw or
935
+ // require one — the debug-only scan path is conditional on its presence.
936
+ await harness.coordinator.replay({userId: USER});
937
+ });
938
+ });
939
+
940
+ describe("batched drain on top of the global FIFO (B3)", () => {
941
+ const enqueueN = (
942
+ harness: Harness,
943
+ count: number,
944
+ {collection = "todos", prefix = "m"}: {collection?: string; prefix?: string} = {}
945
+ ): void => {
946
+ for (let i = 0; i < count; i++) {
947
+ enqueue(harness, {collection, entityId: `${prefix}-e${i}`, mutationId: `${prefix}-${i}`});
948
+ }
949
+ };
950
+
951
+ it("120 queued across 2 collections drains in exactly 3 batch round-trips, order preserved", async () => {
952
+ const harness = makeBatchHarness();
953
+ // Interleave two collections in enqueue order so global FIFO ordering is
954
+ // actually exercised, not just per-collection ordering.
955
+ for (let i = 0; i < 60; i++) {
956
+ enqueue(harness, {collection: "todos", entityId: `t-e${i}`, mutationId: `t-${i}`});
957
+ enqueue(harness, {collection: "notes", entityId: `n-e${i}`, mutationId: `n-${i}`});
958
+ }
959
+ await harness.coordinator.replay({userId: USER});
960
+ expect(harness.transport.sentBatches).toHaveLength(3);
961
+ // Default batchSize is 50: 120 mutations drain as 50 + 50 + 20.
962
+ expect(harness.transport.sentBatches.map((batch) => batch.length)).toEqual([50, 50, 20]);
963
+ // Global enqueue order preserved across the whole drain, not just within
964
+ // a chunk — assert via server-assigned seq order.
965
+ const allMutationIds = harness.transport.sentBatches.flat();
966
+ expect(allMutationIds).toHaveLength(120);
967
+ for (const id of allMutationIds) {
968
+ expect(harness.outbox.getMutation({mutationId: id})?.status).toBe("acked");
969
+ }
970
+ // Cross-check enqueue order: the Nth mutation sent must be the Nth
971
+ // enqueued (t-0, n-0, t-1, n-1, ...).
972
+ const expectedOrder: string[] = [];
973
+ for (let i = 0; i < 60; i++) {
974
+ expectedOrder.push(`t-${i}`, `n-${i}`);
975
+ }
976
+ expect(allMutationIds).toEqual(expectedOrder);
977
+ });
978
+
979
+ it("at most one mutation per entity per chunk: a second mutation for an already-included entity cuts the chunk short", async () => {
980
+ const harness = makeBatchHarness();
981
+ enqueue(harness, {entityId: "a", mutationId: "m1", operation: "create"});
982
+ enqueue(harness, {entityId: "shared", mutationId: "m2", operation: "create"});
983
+ harness.outbox.enqueue({
984
+ args: {title: "v2"},
985
+ collection: "todos",
986
+ entityId: "shared",
987
+ mutationId: "m3",
988
+ operation: "update",
989
+ userId: USER,
990
+ });
991
+ enqueue(harness, {entityId: "other", mutationId: "m4"});
992
+
993
+ await harness.coordinator.replay({userId: USER});
994
+ // m1 and m2 (distinct entities) fill the first chunk; m3 (second
995
+ // mutation for "shared", already in this chunk via m2) cuts it short —
996
+ // m4 is deferred behind the cut too, preserving global FIFO order
997
+ // (INV-1) rather than reordering around it. Once m1/m2 ack, the
998
+ // remaining queue is [m3, m4] — distinct entities, so they batch
999
+ // together in a second chunk (m3 now carries the fresh A2 base).
1000
+ expect(harness.transport.sentBatches[0]).toEqual(["m1", "m2"]);
1001
+ expect(harness.transport.sentBatches[1]).toEqual(["m3", "m4"]);
1002
+ for (const id of ["m1", "m2", "m3", "m4"]) {
1003
+ expect(harness.outbox.getMutation({mutationId: id})?.status).toBe("acked");
1004
+ }
1005
+ });
1006
+
1007
+ it("respects a configured batchSize", async () => {
1008
+ const harness = makeBatchHarness({batchSize: 10});
1009
+ enqueueN(harness, 25);
1010
+ await harness.coordinator.replay({userId: USER});
1011
+ expect(harness.transport.sentBatches.map((b) => b.length)).toEqual([10, 10, 5]);
1012
+ });
1013
+
1014
+ it("capability detection: HTTP-style unsupported response falls back to single sends after 2 CONSECUTIVE strikes (FIX 5), re-probed after reconnect", async () => {
1015
+ const harness = makeBatchHarness();
1016
+ harness.transport.setBatchResponder(() => ({type: "unsupported"}));
1017
+ enqueueN(harness, 5);
1018
+
1019
+ await harness.coordinator.replay({userId: USER});
1020
+ // FIX 5: a single unsupported result must not latch — it takes 2
1021
+ // CONSECUTIVE unsupported results (the same 5-mutation chunk retried
1022
+ // once) before falling back to single sends, still in FIFO order.
1023
+ expect(harness.transport.sentBatches).toHaveLength(2);
1024
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual([
1025
+ "m-0",
1026
+ "m-1",
1027
+ "m-2",
1028
+ "m-3",
1029
+ "m-4",
1030
+ ]);
1031
+ for (let i = 0; i < 5; i++) {
1032
+ expect(harness.outbox.getMutation({mutationId: `m-${i}`})?.status).toBe("acked");
1033
+ }
1034
+
1035
+ // Further mutations on the SAME connection keep using single sends —
1036
+ // batching is not re-probed until a reconnect (or the 60s timer).
1037
+ enqueueN(harness, 2, {prefix: "later"});
1038
+ await harness.coordinator.replay({userId: USER});
1039
+ expect(harness.transport.sentBatches).toHaveLength(2);
1040
+
1041
+ // Re-probe after reconnect: batching works again.
1042
+ harness.transport.setBatchResponder();
1043
+ harness.coordinator.notifyReconnect();
1044
+ enqueueN(harness, 3, {prefix: "reconnected"});
1045
+ await harness.coordinator.replay({userId: USER});
1046
+ expect(harness.transport.sentBatches).toHaveLength(3);
1047
+ expect(harness.transport.sentBatches[2]).toEqual([
1048
+ "reconnected-0",
1049
+ "reconnected-1",
1050
+ "reconnected-2",
1051
+ ]);
1052
+ });
1053
+
1054
+ it("a single stray unsupported result does not latch — the very next batch send on the same connection succeeds normally (FIX 5)", async () => {
1055
+ const harness = makeBatchHarness();
1056
+ enqueueN(harness, 4);
1057
+ let calls = 0;
1058
+ harness.transport.setBatchResponder((request) => {
1059
+ calls += 1;
1060
+ if (calls === 1) {
1061
+ return {type: "unsupported"};
1062
+ }
1063
+ return {
1064
+ results: request.mutations.map((mutation) => ({
1065
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1066
+ type: "ack" as const,
1067
+ })),
1068
+ type: "results",
1069
+ };
1070
+ });
1071
+
1072
+ await harness.coordinator.replay({userId: USER});
1073
+ // Two batch sends: the stray unsupported one, then a real one that
1074
+ // succeeds — never falling back to single sends.
1075
+ expect(harness.transport.sentBatches).toHaveLength(2);
1076
+ expect(harness.transport.sentMutations).toHaveLength(0);
1077
+ for (let i = 0; i < 4; i++) {
1078
+ expect(harness.outbox.getMutation({mutationId: `m-${i}`})?.status).toBe("acked");
1079
+ }
1080
+
1081
+ // A later stray unsupported result also doesn't latch, since the
1082
+ // counter reset after the successful batch above.
1083
+ enqueueN(harness, 2, {prefix: "later"});
1084
+ calls = 0;
1085
+ await harness.coordinator.replay({userId: USER});
1086
+ expect(harness.transport.sentMutations).toHaveLength(0);
1087
+ });
1088
+
1089
+ it("FIX 5: while latched, batching is re-probed on a 60s timer even without a reconnect", async () => {
1090
+ const store = createSyncStore({collections: ["todos"]});
1091
+ const outbox = createOutbox({store});
1092
+ const transport = createFakeTransport();
1093
+ const clock = {value: 1_000_000};
1094
+ const {timers, ...timerArgs} = makeFakeTimers(clock);
1095
+ transport.setBatchResponder(() => ({type: "unsupported"}));
1096
+ const coordinator = createReplayCoordinator({
1097
+ ...timerArgs,
1098
+ now: () => clock.value,
1099
+ outbox,
1100
+ sendMutation: transport.sendMutation,
1101
+ sendMutationBatch: transport.sendMutationBatch,
1102
+ store,
1103
+ });
1104
+ for (let i = 0; i < 3; i++) {
1105
+ outbox.enqueue({
1106
+ args: {title: `t${i}`},
1107
+ collection: "todos",
1108
+ entityId: `t${i}`,
1109
+ mutationId: `m${i}`,
1110
+ operation: "create",
1111
+ userId: USER,
1112
+ });
1113
+ }
1114
+
1115
+ // Two consecutive unsupported batch sends latch batchUnsupported —
1116
+ // the coordinator falls back to single sends for the same mutations
1117
+ // (auto-ack default responder handles the single-send fallback).
1118
+ await coordinator.replay({userId: USER});
1119
+ expect(outbox.getMutation({mutationId: "m0"})?.status).toBe("acked");
1120
+ expect(transport.sentBatches).toHaveLength(2);
1121
+ expect(transport.sentMutations.map((m) => m.mutationId)).toEqual(["m0", "m1", "m2"]);
1122
+
1123
+ // Latched: further mutations on this connection use single sends only.
1124
+ outbox.enqueue({
1125
+ args: {title: "later"},
1126
+ collection: "todos",
1127
+ entityId: "later",
1128
+ mutationId: "m-later",
1129
+ operation: "create",
1130
+ userId: USER,
1131
+ });
1132
+ await coordinator.replay({userId: USER});
1133
+ expect(transport.sentBatches).toHaveLength(2);
1134
+
1135
+ // Advance past the 60s re-probe interval with NO reconnect — the armed
1136
+ // timer clears the latch on its own.
1137
+ clock.value += BATCH_UNSUPPORTED_REPROBE_INTERVAL_MS;
1138
+ timers.flush();
1139
+ transport.setBatchResponder((request) => ({
1140
+ results: request.mutations.map((mutation) => ({
1141
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1142
+ type: "ack" as const,
1143
+ })),
1144
+ type: "results",
1145
+ }));
1146
+ // Two mutations so the chunk genuinely exercises the batch path
1147
+ // (a lone eligible mutation reuses the single-send path regardless of
1148
+ // batchUnsupported — see the "lone chunk" comment in drainOnce).
1149
+ outbox.enqueue({
1150
+ args: {title: "reprobed-a"},
1151
+ collection: "todos",
1152
+ entityId: "reprobed-a",
1153
+ mutationId: "m-reprobed-a",
1154
+ operation: "create",
1155
+ userId: USER,
1156
+ });
1157
+ outbox.enqueue({
1158
+ args: {title: "reprobed-b"},
1159
+ collection: "todos",
1160
+ entityId: "reprobed-b",
1161
+ mutationId: "m-reprobed-b",
1162
+ operation: "create",
1163
+ userId: USER,
1164
+ });
1165
+ await coordinator.replay({userId: USER});
1166
+ expect(transport.sentBatches).toHaveLength(3);
1167
+ expect(transport.sentBatches[2]).toEqual(["m-reprobed-a", "m-reprobed-b"]);
1168
+ });
1169
+
1170
+ it("short response (server halted mid-batch) requeues the tail untouched, never burning error-nack budget; next drain resends from the halt point", async () => {
1171
+ const harness = makeBatchHarness();
1172
+ enqueueN(harness, 5);
1173
+ harness.transport.respondBatchWith((request) => ({
1174
+ results: request.mutations.slice(0, 2).map((mutation) => ({
1175
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1176
+ type: "ack" as const,
1177
+ })),
1178
+ type: "results",
1179
+ }));
1180
+
1181
+ await harness.coordinator.replay({userId: USER});
1182
+ expect(harness.outbox.getMutation({mutationId: "m-0"})?.status).toBe("acked");
1183
+ expect(harness.outbox.getMutation({mutationId: "m-1"})?.status).toBe("acked");
1184
+ // m-2..m-4 got no result: requeued untouched. The short response halts
1185
+ // THIS replay() call (INV-1 — nothing after an unresolved halt point is
1186
+ // attempted this pass) rather than being immediately re-swept within
1187
+ // the same call.
1188
+ for (let i = 2; i < 5; i++) {
1189
+ const mutation = harness.outbox.getMutation({mutationId: `m-${i}`});
1190
+ expect(mutation?.status).toBe("queued");
1191
+ expect(mutation?.attemptCount).toBe(1); // markInFlight counted the attempt
1192
+ expect(mutation?.errorNackCount).toBe(0); // never treated as an error-nack
1193
+ }
1194
+
1195
+ // The next drain (a fresh trigger) resends from the halt point; the
1196
+ // server ledger would dedupe any overlap (INV-3) — here nothing
1197
+ // overlaps since the tail was never actually applied.
1198
+ await harness.coordinator.replay({userId: USER});
1199
+ for (let i = 0; i < 5; i++) {
1200
+ expect(harness.outbox.getMutation({mutationId: `m-${i}`})?.status).toBe("acked");
1201
+ }
1202
+ // Applied exactly once: m-0..m-4 sent in the first (truncated) batch,
1203
+ // m-2..m-4 resent in a second batch — never duplicated in either.
1204
+ const allSent = harness.transport.sentBatches.flat();
1205
+ const counts = new Map<string, number>();
1206
+ for (const id of allSent) {
1207
+ counts.set(id, (counts.get(id) ?? 0) + 1);
1208
+ }
1209
+ for (let i = 0; i < 5; i++) {
1210
+ expect(counts.get(`m-${i}`)).toBe(i < 2 ? 1 : 2);
1211
+ }
1212
+ });
1213
+
1214
+ it("a lone eligible mutation in a chunk is sent as a single send, not a batch of one", async () => {
1215
+ const harness = makeBatchHarness();
1216
+ enqueue(harness, {entityId: "solo", mutationId: "solo-1"});
1217
+ await harness.coordinator.replay({userId: USER});
1218
+ expect(harness.transport.sentBatches).toHaveLength(0);
1219
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["solo-1"]);
1220
+ expect(harness.outbox.getMutation({mutationId: "solo-1"})?.status).toBe("acked");
1221
+ });
1222
+ });
1223
+
1224
+ describe("stop-the-line policy (B4)", () => {
1225
+ it("mid-batch socket disconnect (transport rejection) re-queues the WHOLE chunk untouched and halts the drain", async () => {
1226
+ const harness = makeBatchHarness();
1227
+ const enqueueThree = (): void => {
1228
+ enqueue(harness, {entityId: "e1", mutationId: "m1"});
1229
+ enqueue(harness, {entityId: "e2", mutationId: "m2"});
1230
+ enqueue(harness, {entityId: "e3", mutationId: "m3"});
1231
+ };
1232
+ enqueueThree();
1233
+ harness.transport.setBatchResponder(() => {
1234
+ throw new Error("socket disconnected mid-batch");
1235
+ });
1236
+
1237
+ await harness.coordinator.replay({userId: USER});
1238
+ for (const id of ["m1", "m2", "m3"]) {
1239
+ expect(harness.outbox.getMutation({mutationId: id})?.status).toBe("queued");
1240
+ }
1241
+
1242
+ harness.transport.setBatchResponder();
1243
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 30;
1244
+ await harness.coordinator.replay({userId: USER});
1245
+ for (const id of ["m1", "m2", "m3"]) {
1246
+ expect(harness.outbox.getMutation({mutationId: id})?.status).toBe("acked");
1247
+ }
1248
+ // Applied exactly once: only one ack recorded per mutation across both
1249
+ // drains (the coordinator never double-applies a chunk).
1250
+ expect(harness.transport.sentMutations).toHaveLength(0);
1251
+ expect(harness.transport.sentBatches.flat().filter((id) => id === "m1")).toHaveLength(2);
1252
+ });
1253
+
1254
+ it("a conflict blocks only its entity's later mutations; other entities keep draining", async () => {
1255
+ const harness = makeBatchHarness();
1256
+ // Entity X has two queued mutations (second must be blocked by the first's
1257
+ // conflict); entity Y has one and should proceed independently. Y is
1258
+ // enqueued BEFORE x2 so the first chunk (x1, y1 — distinct entities)
1259
+ // has length ≥ 2 and genuinely exercises the batch path rather than
1260
+ // degenerating into a lone single-send.
1261
+ enqueue(harness, {
1262
+ baseVersion: 1,
1263
+ entityId: "x",
1264
+ mutationId: "x1",
1265
+ operation: "update",
1266
+ });
1267
+ enqueue(harness, {entityId: "y", mutationId: "y1"});
1268
+ harness.outbox.enqueue({
1269
+ args: {title: "x-v2"},
1270
+ baseVersion: 1,
1271
+ collection: "todos",
1272
+ entityId: "x",
1273
+ mutationId: "x2",
1274
+ operation: "update",
1275
+ userId: USER,
1276
+ });
1277
+
1278
+ harness.transport.setBatchResponder((request) => ({
1279
+ results: request.mutations.map((mutation) => {
1280
+ if (mutation.mutationId === "x1") {
1281
+ return {
1282
+ nack: {code: "conflict" as const, mutationId: mutation.mutationId, serverSeq: 9},
1283
+ type: "nack" as const,
1284
+ };
1285
+ }
1286
+ return {
1287
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1288
+ type: "ack" as const,
1289
+ };
1290
+ }),
1291
+ type: "results",
1292
+ }));
1293
+
1294
+ await harness.coordinator.replay({userId: USER});
1295
+ expect(harness.outbox.getMutation({mutationId: "x1"})?.status).toBe("conflicted");
1296
+ expect(harness.outbox.getMutation({mutationId: "y1"})?.status).toBe("acked");
1297
+ // x2 stays queued and blocked — it must never have been sent while x1's
1298
+ // conflict is unresolved.
1299
+ expect(harness.outbox.getMutation({mutationId: "x2"})?.status).toBe("queued");
1300
+ expect(harness.transport.sentBatches.flat()).not.toContain("x2");
1301
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:x");
1302
+
1303
+ // A further replay call still skips x2 — it stays absent from
1304
+ // subsequent batches while the conflict is unresolved.
1305
+ harness.transport.setBatchResponder();
1306
+ await harness.coordinator.replay({userId: USER});
1307
+ expect(harness.outbox.getMutation({mutationId: "x2"})?.status).toBe("queued");
1308
+
1309
+ // Resolve the conflict (keepMine requeues under a fresh mutationId) —
1310
+ // x2 (now unblocked) drains in its original relative position.
1311
+ const {resolveConflict} = await import("../mutations/resolveConflict");
1312
+ resolveConflict({
1313
+ mutationId: "x1",
1314
+ outbox: harness.outbox,
1315
+ store: harness.store,
1316
+ strategy: "keepMine",
1317
+ });
1318
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).not.toContain("todos:x");
1319
+ await harness.coordinator.replay({userId: USER});
1320
+ expect(harness.outbox.getMutation({mutationId: "x2"})?.status).toBe("acked");
1321
+ });
1322
+
1323
+ it("haltQueueOnConflict: true halts the entire drain — nothing after the conflict is sent at all", async () => {
1324
+ const harness = makeBatchHarness({haltQueueOnConflict: true});
1325
+ enqueue(harness, {baseVersion: 1, entityId: "x", mutationId: "x1", operation: "update"});
1326
+ enqueue(harness, {entityId: "y", mutationId: "y1"});
1327
+ enqueue(harness, {entityId: "z", mutationId: "z1"});
1328
+
1329
+ // Realistic server behavior (B2 stop-on-first-non-ack): x1 is first in
1330
+ // the chunk and conflicts, so the server never attempts y1/z1 — the
1331
+ // response is truncated to just x1's nack.
1332
+ harness.transport.setBatchResponder((request) => ({
1333
+ results: [
1334
+ {
1335
+ nack: {
1336
+ code: "conflict" as const,
1337
+ mutationId: request.mutations[0].mutationId,
1338
+ serverSeq: 9,
1339
+ },
1340
+ type: "nack" as const,
1341
+ },
1342
+ ],
1343
+ type: "results",
1344
+ }));
1345
+
1346
+ await harness.coordinator.replay({userId: USER});
1347
+ expect(harness.outbox.getMutation({mutationId: "x1"})?.status).toBe("conflicted");
1348
+ // y1 and z1 got no result (server never attempted them) — requeued
1349
+ // untouched, and haltQueueOnConflict stops the drain from building a
1350
+ // follow-up chunk to retry them immediately.
1351
+ expect(harness.outbox.getMutation({mutationId: "y1"})?.status).toBe("queued");
1352
+ expect(harness.outbox.getMutation({mutationId: "z1"})?.status).toBe("queued");
1353
+ expect(harness.transport.sentBatches).toHaveLength(1);
1354
+ });
1355
+
1356
+ it("haltQueueOnConflict also halts when the conflict is delivered via the single-send fallback (lone chunk)", async () => {
1357
+ // batchSize 1 forces every chunk to be a "lone eligible mutation",
1358
+ // which reuses the single-mutation send path (not a batch of one) —
1359
+ // haltQueueOnConflict must still stop the drain in that path.
1360
+ const harness = makeBatchHarness({batchSize: 1, haltQueueOnConflict: true});
1361
+ enqueue(harness, {baseVersion: 1, entityId: "x", mutationId: "x1", operation: "update"});
1362
+ enqueue(harness, {entityId: "y", mutationId: "y1"});
1363
+ harness.transport.respondWithNack({code: "conflict", serverSeq: 9});
1364
+
1365
+ await harness.coordinator.replay({userId: USER});
1366
+ expect(harness.outbox.getMutation({mutationId: "x1"})?.status).toBe("conflicted");
1367
+ expect(harness.outbox.getMutation({mutationId: "y1"})?.status).toBe("queued");
1368
+ expect(harness.transport.sentMutations.map((m) => m.mutationId)).toEqual(["x1"]);
1369
+ });
1370
+
1371
+ it("validation failure: successors for that entity are skipped and surfaced; retryFailed re-enables them", async () => {
1372
+ const harness = makeBatchHarness();
1373
+ // "good" is enqueued BEFORE b2 so the first chunk (b1, g1 — distinct
1374
+ // entities) has length ≥ 2 and genuinely exercises the batch path.
1375
+ enqueue(harness, {entityId: "bad", mutationId: "b1"});
1376
+ enqueue(harness, {entityId: "good", mutationId: "g1"});
1377
+ harness.outbox.enqueue({
1378
+ args: {title: "b2"},
1379
+ collection: "todos",
1380
+ entityId: "bad",
1381
+ mutationId: "b2",
1382
+ operation: "update",
1383
+ userId: USER,
1384
+ });
1385
+
1386
+ harness.transport.setBatchResponder((request) => ({
1387
+ results: request.mutations.map((mutation) =>
1388
+ mutation.mutationId === "b1"
1389
+ ? {
1390
+ nack: {code: "validation" as const, mutationId: mutation.mutationId},
1391
+ type: "nack" as const,
1392
+ }
1393
+ : {
1394
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1395
+ type: "ack" as const,
1396
+ }
1397
+ ),
1398
+ type: "results",
1399
+ }));
1400
+
1401
+ await harness.coordinator.replay({userId: USER});
1402
+ expect(harness.outbox.getMutation({mutationId: "b1"})?.status).toBe("failed");
1403
+ expect(harness.outbox.getMutation({mutationId: "g1"})?.status).toBe("acked");
1404
+ // b2 is skipped-and-surfaced: stays queued, never sent.
1405
+ expect(harness.outbox.getMutation({mutationId: "b2"})?.status).toBe("queued");
1406
+ expect(harness.transport.sentBatches.flat()).not.toContain("b2");
1407
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:bad");
1408
+
1409
+ // retryFailed re-enables the entity's queued successors.
1410
+ harness.coordinator.retryFailed({entityId: "bad"});
1411
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).not.toContain("todos:bad");
1412
+ harness.transport.setBatchResponder();
1413
+ await harness.coordinator.replay({userId: USER});
1414
+ expect(harness.outbox.getMutation({mutationId: "b2"})?.status).toBe("acked");
1415
+ });
1416
+
1417
+ it("FIX 2: a cross-collection reference to a blocked entity's id is also blocked, and unblocks with its root", async () => {
1418
+ // P (create project, conflicts) and T (create todo in another collection,
1419
+ // args reference P's id) — T must never drain while P is blocked, even
1420
+ // though T's own entity has no conflict of its own. Y is an unrelated
1421
+ // entity enqueued alongside P so P's own chunk has length >= 2 and
1422
+ // genuinely exercises the batch path rather than degenerating into a
1423
+ // lone single-send (the FIX 2 same-batch guard excludes T from P's
1424
+ // chunk since T references P, whose outcome isn't known yet).
1425
+ const harness = makeBatchHarness();
1426
+ enqueue(harness, {collection: "notes", entityId: "p", mutationId: "p1"});
1427
+ enqueue(harness, {entityId: "y", mutationId: "y1"});
1428
+ harness.outbox.enqueue({
1429
+ args: {projectId: "p", title: "todo referencing p"},
1430
+ collection: "todos",
1431
+ entityId: "t",
1432
+ mutationId: "t1",
1433
+ operation: "create",
1434
+ userId: USER,
1435
+ });
1436
+ harness.store.upsertEntity({
1437
+ collection: "todos",
1438
+ data: {projectId: "p", title: "todo referencing p"},
1439
+ id: "t",
1440
+ pendingMutationId: "t1",
1441
+ });
1442
+
1443
+ harness.transport.setBatchResponder((request) => ({
1444
+ results: request.mutations.map((mutation) =>
1445
+ mutation.mutationId === "p1"
1446
+ ? {
1447
+ nack: {code: "conflict" as const, mutationId: mutation.mutationId, serverSeq: 3},
1448
+ type: "nack" as const,
1449
+ }
1450
+ : {
1451
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1452
+ type: "ack" as const,
1453
+ }
1454
+ ),
1455
+ type: "results",
1456
+ }));
1457
+
1458
+ await harness.coordinator.replay({userId: USER});
1459
+ expect(harness.outbox.getMutation({mutationId: "p1"})?.status).toBe("conflicted");
1460
+ expect(harness.outbox.getMutation({mutationId: "y1"})?.status).toBe("acked");
1461
+ // t1 was never sent — it stays queued, budgets untouched.
1462
+ expect(harness.outbox.getMutation({mutationId: "t1"})?.status).toBe("queued");
1463
+ expect(harness.outbox.getMutation({mutationId: "t1"})?.errorNackCount).toBe(0);
1464
+ expect(harness.transport.sentBatches.flat()).not.toContain("t1");
1465
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("notes:p");
1466
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:t");
1467
+
1468
+ // A further replay still skips t1 while p is blocked.
1469
+ harness.transport.setBatchResponder();
1470
+ await harness.coordinator.replay({userId: USER});
1471
+ expect(harness.outbox.getMutation({mutationId: "t1"})?.status).toBe("queued");
1472
+
1473
+ // Resolving p (keepMine requeues under a fresh mutationId) naturally
1474
+ // unblocks t on the next drain — no persisted dependency graph needed.
1475
+ const {resolveConflict} = await import("../mutations/resolveConflict");
1476
+ resolveConflict({
1477
+ mutationId: "p1",
1478
+ outbox: harness.outbox,
1479
+ store: harness.store,
1480
+ strategy: "keepMine",
1481
+ });
1482
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).not.toContain("todos:t");
1483
+ await harness.coordinator.replay({userId: USER});
1484
+ expect(harness.outbox.getMutation({mutationId: "t1"})?.status).toBe("acked");
1485
+ });
1486
+
1487
+ it("FIX 2: reference blocking is conservative — a nested/array reference to a blocked id is also caught", async () => {
1488
+ const harness = makeBatchHarness();
1489
+ enqueue(harness, {collection: "notes", entityId: "p", mutationId: "p1"});
1490
+ enqueue(harness, {entityId: "y", mutationId: "y1"});
1491
+ harness.outbox.enqueue({
1492
+ args: {meta: {tags: ["x", "p"]}, title: "nested ref"},
1493
+ collection: "todos",
1494
+ entityId: "t",
1495
+ mutationId: "t1",
1496
+ operation: "create",
1497
+ userId: USER,
1498
+ });
1499
+
1500
+ harness.transport.setBatchResponder((request) => ({
1501
+ results: request.mutations.map((mutation) =>
1502
+ mutation.mutationId === "p1"
1503
+ ? {
1504
+ nack: {code: "conflict" as const, mutationId: mutation.mutationId, serverSeq: 3},
1505
+ type: "nack" as const,
1506
+ }
1507
+ : {
1508
+ ack: {id: mutation.id ?? "", mutationId: mutation.mutationId, seq: 1},
1509
+ type: "ack" as const,
1510
+ }
1511
+ ),
1512
+ type: "results",
1513
+ }));
1514
+
1515
+ await harness.coordinator.replay({userId: USER});
1516
+ expect(harness.outbox.getMutation({mutationId: "t1"})?.status).toBe("queued");
1517
+ });
1518
+
1519
+ it("FIX 3: coordinator lifecycle scoping — reset() clears all state so a different user reusing a blocked entity id is unaffected", async () => {
1520
+ const harness = makeHarness();
1521
+ enqueue(harness, {entityId: "singleton", mutationId: "m1"});
1522
+ harness.transport.respondWithNack({code: "validation", message: "bad"});
1523
+ await harness.coordinator.replay({userId: USER});
1524
+ // A queued successor keeps the block observable (FIX 4: a block with no
1525
+ // queued successor is GC'd immediately — see the FIX 4 tests below).
1526
+ harness.outbox.enqueue({
1527
+ args: {title: "v2"},
1528
+ collection: "todos",
1529
+ entityId: "singleton",
1530
+ mutationId: "m1b",
1531
+ operation: "update",
1532
+ userId: USER,
1533
+ });
1534
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:singleton");
1535
+
1536
+ // Lifecycle boundary: dispose()/reset() as client.ts wires on a
1537
+ // different-user login wipe path.
1538
+ harness.coordinator.reset();
1539
+
1540
+ // A brand-new user reusing the same deterministic entity id must never
1541
+ // be falsely blocked by the previous user's stale in-memory state.
1542
+ const OTHER_USER = "user-2";
1543
+ harness.outbox.enqueue({
1544
+ args: {title: "fresh"},
1545
+ collection: "todos",
1546
+ entityId: "singleton",
1547
+ mutationId: "m2",
1548
+ operation: "create",
1549
+ userId: OTHER_USER,
1550
+ });
1551
+ harness.transport.respondWithAck({seq: 1});
1552
+ await harness.coordinator.replay({userId: OTHER_USER});
1553
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
1554
+ expect(harness.coordinator.getBlockedEntities({userId: OTHER_USER})).toHaveLength(0);
1555
+ });
1556
+
1557
+ it("FIX 3: validationBlockedEntities is keyed per-user — one user's block never leaks to another", async () => {
1558
+ const harness = makeHarness();
1559
+ const OTHER_USER = "user-2";
1560
+ enqueue(harness, {entityId: "shared-id", mutationId: "m1", userId: USER});
1561
+ harness.transport.respondWithNack({code: "validation", message: "bad"});
1562
+ await harness.coordinator.replay({userId: USER});
1563
+ // A queued successor keeps USER's block observable (FIX 4).
1564
+ harness.outbox.enqueue({
1565
+ args: {title: "v2"},
1566
+ collection: "todos",
1567
+ entityId: "shared-id",
1568
+ mutationId: "m1b",
1569
+ operation: "update",
1570
+ userId: USER,
1571
+ });
1572
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:shared-id");
1573
+
1574
+ // Same entity id, different user: must drain freely, unaffected by
1575
+ // USER's block, and must not appear in USER's blocked list.
1576
+ harness.outbox.enqueue({
1577
+ args: {title: "other user's doc"},
1578
+ collection: "todos",
1579
+ entityId: "shared-id",
1580
+ mutationId: "m2",
1581
+ operation: "create",
1582
+ userId: OTHER_USER,
1583
+ });
1584
+ harness.transport.respondWithAck({seq: 7});
1585
+ await harness.coordinator.replay({userId: OTHER_USER});
1586
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
1587
+ expect(harness.coordinator.getBlockedEntities({userId: OTHER_USER})).toHaveLength(0);
1588
+ // USER's own block is untouched by the other user's activity.
1589
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:shared-id");
1590
+ });
1591
+
1592
+ it("FIX 4: a validation block with no queued successor is GC'd once its failed row is pruned, letting a later NEW mutation for that entity drain", async () => {
1593
+ const harness = makeHarness();
1594
+ enqueue(harness, {entityId: "e1", mutationId: "m1"});
1595
+ harness.transport.respondWithNack({code: "validation", message: "bad"});
1596
+ await harness.coordinator.replay({userId: USER});
1597
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
1598
+ // The failed row still exists (not yet pruned) with no successor
1599
+ // queued — the block surfaces the failure until the user acts or the
1600
+ // row ages out, exactly like the pre-FIX-4 behavior.
1601
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:e1");
1602
+
1603
+ // Prune (removes the failed row — keepFailed: 0 forces it out here;
1604
+ // the default keepFailed of 50 would keep a single row around, which
1605
+ // is exactly the realistic "not pruned yet" case already covered
1606
+ // above): with NO queued successor left to protect the ordering of,
1607
+ // the block is now stale — GC'd, so a brand new mutation for the same
1608
+ // entity is free to drain rather than being quarantined forever
1609
+ // pending an explicit retryFailed the user may never call.
1610
+ harness.outbox.prune({keepFailed: 0, userId: USER});
1611
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).not.toContain("todos:e1");
1612
+ harness.outbox.enqueue({
1613
+ args: {title: "fresh attempt"},
1614
+ collection: "todos",
1615
+ entityId: "e1",
1616
+ mutationId: "m2",
1617
+ operation: "create",
1618
+ userId: USER,
1619
+ });
1620
+ harness.transport.respondWithAck({seq: 1});
1621
+ await harness.coordinator.replay({userId: USER});
1622
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
1623
+ });
1624
+
1625
+ it("FIX 4: a validation block WITH a queued successor stays blocked until retryFailed, surviving prune of the failed row", async () => {
1626
+ const harness = makeHarness();
1627
+ enqueue(harness, {entityId: "e1", mutationId: "m1"});
1628
+ harness.transport.respondWithNack({code: "validation", message: "bad"});
1629
+ await harness.coordinator.replay({userId: USER});
1630
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("failed");
1631
+
1632
+ // A successor is queued before anything prunes the failed row.
1633
+ harness.outbox.enqueue({
1634
+ args: {title: "v2"},
1635
+ collection: "todos",
1636
+ entityId: "e1",
1637
+ mutationId: "m2",
1638
+ operation: "update",
1639
+ userId: USER,
1640
+ });
1641
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:e1");
1642
+
1643
+ // Pruning the failed row (keepFailed: 0 forces it out) must not drop
1644
+ // the block while m2 is queued.
1645
+ harness.outbox.prune({keepFailed: 0, userId: USER});
1646
+ expect(harness.outbox.getMutation({mutationId: "m1"})).toBeUndefined();
1647
+ expect(harness.coordinator.getBlockedEntities({userId: USER})).toContain("todos:e1");
1648
+ harness.transport.setDefaultResponder();
1649
+ await harness.coordinator.replay({userId: USER});
1650
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("queued");
1651
+
1652
+ harness.coordinator.retryFailed({entityId: "e1"});
1653
+ await harness.coordinator.replay({userId: USER});
1654
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
1655
+ });
1656
+
1657
+ it("error nack halts the whole drain (transient — retry without user action)", async () => {
1658
+ const harness = makeBatchHarness();
1659
+ enqueue(harness, {entityId: "e1", mutationId: "m1"});
1660
+ enqueue(harness, {entityId: "e2", mutationId: "m2"});
1661
+ harness.transport.setBatchResponder((request) => ({
1662
+ results: request.mutations.map((mutation) => ({
1663
+ nack: {code: "error" as const, mutationId: mutation.mutationId},
1664
+ type: "nack" as const,
1665
+ })),
1666
+ type: "results",
1667
+ }));
1668
+
1669
+ await harness.coordinator.replay({userId: USER});
1670
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
1671
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("queued");
1672
+
1673
+ harness.transport.setBatchResponder();
1674
+ harness.clock.value += ERROR_NACK_BASE_BACKOFF_MS * 30;
1675
+ await harness.coordinator.replay({userId: USER});
1676
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
1677
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
1678
+ });
1679
+
1680
+ it("unauthorized halts everything and enters auth pause with no data touched", async () => {
1681
+ const harness = makeBatchHarness();
1682
+ enqueue(harness, {entityId: "e1", mutationId: "m1"});
1683
+ enqueue(harness, {entityId: "e2", mutationId: "m2"});
1684
+ // Realistic server behavior (B2 stop-on-first-non-ack): the response is
1685
+ // truncated at the first nack — m2 gets no result at all, not a second
1686
+ // nack, since the server never attempted it.
1687
+ harness.transport.setBatchResponder((request) => ({
1688
+ results: [
1689
+ {
1690
+ nack: {code: "unauthorized" as const, mutationId: request.mutations[0].mutationId},
1691
+ type: "nack" as const,
1692
+ },
1693
+ ],
1694
+ type: "results",
1695
+ }));
1696
+
1697
+ const result = await harness.coordinator.replay({userId: USER});
1698
+ expect(result).toEqual({paused: "auth"});
1699
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("queued");
1700
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("queued");
1701
+
1702
+ harness.transport.setBatchResponder();
1703
+ const resumed = await harness.coordinator.replay({userId: USER});
1704
+ expect(resumed).toEqual({});
1705
+ expect(harness.outbox.getMutation({mutationId: "m1"})?.status).toBe("acked");
1706
+ expect(harness.outbox.getMutation({mutationId: "m2"})?.status).toBe("acked");
1707
+ });
1708
+ });
1709
+ });