Open History to see the last commit
1import { migrate } from "../ingest/migrate";
2import { test } from "node:test";
3import assert from "node:assert/strict";
4import { writeFile } from "node:fs/promises";
5import { setTimeout as delay } from "node:timers/promises";
6import { Pool } from "pg";
7import { runSession } from "../ingest/session";
8import { updateThreadView } from "../ingest/thread-watch";
9import { randomUUID } from "node:crypto";
10
11test("invalid time budgets fail before database acquisition", async () => {
12 const pool = new Pool();
13 try {
14 for (const value of [NaN, Infinity, -1])
15 await assert.rejects(runSession(pool, { budgetMs: value }), /Invalid/);
16 } finally {
17 await pool.end();
18 }
19});
20
21test(
22 "late standby receives a handoff within the original request deadline",
23 { skip: !process.env.RUN_SOURCE_TESTS, timeout: 90000 },
24 async () => {
25 const schema = `hn_handoff_${Date.now()}`;
26 const admin = new Pool({
27 connectionString: process.env.DATABASE_URL_UNPOOLED,
28 });
29 const pool = new Pool({
30 connectionString: process.env.DATABASE_URL_UNPOOLED,
31 options: `-c search_path=${schema}`,
32 max: 6,
33 });
34 const stop = new AbortController();
35 const sessions: Promise<unknown>[] = [];
36 const waitFor = async (check: () => Promise<boolean>) => {
37 const until = Date.now() + 60000;
38 while (!(await check())) {
39 if (Date.now() >= until) throw new Error("Handoff probe timed out");
40 await delay(250);
41 }
42 };
43 try {
44 await admin.query(`CREATE SCHEMA ${schema}`);
45 await migrate(pool);
46 const options = {
47 budgetMs: 90000,
48 tenureMs: 30000,
49 overlapMs: 20000,
50 signal: stop.signal,
51 };
52 const first = runSession(pool, { ...options, owner: "first" });
53 sessions.push(first);
54 // Deliberately withhold the standby until the active tenure has elapsed.
55 await waitFor(
56 async () =>
57 (
58 await pool.query(
59 "SELECT 1 FROM ingest_events WHERE kind='handoff_waiting'",
60 )
61 ).rowCount === 1,
62 );
63 const waiting = (
64 await pool.query(
65 "SELECT active_owner,active_until>clock_timestamp() AS owned FROM ingest_leases",
66 )
67 ).rows[0];
68 assert.equal(waiting.active_owner, "first");
69 assert.equal(waiting.owned, true);
70 const storyIds: number[] = (
71 await pool.query(
72 "SELECT id FROM hn_items WHERE comments BETWEEN 1 AND 100 AND NOT deleted AND NOT dead ORDER BY comments DESC LIMIT 4",
73 )
74 ).rows.map((row) => row.id);
75 assert.equal(storyIds.length, 4, "Four live discussions are available");
76 await Promise.all(
77 storyIds.map((id) => updateThreadView(pool, id, randomUUID())),
78 );
79 const renewViews = setInterval(() => {
80 void pool
81 .query("UPDATE hn_thread_views SET requested_at=clock_timestamp()")
82 .catch(() => {});
83 }, 10000);
84 stop.signal.addEventListener("abort", () => clearInterval(renewViews), {
85 once: true,
86 });
87 await waitFor(
88 async () =>
89 (
90 await pool.query(
91 "SELECT DISTINCT story_id FROM hn_comments WHERE story_id=ANY($1::integer[])",
92 [storyIds],
93 )
94 ).rowCount === 4,
95 );
96 const started = Date.now();
97 const second = runSession(pool, { ...options, owner: "second" });
98 sessions.push(second);
99 const retired = await first;
100 assert.equal(retired.transferred, true);
101 await waitFor(async () =>
102 (await pool.query("SELECT owner,state FROM ingest_status")).rows.some(
103 (row) => row.owner === "second" && row.state === "healthy",
104 ),
105 );
106 await waitFor(
107 async () =>
108 (
109 await pool.query(
110 "SELECT 1 FROM hn_threads WHERE story_id=ANY($1::integer[]) AND state='healthy'",
111 [storyIds],
112 )
113 ).rowCount === 4,
114 );
115 assert.equal(
116 (
117 await pool.query(
118 "SELECT DISTINCT story_id FROM hn_comments WHERE story_id=ANY($1::integer[])",
119 [storyIds],
120 )
121 ).rowCount,
122 4,
123 );
124 const events = (
125 await pool.query(
126 "SELECT kind,occurred_at FROM ingest_events ORDER BY id",
127 )
128 ).rows;
129 assert.ok(!events.some((row) => row.kind === "handoff_unavailable"));
130 const promoted = +new Date(
131 events.find((row) => row.kind === "promoted").occurred_at,
132 );
133 const handedOff = +new Date(
134 events.find((row) => row.kind === "handoff").occurred_at,
135 );
136 assert.ok(promoted - handedOff <= 5000);
137 const absolute = (
138 await pool.query(
139 "SELECT active_session_end,active_deadline FROM ingest_leases",
140 )
141 ).rows[0];
142 assert.ok(
143 +absolute.active_session_end <= +absolute.active_deadline - 10000,
144 );
145 await writeFile(
146 new URL("../.local/handoff-results.json", import.meta.url),
147 JSON.stringify(
148 {
149 measuredAt: new Date().toISOString(),
150 environment:
151 "isolated staging schema, real HN source, local workers",
152 delayedStandbyToHealthyMs: Date.now() - started,
153 handoffToPromotionMs: promoted - handedOff,
154 simultaneousDiscussions: storyIds.length,
155 },
156 null,
157 2,
158 ),
159 );
160 } finally {
161 stop.abort();
162 await Promise.allSettled(sessions);
163 await pool.end();
164 await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
165 await admin.end();
166 }
167 },
168);