Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

test-realtime.ts

246 lines7.8 KB

1import assert from "node:assert/strict";
2import { randomUUID } from "node:crypto";
3import { pool } from "../src/server/db";
4import { newSession, authenticate } from "../src/server/auth";
5import { createWorld, joinWorld } from "../src/server/worlds";
6import { trustedRealtime, memberQuery, historyQuery } from "../src/server/live";
7import {
8 conversationQuery,
9 createGeneration,
10 recordDrawing,
11 runGeneration,
12 expireGenerations,
13} from "../src/server/ai";
14import { compileBlueprint } from "../src/shared/blueprint";
15import { writeFile, mkdir } from "node:fs/promises";
16​
17// Real Postgres and Realtime, disposable fixtures, no Gateway calls. Only
18// production requests carry the persisted session used by scheduled dispatch.
19const rt = trustedRealtime(true);
20const jobs: string[] = [];
21let world: string | undefined;
22const guests: string[] = [];
23const fixture = {
24 version: 1,
25 catalogue: "workshop-1",
26 title: "Realtime fixture",
27 summary: "A green brick.",
28 parts: [
29 {
30 id: "brick",
31 part: "brick-2x2",
32 colour: "jade",
33 turn: 0,
34 at: [0, 0, 0],
35 attach: null,
36 },
37 ],
38};
39try {
40 const user = await newSession("Realtime qualification", "#289b74");
41 guests.push(user.guest);
42 const a = await authenticate(`Bearer ${user.token}`);
43 const w = await createWorld(
44 "Realtime qualification — disposable",
45 a.guest,
46 false,
47 );
48 world = w.id;
49 await joinWorld(a, w.slug);
50 const member = await rt.subscribe(memberQuery(world!, a));
51 await member.awaitRows((rows) => rows[0]?.role === "editor", 20000);
52 console.log("Live member connected");
53 await pool.query(
54 "UPDATE guests SET name='Renamed in another tab',color='#edbc46' WHERE id=$1",
55 [a.guest],
56 );
57 await member.awaitRows(
58 (rows) =>
59 rows[0]?.name === "Renamed in another tab" &&
60 rows[0]?.color === "#edbc46",
61 20000,
62 );
63 await pool.query(
64 "UPDATE world_memberships SET role='viewer' WHERE world=$1 AND guest=$2",
65 [world, a.guest],
66 );
67 await member.awaitRows((rows) => rows[0]?.role === "viewer", 20000);
68 await pool.query(
69 "UPDATE world_memberships SET role='editor' WHERE world=$1 AND guest=$2",
70 [world, a.guest],
71 );
72 await member.awaitRows((rows) => rows[0]?.role === "editor", 20000);
73 const history = await rt.subscribe(historyQuery(world!, a));
74 await history.awaitRows((rows) => rows[0]?.generation === 1, 20000);
75 await pool.query(
76 "DELETE FROM guest_world_history WHERE world=$1 AND guest=$2",
77 [world, a.guest],
78 );
79 await history.awaitRows((rows) => rows.length === 0, 20000);
80​
81 // Representative history includes expanded models that must stay server side.
82 const preview = {
83 parts: compileBlueprint(fixture).parts,
84 title: fixture.title,
85 };
86 for (let i = 0; i < 20; i++) {
87 const id = randomUUID();
88 jobs.push(id);
89 await pool.query(
90 "INSERT INTO ai_generations(id,guest,target,prompt,model,status,blueprint,preview) VALUES($1,$2,$3,'Historical fixture','fixture','accepted',$4::jsonb,$5::jsonb)",
91 [
92 id,
93 a.guest,
94 world,
95 JSON.stringify(fixture),
96 JSON.stringify({
97 ...preview,
98 parts: Array(100).fill(preview.parts[0]),
99 }),
100 ],
101 );
102 }
103 const id = randomUUID();
104 jobs.push(id);
105 await createGeneration(
106 a,
107 { id, prompt: "A synthetic drawing", target: world },
108 { dispatch: false },
109 );
110 console.log("Profile, roles and history passed");
111 const query = conversationQuery(a, world!);
112 const chat = await rt.subscribe(query);
113 await chat.awaitRows(
114 (rows) => rows.some((r) => r.id === id && r.status === "queued"),
115 20000,
116 );
117 await pool.query("UPDATE ai_generations SET status='designing' WHERE id=$1", [
118 id,
119 ]);
120 await recordDrawing(id, preview);
121 await chat.awaitRows(
122 (rows) => rows.some((r) => r.id === id && r.preview?.parts.length === 1),
123 20000,
124 );
125 console.log("Narrowed conversation connected");
126 const rows = chat.getSnapshot().data!;
127 assert.ok(
128 rows
129 .filter((r) => r.status === "accepted")
130 .every(
131 (r) => !r.preview && r.summary === fixture.summary && !r.blueprint,
132 ),
133 );
134 const old = await pool.query(
135 "SELECT blueprint,preview,prompt,status FROM ai_generations WHERE target=$1",
136 [world],
137 );
138 const oldBytes = Buffer.byteLength(JSON.stringify(old.rows));
139 const newBytes = Buffer.byteLength(JSON.stringify(rows));
140 assert.ok(newBytes < oldBytes / 5, `${oldBytes} -> ${newBytes}`);
141 const explain = await pool.query(
142 `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`,
143 query.parameters.map((p) => p.value),
144 );
145 await mkdir("artifacts/realtime-fixes", { recursive: true });
146 await writeFile(
147 "artifacts/realtime-fixes/query-plan.json",
148 JSON.stringify(explain.rows, null, 2),
149 );
150 await pool.query(
151 "UPDATE ai_generations SET status='ready',blueprint=$2::jsonb,lease_until=NULL WHERE id=$1",
152 [id, JSON.stringify(fixture)],
153 );
154 await chat.awaitRows(
155 (rows) =>
156 rows.some((r) => r.id === id && r.status === "ready" && !!r.preview),
157 20000,
158 );
159​
160 // Inference runs in this process; cancellation is committed by another
161 // invocation. There is no shared AbortController and no status SELECT loop.
162 const cancelId = randomUUID();
163 jobs.push(cancelId);
164 await createGeneration(
165 a,
166 { id: cancelId, prompt: "Synthetic cancellable build", target: world },
167 { dispatch: false },
168 );
169 let started!: () => void;
170 const startedPromise = new Promise<void>((resolve) => {
171 started = resolve;
172 });
173 const run = runGeneration(a, cancelId, async (_p, _r, signal) => {
174 started();
175 return await new Promise((_resolve, reject) => {
176 const fail = () => reject(signal.reason);
177 if (signal.aborted) fail();
178 else signal.addEventListener("abort", fail, { once: true });
179 });
180 });
181 await startedPromise;
182 await pool.query("UPDATE ai_generations SET status='cancelled' WHERE id=$1", [
183 cancelId,
184 ]);
185 const result = await Promise.race([
186 run,
187 new Promise<never>((_, reject) =>
188 setTimeout(
189 () => reject(new Error("Realtime cancellation timed out")),
190 20000,
191 ).unref(),
192 ),
193 ]);
194 assert.equal(result.status, "cancelled");
195 const expiredId = randomUUID();
196 jobs.push(expiredId);
197 await createGeneration(
198 a,
199 { id: expiredId, prompt: "Interrupted fixture", target: world },
200 { dispatch: false },
201 );
202 await pool.query(
203 "UPDATE ai_generations SET lease_until=clock_timestamp()-interval '1 second' WHERE id=$1",
204 [expiredId],
205 );
206 await expireGenerations();
207 await chat.awaitRows(
208 (rows) => rows.some((r) => r.id === expiredId && r.status === "failed"),
209 20000,
210 );
211 await pool.query(
212 "UPDATE world_memberships SET active=0 WHERE world=$1 AND guest=$2",
213 [world, a.guest],
214 );
215 await chat.awaitRows((rows) => rows.length === 0, 20000);
216 await member.awaitRows((rows) => rows.length === 0, 20000);
217 console.log(
218 `Realtime qualification passed: live profile/role, empty history, narrowed chat/drawings, cross-process cancellation, expiry and access withdrawal. History payload ${oldBytes} -> ${newBytes} bytes. No inference calls.`,
219 );
220} catch (error) {
221 console.error("[realtime-qualification]", error);
222 throw error;
223} finally {
224 rt.close();
225 if (jobs.length)
226 await pool.query("DELETE FROM ai_generations WHERE id=ANY($1::uuid[])", [
227 jobs,
228 ]);
229 if (world) {
230 for (const table of [
231 "viewer_sessions",
232 "guest_world_history",
233 "world_memberships",
234 "spatial_buckets",
235 ])
236 await pool.query(`DELETE FROM ${table} WHERE world=$1`, [world]);
237 await pool.query("DELETE FROM worlds WHERE id=$1", [world]);
238 }
239 if (guests.length) {
240 await pool.query("DELETE FROM guest_sessions WHERE guest=ANY($1::uuid[])", [
241 guests,
242 ]);
243 await pool.query("DELETE FROM guests WHERE id=ANY($1::uuid[])", [guests]);
244 }
245 await pool.end();