|
| 1 | +// Plan F.3: integration test that round-trips a `ChatSnapshotV1` blob |
| 2 | +// through the SDK's snapshot helpers + a real MinIO backing store. Mirrors |
| 3 | +// the testcontainer pattern from `objectStore.test.ts`. |
| 4 | +// |
| 5 | +// What this verifies end-to-end: |
| 6 | +// - SDK's `writeChatSnapshot` calls `apiClient.createUploadPayloadUrl` |
| 7 | +// to mint a presigned PUT, then PUTs JSON to it. |
| 8 | +// - SDK's `readChatSnapshot` calls `apiClient.getPayloadUrl` to mint a |
| 9 | +// presigned GET, then fetches and parses. |
| 10 | +// - The webapp's `generatePresignedUrl` produces URLs MinIO accepts. |
| 11 | +// - The blob round-trips with `version: 1` shape preserved. |
| 12 | +// - 404 (no snapshot for a fresh session) returns `undefined`, not an |
| 13 | +// error. |
| 14 | +// |
| 15 | +// This is the integration safety net behind the unit tests in |
| 16 | +// `packages/trigger-sdk/test/chat-snapshot.test.ts` — those tests mock |
| 17 | +// `fetch`; this one drives a real S3-compatible backend. |
| 18 | + |
| 19 | +import { postgresAndMinioTest } from "@internal/testcontainers"; |
| 20 | +import { apiClientManager } from "@trigger.dev/core/v3"; |
| 21 | +import { |
| 22 | + __readChatSnapshotProductionPathForTests as readChatSnapshot, |
| 23 | + __writeChatSnapshotProductionPathForTests as writeChatSnapshot, |
| 24 | + type ChatSnapshotV1, |
| 25 | +} from "@trigger.dev/sdk/ai"; |
| 26 | +import type { UIMessage } from "ai"; |
| 27 | +import { afterEach, describe, expect, vi } from "vitest"; |
| 28 | +import { env } from "~/env.server"; |
| 29 | +import { generatePresignedUrl } from "~/v3/objectStore.server"; |
| 30 | + |
| 31 | +vi.setConfig({ testTimeout: 60_000 }); |
| 32 | + |
| 33 | +// ── Helpers ──────────────────────────────────────────────────────────── |
| 34 | + |
| 35 | +function makeSnapshot(opts: { messages?: UIMessage[]; lastOutEventId?: string } = {}): ChatSnapshotV1 { |
| 36 | + return { |
| 37 | + version: 1, |
| 38 | + savedAt: 1_700_000_000_000, |
| 39 | + messages: opts.messages ?? [ |
| 40 | + { |
| 41 | + id: "u-1", |
| 42 | + role: "user", |
| 43 | + parts: [{ type: "text", text: "hello" }], |
| 44 | + }, |
| 45 | + { |
| 46 | + id: "a-1", |
| 47 | + role: "assistant", |
| 48 | + parts: [{ type: "text", text: "world" }], |
| 49 | + }, |
| 50 | + ], |
| 51 | + lastOutEventId: opts.lastOutEventId ?? "evt-42", |
| 52 | + lastOutTimestamp: 1_700_000_000_500, |
| 53 | + }; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Stub `apiClientManager.clientOrThrow()` so the SDK helpers see a fake |
| 58 | + * api client whose `getPayloadUrl` / `createUploadPayloadUrl` return |
| 59 | + * presigned URLs minted by the webapp's real `generatePresignedUrl` |
| 60 | + * (which signs against MinIO). |
| 61 | + * |
| 62 | + * The SDK helpers internally do `fetch(presignedUrl, ...)` to read/write |
| 63 | + * the blob, so MinIO ends up holding the actual bytes. |
| 64 | + */ |
| 65 | +function stubApiClient(opts: { projectRef: string; envSlug: string }) { |
| 66 | + vi.spyOn(apiClientManager, "clientOrThrow").mockReturnValue({ |
| 67 | + async getPayloadUrl(filename: string) { |
| 68 | + const result = await generatePresignedUrl(opts.projectRef, opts.envSlug, filename, "GET"); |
| 69 | + if (!result.success) throw new Error(result.error); |
| 70 | + return { presignedUrl: result.url }; |
| 71 | + }, |
| 72 | + async createUploadPayloadUrl(filename: string) { |
| 73 | + const result = await generatePresignedUrl(opts.projectRef, opts.envSlug, filename, "PUT"); |
| 74 | + if (!result.success) throw new Error(result.error); |
| 75 | + return { presignedUrl: result.url }; |
| 76 | + }, |
| 77 | + } as never); |
| 78 | +} |
| 79 | + |
| 80 | +// Suppress noisy warnings from logger.warn during error-path tests. |
| 81 | +let warnSpy: ReturnType<typeof vi.spyOn>; |
| 82 | + |
| 83 | +afterEach(() => { |
| 84 | + vi.restoreAllMocks(); |
| 85 | + warnSpy?.mockRestore(); |
| 86 | +}); |
| 87 | + |
| 88 | +// ── Tests ────────────────────────────────────────────────────────────── |
| 89 | + |
| 90 | +describe("chat snapshot integration (MinIO + SDK helpers)", () => { |
| 91 | + postgresAndMinioTest("round-trips a snapshot through real MinIO", async ({ minioConfig }) => { |
| 92 | + env.OBJECT_STORE_BASE_URL = minioConfig.baseUrl; |
| 93 | + env.OBJECT_STORE_ACCESS_KEY_ID = minioConfig.accessKeyId; |
| 94 | + env.OBJECT_STORE_SECRET_ACCESS_KEY = minioConfig.secretAccessKey; |
| 95 | + env.OBJECT_STORE_REGION = minioConfig.region; |
| 96 | + env.OBJECT_STORE_DEFAULT_PROTOCOL = undefined; |
| 97 | + |
| 98 | + stubApiClient({ projectRef: "proj_snap_rt", envSlug: "dev" }); |
| 99 | + |
| 100 | + const sessionId = "sess_round_trip_1"; |
| 101 | + const snapshot = makeSnapshot(); |
| 102 | + |
| 103 | + // Write through the SDK helper — should land in MinIO at |
| 104 | + // `packets/proj_snap_rt/dev/sessions/sess_round_trip_1/snapshot.json`. |
| 105 | + await writeChatSnapshot(sessionId, snapshot); |
| 106 | + |
| 107 | + // Read back through the SDK helper — should reconstruct the original. |
| 108 | + const result = await readChatSnapshot(sessionId); |
| 109 | + |
| 110 | + expect(result).toEqual(snapshot); |
| 111 | + }); |
| 112 | + |
| 113 | + postgresAndMinioTest("returns undefined for a fresh session with no snapshot", async ({ minioConfig }) => { |
| 114 | + env.OBJECT_STORE_BASE_URL = minioConfig.baseUrl; |
| 115 | + env.OBJECT_STORE_ACCESS_KEY_ID = minioConfig.accessKeyId; |
| 116 | + env.OBJECT_STORE_SECRET_ACCESS_KEY = minioConfig.secretAccessKey; |
| 117 | + env.OBJECT_STORE_REGION = minioConfig.region; |
| 118 | + env.OBJECT_STORE_DEFAULT_PROTOCOL = undefined; |
| 119 | + |
| 120 | + stubApiClient({ projectRef: "proj_snap_404", envSlug: "dev" }); |
| 121 | + |
| 122 | + warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); |
| 123 | + |
| 124 | + // Session never had a snapshot written — read returns undefined. |
| 125 | + const result = await readChatSnapshot("sess_never_existed"); |
| 126 | + expect(result).toBeUndefined(); |
| 127 | + }); |
| 128 | + |
| 129 | + postgresAndMinioTest("overwrites a prior snapshot in place (single-writer)", async ({ minioConfig }) => { |
| 130 | + // The runtime guarantees one attempt alive at a time, and |
| 131 | + // `writeChatSnapshot` runs awaited after `onTurnComplete`. Verify |
| 132 | + // that a second write to the same key replaces the first cleanly — |
| 133 | + // the read-after-write reflects the latest blob. |
| 134 | + env.OBJECT_STORE_BASE_URL = minioConfig.baseUrl; |
| 135 | + env.OBJECT_STORE_ACCESS_KEY_ID = minioConfig.accessKeyId; |
| 136 | + env.OBJECT_STORE_SECRET_ACCESS_KEY = minioConfig.secretAccessKey; |
| 137 | + env.OBJECT_STORE_REGION = minioConfig.region; |
| 138 | + env.OBJECT_STORE_DEFAULT_PROTOCOL = undefined; |
| 139 | + |
| 140 | + stubApiClient({ projectRef: "proj_snap_overwrite", envSlug: "dev" }); |
| 141 | + |
| 142 | + const sessionId = "sess_overwrite"; |
| 143 | + |
| 144 | + const turn1 = makeSnapshot({ |
| 145 | + messages: [ |
| 146 | + { id: "u-1", role: "user", parts: [{ type: "text", text: "first" }] }, |
| 147 | + ], |
| 148 | + lastOutEventId: "evt-turn1", |
| 149 | + }); |
| 150 | + const turn2 = makeSnapshot({ |
| 151 | + messages: [ |
| 152 | + { id: "u-1", role: "user", parts: [{ type: "text", text: "first" }] }, |
| 153 | + { id: "a-1", role: "assistant", parts: [{ type: "text", text: "reply-1" }] }, |
| 154 | + { id: "u-2", role: "user", parts: [{ type: "text", text: "second" }] }, |
| 155 | + { id: "a-2", role: "assistant", parts: [{ type: "text", text: "reply-2" }] }, |
| 156 | + ], |
| 157 | + lastOutEventId: "evt-turn2", |
| 158 | + }); |
| 159 | + |
| 160 | + await writeChatSnapshot(sessionId, turn1); |
| 161 | + await writeChatSnapshot(sessionId, turn2); |
| 162 | + |
| 163 | + const result = await readChatSnapshot(sessionId); |
| 164 | + expect(result).toEqual(turn2); |
| 165 | + expect(result?.messages).toHaveLength(4); |
| 166 | + expect(result?.lastOutEventId).toBe("evt-turn2"); |
| 167 | + }); |
| 168 | + |
| 169 | + postgresAndMinioTest("isolates snapshots by sessionId (no cross-talk)", async ({ minioConfig }) => { |
| 170 | + env.OBJECT_STORE_BASE_URL = minioConfig.baseUrl; |
| 171 | + env.OBJECT_STORE_ACCESS_KEY_ID = minioConfig.accessKeyId; |
| 172 | + env.OBJECT_STORE_SECRET_ACCESS_KEY = minioConfig.secretAccessKey; |
| 173 | + env.OBJECT_STORE_REGION = minioConfig.region; |
| 174 | + env.OBJECT_STORE_DEFAULT_PROTOCOL = undefined; |
| 175 | + |
| 176 | + stubApiClient({ projectRef: "proj_snap_iso", envSlug: "dev" }); |
| 177 | + |
| 178 | + const sessA = "sess_iso_A"; |
| 179 | + const sessB = "sess_iso_B"; |
| 180 | + const snapA = makeSnapshot({ lastOutEventId: "evt-A" }); |
| 181 | + const snapB = makeSnapshot({ lastOutEventId: "evt-B" }); |
| 182 | + |
| 183 | + await writeChatSnapshot(sessA, snapA); |
| 184 | + await writeChatSnapshot(sessB, snapB); |
| 185 | + |
| 186 | + const readA = await readChatSnapshot(sessA); |
| 187 | + const readB = await readChatSnapshot(sessB); |
| 188 | + |
| 189 | + expect(readA?.lastOutEventId).toBe("evt-A"); |
| 190 | + expect(readB?.lastOutEventId).toBe("evt-B"); |
| 191 | + // Distinct objects — modifying one shouldn't affect the other. |
| 192 | + expect(readA?.lastOutEventId).not.toBe(readB?.lastOutEventId); |
| 193 | + }); |
| 194 | + |
| 195 | + postgresAndMinioTest("handles snapshots with large message lists (~50 messages)", async ({ minioConfig }) => { |
| 196 | + // Stress test: a 50-turn chat snapshot. Plan F.4 mentions the |
| 197 | + // pre-change baseline grew past 512 KiB around turn 10-30 with tool |
| 198 | + // use; the post-slim wire keeps wire payloads small but the snapshot |
| 199 | + // itself can still get large. Verify the helpers handle a realistic |
| 200 | + // payload size. |
| 201 | + env.OBJECT_STORE_BASE_URL = minioConfig.baseUrl; |
| 202 | + env.OBJECT_STORE_ACCESS_KEY_ID = minioConfig.accessKeyId; |
| 203 | + env.OBJECT_STORE_SECRET_ACCESS_KEY = minioConfig.secretAccessKey; |
| 204 | + env.OBJECT_STORE_REGION = minioConfig.region; |
| 205 | + env.OBJECT_STORE_DEFAULT_PROTOCOL = undefined; |
| 206 | + |
| 207 | + stubApiClient({ projectRef: "proj_snap_big", envSlug: "dev" }); |
| 208 | + |
| 209 | + const messages: UIMessage[] = []; |
| 210 | + for (let i = 0; i < 50; i++) { |
| 211 | + messages.push({ |
| 212 | + id: `u-${i}`, |
| 213 | + role: "user", |
| 214 | + parts: [{ type: "text", text: `user message ${i}: ${"x".repeat(200)}` }], |
| 215 | + }); |
| 216 | + messages.push({ |
| 217 | + id: `a-${i}`, |
| 218 | + role: "assistant", |
| 219 | + parts: [{ type: "text", text: `assistant reply ${i}: ${"y".repeat(500)}` }], |
| 220 | + }); |
| 221 | + } |
| 222 | + const snapshot = makeSnapshot({ messages, lastOutEventId: "evt-50" }); |
| 223 | + |
| 224 | + await writeChatSnapshot("sess_big_chat", snapshot); |
| 225 | + const result = await readChatSnapshot("sess_big_chat"); |
| 226 | + |
| 227 | + expect(result).toBeDefined(); |
| 228 | + expect(result!.messages).toHaveLength(100); |
| 229 | + expect(result!.lastOutEventId).toBe("evt-50"); |
| 230 | + // Spot-check ordering integrity — the messages array round-tripped |
| 231 | + // in the same order. |
| 232 | + expect(result!.messages[0]!.id).toBe("u-0"); |
| 233 | + expect(result!.messages[99]!.id).toBe("a-49"); |
| 234 | + }); |
| 235 | +}); |
0 commit comments