-
Notifications
You must be signed in to change notification settings - Fork 326
Add world.snapshots storage interface (local, postgres, vercel) #3250
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
753c981
Add opt-in QuickJS WASM VM engine (WORKFLOW_VM=quickjs) with full eve…
TooTallNate adb3d0e
QuickJS engine: AbortController, setAttributes, terminal drain, turbo…
TooTallNate 6be76e2
QuickJS engine: hook.getConflict support, cross-run writable forwardi…
TooTallNate 9d2530e
QuickJS engine: stream framing round-trip, bound step proxies, webhoo…
TooTallNate c57127d
Apply biome fixes to QuickJS engine files
TooTallNate ff400af
Address review feedback: anchor source-map strip to end-of-input, use…
TooTallNate 5d4c578
CI: include generated QuickJS source assets in shared e2e build artif…
TooTallNate 24017cc
Fix same-token hook ordering and conflicted-hook disposal in the Quic…
TooTallNate ad80ba8
CI: run both VM engines across all frameworks and worlds; label jobs …
TooTallNate 2bd67b9
Fix stack overflow stripping inline source maps from webpack dev bund…
TooTallNate 2a082dd
e2e: poll step listings until analytics rows include attempt (optiona…
TooTallNate 0518e1c
e2e: use --withData to force storage-backed step listings for attempt…
TooTallNate 6336b47
Sort imports in QuickJS serialization files (biome organizeImports)
TooTallNate 2f3434d
QuickJS engine: resolve the run's full payload-key capability so seal…
TooTallNate 1ff0ed9
Address review: crypto/process parity, loud Intl guards, lazy engine …
TooTallNate fe96bca
QuickJS engine: implement resilient resumeHook (hookInput materializa…
TooTallNate 4506623
QuickJS engine: inline step execution via live-VM continuation loop +…
TooTallNate b232778
Address review: exclusive inline step claims, self-write requeue, in-…
TooTallNate 6aea4c5
Add world.snapshots storage interface with local, postgres, and verce…
TooTallNate 968cfa1
Address review: validate runId before filesystem paths in snapshots s…
TooTallNate 8f88b5e
Merge origin/main (post-#3048) into quickjs-vm-perf; address review t…
TooTallNate d2a115b
Merge branch 'quickjs-vm-perf' into quickjs-vm-snapshots
TooTallNate 0584471
Merge remote-tracking branch 'origin/main' into quickjs-vm-snapshots
TooTallNate 374dbaa
Address review: atomic snapshot envelope, optional interface, idempot…
TooTallNate File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| '@workflow/world': minor | ||
| '@workflow/world-local': minor | ||
| '@workflow/world-postgres': minor | ||
| '@workflow/world-vercel': minor | ||
| --- | ||
|
|
||
| Add an OPTIONAL `snapshots` storage interface (`save`/`load`/`delete` + `SnapshotMetadata`, plus `encodeSnapshotEnvelope`/`decodeSnapshotEnvelope` helpers that pack metadata and bytes into one atomically-storable blob) for VM-memory snapshotting, with implementations in world-local (single envelope file per run), world-postgres (`workflow_snapshots` table storing the envelope), and world-vercel (workflow-server `/v2/runs/:runId/snapshot` endpoints with W3C trace-context injection; delete is 404-idempotent). Inert until the runtime opts in; community World implementations that don't provide `snapshots` are unaffected (the runtime feature-detects and falls back to full replay). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
packages/world-local/src/storage/snapshots-storage.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import { promises as fs } from 'node:fs'; | ||
| import os from 'node:os'; | ||
| import path from 'node:path'; | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest'; | ||
| import { createSnapshotsStorage } from './snapshots-storage.js'; | ||
|
|
||
| describe('snapshots storage (world-local)', () => { | ||
| let testDir: string; | ||
| let snapshots: ReturnType<typeof createSnapshotsStorage>; | ||
|
|
||
| beforeEach(async () => { | ||
| testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'snapshots-test-')); | ||
| snapshots = createSnapshotsStorage(testDir); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await fs.rm(testDir, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| it('returns null when no snapshot exists', async () => { | ||
| expect(await snapshots.load('wrun_missing')).toBeNull(); | ||
| }); | ||
|
|
||
| it('round-trips snapshot bytes and metadata', async () => { | ||
| const data = new Uint8Array([1, 2, 3, 250, 251, 252]); | ||
| const createdAt = new Date('2025-06-01T12:00:00Z'); | ||
| await snapshots.save('wrun_a', data, { | ||
| eventsCursor: 'evnt_123', | ||
| createdAt, | ||
| }); | ||
|
|
||
| const loaded = await snapshots.load('wrun_a'); | ||
| expect(loaded).not.toBeNull(); | ||
| expect(new Uint8Array(loaded!.data)).toEqual(data); | ||
| expect(loaded!.metadata.eventsCursor).toBe('evnt_123'); | ||
| expect(+loaded!.metadata.createdAt).toBe(+createdAt); | ||
| }); | ||
|
|
||
| it('overwrites the previous snapshot on save', async () => { | ||
| await snapshots.save('wrun_a', new Uint8Array([1]), { | ||
| eventsCursor: null, | ||
| createdAt: new Date(), | ||
| }); | ||
| await snapshots.save('wrun_a', new Uint8Array([9, 9]), { | ||
| eventsCursor: 'evnt_9', | ||
| createdAt: new Date(), | ||
| }); | ||
|
|
||
| const loaded = await snapshots.load('wrun_a'); | ||
| expect(new Uint8Array(loaded!.data)).toEqual(new Uint8Array([9, 9])); | ||
| expect(loaded!.metadata.eventsCursor).toBe('evnt_9'); | ||
| }); | ||
|
|
||
| it('supports a null events cursor', async () => { | ||
| await snapshots.save('wrun_b', new Uint8Array([7]), { | ||
| eventsCursor: null, | ||
| createdAt: new Date(), | ||
| }); | ||
| const loaded = await snapshots.load('wrun_b'); | ||
| expect(loaded!.metadata.eventsCursor).toBeNull(); | ||
| }); | ||
|
|
||
| it('delete removes the snapshot (idempotent)', async () => { | ||
| await snapshots.save('wrun_c', new Uint8Array([1]), { | ||
| eventsCursor: null, | ||
| createdAt: new Date(), | ||
| }); | ||
| await snapshots.delete('wrun_c'); | ||
| expect(await snapshots.load('wrun_c')).toBeNull(); | ||
| // Deleting again is a no-op. | ||
| await snapshots.delete('wrun_c'); | ||
| }); | ||
|
|
||
| it('stores metadata and bytes in ONE file (atomic pairing — no torn save)', async () => { | ||
| await snapshots.save('wrun_atomic', new Uint8Array([1, 2, 3]), { | ||
| eventsCursor: 'evnt_x', | ||
| createdAt: new Date(), | ||
| }); | ||
| const files = await fs.readdir(path.join(testDir, 'snapshots')); | ||
| expect(files).toEqual(['wrun_atomic.snapshot']); | ||
| }); | ||
|
|
||
| it('treats a corrupt envelope file as a miss instead of returning torn state', async () => { | ||
| await snapshots.save('wrun_corrupt', new Uint8Array([1, 2, 3]), { | ||
| eventsCursor: 'evnt_x', | ||
| createdAt: new Date(), | ||
| }); | ||
| await fs.writeFile( | ||
| path.join(testDir, 'snapshots', 'wrun_corrupt.snapshot'), | ||
| Buffer.from([0xde, 0xad]) | ||
| ); | ||
| expect(await snapshots.load('wrun_corrupt')).toBeNull(); | ||
| }); | ||
|
|
||
| it('rejects path-traversal runIds on every operation', async () => { | ||
| const hostile = [ | ||
| '../escape', | ||
| '..', | ||
| 'a/b', | ||
| 'a\\b', | ||
| 'nul\0byte', | ||
| '.hidden', | ||
| 'dotted.name', | ||
| '', | ||
| ]; | ||
| const metadata = { eventsCursor: null, createdAt: new Date() }; | ||
| for (const runId of hostile) { | ||
| await expect( | ||
| snapshots.save(runId, new Uint8Array([1]), metadata) | ||
| ).rejects.toThrow(/unsafe|invalid/i); | ||
| await expect(snapshots.load(runId)).rejects.toThrow(/unsafe|invalid/i); | ||
| await expect(snapshots.delete(runId)).rejects.toThrow(/unsafe|invalid/i); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import fs from 'node:fs/promises'; | ||
| import path from 'node:path'; | ||
| import type { SnapshotMetadata } from '@workflow/world'; | ||
| import { | ||
| decodeSnapshotEnvelope, | ||
| encodeSnapshotEnvelope, | ||
| } from '@workflow/world'; | ||
| import { | ||
| assertSafeEntityId, | ||
| ensureDir, | ||
| readBuffer, | ||
| resolveWithinBase, | ||
| write, | ||
| } from '../fs.js'; | ||
|
|
||
| /** | ||
| * Create the snapshots sub-storage for a local World implementation. | ||
| * | ||
| * Snapshots are stored as ONE file per run: | ||
| * {basedir}/snapshots/{runId}.snapshot — snapshot envelope (metadata + | ||
| * opaque VM snapshot bytes; see `encodeSnapshotEnvelope`) | ||
| * | ||
| * A single file matters: `write()` is atomic per file (temp + rename), | ||
| * but two files (bytes + metadata) written separately can tear — a crash | ||
| * between the renames, or a concurrent `load` interleaving them, pairs a | ||
| * heap image from one suspension with an `eventsCursor` from another, | ||
| * and the restore silently replays from the wrong log position. The | ||
| * envelope makes the pairing structurally atomic. | ||
| * | ||
| * Compression and encryption are handled by `@workflow/core`'s snapshot | ||
| * entrypoint (`compress → encrypt → save`); this world layer stores the | ||
| * resulting bytes verbatim. | ||
| */ | ||
| export function createSnapshotsStorage(basedir: string) { | ||
| const snapshotsDir = path.join(basedir, 'snapshots'); | ||
|
|
||
| // `runId` arrives from the request body: validate it before it touches a | ||
| // filesystem path (primary defense — rejects `../`, `/`, `\`, NUL, `.`), | ||
| // and contain the join under the snapshots dir (defense in depth), the | ||
| // same two-layer scheme the other world-local storages use. | ||
| function envelopePath(runId: string): string { | ||
| assertSafeEntityId('runId', runId); | ||
| return resolveWithinBase(snapshotsDir, `${runId}.snapshot`); | ||
| } | ||
|
|
||
| return { | ||
| async save( | ||
| runId: string, | ||
| data: Uint8Array, | ||
| metadata: SnapshotMetadata | ||
| ): Promise<void> { | ||
| await ensureDir(snapshotsDir); | ||
| await write( | ||
| envelopePath(runId), | ||
| Buffer.from(encodeSnapshotEnvelope(metadata, data)), | ||
| { overwrite: true } | ||
| ); | ||
| }, | ||
|
|
||
| async load( | ||
| runId: string | ||
| ): Promise<{ data: Uint8Array; metadata: SnapshotMetadata } | null> { | ||
| let envelope: Buffer; | ||
| try { | ||
| envelope = await readBuffer(envelopePath(runId)); | ||
| } catch (error: any) { | ||
| if (error.code === 'ENOENT') { | ||
| return null; | ||
| } | ||
| throw error; | ||
| } | ||
| // Anything that fails to decode (truncated, corrupt, unknown | ||
| // version, schema-invalid metadata) is a clean miss — the caller | ||
| // falls back to full replay, never to fabricated metadata. | ||
| return decodeSnapshotEnvelope( | ||
| new Uint8Array( | ||
| envelope.buffer, | ||
| envelope.byteOffset, | ||
| envelope.byteLength | ||
| ) | ||
| ); | ||
| }, | ||
|
|
||
| async delete(runId: string): Promise<void> { | ||
| // `force: true` — idempotent by contract (terminal-state cleanup | ||
| // retries, and runs that never snapshotted delete too). | ||
| await fs.rm(envelopePath(runId), { force: true }); | ||
| }, | ||
| }; | ||
| } | ||
6 changes: 6 additions & 0 deletions
6
packages/world-postgres/src/drizzle/migrations/0019_add_snapshots_table.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| CREATE TABLE IF NOT EXISTS "workflow"."workflow_snapshots" ( | ||
| "run_id" varchar PRIMARY KEY NOT NULL, | ||
| "data" "bytea" NOT NULL, | ||
| "events_cursor" varchar, | ||
| "created_at" timestamp DEFAULT now() NOT NULL | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import type { SnapshotMetadata, Storage } from '@workflow/world'; | ||
| import { | ||
| decodeSnapshotEnvelope, | ||
| encodeSnapshotEnvelope, | ||
| } from '@workflow/world'; | ||
| import { eq } from 'drizzle-orm'; | ||
| import { type Drizzle, Schema } from './drizzle/index.js'; | ||
|
|
||
| /** | ||
| * Snapshot storage for world-postgres. | ||
| * | ||
| * Compression and encryption are handled by `@workflow/core`'s | ||
| * snapshot entrypoint (`compress(snapshot) → encrypt → save`). This | ||
| * world layer treats the bytes as opaque — it does NOT add its own | ||
| * compression. | ||
| * | ||
| * The `data` column stores a snapshot ENVELOPE (metadata + bytes in one | ||
| * blob; see `encodeSnapshotEnvelope`): the full metadata object | ||
| * round-trips losslessly through the envelope, so new metadata fields | ||
| * never require a schema migration, and the metadata/bytes pairing is | ||
| * atomic by construction. The `events_cursor` / `created_at` columns | ||
| * are denormalized copies kept for observability (SQL inspection) — | ||
| * loads read the envelope, never the columns. | ||
| * | ||
| * Each run has at most one row; `save()` upserts the latest | ||
| * suspension's bytes. | ||
| */ | ||
| export function createSnapshotsStorage( | ||
| drizzle: Drizzle | ||
| ): NonNullable<Storage['snapshots']> { | ||
| const { snapshots } = Schema; | ||
|
|
||
| return { | ||
| async save( | ||
| runId: string, | ||
| data: Uint8Array, | ||
| metadata: SnapshotMetadata | ||
| ): Promise<void> { | ||
| const blob = Buffer.from(encodeSnapshotEnvelope(metadata, data)); | ||
| await drizzle | ||
| .insert(snapshots) | ||
| .values({ | ||
| runId, | ||
| data: blob, | ||
| eventsCursor: metadata.eventsCursor, | ||
| createdAt: metadata.createdAt, | ||
| }) | ||
| .onConflictDoUpdate({ | ||
| target: snapshots.runId, | ||
| set: { | ||
| data: blob, | ||
| eventsCursor: metadata.eventsCursor, | ||
| createdAt: metadata.createdAt, | ||
| }, | ||
| }); | ||
| }, | ||
|
|
||
| async load( | ||
| runId: string | ||
| ): Promise<{ data: Uint8Array; metadata: SnapshotMetadata } | null> { | ||
| const [row] = await drizzle | ||
| .select() | ||
| .from(snapshots) | ||
| .where(eq(snapshots.runId, runId)) | ||
| .limit(1); | ||
|
|
||
| if (!row) return null; | ||
|
|
||
| // Anything that fails to decode (corrupt, unknown version, | ||
| // schema-invalid metadata) is a clean miss — the caller falls back | ||
| // to full replay, never to fabricated metadata. | ||
| return decodeSnapshotEnvelope( | ||
| new Uint8Array( | ||
| row.data.buffer, | ||
| row.data.byteOffset, | ||
| row.data.byteLength | ||
| ) | ||
| ); | ||
| }, | ||
|
|
||
| async delete(runId: string): Promise<void> { | ||
| // Plain DELETE — naturally idempotent (0 rows affected is success). | ||
| await drizzle.delete(snapshots).where(eq(snapshots.runId, runId)); | ||
| }, | ||
| }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.