Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion services/platform/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,11 @@ connection a stuck lane still holds), and bounds each of its steps. A lane reads
ends the tail within seconds or fails the lane naming it. The harness's outbound
boundary hands fetch the caller's own abort signal: a signal that only followed it
through an intermediate `Request` was lost to garbage collection, and a closed
tail then read on forever (#4112).
tail then read on forever (#4112). A lane that returns with an SSE stream still
open on the backend fails `harness: <lane> leaves no SSE stream open`, and the
harness ends the stream before the next lane starts: the teardown would end it
without a word. A lane's own cleanup runs through `withCleanup`, which runs
every step and never lets a cleanup failure replace the lane's error (#4152).

## Measure backend work

Expand Down
39 changes: 26 additions & 13 deletions services/platform/backend/integration-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,12 +224,15 @@ import {
isSkippedCheck,
ITEST_VECTOR_WIDTH,
itestObjectStore,
recordOpenStreams,
recordSkip,
requestedLanes,
settleTeardown,
signUpUser,
withCleanup,
withinDeadline,
type SseEvent,
type TeardownStep,
} from './integration-lane-helpers.ts';
import {
itestResolve,
Expand Down Expand Up @@ -51076,7 +51079,21 @@ async function checkBellHintWire(
const mateStream = connectSse(`${base}/events?orgId=${orgId}`, {
cookie: mateCookie,
});
try {
// On every path: both tails end (a tail that will not fails the lane in
// seconds, naming it, instead of holding it to the lane deadline), and the
// project goes, since later lanes count the organization's projects. A step
// that fails after the body did never hides the body's error.
const cleanup: TeardownStep[] = [
["closes the owner's tail", () => ownerStream.close()],
["closes the teammate's tail", () => mateStream.close()],
[
'deletes the bell-wire project',
() => sql`
DELETE FROM app.projects WHERE id = 'p-bell-wire' AND org_id = ${orgId}
`,
],
];
await withCleanup(cleanup, async () => {
await sleep(500); // both tails established
const startId = await latestOutboxId(sql);

Expand Down Expand Up @@ -51181,18 +51198,7 @@ async function checkBellHintWire(
(row[0]?.read ?? false),
`joined=${joined.status}, recipientHint=${mateGotIt}, otherMemberSpared=${ownerSpared}, outbox=${outboxRows.map((r) => `${r.entity}→${r.userId === mateId ? 'recipient' : (r.userId ?? 'org-wide')}`).join(',') || 'none'} (want notification→recipient), readAll=${markAll.status}/hint=${mateToldOfRead}, read=${row[0]?.read}`,
);
} finally {
// On every path: both tails end (a tail that will not fails the lane in
// seconds, naming it, instead of holding it to the lane deadline), and
// the project goes, since later lanes count the organization's projects.
try {
await Promise.all([ownerStream.close(), mateStream.close()]);
} finally {
await sql`
DELETE FROM app.projects WHERE id = 'p-bell-wire' AND org_id = ${orgId}
`;
}
}
});
}

/**
Expand Down Expand Up @@ -64649,6 +64655,9 @@ async function runLanes(
);
globalThis.fetch = boundary;
}
// The teardown's graceful close would end a tail the lane left open
// without a word; counted here, the leak names the lane.
await recordOpenStreams(name, record);
const membershipsAfter = await withinDeadline(
sharedMemberships(sql, ctx.userId),
PROBE_DEADLINE_MS,
Expand Down Expand Up @@ -65066,6 +65075,10 @@ async function main(): Promise<void> {
`org-create scaffold job consumed=${scaffoldDrained}`,
);

// The checks above open `/events` tails of their own (checkAuthAndSse);
// one they left open would otherwise be charged to the first lane.
await recordOpenStreams('the run before its lanes', record);

// Every lane from here on rides the shared session. `runLanes` makes a
// truncation LOUD: a lane that throws, or one that leaves the shared
// session dead, ends the run as a recorded FAIL naming the lane and the
Expand Down
120 changes: 119 additions & 1 deletion services/platform/backend/integration-lane-helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import {
fullCoverageBlockers,
isSkippedCheck,
itestObjectStore,
recordOpenStreams,
recordSkip,
requestedLanes,
settleTeardown,
withCleanup,
} from './integration-lane-helpers';
import { createEventsHandler } from './realtime/sse';
import { createEventsHandler, liveStreamCount } from './realtime/sse';

const store = {
ITEST_S3_ENDPOINT: 'http://127.0.0.1:9000',
Expand Down Expand Up @@ -364,3 +366,119 @@ describe('settleTeardown', () => {
}
});
});

describe('withCleanup', () => {
it("reports the body's error when a cleanup step fails too, and runs every step", async () => {
// The bell-wire lane's shape (#4152): the lane fails, then a tail will
// not close. A plain `finally` reported the tail; the lane's error won.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
const lane = new Error('the recipient never heard the hint');
const ran: string[] = [];
await expect(
withCleanup(
[
[
"closes the owner's tail",
() => Promise.reject(new Error('the tail did not settle')),
],
['deletes the project', () => Promise.resolve(ran.push('delete'))],
],
() => Promise.reject(lane),
),
).rejects.toBe(lane);
expect(ran).toEqual(['delete']);
expect(warn.mock.calls).toEqual([
[
"[itest] the cleanup step that closes the owner's tail failed: Error: the tail did not settle (logged only: the lane fails with the error before it)",
],
]);
} finally {
warn.mockRestore();
}
});

it('fails a passing body with its first cleanup failure, naming the step', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
const ran: string[] = [];
await expect(
withCleanup(
[
["closes the owner's tail", () => Promise.reject(new Error('one'))],
["closes the mate's tail", () => Promise.reject(new Error('two'))],
['deletes the project', () => Promise.resolve(ran.push('delete'))],
],
() => Promise.resolve('passed'),
),
).rejects.toThrow(
"the cleanup step that closes the owner's tail failed: Error: one",
);
expect(ran).toEqual(['delete']);
expect(warn.mock.calls).toEqual([
[
"[itest] the cleanup step that closes the mate's tail failed: Error: two (logged only: the lane fails with the error before it)",
],
]);
} finally {
warn.mockRestore();
}
});

it("returns the body's value once every step has run", async () => {
const ran: string[] = [];
await expect(
withCleanup(
[['deletes the project', () => Promise.resolve(ran.push('delete'))]],
() => Promise.resolve('passed'),
),
).resolves.toBe('passed');
expect(ran).toEqual(['delete']);
});
});

describe('recordOpenStreams', () => {
it('fails a lane that passed with an /events tail still open, naming it, and ends the stream', async () => {
// Since #4133 the teardown's graceful close ended such a tail without a
// word, and the run exited 0 (#4152).
const { server, origin } = await serveEvents();
try {
const tail = connectSse(`${origin}/events?orgId=org1`, {});
while (tail.events.length === 0) await sleep(10);
const { checks, record } = recorder();
await recordOpenStreams('checkLeakyLane', record, 200);

expect(checks).toEqual([
{
name: 'harness: checkLeakyLane leaves no SSE stream open',
ok: false,
detail: expect.stringMatching(
/^1 SSE stream\(s\) still open on the backend 0\.2 s after it returned/,
),
},
]);
expect(liveStreamCount()).toBe(0);
// The harness ended the stream: the tail is over, not stuck.
await tail.close();
} finally {
await closeServerGracefully(server, { forceAfterMs: 3_000 });
}
});

it('records nothing for a lane that closed its tail', async () => {
const { server, origin } = await serveEvents();
try {
const tail = connectSse(`${origin}/events?orgId=org1`, {});
while (tail.events.length === 0) await sleep(10);
await tail.close();
const { checks, record } = recorder();
// At once: the stream may not have left the backend yet.
await recordOpenStreams('checkTidyLane', record);

expect(checks).toEqual([]);
expect(liveStreamCount()).toBe(0);
} finally {
await closeServerGracefully(server, { forceAfterMs: 3_000 });
}
});
});
98 changes: 97 additions & 1 deletion services/platform/backend/integration-lane-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
* in modules of their own (`*.integration.ts`), so a lane never carries a
* second copy of the suite's cookie handling or its throwaway sign-up.
*/
import { setTimeout as sleep } from 'node:timers/promises';

import { z } from 'zod';

import { endAllEventStreams, liveStreamCount } from './realtime/sse.ts';

/** The password every throwaway `itest-` user signs up with. */
export const ITEST_PASSWORD = 'itest-password-1';

Expand Down Expand Up @@ -342,7 +346,8 @@ export function connectSse(
return { events, done, close };
}

/** One step of the harness's teardown: what it does, and the work. */
/** One step of a teardown, the harness's ({@link settleTeardown}) or a
* lane's own ({@link withCleanup}): what it does, and the work. */
export type TeardownStep = readonly [what: string, run: () => Promise<unknown>];

/** The longest one teardown step may take. Each is a close or one query. */
Expand Down Expand Up @@ -372,3 +377,94 @@ export async function settleTeardown(
}
}
}

/**
* Runs `body`, then every step of `cleanup` in order, on every path: a
* lane's `try`/`finally`, without the way a `finally` that throws replaces
* the error in flight. A lane that failed and whose cleanup then failed too
* (an SSE tail that would not close, a DELETE) truncated the run under the
* cleanup's error, and the lane's own failure was lost (#4152). A step that
* throws never stops the next one. When the body threw, its error is the one
* that propagates and each cleanup failure is only logged; when the body
* passed, the first cleanup failure fails the lane. Either way a failure
* names its step.
*/
export async function withCleanup<T>(
cleanup: readonly TeardownStep[],
body: () => Promise<T>,
): Promise<T> {
let value: T;
try {
value = await body();
} catch (error) {
warnCleanupFailures(await runCleanup(cleanup));
throw error;
}
const [first, ...rest] = await runCleanup(cleanup);
warnCleanupFailures(rest);
if (first !== undefined) throw first;
return value;
}

/** Runs every step in order; each failure comes back as an error naming its
* step. */
async function runCleanup(cleanup: readonly TeardownStep[]): Promise<Error[]> {
const failures: Error[] = [];
for (const [what, run] of cleanup) {
try {
await run();
} catch (error) {
failures.push(
new Error(`the cleanup step that ${what} failed: ${errorText(error)}`, {
cause: error,
}),
);
}
}
return failures;
}

/** Logs the cleanup failures an earlier error outranks. */
function warnCleanupFailures(failures: readonly Error[]): void {
for (const failure of failures) {
console.warn(
`[itest] ${failure.message} (logged only: the lane fails with the error before it)`,
);
}
}

/** How long the streams a lane closed get to leave the backend: a close
* reaches the stream's `finally` within a few ticks. */
const OPEN_STREAM_SETTLE_MS = 5_000;

/**
* Fails `subject` (a lane, or the run before its lanes) for the SSE streams
* it left open on the backend, and ends them. The harness's teardown ends
* every stream the way a deployment's shutdown does (#4112), so a tail a
* lane leaked on its passing path was ended without a word: the run logged
* `ended N open SSE stream(s)` and exited 0 (#4152). Asked after each lane,
* the count names the lane, and the next lane starts with no stream open. A
* stream whose client has just closed it leaves a few ticks later, so the
* count gets `settleMs` to reach zero first. Records nothing when it does.
*/
export async function recordOpenStreams(
subject: string,
record: RecordCheck,
settleMs: number = OPEN_STREAM_SETTLE_MS,
): Promise<void> {
const settleBy = Date.now() + settleMs;
while (liveStreamCount() > 0 && Date.now() < settleBy) {
await sleep(20);
}
const open = endAllEventStreams();
if (open === 0) return;
record(
`harness: ${subject} leaves no SSE stream open`,
false,
`${open} SSE stream(s) still open on the backend ${deadlineText(settleMs)} ` +
`after it returned: a tail it did not close on this path, or a close ` +
`that never reached the backend. Shutdown would have ended them ` +
`without a word; the harness ended them, so later lanes start with ` +
`none. Close every tail on every path (withCleanup()).`,
);
}
Loading
Loading