fix: release QA hardening across processing, media, security, and CI gates (#649)

A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
This commit is contained in:
SnapOtter
2026-07-27 15:37:30 +08:00
committed by GitHub
parent bc32f86a07
commit d10d0f544f
855 changed files with 54564 additions and 13092 deletions
+89
View File
@@ -4,15 +4,24 @@ type RedisStub = {
ping: ReturnType<typeof vi.fn>;
quit: ReturnType<typeof vi.fn>;
info: ReturnType<typeof vi.fn>;
once: ReturnType<typeof vi.fn>;
/** Fires the handler registered for an event, as ioredis would. */
emitOnce: (event: string) => void;
};
const { RedisMock, stubs } = vi.hoisted(() => {
const created: RedisStub[] = [];
const mock = vi.fn(function RedisMock() {
const handlers = new Map<string, () => void>();
const stub: RedisStub = {
ping: vi.fn().mockResolvedValue("PONG"),
quit: vi.fn().mockResolvedValue("OK"),
info: vi.fn().mockResolvedValue("# Server\r\nredis_version:8.0.1\r\n"),
once: vi.fn((event: string, handler: () => void) => {
handlers.set(event, handler);
return stub;
}),
emitOnce: (event: string) => handlers.get(event)?.(),
};
created.push(stub);
return stub;
@@ -20,6 +29,13 @@ const { RedisMock, stubs } = vi.hoisted(() => {
return { RedisMock: mock, stubs: created };
});
/**
* Every connection carries an inactivity timeout so a socket whose peer moved
* away cannot sit there forever waiting for a reply that will never come
* (PERF-20260726-007). It has to clear BullMQ's 10 s blocking reads.
*/
const SOCKET_TIMEOUT_MS = 30_000;
vi.mock("ioredis", () => ({
default: RedisMock,
}));
@@ -49,6 +65,7 @@ describe("Redis connection factory", () => {
expect(RedisMock).toHaveBeenCalledWith(expect.any(String), {
enableReadyCheck: true,
maxRetriesPerRequest: null,
socketTimeout: SOCKET_TIMEOUT_MS,
});
});
@@ -60,9 +77,27 @@ describe("Redis connection factory", () => {
expect(RedisMock).toHaveBeenCalledWith(expect.any(String), {
enableReadyCheck: false,
maxRetriesPerRequest: null,
socketTimeout: SOCKET_TIMEOUT_MS,
});
});
it("gives every connection an inactivity timeout clear of BullMQ's blocking reads", async () => {
const { createRedisConnection, createRedisSubscriberConnection } = await freshModule();
createRedisConnection();
createRedisSubscriberConnection();
// A socket the server stopped answering has to be destroyed by something,
// or a consumer parked on a blocking read waits on it forever.
for (const call of RedisMock.mock.calls) {
const options = call[1] as { socketTimeout?: number };
expect(options.socketTimeout).toBe(SOCKET_TIMEOUT_MS);
// BullMQ caps every blocking read at 10 s, so anything at or under that
// would kill healthy idle consumers.
expect(options.socketTimeout).toBeGreaterThan(10_000);
}
});
it("createBullMQConnection builds a command connection and returns the ioredis instance", async () => {
const { createBullMQConnection } = await freshModule();
@@ -73,11 +108,65 @@ describe("Redis connection factory", () => {
expect(RedisMock).toHaveBeenCalledWith(expect.any(String), {
enableReadyCheck: true,
maxRetriesPerRequest: null,
socketTimeout: SOCKET_TIMEOUT_MS,
});
// ...and hands the raw instance straight through (cast only).
expect(conn).toBe(stubs[0]);
});
it("keeps a subscriber socket probed so a dead one can be noticed", async () => {
vi.useFakeTimers();
try {
const { createRedisSubscriberConnection } = await freshModule();
const subscriber = createRedisSubscriberConnection();
expect(subscriber.ping).not.toHaveBeenCalled();
// Nothing writes on a subscriber after SUBSCRIBE, so without this ping
// there is no outstanding command for the inactivity timeout to time.
await vi.advanceTimersByTimeAsync(10_000);
expect(subscriber.ping).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(20_000);
expect(subscriber.ping).toHaveBeenCalledTimes(3);
} finally {
vi.useRealTimers();
}
});
it("stops probing once the subscriber connection has ended", async () => {
vi.useFakeTimers();
try {
const { createRedisSubscriberConnection } = await freshModule();
const subscriber = createRedisSubscriberConnection();
subscriber.emitOnce("end");
await vi.advanceTimersByTimeAsync(60_000);
expect(subscriber.ping).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
it("swallows a rejected probe, because a rejection is the reconnect starting", async () => {
vi.useFakeTimers();
const unhandled = vi.fn();
process.on("unhandledRejection", unhandled);
try {
const { createRedisSubscriberConnection } = await freshModule();
const subscriber = createRedisSubscriberConnection();
subscriber.ping.mockRejectedValue(new Error("Connection is closed."));
await vi.advanceTimersByTimeAsync(10_000);
expect(subscriber.ping).toHaveBeenCalledTimes(1);
expect(unhandled).not.toHaveBeenCalled();
} finally {
process.off("unhandledRejection", unhandled);
vi.useRealTimers();
}
});
it("sharedRedis memoizes a single connection across calls", async () => {
const { sharedRedis } = await freshModule();
+78 -4
View File
@@ -5,6 +5,9 @@ const insertedValues = vi.hoisted(() => vi.fn());
const queueAdd = vi.hoisted(() => vi.fn());
const getJob = vi.hoisted(() => vi.fn());
const queueEventClose = vi.hoisted(() => vi.fn());
const queueEventRun = vi.hoisted(() => vi.fn());
const queueEventOn = vi.hoisted(() => vi.fn());
const queueEventsCtor = vi.hoisted(() => vi.fn());
const flowProducerClose = vi.hoisted(() => vi.fn());
const assertAiJobQuotaMock = vi.hoisted(() => vi.fn());
const isFeatureEnabledMock = vi.hoisted(() => vi.fn());
@@ -50,8 +53,15 @@ async function loadEnqueueModule(
updateSetMock.mockReset();
updateMock.mockReset();
queueEventRun.mockReset();
queueEventOn.mockReset();
queueEventsCtor.mockReset();
queueAdd.mockResolvedValue({ id: "job-1" });
queueEventClose.mockResolvedValue(undefined);
// run() resolves only when the consumer is closing; a never-settling promise
// is the honest stand-in for a loop that stays up for the process's life.
queueEventRun.mockReturnValue(new Promise(() => {}));
flowProducerClose.mockResolvedValue(undefined);
assertAiJobQuotaMock.mockResolvedValue(undefined);
isFeatureEnabledMock.mockReturnValue(options.teamRetentionEnabled ?? false);
@@ -73,10 +83,15 @@ async function loadEnqueueModule(
});
vi.doMock("bullmq", () => ({
QueueEvents: vi.fn(() => ({
close: queueEventClose,
waitUntilReady: vi.fn().mockResolvedValue(undefined),
})),
QueueEvents: vi.fn((name: string, opts: Record<string, unknown>) => {
queueEventsCtor(name, opts);
return {
close: queueEventClose,
waitUntilReady: vi.fn().mockResolvedValue(undefined),
run: queueEventRun,
on: queueEventOn,
};
}),
FlowProducer: vi.fn(() => ({
close: flowProducerClose,
})),
@@ -285,6 +300,65 @@ describe("job enqueue helpers", () => {
expect(flowProducerClose).toHaveBeenCalledTimes(1);
});
it("drives the consumer loop itself rather than relying on BullMQ autorun", async () => {
const { mod } = await loadEnqueueModule();
await mod.warmQueueEvents();
// One consumer per pool, each opted out of autorun and started here.
expect(queueEventsCtor).toHaveBeenCalledTimes(5);
expect(queueEventsCtor).toHaveBeenCalledWith(
expect.stringMatching(/-image$/),
expect.objectContaining({ autorun: false }),
);
expect(queueEventRun).toHaveBeenCalledTimes(5);
expect(queueEventOn).toHaveBeenCalledWith("error", expect.any(Function));
});
it("restarts a consumer loop that stops, instead of leaving the pool deaf", async () => {
vi.useFakeTimers();
const errors = vi.spyOn(console, "error").mockImplementation(() => {});
try {
const { mod } = await loadEnqueueModule();
// BullMQ's autorun would emit 'error' here and never run again, so every
// later sync request on this pool would burn the whole SYNC_WAIT_MS window.
queueEventRun
.mockImplementationOnce(() => Promise.reject(new Error("consumer connection lost")))
.mockReturnValue(new Promise(() => {}));
getJob.mockResolvedValueOnce(undefined);
await mod.waitForJob("image", "job-1");
await vi.advanceTimersByTimeAsync(1100);
expect(queueEventRun).toHaveBeenCalledTimes(2);
expect(errors).toHaveBeenCalledWith(
expect.stringContaining("consumer stopped; restarting"),
expect.any(Error),
);
} finally {
vi.useRealTimers();
}
});
it("stops supervising once the consumer has been closed", async () => {
vi.useFakeTimers();
vi.spyOn(console, "error").mockImplementation(() => {});
try {
const { mod } = await loadEnqueueModule();
queueEventRun.mockImplementation(() => Promise.reject(new Error("consumer connection lost")));
getJob.mockResolvedValueOnce(undefined);
await mod.waitForJob("image", "job-1");
await mod.closeQueueEvents();
const runsAtClose = queueEventRun.mock.calls.length;
await vi.advanceTimersByTimeAsync(5000);
expect(queueEventRun).toHaveBeenCalledTimes(runsAtClose);
} finally {
vi.useRealTimers();
}
});
it("getFlowProducer returns the same cached instance on repeated calls", async () => {
const { mod } = await loadEnqueueModule();
const a = mod.getFlowProducer();