Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

claim.test.ts

680 lines24.0 KB

1/**
2 * Coverage for the single-writer run claim (`src/claim.ts`).
3 *
4 * The point of this file is adversarial, not descriptive: `fenceDurability` is a
5 * validation rule, so every test here is written so that removing the rule it
6 * covers makes it fail. In particular the `InMemoryLockStore` block proves the
7 * epoch fence works in the ONE configuration where the lease provides nothing —
8 * `InMemoryLockStore.withLock` hands the callback a fresh
9 * `new AbortController().signal` it never aborts, and it QUEUES a second caller
10 * rather than refusing it, so `claim.signal` can never fence anything there. If
11 * layer 2 were broken, that configuration would silently allow a superseded
12 * driver to keep appending.
13 */
14import { describe, expect, it, vi } from 'vitest'
15import { EventType, InMemoryRunStore } from '@tanstack/ai'
16// NOT from '@tanstack/ai': the lock primitives live behind their own subpath so
17// consumers opt in explicitly (`packages/ai/src/locks.ts`).
18import { InMemoryLockStore } from '@tanstack/ai/locks'
19import { fakeLog } from './fakes'
20import {
21 DEFAULT_EPOCH_RECHECK_APPENDS,
22 DEFAULT_FENCE_QUIET_MS,
23 RunClaimLostError,
24 RunClaimNotAcquiredError,
25 awaitLogQuiescence,
26 fenceDurability,
27 runDriverLockKey,
28 withRunClaim,
29} from '../src/claim'
30import type { LockStore } from '@tanstack/ai/locks'
31import type { RunClaim } from '../src/claim'
32import type { StreamChunk, StreamDurability } from '@tanstack/ai'
33​
34function chunk(runId: string): StreamChunk {
35 return {
36 type: EventType.RUN_STARTED,
37 runId,
38 threadId: `${runId}-t`,
39 timestamp: 1,
40 }
42​
43async function storedCount(log: StreamDurability): Promise<number> {
44 return (await log.snapshot()).length
46​
47/** A run record in `'running'` state, ready to be claimed. */
48async function runningRun(runId: string): Promise<InMemoryRunStore> {
49 const runs = new InMemoryRunStore()
50 await runs.createOrResume({ runId, threadId: `${runId}-t`, startedAt: 1 })
51 return runs
53​
54/** A lock that runs `fn` immediately and can abort its signal on demand. */
55function abortableLock(): LockStore & {
56 lose: () => void
57 keys: Array<string>
58} {
59 const controllers: Array<AbortController> = []
60 const keys: Array<string> = []
61 return {
62 keys,
63 lose: () => controllers.forEach((c) => c.abort()),
64 withLock: <T>(key: string, fn: (signal: AbortSignal) => Promise<T>) => {
65 keys.push(key)
66 const controller = new AbortController()
67 controllers.push(controller)
68 return fn(controller.signal)
69 },
70 }
72​
73/**
74 * A lock whose lease signal is a LIVE check rather than a one-way controller, so
75 * `aborted` can flap the way a backend polling a lease clock (or re-acquiring a
76 * lease) makes it flap. `InMemoryLockStore` cannot model lease loss at all — it
77 * hands out a signal it never aborts — and a real `AbortController` cannot be
78 * un-aborted, so shadowing `aborted` on the instance is the only way to observe
79 * a fence that must stay closed after the signal stops reporting the loss.
80 */
81function flappableLock(): {
82 locks: LockStore
83 lose: () => void
84 regain: () => void
85} {
86 let aborted = false
87 return {
88 lose: () => {
89 aborted = true
90 },
91 regain: () => {
92 aborted = false
93 },
94 locks: {
95 withLock: <T>(_key: string, fn: (signal: AbortSignal) => Promise<T>) => {
96 const signal = new AbortController().signal
97 Object.defineProperty(signal, 'aborted', {
98 configurable: true,
99 get: () => aborted,
100 })
101 return fn(signal)
102 },
103 },
104 }
106​
107describe('runDriverLockKey', () => {
108 it('is per-run, so two runs never serialize against each other', () => {
109 expect(runDriverLockKey('r1')).toBe('run-driver:r1')
110 expect(runDriverLockKey('r2')).not.toBe(runDriverLockKey('r1'))
111 })
112})
113​
114describe('withRunClaim', () => {
115 it('takes the per-run lock and bumps driverEpoch from absent to 1', async () => {
116 const runs = await runningRun('claim-1')
117 const locks = abortableLock()
118​
119 const epoch = await withRunClaim(
120 { runs, locks, runId: 'claim-1', fenceQuietMs: 0 },
121 (claim) => Promise.resolve(claim.epoch),
122 )
123​
124 expect(epoch).toBe(1)
125 expect(locks.keys).toEqual(['run-driver:claim-1'])
126 expect((await runs.get('claim-1'))?.driverEpoch).toBe(1)
127 })
128​
129 it('increments a pre-existing epoch, so a successor always outranks a predecessor', async () => {
130 const runs = await runningRun('claim-2')
131 await runs.update('claim-2', { driverEpoch: 7 })
132 const epoch = await withRunClaim(
133 { runs, locks: abortableLock(), runId: 'claim-2', fenceQuietMs: 0 },
134 (claim) => Promise.resolve(claim.epoch),
135 )
136 expect(epoch).toBe(8)
137 })
138​
139 it('runs the whole body inside the lock, so snapshot and appends are one critical section', async () => {
140 const runs = await runningRun('claim-3')
141 let insideLock = false
142 const locks: LockStore = {
143 withLock: async (_key, fn) => {
144 insideLock = true
145 try {
146 return await fn(new AbortController().signal)
147 } finally {
148 insideLock = false
149 }
150 },
151 }
152 await withRunClaim({ runs, locks, runId: 'claim-3' }, () => {
153 expect(insideLock).toBe(true)
154 return Promise.resolve()
155 })
156 expect(insideLock).toBe(false)
157 })
158​
159 it('refuses a terminal run rather than driving a finished one', async () => {
160 const runs = await runningRun('claim-4')
161 await runs.update('claim-4', { status: 'completed', finishedAt: 2 })
162 const body = vi.fn(() => Promise.resolve('ran'))
163​
164 await expect(
165 withRunClaim(
166 { runs, locks: abortableLock(), runId: 'claim-4', fenceQuietMs: 0 },
167 body,
168 ),
169 ).rejects.toBeInstanceOf(RunClaimNotAcquiredError)
170 expect(body).not.toHaveBeenCalled()
171 // The epoch must NOT be bumped for a refused claim: bumping would fence a
172 // healthy driver out of a run this caller never took over.
173 expect((await runs.get('claim-4'))?.driverEpoch).toBeUndefined()
174 })
175​
176 it('refuses an unknown run', async () => {
177 await expect(
178 withRunClaim(
179 {
180 runs: new InMemoryRunStore(),
181 locks: abortableLock(),
182 runId: 'nope',
183 fenceQuietMs: 0,
184 },
185 () => Promise.resolve(1),
186 ),
187 ).rejects.toBeInstanceOf(RunClaimNotAcquiredError)
188 })
189​
190 it('reports why the claim was refused', async () => {
191 const runs = await runningRun('claim-5')
192 await runs.update('claim-5', { status: 'aborted', finishedAt: 2 })
193 const refusal = await withRunClaim(
194 { runs, locks: abortableLock(), runId: 'claim-5' },
195 () => Promise.resolve(1),
196 ).catch((error: unknown) => error)
197 expect(refusal).toBeInstanceOf(RunClaimNotAcquiredError)
198 if (refusal instanceof RunClaimNotAcquiredError) {
199 expect(refusal.reason).toBe('terminal')
200 expect(refusal.runId).toBe('claim-5')
201 }
202 })
203​
204 it('exposes the lock signal on the claim, so a fence can observe a lost lease', async () => {
205 const runs = await runningRun('claim-6')
206 const locks = abortableLock()
207 await withRunClaim(
208 { runs, locks, runId: 'claim-6', fenceQuietMs: 0 },
209 (claim) => {
210 expect(claim.signal.aborted).toBe(false)
211 locks.lose()
212 expect(claim.signal.aborted).toBe(true)
213 return Promise.resolve()
214 },
215 )
216 })
217​
218 it('releases the lock even when the body throws', async () => {
219 const runs = await runningRun('claim-7')
220 const locks = new InMemoryLockStore()
221 await expect(
222 withRunClaim({ runs, locks, runId: 'claim-7', fenceQuietMs: 0 }, () =>
223 Promise.reject(new Error('drive failed')),
224 ),
225 ).rejects.toThrow('drive failed')
226 // A poisoned lock would deadlock the next claim.
227 await expect(
228 withRunClaim({ runs, locks, runId: 'claim-7', fenceQuietMs: 0 }, () =>
229 Promise.resolve('ok'),
230 ),
231 ).resolves.toBe('ok')
232 })
233​
234 it('defaults the quiescence window to 5s and the epoch re-check to 32 appends', () => {
235 expect(DEFAULT_FENCE_QUIET_MS).toBe(5_000)
236 expect(DEFAULT_EPOCH_RECHECK_APPENDS).toBe(32)
237 })
238})
239​
240describe('awaitLogQuiescence', () => {
241 it('resolves with the stored length when two snapshots agree', async () => {
242 const log = fakeLog([chunk('quiet-1'), chunk('quiet-1')])
243 expect(await awaitLogQuiescence(log, 0)).toBe(2)
244 })
245​
246 it('resolves 0 for a run with nothing stored', async () => {
247 expect(await awaitLogQuiescence(fakeLog(), 0)).toBe(0)
248 })
249​
250 it('retries while the log is still growing, then settles', async () => {
251 const log = fakeLog()
252 let calls = 0
253 const growing: StreamDurability = {
254 ...log,
255 snapshot: async () => {
256 calls += 1
257 if (calls <= 2) await log.append([chunk('quiet-2')])
258 return log.snapshot()
259 },
260 }
261 // Grows across the first two probes, then stops.
262 expect(await awaitLogQuiescence(growing, 0)).toBe(2)
263 expect(calls).toBeGreaterThanOrEqual(3)
264 })
265​
266 it('gives up rather than looping forever on a log that never settles', async () => {
267 const log = fakeLog()
268 const never: StreamDurability = {
269 ...log,
270 snapshot: async () => {
271 await log.append([chunk('quiet-3')])
272 return log.snapshot()
273 },
274 }
275 await expect(awaitLogQuiescence(never, 0)).rejects.toThrow(/never quiesced/)
276 })
277​
278 it('uses snapshot, never read: a taken-over log is still open', async () => {
279 const log = fakeLog([chunk('quiet-4')])
280 const read = vi.fn(() => {
281 throw new Error('read() would park forever on an open log')
282 })
283 const probed: StreamDurability = { ...log, read }
284 expect(await awaitLogQuiescence(probed, 0)).toBe(1)
285 expect(read).not.toHaveBeenCalled()
286 })
287})
288​
289describe('fenceDurability', () => {
290 function claimWith(signal: AbortSignal, epoch = 1, runId = 'r1'): RunClaim {
291 return { runId, epoch, signal }
292 }
293​
294 it('passes appends through while the claim holds', async () => {
295 const log = fakeLog()
296 const runs = await runningRun('fence-1')
297 await runs.update('fence-1', { driverEpoch: 1 })
298 const fenced = fenceDurability(
299 log,
300 claimWith(new AbortController().signal, 1, 'fence-1'),
301 { runs, epochRecheckAppends: 1 },
302 )
303 await fenced.append([chunk('fence-1')])
304 expect(await storedCount(log)).toBe(1)
305 })
306​
307 it('throws RunClaimLostError instead of appending once the lease signal aborts', async () => {
308 const log = fakeLog()
309 const controller = new AbortController()
310 const runs = await runningRun('fence-2')
311 const fenced = fenceDurability(
312 log,
313 claimWith(controller.signal, 1, 'fence-2'),
314 { runs, epochRecheckAppends: 1 },
315 )
316 controller.abort()
317 await expect(fenced.append([chunk('fence-2')])).rejects.toBeInstanceOf(
318 RunClaimLostError,
319 )
320 // The decisive assertion: nothing landed. A fence that throws AFTER writing
321 // is not a fence.
322 expect(await storedCount(log)).toBe(0)
323 })
324​
325 it('throws when the stored epoch has moved past the one held', async () => {
326 const log = fakeLog()
327 const runs = await runningRun('fence-3')
328 await runs.update('fence-3', { driverEpoch: 4 })
329 const fenced = fenceDurability(
330 log,
331 claimWith(new AbortController().signal, 3, 'fence-3'),
332 { runs, epochRecheckAppends: 1 },
333 )
334 const lost = await fenced
335 .append([chunk('fence-3')])
336 .catch((error: unknown) => error)
337 expect(lost).toBeInstanceOf(RunClaimLostError)
338 if (lost instanceof RunClaimLostError) {
339 expect(lost.heldEpoch).toBe(3)
340 expect(lost.observedEpoch).toBe(4)
341 }
342 expect(await storedCount(log)).toBe(0)
343 })
344​
345 it('re-reads the epoch at most once per epochRecheckAppends appends', async () => {
346 const runs = await runningRun('fence-4')
347 await runs.update('fence-4', { driverEpoch: 1 })
348 const get = vi.spyOn(runs, 'get')
349 const fenced = fenceDurability(
350 fakeLog(),
351 claimWith(new AbortController().signal, 1, 'fence-4'),
352 { runs, epochRecheckAppends: 32 },
353 )
354 for (let i = 0; i < 3; i += 1) await fenced.append([chunk('fence-4')])
355 expect(get).toHaveBeenCalledTimes(1)
356 })
357​
358 it('bounds a superseded driver to epochRecheckAppends appends regardless of rate', async () => {
359 // The whole reason the re-check counts appends instead of elapsed time: a
360 // hot stream cannot outrun the fence.
361 const log = fakeLog()
362 const runs = await runningRun('fence-5')
363 await runs.update('fence-5', { driverEpoch: 1 })
364 const fenced = fenceDurability(
365 log,
366 claimWith(new AbortController().signal, 1, 'fence-5'),
367 { runs, epochRecheckAppends: 4 },
368 )
369 // First append re-reads (epoch still 1), then a successor claims.
370 await fenced.append([chunk('fence-5')])
371 await runs.update('fence-5', { driverEpoch: 2 })
372​
373 let landed = 1
374 const failure = await (async () => {
375 for (let i = 0; i < 100; i += 1) {
376 await fenced.append([chunk('fence-5')])
377 landed += 1
378 }
379 return null
380 })().catch((error: unknown) => error)
381​
382 expect(failure).toBeInstanceOf(RunClaimLostError)
383 // 4 appends per re-read, so at most 4 land after the bump: the one that
384 // re-read before it, plus 3 throttled ones.
385 expect(landed).toBeLessThanOrEqual(4)
386 expect(await storedCount(log)).toBe(landed)
387 })
388​
389 it('treats an unreadable store as "still mine" rather than fencing itself out', async () => {
390 // A store blip must not kill a healthy driver: the lease signal is the
391 // primary fence and it has not fired.
392 const log = fakeLog()
393 const runs = await runningRun('fence-6')
394 vi.spyOn(runs, 'get').mockRejectedValue(new Error('store down'))
395 const fenced = fenceDurability(
396 log,
397 claimWith(new AbortController().signal, 1, 'fence-6'),
398 { runs, epochRecheckAppends: 1 },
399 )
400 await fenced.append([chunk('fence-6')])
401 expect(await storedCount(log)).toBe(1)
402 })
403​
404 it('leaves resumeFrom, read, snapshot and close untouched', async () => {
405 const close = vi.fn(() => Promise.resolve())
406 const controller = new AbortController()
407 controller.abort()
408 const base: StreamDurability = { ...fakeLog(), close }
409 const fenced = fenceDurability(base, claimWith(controller.signal), {
410 runs: new InMemoryRunStore(),
411 })
412 // close() must NOT be fenced. It runs on the teardown path, including the
413 // teardown caused by losing the claim, and a fenced close would wedge the
414 // record at 'running' with live tailers parked forever. Same for the three
415 // read-only methods — hence the already-aborted lease signal above.
416 await fenced.close()
417 expect(close).toHaveBeenCalledTimes(1)
418 expect(fenced.resumeFrom()).toBeNull()
419 expect(await fenced.snapshot()).toEqual([])
420 expect(() => fenced.read('o:0')).not.toThrow()
421 })
422})
423​
424describe('fenceDurability — one refusal closes the fence for good', () => {
425 function claimWith(
426 signal: AbortSignal,
427 epoch: number,
428 runId: string,
429 ): RunClaim {
430 return { runId, epoch, signal }
431 }
432​
433 it('refuses the append AFTER a refused one, and neither chunk lands', async () => {
434 // The load-bearing case. Without the latch the refusal consumes the
435 // epoch-recheck budget, so this second append rides a fresh throttle window
436 // unchecked and lands on the SUCCESSOR's log. That is exactly how
437 // `pipeToRunLog`'s recovery `RUN_ERROR` used to escape the fence.
438 const log = fakeLog()
439 const runs = await runningRun('latch-1')
440 await runs.update('latch-1', { driverEpoch: 9 })
441 const fenced = fenceDurability(
442 log,
443 claimWith(new AbortController().signal, 1, 'latch-1'),
444 { runs, epochRecheckAppends: DEFAULT_EPOCH_RECHECK_APPENDS },
445 )
446​
447 await expect(fenced.append([chunk('latch-1')])).rejects.toBeInstanceOf(
448 RunClaimLostError,
449 )
450 await expect(fenced.append([chunk('latch-1')])).rejects.toBeInstanceOf(
451 RunClaimLostError,
452 )
453​
454 // Asserted through snapshot(): `fakeLog` copies its seed array, so checking
455 // the array handed to it proves nothing.
456 expect(await storedCount(log)).toBe(0)
457 })
458​
459 it('replays the original refusal, so pipeToRunLog still sees RunClaimLostError', async () => {
460 const runs = await runningRun('latch-2')
461 await runs.update('latch-2', { driverEpoch: 5 })
462 const fenced = fenceDurability(
463 fakeLog(),
464 claimWith(new AbortController().signal, 2, 'latch-2'),
465 { runs, epochRecheckAppends: DEFAULT_EPOCH_RECHECK_APPENDS },
466 )
467 await fenced.append([chunk('latch-2')]).catch(() => undefined)
468​
469 const second = await fenced
470 .append([chunk('latch-2')])
471 .catch((error: unknown) => error)
472 expect(second).toBeInstanceOf(RunClaimLostError)
473 if (second instanceof RunClaimLostError) {
474 expect(second.runId).toBe('latch-2')
475 expect(second.heldEpoch).toBe(2)
476 expect(second.observedEpoch).toBe(5)
477 }
478 })
479​
480 it('consults neither the throttle nor the store once latched', async () => {
481 const runs = await runningRun('latch-3')
482 await runs.update('latch-3', { driverEpoch: 4 })
483 const fenced = fenceDurability(
484 fakeLog(),
485 claimWith(new AbortController().signal, 1, 'latch-3'),
486 { runs, epochRecheckAppends: 1 },
487 )
488 await fenced.append([chunk('latch-3')]).catch(() => undefined)
489​
490 // A latched boolean is strictly cheaper than the store read it replaces.
491 const get = vi.spyOn(runs, 'get')
492 await fenced.append([chunk('latch-3')]).catch(() => undefined)
493 await fenced.append([chunk('latch-3')]).catch(() => undefined)
494 expect(get).not.toHaveBeenCalled()
495 })
496​
497 it('latches on a LOST LEASE too, not only on a moved epoch', async () => {
498 // `InMemoryLockStore` hands out a signal it never aborts, so it cannot
499 // exercise this branch at all — hence a lock whose lease signal is a live
500 // check that can flap, as a backend polling a lease clock under skew (or
501 // re-acquiring the lease) can. The claim is gone regardless: the latch must
502 // not let the fence re-open just because the signal stopped reporting it.
503 const log = fakeLog()
504 const runs = await runningRun('latch-4')
505 await runs.update('latch-4', { driverEpoch: 1 })
506 const lease = flappableLock()
507 const fenced = await withRunClaim(
508 { runs, locks: lease.locks, runId: 'latch-4', fenceQuietMs: 0 },
509 (claim) =>
510 Promise.resolve(
511 fenceDurability(log, claim, {
512 runs,
513 epochRecheckAppends: DEFAULT_EPOCH_RECHECK_APPENDS,
514 }),
515 ),
516 )
517​
518 lease.lose()
519 const first = await fenced
520 .append([chunk('latch-4')])
521 .catch((error: unknown) => error)
522 expect(first).toBeInstanceOf(RunClaimLostError)
523 if (first instanceof RunClaimLostError) {
524 expect(first.observedEpoch).toBe('lease-lost')
525 }
526​
527 // The signal stops reporting the loss, and the stored epoch still matches
528 // this claim — so ONLY the latch can refuse the next append.
529 lease.regain()
530 await expect(fenced.append([chunk('latch-4')])).rejects.toBeInstanceOf(
531 RunClaimLostError,
532 )
533 expect(await storedCount(log)).toBe(0)
534 })
535​
536 it('still appends normally across more than DEFAULT_EPOCH_RECHECK_APPENDS appends', async () => {
537 // Proves the latch did not become "refuse eventually": a healthy claim must
538 // cross throttle-window boundaries untouched, and the throttle must still
539 // throttle.
540 const log = fakeLog()
541 const runs = await runningRun('latch-5')
542 await runs.update('latch-5', { driverEpoch: 1 })
543 const get = vi.spyOn(runs, 'get')
544 const fenced = fenceDurability(
545 log,
546 claimWith(new AbortController().signal, 1, 'latch-5'),
547 { runs },
548 )
549​
550 const total = DEFAULT_EPOCH_RECHECK_APPENDS * 2 + 5
551 for (let i = 0; i < total; i += 1) await fenced.append([chunk('latch-5')])
552​
553 expect(await storedCount(log)).toBe(total)
554 // One read per window, not one per append and not zero.
555 expect(get).toHaveBeenCalledTimes(
556 Math.ceil(total / DEFAULT_EPOCH_RECHECK_APPENDS),
557 )
558 })
559​
560 it('still allows close() after the latch has tripped', async () => {
561 // The latch must NOT extend to close(): it runs on the teardown caused by
562 // losing the claim, and a refused close wedges the record at 'running' with
563 // every live tailer parked forever.
564 const close = vi.fn(() => Promise.resolve())
565 const runs = await runningRun('latch-6')
566 await runs.update('latch-6', { driverEpoch: 3 })
567 const base: StreamDurability = { ...fakeLog(), close }
568 const fenced = fenceDurability(
569 base,
570 claimWith(new AbortController().signal, 1, 'latch-6'),
571 { runs, epochRecheckAppends: 1 },
572 )
573​
574 await expect(fenced.append([chunk('latch-6')])).rejects.toBeInstanceOf(
575 RunClaimLostError,
576 )
577 await expect(fenced.close()).resolves.toBeUndefined()
578 expect(close).toHaveBeenCalledTimes(1)
579 })
580})
581​
582describe('the InMemoryLockStore configuration the epoch fence exists for', () => {
583 it('gives the claim a signal that never aborts, so the lease fences nothing', async () => {
584 const runs = await runningRun('mem-1')
585 const locks = new InMemoryLockStore()
586 const first = await withRunClaim({ runs, locks, runId: 'mem-1' }, (claim) =>
587 Promise.resolve(claim),
588 )
589 // A second claim supersedes the first...
590 await withRunClaim({ runs, locks, runId: 'mem-1' }, (claim) =>
591 Promise.resolve(claim.epoch),
592 )
593 // ...and the first host's lease signal is STILL not aborted. This is the
594 // documented `InMemoryLockStore` behavior, and it is precisely why layer 2
595 // has to exist: on this backend layer 1 is inert.
596 expect(first.signal.aborted).toBe(false)
597 })
598​
599 it('fences the superseded driver by epoch even though its lease never aborted', async () => {
600 const runs = await runningRun('mem-2')
601 const locks = new InMemoryLockStore()
602 const log = fakeLog()
603​
604 // Host A claims and builds its fenced log.
605 const hostA = await withRunClaim({ runs, locks, runId: 'mem-2' }, (claim) =>
606 Promise.resolve(
607 fenceDurability(log, claim, { runs, epochRecheckAppends: 1 }),
608 ),
609 )
610 const hostBClaim = await withRunClaim(
611 { runs, locks, runId: 'mem-2' },
612 (claim) => Promise.resolve(claim),
613 )
614 expect(hostBClaim.epoch).toBe(2)
615​
616 // Host A is now superseded. Its lease signal never fired, so the ONLY thing
617 // that can stop it writing is the epoch re-check.
618 expect(hostBClaim.signal.aborted).toBe(false)
619 await expect(hostA.append([chunk('mem-2')])).rejects.toBeInstanceOf(
620 RunClaimLostError,
621 )
622 expect(await storedCount(log)).toBe(0)
623​
624 // And the successor's own fenced log still writes.
625 const hostB = fenceDurability(log, hostBClaim, {
626 runs,
627 epochRecheckAppends: 1,
628 })
629 await hostB.append([chunk('mem-2')])
630 expect(await storedCount(log)).toBe(1)
631 })
632​
633 it('serializes two claims racing on one runId and hands out monotonic epochs', async () => {
634 const runs = await runningRun('mem-3')
635 const locks = new InMemoryLockStore()
636 let concurrent = 0
637 let maxConcurrent = 0
638​
639 const drive = (): Promise<number> =>
640 withRunClaim({ runs, locks, runId: 'mem-3' }, async (claim) => {
641 concurrent += 1
642 maxConcurrent = Math.max(maxConcurrent, concurrent)
643 await Promise.resolve()
644 concurrent -= 1
645 return claim.epoch
646 })
647​
648 const epochs = await Promise.all([drive(), drive()])
649​
650 expect(maxConcurrent).toBe(1)
651 expect([...epochs].sort((a, b) => a - b)).toEqual([1, 2])
652 expect((await runs.get('mem-3'))?.driverEpoch).toBe(2)
653 })
654​
655 it('fences a driver superseded mid-drive, after it has already appended', async () => {
656 const runs = await runningRun('mem-4')
657 const log = fakeLog()
658 // A lease-backed lock in another process would hold its own key; model the
659 // successor as a bare store write, which is all the loser can observe.
660 const fenced = await withRunClaim(
661 { runs, locks: new InMemoryLockStore(), runId: 'mem-4' },
662 (claim) =>
663 Promise.resolve(
664 fenceDurability(log, claim, { runs, epochRecheckAppends: 1 }),
665 ),
666 )
667​
668 await fenced.append([chunk('mem-4')])
669 await fenced.append([chunk('mem-4')])
670 expect(await storedCount(log)).toBe(2)
671​
672 await runs.update('mem-4', { driverEpoch: 2 })
673​
674 await expect(fenced.append([chunk('mem-4')])).rejects.toBeInstanceOf(
675 RunClaimLostError,
676 )
677 // The two pre-supersession appends stand; the third never landed.
678 expect(await storedCount(log)).toBe(2)
679 })
680})