Open History to see the last commit
1/**
2 * Compile-time regression for the offset type threading through the run driver,
3 * the reaper, and everything they wrap.
4 *
5 * WHY A TYPE-LEVEL TEST AND NOT A RUNTIME ONE. The defect was purely a
6 * signature: `SandboxRunDriverOptions.durability` and `ReapOptions.durability`
7 * hardcoded `StreamDurability` (i.e. `StreamDurability<string>`), and
8 * `StreamDurability<TOffset>` is CONTRAVARIANT in `TOffset` through `read`
9 * (and through `upsert` on the upsertable variant). A backend that brands its
10 * cursors — `@tanstack/ai-durable-stream`'s `durableStream`, which returns
11 * `StreamDurability<DurableStreamOffset>` where
12 * `DurableStreamOffset = DurableStreamCursor | '-1' | 'now'` — was therefore
13 * NOT assignable, and the production multi-host durability backend could not be
14 * handed to `sandboxRunDriver` or `reapDetachedRuns` without a cast. Casts of
15 * that shape (`as unknown as`) are a lint ERROR under `src/**` in this repo, so
16 * an application hit a hard wall, and the reaping/takeover docs had to fall
17 * back to `memoryStream` in every snippet. Nothing observable at runtime
18 * differed, so only the compiler can catch a regression.
19 *
20 * `BrandedOffset` below mirrors `DurableStreamOffset`'s SHAPE rather than
21 * importing it: `@tanstack/ai-sandbox` must not depend on a durability backend
22 * (the layering runs the other way), and the union-with-literal-sentinels shape
23 * is what makes the assignment fail. The real composition is asserted against
24 * the actual `durableStream` in
25 * `packages/ai-durable-stream/tests/offset-composition.test-d.ts`.
26 */
27import { expectTypeOf } from 'vitest'
28import { withSandbox } from '../src'
29import type {
30 AlignToStoredLogOptions,
31 ReapOptions,
32 RunDeps,
33 SandboxDefinition,
34 SandboxDurabilityOptions,
35 SandboxMiddlewareOptions,
36 SandboxRunDriverOptions,
37 SandboxRunDurability,
38} from '../src'
39import type { PipeToRunLogOptions, RunController } from '../src/run'
40import type { awaitLogQuiescence, fenceDurability } from '../src/claim'
41import type { RunStore, StreamChunk, StreamDurability } from '@tanstack/ai'
42
43/** Same shape as `DurableStreamOffset`: a branded cursor plus two sentinels. */
44type BrandedOffset = `branded:${string}` | '-1' | 'now'
45
46declare const brandedFactory: (runId: string) => StreamDurability<BrandedOffset>
47declare const brandedLog: StreamDurability<BrandedOffset>
48
49// ---------------------------------------------------------------------------
50// The defect, at the two option types the report named.
51// ---------------------------------------------------------------------------
52
53const driverDurability: SandboxRunDriverOptions<BrandedOffset>['durability'] =
54 brandedFactory
55const reapDurability: ReapOptions<BrandedOffset>['durability'] = brandedFactory
56void driverDurability
57void reapDurability
58
59// Inference, not just explicit instantiation: a caller writes
60// `sandboxRunDriver({ durability: logFor, … })` and never names `TOffset`, so
61// the whole fix is worthless if the parameter cannot be inferred from the
62// factory that is passed.
63declare function inferDriver<TOffset extends string>(
64 input: Pick<SandboxRunDriverOptions<TOffset>, 'durability'>,
65): TOffset
66expectTypeOf(
67 inferDriver({ durability: brandedFactory }),
68).toEqualTypeOf<BrandedOffset>()
69
70declare function inferReap<TOffset extends string>(
71 input: Pick<ReapOptions<TOffset>, 'durability'>,
72): TOffset
73expectTypeOf(
74 inferReap({ durability: brandedFactory }),
75).toEqualTypeOf<BrandedOffset>()
76
77// ---------------------------------------------------------------------------
78// The chain underneath, so nothing collapses the offset back to `string`
79// one layer in.
80// ---------------------------------------------------------------------------
81
82const deps: RunDeps<BrandedOffset>['durability'] = brandedFactory
83const pipeDeps: PipeToRunLogOptions<BrandedOffset>['durability'] =
84 brandedFactory
85const alignLog: AlignToStoredLogOptions<BrandedOffset>['durability'] =
86 brandedLog
87void deps
88void pipeDeps
89void alignLog
90
91// `fenceDurability` sits BETWEEN a caller's log and `pipeToRunLog`. If it
92// returned `StreamDurability<string>` the wall would simply move here.
93expectTypeOf<ReturnType<typeof fenceDurability<BrandedOffset>>>().toEqualTypeOf<
94 StreamDurability<BrandedOffset>
95>()
96expectTypeOf<
97 Parameters<typeof awaitLogQuiescence<BrandedOffset>>[0]
98>().toEqualTypeOf<StreamDurability<BrandedOffset>>()
99
100// `RunController.attach` hands an offset back IN, so it is contravariant too.
101expectTypeOf<
102 Parameters<RunController<BrandedOffset>['attach']>[1]
103>().toEqualTypeOf<BrandedOffset>()
104expectTypeOf<
105 ReturnType<RunController<BrandedOffset>['attach']>
106>().toEqualTypeOf<
107 AsyncIterable<{ offset: BrandedOffset; chunk: StreamChunk }>
108>()
109
110// A branded log must not silently accept an arbitrary string as an offset —
111// that would mean the parameter had been widened to `string` rather than
112// threaded, which is the fix this test exists to rule out.
113declare const branded: StreamDurability<BrandedOffset>
114// @ts-expect-error an unvalidated string is not a branded cursor
115branded.read('not-a-cursor')
116
117// ---------------------------------------------------------------------------
118// `withSandbox`'s durability option — the POST-handler half of the durable
119// path, and the last place the offset wall stood.
120//
121// The driver and the reaper (above) accept a branded backend, but
122// `SandboxDurabilityOptions.adapter` hardcoded `StreamDurability`, so
123// `withSandbox(sandbox, { runs, durability: { adapter } })` — the route that
124// STARTS a durable run — rejected the very adapter the resume route accepted:
125//
126// error TS2322: Type 'StreamDurability<DurableStreamOffset>' is not
127// assignable to type 'StreamDurability<string>'.
128// Types of property 'read' are incompatible.
129// Type 'string' is not assignable to type 'DurableStreamOffset'.
130//
131// An application could therefore wire the recommended production backend on
132// only one of the two routes it needs.
133// ---------------------------------------------------------------------------
134
135declare const definition: SandboxDefinition
136declare const runs: RunStore
137
138const brandedOption: SandboxDurabilityOptions<BrandedOffset> = {
139 adapter: brandedLog,
140}
141const brandedMiddlewareOptions: SandboxMiddlewareOptions<BrandedOffset> = {
142 runs,
143 durability: { adapter: brandedLog },
144}
145void brandedOption
146void brandedMiddlewareOptions
147
148// Inference at the real call site: an application never writes `TOffset`, so a
149// bare `withSandbox(...)` call is what has to compile.
150withSandbox(definition, { runs, durability: { adapter: brandedLog } })
151
152// …including with every other knob present, so the parameter is not silently
153// pinned by a sibling property.
154withSandbox(definition, {
155 runs,
156 durability: {
157 adapter: brandedLog,
158 journal: '/tmp/journal',
159 detachOnDisconnect: false,
160 attach: true,
161 pollIntervalMs: 50,
162 attachWaitMs: 1_000,
163 },
164})
165
166// The bus payload is NOT parameterized, and that is the deliberate half of the
167// fix: `createCapability<T>()` forces one concrete instantiation, so the
168// payload's log is typed as the offset-covariant view (`read` omitted) that
169// every `StreamDurability<TOffset>` is assignable to. Assert both directions —
170// a branded log goes IN, and nothing tries to take an offset back OUT through
171// `read`.
172declare const payload: SandboxRunDurability
173const payloadLog: SandboxRunDurability['adapter'] = brandedLog
174void payloadLog
175expectTypeOf<SandboxRunDurability['adapter']>().not.toHaveProperty('read')
176expectTypeOf(payload.adapter.snapshot).toBeCallableWith()
177
178// ---------------------------------------------------------------------------
179// Backward compatibility: the `= string` default is what keeps every existing
180// call site compiling with no change.
181// ---------------------------------------------------------------------------
182
183declare const plainFactory: (runId: string) => StreamDurability
184
185declare const plainLog: StreamDurability
186
187const defaultDriver: SandboxRunDriverOptions['durability'] = plainFactory
188const defaultReap: ReapOptions['durability'] = plainFactory
189const defaultDeps: RunDeps['durability'] = plainFactory
190const defaultOption: SandboxDurabilityOptions['adapter'] = plainLog
191const defaultMiddleware: SandboxMiddlewareOptions = {
192 runs,
193 durability: { adapter: plainLog },
194}
195void defaultDriver
196void defaultReap
197void defaultDeps
198void defaultOption
199void defaultMiddleware
200
201// A call site that names no offset at all — today's every-existing-app shape.
202withSandbox(definition, { runs, durability: { adapter: plainLog } })
203withSandbox(definition)
204
205expectTypeOf<SandboxRunDriverOptions['durability']>().toEqualTypeOf<
206 (runId: string) => StreamDurability<string>
207>()
208expectTypeOf<ReapOptions['durability']>().toEqualTypeOf<
209 (runId: string) => StreamDurability<string>
210>()
211expectTypeOf<SandboxDurabilityOptions['adapter']>().toEqualTypeOf<
212 StreamDurability<string>
213>()