Skip to content
Merged
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
29 changes: 16 additions & 13 deletions cli/src/engine-native/syncConcurrency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@
export type SyncConcurrency = 1 | 2 | 3;
export type SyncTask<T> = () => Promise<T>;

type PoolState =
| { readonly kind: "accepting"; nextIndex: number }
| { readonly kind: "draining"; readonly index: number; readonly reason: unknown };

function drainAfterFailure(state: PoolState, index: number, reason: unknown): PoolState {
return state.kind === "draining" && state.index < index
? state
: { kind: "draining", index, reason };
}

/**
* Run input-ordered tasks with bounded overlap. Once one task rejects, queued
* tasks stay queued while already-started tasks drain; the earliest rejection
Expand All @@ -17,27 +27,20 @@ export async function runBounded<T>(
concurrency: SyncConcurrency,
): Promise<Array<T>> {
const results = new Array<T>(tasks.length);
const failures = new Map<number, unknown>();
let nextIndex = 0;
let stopped = false;
const pool: { state: PoolState } = { state: { kind: "accepting", nextIndex: 0 } };

const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {
for (;;) {
if (stopped || nextIndex >= tasks.length) return;
const index = nextIndex;
nextIndex += 1;
while (pool.state.kind === "accepting" && pool.state.nextIndex < tasks.length) {
const index = pool.state.nextIndex++;
try {
results[index] = await tasks[index]!();
} catch (error) {
failures.set(index, error);
stopped = true;
} catch (reason) {
pool.state = drainAfterFailure(pool.state, index, reason);
}
}
});
await Promise.all(workers);

for (let index = 0; index < tasks.length; index += 1) {
if (failures.has(index)) throw failures.get(index);
}
if (pool.state.kind === "draining") throw pool.state.reason;
return results;
}
70 changes: 52 additions & 18 deletions cli/test/unit/engine-di.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,28 @@ import { describe, expect, it } from "vitest";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setImmediate as nextTurn } from "node:timers/promises";

import { runBounded, runEngineNative } from "../../src/engine-native";
import { syncLockPath } from "../../src/engine-native/scratch";
import { makeEngineServices } from "../../src/engine-native/services";

describe("sync pipeline coordinator", () => {
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((onResolve, onReject) => {
resolve = onResolve;
reject = onReject;
});
return { promise, resolve, reject };
function gatedFailure(reason: unknown) {
const { promise, resolve } = Promise.withResolvers<void>();
return {
release: resolve,
task: async () => {
await promise;
throw reason;
},
};
}

it("caps overlap and returns results in selection order", async () => {
const names = ["first", "second", "third"] as const;
const controls = names.map(() => deferred<string>());
const thirdStarted = deferred<void>();
const controls = names.map(() => Promise.withResolvers<string>());
const thirdStarted = Promise.withResolvers<void>();
const started: Array<string> = [];
let active = 0;
let maxActive = 0;
Expand All @@ -48,8 +50,8 @@ describe("sync pipeline coordinator", () => {
});

it("runs the next pipeline only after the prior one settles at cap one", async () => {
const first = deferred<number>();
const secondStarted = deferred<void>();
const first = Promise.withResolvers<number>();
const secondStarted = Promise.withResolvers<void>();
const started: Array<string> = [];
const run = runBounded(
[
Expand All @@ -72,14 +74,14 @@ describe("sync pipeline coordinator", () => {
});

it("drains started pipelines, stops queued work, and reports the first input failure", async () => {
const first = deferred<string>();
const second = deferred<string>();
const second = gatedFailure(new Error("second failed"));
const firstFailure = new Error("first failed");
const first = gatedFailure(firstFailure);
let queued = false;
const run = runBounded(
[
async () => await first.promise,
async () => await second.promise,
first.task,
second.task,
async () => {
queued = true;
return "should not run";
Expand All @@ -88,11 +90,43 @@ describe("sync pipeline coordinator", () => {
2,
);
const result = expect(run).rejects.toBe(firstFailure);
second.reject(new Error("second failed"));
first.reject(firstFailure);
second.release();
first.release();
await result;
expect(queued).toBe(false);
});

it("keeps an undefined rejection when a later input fails during drain", async () => {
const failing = gatedFailure(undefined);
const active = gatedFailure(new Error("later input failed"));
const events: Array<string> = [];
const run = runBounded(
[
failing.task,
active.task,
async () => {
events.push("queued task started");
},
],
2,
);
const settled = run.then(
() => events.push("fulfilled"),
(reason: unknown) => {
events.push("rejected");
return reason;
},
);
failing.release();
try {
await nextTurn();
expect(events).toEqual([]);
} finally {
active.release();
}
expect(await settled).toBeUndefined();
expect(events).toEqual(["rejected"]);
});
});

describe("native CLI argument and output behavior", () => {
Expand Down
Loading