From 18d5db2e82c5dc5d44e29f133dcacf6dc11001a0 Mon Sep 17 00:00:00 2001 From: Sven Rogge Date: Thu, 5 Nov 2026 17:05:31 +0100 Subject: [PATCH 1/2] feat: classify converted image outputs in one request --- README.md | 36 ++++ fixtures/classification-lifecycle.ts | 68 +++++++- packages/client/CHANGELOG.md | 6 + packages/client/src/classify-image.ts | 19 +-- packages/client/src/client.ts | 53 +++++- .../src/process-image-classification.spec.ts | 154 ++++++++++++++++++ packages/common/CHANGELOG.md | 6 + packages/common/src/classification.spec.ts | 49 +++++- packages/common/src/classification.ts | 66 ++++++++ packages/common/src/index.ts | 15 ++ packages/core/CHANGELOG.md | 6 + .../core/src/images/classify-image.spec.ts | 41 +++++ packages/core/src/images/classify-image.ts | 45 ++++- packages/core/src/images/image-processor.ts | 38 +++-- packages/server/CHANGELOG.md | 6 + .../src/images/process-image-handler.spec.ts | 54 ++++++ .../src/images/process-image-handler.ts | 8 +- packages/server/src/server.ts | 4 +- packages/typebox/CHANGELOG.md | 6 + packages/typebox/src/index.ts | 8 + 20 files changed, 641 insertions(+), 47 deletions(-) create mode 100644 packages/client/src/process-image-classification.spec.ts diff --git a/README.md b/README.md index 89cd909..ec36259 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,42 @@ in this mode. Callers must require `embedded-preview/1` before uploading to avoi silently ignoring the option. No broad camera-format or physical-device compatibility is claimed; extractor tests use synthetic TIFF/DNG containers. +#### Classifying while converting + +`POST /images/process` accepts an optional `classify` property on each image option. As soon as +that entry's output has been produced, the server classifies exactly those output bytes and streams +the result as an `application/json` part, so a RAW file is uploaded once and the converted preview +never travels back and forth. Add `discard: true` to receive only the classification. + +```ts +import { processImage, ProcessedFile } from "@m4k/client"; + +for await (const event of processImage("http://localhost:3000", Bun.file("IMG_0001.DNG"), [ + { + embeddedPreview: true, + format: "jpeg", + resize: { width: 512, height: 512 }, + classify: { classifierId: "clip-image-labels", classifierVersion: "1", labels: ["landscape", "receipt"] }, + discard: true, + }, + { embeddedPreview: true, format: "jpeg", resize: { width: 2048, height: 2048 }, name: "web.jpg" }, +])) { + if (event instanceof ProcessedFile) await Array.fromAsync(event.stream); + else if ("classification" in event) console.log(event.classification.index, event.classification.labels); +} +``` + +The part is `{"classification": {"index": 0, "classifierId", "classifierVersion", "sha256", "labels"}}`; +`index` is the position of the producing entry in the options array, `sha256` is the hash of the +classified output. Every classified entry needs an explicit `jpeg`, `png` or `webp` format within +the classifier limits (8 MiB / 1,048,576 pixels), which is why a resize is usually appropriate. +Several entries (and their classifications) share one upload and one decode. Unlike the standalone +endpoint, a classification queues for the single inference slot instead of failing with 429, because +the conversion has already been done. There is no fallback: a failing classification ends the stream +with an error. Servers advertise `inline-classification/1` in `imageProfiles`; the client requires it +(and the pinned classifier) before uploading and fails if the server omits a requested classification. +`classify` is only available as JSON options (`X-Options` or `options`), not as a flat query parameter. + ### Using the client The client is available as a standalone package [@m4k/client](./packages/client). You can use it to connect to the m4k server. diff --git a/fixtures/classification-lifecycle.ts b/fixtures/classification-lifecycle.ts index 60e3c27..858604f 100644 --- a/fixtures/classification-lifecycle.ts +++ b/fixtures/classification-lifecycle.ts @@ -13,7 +13,7 @@ let pixels: object | undefined; async function infer(_image: unknown, labels: string[]) { inferences++; - if (scenario === "inference-abort" && inferences === 1) { + if (["inference-abort", "process-wait"].includes(scenario) && inferences === 1) { inferenceStarted.resolve(); await pendingInference.promise; } @@ -47,7 +47,71 @@ const options = { }; const expectedSha256 = new Bun.CryptoHasher("sha256").update(bytes).digest("hex"); -if (scenario === "handler-success") { +/** Drains `processImage` (or the server handler's parts) into plain, comparable events. */ +async function collect(events: AsyncIterable) { + const out: unknown[] = []; + for await (const event of events) { + if (typeof event === "object" && event !== null && "stream" in event && "name" in event) { + const chunks: Uint8Array[] = []; + for await (const chunk of event.stream as AsyncIterable) chunks.push(chunk); + const data = Buffer.concat(chunks); + out.push({ + file: event.name as string, + sha256: new Bun.CryptoHasher("sha256").update(data).digest("hex"), + }); + } else out.push(event); + } + return out; +} + +if (scenario === "process-inline" || scenario === "process-discard") { + const { processImage } = await import("../packages/core/src/images/image-processor.ts"); + const events = await collect( + processImage(new Blob([bytes], { type: "image/jpeg" }), [ + { + format: "jpeg", + resize: { width: 16 }, + classify: options, + ...(scenario === "process-discard" ? { discard: true } : {}), + }, + { format: "webp" }, + ])!, + ); + console.log(JSON.stringify({ events, loads, inferences, pixels, expectedSha256 })); +} else if (scenario === "handler-process") { + const { processImageHandler } = + await import("../packages/server/src/images/process-image-handler.ts"); + const response = await processImageHandler( + new Request("http://m4k/images/process", { + method: "POST", + body: bytes, + headers: { + "X-Options": JSON.stringify([ + { format: "jpeg", resize: { width: 16 }, classify: options, discard: true }, + { format: "webp", name: "keep.webp" }, + ]), + }, + }), + ); + console.log(JSON.stringify({ status: response.status, body: await response.text(), inferences })); +} else if (scenario === "process-wait") { + const { processImage } = await import("../packages/core/src/images/image-processor.ts"); + const run = () => + collect(processImage(new Blob([bytes], { type: "image/jpeg" }), { format: "jpeg", classify: options })!).then( + (events) => ({ events }), + (error: Error) => ({ error: error.message }), + ); + const first = run(); + await inferenceStarted.promise; + const second = run(); + // Let the second conversion finish and reach the occupied inference slot. + await Bun.sleep(300); + const inferencesWhileWaiting = inferences; + pendingInference.resolve(); + console.log( + JSON.stringify({ first: await first, second: await second, inferencesWhileWaiting, inferences }), + ); +} else if (scenario === "handler-success") { const { classifyImageHandler } = await import("../packages/server/src/images/classify-image-handler.ts"); const response = await classifyImageHandler( diff --git a/packages/client/CHANGELOG.md b/packages/client/CHANGELOG.md index 70752d7..5956bd6 100644 --- a/packages/client/CHANGELOG.md +++ b/packages/client/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to `@m4k/client` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `processImage` accepts `classify`/`discard`, requires the `inline-classification/1` profile, validates every classification part and fails when one is missing. + ## [0.2.12] ### Added diff --git a/packages/client/src/classify-image.ts b/packages/client/src/classify-image.ts index 3663117..d411564 100644 --- a/packages/client/src/classify-image.ts +++ b/packages/client/src/classify-image.ts @@ -1,6 +1,7 @@ import { imageClassifier, encodeOptions, + isValidClassificationResult, validateClassificationOptions, type ClassificationOptions, type ClassificationResult, @@ -46,23 +47,7 @@ export async function classifyImage( }); if (!response.ok) throw new Error(`M4K classification failed (${response.status})`); const result = (await readJsonResponse(response)) as ClassificationResult; - if ( - result.classifierId !== options.classifierId || - result.classifierVersion !== options.classifierVersion || - !/^[a-f0-9]{64}$/.test(result.sha256) || - !Array.isArray(result.labels) || - result.labels.length !== options.labels.length || - new Set(result.labels.map((entry) => entry.label)).size !== options.labels.length || - result.labels.some( - (entry) => - !options.labels.includes(entry.label) || - !Number.isFinite(entry.score) || - entry.score < 0 || - entry.score > 1, - ) || - Math.abs(result.labels.reduce((sum, entry) => sum + entry.score, 0) - 1) > 1e-3 - ) - throw new Error("Invalid classification response"); + if (!isValidClassificationResult(result, options)) throw new Error("Invalid classification response"); const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", await input.arrayBuffer())); const sha256 = [...hash].map((byte) => byte.toString(16).padStart(2, "0")).join(""); if (result.sha256 !== sha256) diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 1b36794..aeb1883 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -1,7 +1,12 @@ import { ProcessedFile, + imageClassifier, + inlineClassificationProfile, + invalidInlineClassification, isImageNoOp, + isValidClassificationResult, encodeOptions, + type InlineClassification, type ProcessingError, type Progress, type QueuePosition, @@ -31,6 +36,10 @@ export async function* processAudio( /** * Process an image. + * + * An entry with `classify` is classified on the server right after its output was produced, so + * the converted file never travels back for classification. Its `InlineClassification` is yielded + * after the file (or instead of it, with `discard`). The stream fails if the server omits one. * @param host - The host of the server. * @param input - The input image. Can be a stream or a blob. * @param opts - The options for the image processing. @@ -44,22 +53,37 @@ export async function* processImage( { signal }: { signal?: AbortSignal } = {}, ) { const optsArr = Array.isArray(opts) ? opts : [opts]; - if (optsArr.some((option) => option.embeddedPreview)) { + const invalid = invalidInlineClassification(optsArr); + if (invalid) throw new RangeError(invalid); + const classifying = optsArr.some((option) => option.classify); + if (classifying || optsArr.some((option) => option.embeddedPreview)) { const response = await fetch(`${host}/info`, { ...(signal ? { signal } : {}), redirect: "error", }); - if (!response.ok) throw new Error("M4K preview capability check failed"); + if (!response.ok) throw new Error("M4K capability check failed"); const info = (await readJsonResponse(response)) as { service?: string; imageProfiles?: string[]; + classifiers?: { id: string; version: string; revision: string }[]; }; + const profiles = + info.service === "m4k" && Array.isArray(info.imageProfiles) ? info.imageProfiles : []; + const preview = optsArr.some((option) => option.embeddedPreview); + if (preview && !profiles.includes("embedded-preview/1")) + throw new RangeError("M4K does not support embedded preview extraction"); if ( - info.service !== "m4k" || - !Array.isArray(info.imageProfiles) || - !info.imageProfiles.includes("embedded-preview/1") + classifying && + (!profiles.includes(inlineClassificationProfile) || + !Array.isArray(info.classifiers) || + !info.classifiers.some( + (c) => + c.id === imageClassifier.id && + c.version === imageClassifier.version && + c.revision === imageClassifier.revision, + )) ) - throw new RangeError("M4K does not support embedded preview extraction"); + throw new RangeError("M4K does not support classification while processing images"); } if (input instanceof Blob && input.type) { const inputExt = input.type.replace(/^image\//, "").toLowerCase(); @@ -119,13 +143,27 @@ async function* runFetch( if (!res.ok) { throw new Error(`Failed to optimize: [${res.statusText}] ${await res.text()}`); } + const requested = (Array.isArray(opts) ? opts : [opts]) as RemoteImageOptions[]; + const awaiting = new Set(requested.flatMap((o, i) => ("classify" in o && o.classify ? [i] : []))); + // Audio and video entries have no `classify`; this only guards image requests. for await (const part of streamParts(res)) { if (part.type === "application/json") { - const msg = (await part.json()) as Progress | QueuePosition | ProcessingError; + const msg = (await part.json()) as + | Progress + | QueuePosition + | ProcessingError + | InlineClassification; if ("error" in msg) { signal?.throwIfAborted(); throw new Error(msg.error); } + if ("classification" in msg) { + const { index } = msg.classification; + const asked = requested[index]?.classify; + const expected = awaiting.delete(index) && asked !== undefined; + if (!expected || !isValidClassificationResult(msg.classification, asked)) + throw new Error("Invalid classification response"); + } yield msg; } else if (part.type !== "text/plain") { yield new ProcessedFile(part.filename!, part.type!, part) as ProcessedFile & { @@ -133,6 +171,7 @@ async function* runFetch( }; } } + if (awaiting.size > 0) throw new Error("M4K did not return every requested classification"); } function inputToStream(input: AsyncIterable | Blob) { diff --git a/packages/client/src/process-image-classification.spec.ts b/packages/client/src/process-image-classification.spec.ts new file mode 100644 index 0000000..b0acb04 --- /dev/null +++ b/packages/client/src/process-image-classification.spec.ts @@ -0,0 +1,154 @@ +import { imageClassifier, inlineClassificationProfile, ProcessedFile } from "@m4k/common"; +import { describe, expect, test } from "bun:test"; +import { processImage } from "./client.js"; + +const classify = { + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + labels: ["landscape", "receipt"], +}; +const sha256 = "a".repeat(64); +const result = (index: number) => ({ + index, + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + sha256, + labels: [ + { label: "landscape", score: 0.75 }, + { label: "receipt", score: 0.25 }, + ], +}); + +/** A fake m4k: `/info` plus a canned multipart answer for `/images/process`. */ +function fakeServer(options: { + profiles?: string[]; + parts: (string | { json: unknown })[]; + posts?: { count: number }; +}) { + const boundary = "test-boundary"; + return Bun.serve({ + port: 0, + fetch(request) { + if (request.method === "GET") + return Response.json({ + service: "m4k", + classifiers: [imageClassifier], + imageProfiles: options.profiles ?? [inlineClassificationProfile], + }); + if (options.posts) options.posts.count++; + const body = options.parts + .map((part) => + typeof part === "string" + ? `--${boundary}\r\nContent-Disposition: attachment; filename="${part}"\r\nContent-Type: image/jpeg\r\n\r\nbytes\r\n` + : `--${boundary}\r\nContent-Type: application/json\r\n\r\n${JSON.stringify(part.json)}\r\n`, + ) + .join(""); + return new Response(`${body}--${boundary}--\r\n`, { + headers: { "content-type": `multipart/mixed; boundary="${boundary}"` }, + }); + }, + }); +} + +async function run(host: string, opts: Parameters[2]) { + const events: unknown[] = []; + for await (const event of processImage(host, new Blob(["input"], { type: "image/png" }), opts)) { + if (event instanceof ProcessedFile) { + await Array.fromAsync(event.stream!); + events.push(`file:${event.name}`); + } else events.push(event); + } + return events; +} + +describe("processImage() with classification", () => { + test("yields the classification after the file it belongs to", async () => { + const server = fakeServer({ + parts: ["file1.jpeg", { json: { classification: result(0) } }, "file2.webp"], + }); + + const events = await run(server.url.origin, [ + { format: "jpeg", classify }, + { format: "webp" }, + ]).finally(() => server.stop(true)); + + expect(events).toEqual(["file:file1.jpeg", { classification: result(0) }, "file:file2.webp"]); + }); + + test("does not upload to a server without inline classification", async () => { + const posts = { count: 0 }; + const server = fakeServer({ profiles: ["embedded-preview/1"], parts: [], posts }); + + const error = await run(server.url.origin, { format: "jpeg", classify }).then( + () => null, + (e: unknown) => e, + ); + server.stop(true); + + expect(error).toBeInstanceOf(RangeError); + expect(posts.count).toBe(0); + }); + + test("fails when the server omits a requested classification", async () => { + const server = fakeServer({ parts: ["file1.jpeg"] }); + + const error = await run(server.url.origin, { format: "jpeg", classify }).then( + () => null, + (e: unknown) => e, + ); + server.stop(true); + + expect(String(error)).toContain("every requested classification"); + }); + + test("rejects a classification for candidates that were not requested", async () => { + const forged = { ...result(0), labels: [{ label: "dog", score: 1 }] }; + const server = fakeServer({ parts: [{ json: { classification: forged } }] }); + + const error = await run(server.url.origin, { format: "jpeg", classify, discard: true }).then( + () => null, + (e: unknown) => e, + ); + server.stop(true); + + expect(String(error)).toContain("Invalid classification response"); + }); + + test("rejects a classification for an entry that did not ask for one", async () => { + const server = fakeServer({ parts: [{ json: { classification: result(1) } }] }); + + const error = await run(server.url.origin, [ + { format: "jpeg", classify, discard: true }, + { format: "webp" }, + ]).then( + () => null, + (e: unknown) => e, + ); + server.stop(true); + + expect(String(error)).toContain("Invalid classification response"); + }); + + test("refuses an avif output before contacting the server", async () => { + const options = { format: "avif" as const, classify }; + + const error = await run("http://127.0.0.1:1", options).then( + () => null, + (e: unknown) => e, + ); + + expect(error).toBeInstanceOf(RangeError); + }); + + test("never short-circuits a classifying entry as a no-op conversion", async () => { + const server = fakeServer({ + parts: ["file1.png", { json: { classification: result(0) } }], + }); + + const events = await run(server.url.origin, { format: "png", classify }).finally(() => + server.stop(true), + ); + + expect(events).toContainEqual({ classification: result(0) }); + }); +}); diff --git a/packages/common/CHANGELOG.md b/packages/common/CHANGELOG.md index 332ec56..1094d34 100644 --- a/packages/common/CHANGELOG.md +++ b/packages/common/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to `@m4k/common` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `classify` and `discard` image options, `InlineClassification`, `invalidInlineClassification` and `isValidClassificationResult`. + ## [0.2.9] ### Added diff --git a/packages/common/src/classification.spec.ts b/packages/common/src/classification.spec.ts index a19f335..f04d7b4 100644 --- a/packages/common/src/classification.spec.ts +++ b/packages/common/src/classification.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { validateClassificationOptions } from "./classification.js"; +import { invalidInlineClassification, validateClassificationOptions } from "./classification.js"; +import { isImageNoOp } from "./index.js"; const config = { classifierId: "clip-image-labels", @@ -48,3 +49,49 @@ describe("validateClassificationOptions", () => { expect(results).toEqual([false, false, false, false, false]); }); }); + +describe("invalidInlineClassification", () => { + test("accepts a classified jpeg output and a plain sibling", () => { + const options = [{ format: "jpeg", classify: config }, { format: "avif" }]; + + const problem = invalidInlineClassification(options); + + expect(problem).toBeUndefined(); + }); + + test("requires an explicit format the classifier can read", () => { + const missing = invalidInlineClassification([{ classify: config }]); + const avif = invalidInlineClassification([{ format: "avif", classify: config }]); + + expect(missing).toContain("jpeg, png or webp"); + expect(avif).toContain("[0]"); + }); + + test("rejects discarding without classification or together with an output path", () => { + const alone = invalidInlineClassification([{ format: "jpeg", discard: true }]); + const withOutput = invalidInlineClassification([ + { format: "jpeg", classify: config, discard: true, output: "/tmp/x.jpg" }, + ]); + + expect(alone).toContain("discard requires classify"); + expect(withOutput).toContain("output"); + }); + + test("rejects an unsupported candidate set", () => { + const options = [{ format: "jpeg", classify: { ...config, labels: ["only"] } }]; + + const problem = invalidInlineClassification(options); + + expect(problem).toContain("Unsupported classifier"); + }); +}); + +describe("isImageNoOp", () => { + test("is never a no-op when the output is classified", () => { + const options = { format: "png" as const, classify: config }; + + const noOp = isImageNoOp(options, "png"); + + expect(noOp).toBe(false); + }); +}); diff --git a/packages/common/src/classification.ts b/packages/common/src/classification.ts index efe60c0..8f496a1 100644 --- a/packages/common/src/classification.ts +++ b/packages/common/src/classification.ts @@ -52,3 +52,69 @@ export function validateClassificationOptions(value: unknown): value is Classifi ) ); } + +/** Profile advertised in `GET /info` `imageProfiles` by servers that classify inside `/images/process`. */ +export const inlineClassificationProfile = "inline-classification/1"; + +/** Image formats the classifier accepts; an inline classification must produce one of them. */ +export const classifiableFormats = ["jpeg", "png", "webp"] as const; + +/** One classification streamed by `/images/process`: the result for the output at `index`. */ +export type InlineClassification = { + classification: ClassificationResult & { + /** Position of the producing entry in the request's options array. */ + index: number; + }; +}; + +/** + * Checks the classification-related fields of an image-options array before any work starts. + * Returns the problem, or `undefined` when the combination is acceptable. + */ +export function invalidInlineClassification( + options: readonly { + classify?: unknown; + discard?: boolean; + format?: string; + ext?: string; + output?: string; + }[], +): string | undefined { + for (const [index, option] of options.entries()) { + const at = `[${index}] `; + if (option.classify === undefined) { + if (option.discard) return `${at}discard requires classify`; + continue; + } + if (!validateClassificationOptions(option.classify)) + return `${at}Unsupported classifier configuration`; + const format = option.ext ?? option.format; + if (!(classifiableFormats as readonly (string | undefined)[]).includes(format)) + return `${at}classify requires an explicit jpeg, png or webp output format`; + if (option.discard && option.output) return `${at}discard cannot be combined with output`; + } + return undefined; +} + +/** Whether a result is well-formed for the requested candidates. The byte hash is checked by the caller. */ +export function isValidClassificationResult( + result: ClassificationResult, + options: ClassificationOptions, +): boolean { + return ( + result.classifierId === options.classifierId && + result.classifierVersion === options.classifierVersion && + /^[a-f0-9]{64}$/.test(result.sha256) && + Array.isArray(result.labels) && + result.labels.length === options.labels.length && + new Set(result.labels.map((entry) => entry.label)).size === options.labels.length && + result.labels.every( + (entry) => + options.labels.includes(entry.label) && + Number.isFinite(entry.score) && + entry.score >= 0 && + entry.score <= 1, + ) && + Math.abs(result.labels.reduce((sum, entry) => sum + entry.score, 0) - 1) <= 1e-3 + ); +} diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts index 39293bf..4b92ca5 100644 --- a/packages/common/src/index.ts +++ b/packages/common/src/index.ts @@ -1,9 +1,15 @@ +import type { ClassificationOptions } from "./classification.js"; export { + classifiableFormats, imageClassifier, + inlineClassificationProfile, encodeOptions, + invalidInlineClassification, + isValidClassificationResult, validateClassificationOptions, type ClassificationOptions, type ClassificationResult, + type InlineClassification, } from "./classification.js"; export type Progress = { @@ -34,6 +40,14 @@ type ImageFormat = | "jp2"; export type ImageOptions = { + /** + * Classify this entry's output as soon as it has been produced, on the same server. The result + * is streamed as an `InlineClassification` part; the output bytes are classified exactly as + * returned. Requires an explicit `jpeg`, `png` or `webp` format within the classifier's limits. + */ + classify?: ClassificationOptions; + /** Return only the classification, not the converted file. Requires `classify`. */ + discard?: boolean; /** Extract a bounded embedded JPEG preview from a TIFF-based camera file; never demosaic RAW. */ embeddedPreview?: boolean; /** The rotation of the image. If not provided, the image will be auto-rotated, according to the EXIF data. To disable auto-rotation, set to `0`. */ @@ -172,6 +186,7 @@ export function isImageNoOp(opt: ImageOptions, inputExt: string): boolean { if (outFmt !== inputExt) return false; return ( !opt.embeddedPreview && + !opt.classify && !opt.resize && !opt.crop && opt.rotate == null && diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index f3764e5..ef0d942 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to `m4k` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `processImage` classifies an entry's output right after conversion (`classify`, `discard`) and yields an `InlineClassification`; the inference slot can be awaited with `classifyImage(..., { wait: true })`. + ## [0.3.7] ### Fixed diff --git a/packages/core/src/images/classify-image.spec.ts b/packages/core/src/images/classify-image.spec.ts index 50eb2d1..b976164 100644 --- a/packages/core/src/images/classify-image.spec.ts +++ b/packages/core/src/images/classify-image.spec.ts @@ -38,4 +38,45 @@ describe("classifyImage lifecycle", () => { expect(result.inferences).toBe(2); expect(result.retry.sha256).toBe(result.expectedSha256); }); + + test("classifies the exact bytes of a converted output on the same call", async () => { + const scenario = "process-inline"; + + const result = await runClassificationScenario(scenario); + + const events = result.events.filter((event: object) => !("position" in event)); + const [start, file, classified, firstDone, second, done] = events; + expect(start).toEqual({ progress: 0 }); + expect(file.file).toBe("file1.jpeg"); + expect(classified.classification.index).toBe(0); + expect(classified.classification.sha256).toBe(file.sha256); + expect(classified.classification.sha256).not.toBe(result.expectedSha256); + expect(firstDone).toEqual({ progress: 50 }); + expect(second.file).toBe("file2.webp"); + expect(done).toEqual({ progress: 100 }); + expect(result.inferences).toBe(1); + expect(result.pixels.width).toBe(16); + }); + + test("returns only the classification when the converted file is discarded", async () => { + const scenario = "process-discard"; + + const result = await runClassificationScenario(scenario); + + const files = result.events.filter((event: object) => "file" in event); + expect(files.map((event: { file: string }) => event.file)).toEqual(["file2.webp"]); + expect(result.events.filter((event: object) => "classification" in event)).toHaveLength(1); + }); + + test("queues a second conversion for the inference slot instead of failing busy", async () => { + const scenario = "process-wait"; + + const result = await runClassificationScenario(scenario); + + expect(result.inferencesWhileWaiting).toBe(1); + expect(result.inferences).toBe(2); + expect(result.first.error).toBeUndefined(); + expect(result.second.error).toBeUndefined(); + expect(result.second.events.some((event: object) => "classification" in event)).toBe(true); + }); }); diff --git a/packages/core/src/images/classify-image.ts b/packages/core/src/images/classify-image.ts index c0d6dde..5565ce5 100644 --- a/packages/core/src/images/classify-image.ts +++ b/packages/core/src/images/classify-image.ts @@ -11,6 +11,37 @@ import { waitForLoad } from "../util/wait-for-load.js"; let classifier: Promise>> | undefined; let busy = false; +/** Callers that chose to wait for the inference slot, in arrival order. */ +const waiting: (() => void)[] = []; + +/** Takes the single inference slot, or throws when it is taken and the caller does not wait. */ +async function acquire(wait: boolean, signal?: AbortSignal) { + signal?.throwIfAborted(); + if (!busy) { + busy = true; + return; + } + if (!wait) throw new Error("Classifier is busy"); + await new Promise((resolve, reject) => { + const turn = () => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }; + const onAbort = () => { + waiting.splice(waiting.indexOf(turn), 1); + reject(signal!.reason); + }; + waiting.push(turn); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** Hands the slot to the next waiter, which keeps `busy` set, or frees it. */ +function release() { + const next = waiting.shift(); + if (next) next(); + else busy = false; +} async function loadClassifier() { const { env, pipeline } = await import("@huggingface/transformers"); env.cacheDir = process.env.M4K_MODEL_CACHE ?? `${process.env.M4K_TMP_DIR ?? "/tmp/m4k"}/models`; @@ -38,19 +69,21 @@ async function decodePreview(input: Uint8Array) { } } -/** Bounded preview-only inference. No arbitrary models, remote image URLs or file outputs. */ +/** + * Bounded preview-only inference. No arbitrary models, remote image URLs or file outputs. + * One inference runs at a time: a second caller fails with "Classifier is busy", unless it passes + * `wait` to queue for its turn (used by `processImage`, whose conversion has already been paid for). + */ export async function classifyImage( input: Uint8Array, options: ClassificationOptions, - { signal }: { signal?: AbortSignal } = {}, + { signal, wait = false }: { signal?: AbortSignal; wait?: boolean } = {}, ): Promise { if (!validateClassificationOptions(options)) throw new RangeError("Unsupported classifier configuration"); if (input.byteLength > imageClassifier.maxBytes) throw new RangeError("Classification preview exceeds byte limit"); - signal?.throwIfAborted(); - if (busy) throw new Error("Classifier is busy"); - busy = true; + await acquire(wait, signal); try { const bytes = Uint8Array.from(input); const candidates = [...options.labels]; @@ -79,6 +112,6 @@ export async function classifyImage( labels: labels as ClassificationResult["labels"], }; } finally { - busy = false; + release(); } } diff --git a/packages/core/src/images/image-processor.ts b/packages/core/src/images/image-processor.ts index c613f23..c6fef6d 100644 --- a/packages/core/src/images/image-processor.ts +++ b/packages/core/src/images/image-processor.ts @@ -1,4 +1,10 @@ -import { type ImageOptions, ProcessedFile, isImageNoOp } from "@m4k/common"; +import { + type ImageOptions, + type InlineClassification, + ProcessedFile, + invalidInlineClassification, + isImageNoOp, +} from "@m4k/common"; import { spawn } from "node:child_process"; import { createReadStream } from "node:fs"; import { readFile, rm } from "node:fs/promises"; @@ -7,6 +13,7 @@ import { createQueue } from "tasque"; import { ffmpeg, createTmp, randomId } from "../util/ffmpeg-processor.js"; import { exhaustAsyncIterableToWritable } from "../util/streams.js"; +import { classifyImage } from "./classify-image.js"; import { extractEmbeddedPreview } from "./extract-embedded-preview.js"; export { ffmpeg }; @@ -21,7 +28,8 @@ const imageTmpDir = `${process.env.M4K_TMP_DIR ?? "/tmp/m4k"}/image`; * @param input - The input image. Can be a file path, a stream or a blob. * @param opts - The options for the image processing. * @param signal - An optional abort signal. - * @returns An iterable of the processed images. + * @returns An iterable of the processed images. An entry with `classify` is followed by an + * `InlineClassification` of exactly its output bytes; the file itself is omitted if `discard` is set. */ export function processImage( input: string | AsyncIterable | Blob, @@ -30,6 +38,8 @@ export function processImage( ) { const iterable = imageQueue.iterate(async function* () { const optsArr = Array.isArray(opts) ? opts : [opts]; + const invalid = invalidInlineClassification(optsArr); + if (invalid) throw new RangeError(invalid); const preview = optsArr.some((o) => o.embeddedPreview); if ( preview && @@ -54,7 +64,7 @@ export function processImage( return; } - let files: ProcessedFile[]; + let files: OutputFile[]; try { files = await runSharp(resolvedInput, optsArr); } catch { @@ -64,7 +74,17 @@ export function processImage( yield { progress: 0 }; for (let i = 0; i < files.length; i++) { - yield files[i]; + const { name, type, bytes } = files[i]; + const { classify, discard } = optsArr[i]; + if (!discard) yield new ProcessedFile(name, type, toAsyncIterable(bytes)); + if (classify) { + // Queues for the single inference slot: the conversion above is not repeated when busy. + const result = await classifyImage(bytes, classify, { + ...(signal ? { signal } : {}), + wait: true, + }); + yield { classification: { index: i, ...result } } satisfies InlineClassification; + } yield { progress: Math.round(((i + 1) / files.length) * 100) }; } }, signal); @@ -85,10 +105,9 @@ export const imageQueue = createQueue({ max: Number(process.env.IMAGE_QUEUE_SIZE ?? 100), }); -async function runSharp( - input: string | Buffer | Blob, - opts: ImageOptions[], -): Promise { +type OutputFile = { name: string; type: string; bytes: Buffer }; + +async function runSharp(input: string | Buffer | Blob, opts: ImageOptions[]): Promise { const sharpInstance = sharp(); void exhaustAsyncIterableToWritable(toSharpInput(input), sharpInstance); return Promise.all( @@ -127,8 +146,7 @@ async function runSharp( }); } s = s.toFormat(ext, { quality }); - const buf = await s.toBuffer(); - return new ProcessedFile(`file${idx + 1}.${ext}`, `image/${ext}`, toAsyncIterable(buf)); + return { name: `file${idx + 1}.${ext}`, type: `image/${ext}`, bytes: await s.toBuffer() }; }, ), ); diff --git a/packages/server/CHANGELOG.md b/packages/server/CHANGELOG.md index 158f7ab..cf3ec5f 100644 --- a/packages/server/CHANGELOG.md +++ b/packages/server/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to `@m4k/server` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `POST /images/process` validates and streams inline classifications and advertises `inline-classification/1`. + ## [0.2.13] ### Added diff --git a/packages/server/src/images/process-image-handler.spec.ts b/packages/server/src/images/process-image-handler.spec.ts index cb23ed8..d484515 100644 --- a/packages/server/src/images/process-image-handler.spec.ts +++ b/packages/server/src/images/process-image-handler.spec.ts @@ -3,6 +3,7 @@ import { streamParts } from "@sv2dev/multipart-stream"; import { describe, expect, it } from "bun:test"; import sharp from "sharp"; import { embeddedPreviewFixture } from "../../../../fixtures/embedded-preview.js"; +import { runClassificationScenario } from "../../../../fixtures/run-classification-scenario.js"; import { processImageHandler } from "./process-image-handler"; const fixture = Bun.file("../../fixtures/image.jpeg"); @@ -272,3 +273,56 @@ async function collectResponse(response: Response) { } return collected; } + +describe("/process with classification", () => { + const classify = { + classifierId: "clip-image-labels", + classifierVersion: "1", + labels: ["landscape", "receipt"], + }; + const post = (options: unknown) => + processImageHandler( + new Request("http://m4k/images/process", { + method: "POST", + body: fixture, + headers: { "X-Options": JSON.stringify(options) }, + }), + ); + + it("rejects classification of an output the classifier cannot read", async () => { + const options = { format: "avif", classify }; + + const response = await post(options); + + expect(response.status).toBe(400); + expect(await response.text()).toContain("jpeg, png or webp"); + }); + + it("rejects discarding without classification", async () => { + const options = { format: "jpeg", discard: true }; + + const response = await post(options); + + expect(response.status).toBe(400); + }); + + it("rejects an unsupported classifier before reading the input", async () => { + const options = { format: "jpeg", classify: { ...classify, labels: ["only-one"] } }; + + const response = await post(options); + + expect(response.status).toBe(400); + }); + + it("streams the classification and maps later files onto their own names after a discard", async () => { + const scenario = "handler-process"; + + const result = await runClassificationScenario(scenario); + + expect(result.status).toBe(200); + expect(result.body).toContain('"classification":{"index":0'); + expect(result.body).toContain('filename="keep.webp"'); + expect(result.body).not.toContain("file1.jpeg"); + expect(result.inferences).toBe(1); + }); +}); diff --git a/packages/server/src/images/process-image-handler.ts b/packages/server/src/images/process-image-handler.ts index a0063a3..176b092 100644 --- a/packages/server/src/images/process-image-handler.ts +++ b/packages/server/src/images/process-image-handler.ts @@ -1,4 +1,4 @@ -import type { RemoteImageOptions } from "@m4k/common"; +import { invalidInlineClassification, type RemoteImageOptions } from "@m4k/common"; import { imageOptionsSchema } from "@m4k/typebox"; import { Type as T } from "@sinclair/typebox"; import { TypeCompiler } from "@sinclair/typebox/compiler"; @@ -19,6 +19,10 @@ export async function processImageHandler(request: Request) { return error(400, (err as RangeError).message); } if (optsArr.length === 0) return error(400, "No options provided"); + const invalid = invalidInlineClassification(optsArr); + if (invalid) return error(400, invalid); + // Entries with `discard` produce no file part, so files map onto the remaining entries in order. + const emitting = optsArr.filter((opts) => !opts.discard); const iterable = processImage(request.body, optsArr, { signal: request.signal, @@ -29,7 +33,7 @@ export async function processImageHandler(request: Request) { let idx = 0; for await (const value of iterable) { if (value instanceof ProcessedFile) { - const { output, name } = optsArr[idx]; + const { output, name } = emitting[idx]; if (output) { const out = Bun.file(output); const writer = out.writer(); diff --git a/packages/server/src/server.ts b/packages/server/src/server.ts index bb3ab30..fc99666 100644 --- a/packages/server/src/server.ts +++ b/packages/server/src/server.ts @@ -1,6 +1,6 @@ import type { ServeOptions, Server } from "bun"; import { version } from "../package.json"; -import { imageClassifier } from "@m4k/common"; +import { imageClassifier, inlineClassificationProfile } from "@m4k/common"; import { classifyImageHandler } from "./images/classify-image-handler.js"; import { processAudioHandler } from "./audio/process-audio-handler.js"; import { processImageHandler } from "./images/process-image-handler.js"; @@ -32,7 +32,7 @@ const routes = { version, service: "m4k", classifiers: [imageClassifier], - imageProfiles: ["embedded-preview/1"], + imageProfiles: ["embedded-preview/1", inlineClassificationProfile], }), }, POST: { diff --git a/packages/typebox/CHANGELOG.md b/packages/typebox/CHANGELOG.md index 8f80593..a2c7a78 100644 --- a/packages/typebox/CHANGELOG.md +++ b/packages/typebox/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to `@m4k/typebox` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `classify` and `discard` in `imageOptionsSchema`. + ## [0.1.8] ### Added diff --git a/packages/typebox/src/index.ts b/packages/typebox/src/index.ts index d93337a..1356d00 100644 --- a/packages/typebox/src/index.ts +++ b/packages/typebox/src/index.ts @@ -30,6 +30,14 @@ const imageFormat = T.Union([ T.Literal("jp2"), ]); export const imageOptionsSchema = T.Object({ + classify: T.Optional( + T.Object({ + classifierId: T.String(), + classifierVersion: T.String(), + labels: T.Array(T.String()), + }), + ), + discard: T.Optional(T.Boolean()), embeddedPreview: T.Optional(T.Boolean()), rotate: T.Optional(T.Number()), resize: T.Optional( From 267e743d4d9ac8f15c0d838fe1ab58532c68d2b2 Mon Sep 17 00:00:00 2001 From: Sven Rogge Date: Thu, 5 Nov 2026 20:01:02 +0100 Subject: [PATCH 2/2] fix: bound inline classification and address review regressions --- README.md | 4 +- fixtures/classification-lifecycle.ts | 50 +++++++++-- packages/client/CHANGELOG.md | 4 + packages/client/src/client.ts | 11 +-- .../src/process-image-classification.spec.ts | 77 ++++++++++++++++- packages/client/src/read-json-response.ts | 7 +- packages/core/CHANGELOG.md | 4 + .../core/src/images/classify-image.spec.ts | 13 +++ packages/core/src/images/classify-image.ts | 43 ++-------- packages/core/src/images/image-processor.ts | 6 +- .../core/src/images/inference-slot.spec.ts | 83 +++++++++++++++++++ packages/core/src/images/inference-slot.ts | 35 ++++++++ .../src/images/process-image-handler.spec.ts | 20 ++++- 13 files changed, 306 insertions(+), 51 deletions(-) create mode 100644 packages/core/src/images/inference-slot.spec.ts create mode 100644 packages/core/src/images/inference-slot.ts diff --git a/README.md b/README.md index ec36259..2b43302 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,9 @@ The part is `{"classification": {"index": 0, "classifierId", "classifierVersion" `index` is the position of the producing entry in the options array, `sha256` is the hash of the classified output. Every classified entry needs an explicit `jpeg`, `png` or `webp` format within the classifier limits (8 MiB / 1,048,576 pixels), which is why a resize is usually appropriate. -Several entries (and their classifications) share one upload and one decode. Unlike the standalone +Several entries share one upload; each classified entry separately decodes its converted output. +Inline inference admits at most eight waiting callers; excess requests fail rather than retaining +unbounded preview buffers. Unlike the standalone endpoint, a classification queues for the single inference slot instead of failing with 429, because the conversion has already been done. There is no fallback: a failing classification ends the stream with an error. Servers advertise `inline-classification/1` in `imageProfiles`; the client requires it diff --git a/fixtures/classification-lifecycle.ts b/fixtures/classification-lifecycle.ts index 858604f..02ccce1 100644 --- a/fixtures/classification-lifecycle.ts +++ b/fixtures/classification-lifecycle.ts @@ -7,13 +7,30 @@ const loadStarted = Promise.withResolvers(); const pendingLoad = Promise.withResolvers(); const inferenceStarted = Promise.withResolvers(); const pendingInference = Promise.withResolvers(); +const waiterEntered = Promise.withResolvers(); +if (["process-wait", "queue-snapshot"].includes(scenario)) { + const { acquireInferenceSlot, releaseInferenceSlot } = + await import("../packages/core/src/images/inference-slot.ts"); + let admissions = 0; + mock.module("../packages/core/src/images/inference-slot.ts", () => ({ + acquireInferenceSlot: (wait: boolean, signal?: AbortSignal) => { + const admitted = acquireInferenceSlot(wait, signal); + if (++admissions === 2) waiterEntered.resolve(); + return admitted; + }, + releaseInferenceSlot, + })); +} let loads = 0; let inferences = 0; let pixels: object | undefined; async function infer(_image: unknown, labels: string[]) { inferences++; - if (["inference-abort", "process-wait"].includes(scenario) && inferences === 1) { + if ( + ["inference-abort", "process-wait", "queue-snapshot"].includes(scenario) && + inferences === 1 + ) { inferenceStarted.resolve(); await pendingInference.promise; } @@ -97,20 +114,43 @@ if (scenario === "process-inline" || scenario === "process-discard") { } else if (scenario === "process-wait") { const { processImage } = await import("../packages/core/src/images/image-processor.ts"); const run = () => - collect(processImage(new Blob([bytes], { type: "image/jpeg" }), { format: "jpeg", classify: options })!).then( + collect( + processImage(new Blob([bytes], { type: "image/jpeg" }), { + format: "jpeg", + classify: options, + })!, + ).then( (events) => ({ events }), (error: Error) => ({ error: error.message }), ); const first = run(); await inferenceStarted.promise; const second = run(); - // Let the second conversion finish and reach the occupied inference slot. - await Bun.sleep(300); + // The real slot has synchronously admitted the second request behind active inference. + await waiterEntered.promise; const inferencesWhileWaiting = inferences; pendingInference.resolve(); console.log( - JSON.stringify({ first: await first, second: await second, inferencesWhileWaiting, inferences }), + JSON.stringify({ + first: await first, + second: await second, + inferencesWhileWaiting, + inferences, + }), ); +} else if (scenario === "queue-snapshot") { + const { classifyImage } = await import("../packages/core/src/images/classify-image.ts"); + const first = classifyImage(bytes, options); + await inferenceStarted.promise; + const input = Uint8Array.from(bytes); + const requested = { ...options, labels: [...options.labels] }; + const second = classifyImage(input, requested, { wait: true }); + await waiterEntered.promise; + input.fill(0); + requested.labels.splice(0, requested.labels.length, "changed"); + pendingInference.resolve(); + await first; + console.log(JSON.stringify({ result: await second, expectedSha256, inferences })); } else if (scenario === "handler-success") { const { classifyImageHandler } = await import("../packages/server/src/images/classify-image-handler.ts"); diff --git a/packages/client/CHANGELOG.md b/packages/client/CHANGELOG.md index 5956bd6..73fa7a3 100644 --- a/packages/client/CHANGELOG.md +++ b/packages/client/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `processImage` accepts `classify`/`discard`, requires the `inline-classification/1` profile, validates every classification part and fails when one is missing. +### Fixed + +- Reject redirected classification uploads and bound streamed JSON control parts to 64 KiB before parsing. + ## [0.2.12] ### Added diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index aeb1883..d291127 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -14,7 +14,7 @@ import { type RemoteImageOptions, type RemoteVideoOptions, } from "@m4k/common"; -import { readJsonResponse } from "./read-json-response.js"; +import { readJsonParts, readJsonResponse } from "./read-json-response.js"; import { iterableToStream, streamParts } from "@sv2dev/multipart-stream"; /** @@ -121,6 +121,7 @@ export async function* processVideo( yield* runFetch(`${host}/videos/process`, input, opts, { signal }); } +/** Stream conversion results, rejecting redirects for pinned profiles and bounding JSON parts. */ async function* runFetch( url: string, input: AsyncIterable | Blob, @@ -128,12 +129,12 @@ async function* runFetch( { signal }: { signal?: AbortSignal } = {}, ) { signal?.throwIfAborted(); - const preview = (Array.isArray(opts) ? opts : [opts]).some( - (option) => option.embeddedPreview === true, + const pinned = (Array.isArray(opts) ? opts : [opts]).some( + (option) => option.embeddedPreview === true || !!option.classify, ); const res = await fetch( new Request(url, { - redirect: preview ? "error" : "follow", + redirect: pinned ? "error" : "follow", method: "POST", body: inputToStream(input), headers: { "X-Options": encodeOptions(opts) }, @@ -148,7 +149,7 @@ async function* runFetch( // Audio and video entries have no `classify`; this only guards image requests. for await (const part of streamParts(res)) { if (part.type === "application/json") { - const msg = (await part.json()) as + const msg = (await readJsonParts(part)) as | Progress | QueuePosition | ProcessingError diff --git a/packages/client/src/process-image-classification.spec.ts b/packages/client/src/process-image-classification.spec.ts index b0acb04..5c8455a 100644 --- a/packages/client/src/process-image-classification.spec.ts +++ b/packages/client/src/process-image-classification.spec.ts @@ -102,7 +102,13 @@ describe("processImage() with classification", () => { }); test("rejects a classification for candidates that were not requested", async () => { - const forged = { ...result(0), labels: [{ label: "dog", score: 1 }] }; + const forged = { + ...result(0), + labels: [ + { label: "dog", score: 0.75 }, + { label: "receipt", score: 0.25 }, + ], + }; const server = fakeServer({ parts: [{ json: { classification: forged } }] }); const error = await run(server.url.origin, { format: "jpeg", classify, discard: true }).then( @@ -129,6 +135,75 @@ describe("processImage() with classification", () => { expect(String(error)).toContain("Invalid classification response"); }); + test("bounds inline JSON before parsing an oversized classification", async () => { + const server = fakeServer({ + parts: [{ json: { classification: { ...result(0), padding: "x".repeat(65536) } } }], + }); + + const error = await run(server.url.origin, { format: "jpeg", classify, discard: true }) + .catch((error: unknown) => error) + .finally(() => server.stop(true)); + + expect(String(error)).toContain("exceeds 64 KiB"); + }); + + for (const status of [307, 308]) { + test(`refuses a ${status} redirect without forwarding classification bytes or options`, async () => { + let forwarded = 0; + const target = Bun.serve({ + port: 0, + fetch() { + forwarded++; + return new Response("unexpected"); + }, + }); + const server = Bun.serve({ + port: 0, + fetch(request) { + if (request.method === "GET") + return Response.json({ + service: "m4k", + classifiers: [imageClassifier], + imageProfiles: [inlineClassificationProfile], + }); + return Response.redirect(target.url, status); + }, + }); + + const error = await run(server.url.origin, { format: "jpeg", classify }) + .then( + () => null, + (error: unknown) => error, + ) + .finally(() => { + server.stop(true); + target.stop(true); + }); + + expect(error).toBeInstanceOf(Error); + expect(forwarded).toBe(0); + }); + } + + test("preserves redirects for ordinary conversions without a pinned profile", async () => { + const posts = { count: 0 }; + const target = fakeServer({ parts: ["converted.jpeg"], posts }); + const server = Bun.serve({ + port: 0, + fetch() { + return Response.redirect(target.url, 307); + }, + }); + + const events = await run(server.url.origin, { format: "jpeg" }).finally(() => { + server.stop(true); + target.stop(true); + }); + + expect(events).toEqual(["file:converted.jpeg"]); + expect(posts.count).toBe(1); + }); + test("refuses an avif output before contacting the server", async () => { const options = { format: "avif" as const, classify }; diff --git a/packages/client/src/read-json-response.ts b/packages/client/src/read-json-response.ts index c1c83ce..3d9f6ac 100644 --- a/packages/client/src/read-json-response.ts +++ b/packages/client/src/read-json-response.ts @@ -1,9 +1,14 @@ /** Capabilities and classifier annotations are bounded JSON, not media streams. */ export async function readJsonResponse(response: Response): Promise { if (!response.body) throw new Error("Empty M4K JSON response"); + return readJsonParts(response.body); +} + +/** Decode one bounded UTF-8 JSON control part without buffering an unbounded media stream. */ +export async function readJsonParts(parts: AsyncIterable): Promise { const chunks: Uint8Array[] = []; let size = 0; - for await (const chunk of response.body) { + for await (const chunk of parts) { size += chunk.byteLength; if (size > 65536) throw new Error("M4K JSON response exceeds 64 KiB"); chunks.push(chunk); diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index ef0d942..18fdb5e 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `processImage` classifies an entry's output right after conversion (`classify`, `discard`) and yields an `InlineClassification`; the inference slot can be awaited with `classifyImage(..., { wait: true })`. +### Fixed + +- Bound inference admission to eight waiting callers, support cancellation without losing the slot, and snapshot validated bytes/candidates before awaiting inference. + ## [0.3.7] ### Fixed diff --git a/packages/core/src/images/classify-image.spec.ts b/packages/core/src/images/classify-image.spec.ts index b976164..5012e24 100644 --- a/packages/core/src/images/classify-image.spec.ts +++ b/packages/core/src/images/classify-image.spec.ts @@ -68,6 +68,19 @@ describe("classifyImage lifecycle", () => { expect(result.events.filter((event: object) => "classification" in event)).toHaveLength(1); }); + test("snapshots validated bytes and candidates before waiting for inference", async () => { + const scenario = "queue-snapshot"; + + const result = await runClassificationScenario(scenario); + + expect(result.result.sha256).toBe(result.expectedSha256); + expect(result.result.labels.map((entry: { label: string }) => entry.label)).toEqual([ + "landscape", + "receipt", + ]); + expect(result.inferences).toBe(2); + }); + test("queues a second conversion for the inference slot instead of failing busy", async () => { const scenario = "process-wait"; diff --git a/packages/core/src/images/classify-image.ts b/packages/core/src/images/classify-image.ts index 5565ce5..1c0db5f 100644 --- a/packages/core/src/images/classify-image.ts +++ b/packages/core/src/images/classify-image.ts @@ -8,40 +8,9 @@ import { } from "@m4k/common"; import { waitForLoad } from "../util/wait-for-load.js"; +import { acquireInferenceSlot, releaseInferenceSlot } from "./inference-slot.js"; let classifier: Promise>> | undefined; -let busy = false; -/** Callers that chose to wait for the inference slot, in arrival order. */ -const waiting: (() => void)[] = []; - -/** Takes the single inference slot, or throws when it is taken and the caller does not wait. */ -async function acquire(wait: boolean, signal?: AbortSignal) { - signal?.throwIfAborted(); - if (!busy) { - busy = true; - return; - } - if (!wait) throw new Error("Classifier is busy"); - await new Promise((resolve, reject) => { - const turn = () => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }; - const onAbort = () => { - waiting.splice(waiting.indexOf(turn), 1); - reject(signal!.reason); - }; - waiting.push(turn); - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} - -/** Hands the slot to the next waiter, which keeps `busy` set, or frees it. */ -function release() { - const next = waiting.shift(); - if (next) next(); - else busy = false; -} async function loadClassifier() { const { env, pipeline } = await import("@huggingface/transformers"); env.cacheDir = process.env.M4K_MODEL_CACHE ?? `${process.env.M4K_TMP_DIR ?? "/tmp/m4k"}/models`; @@ -83,10 +52,12 @@ export async function classifyImage( throw new RangeError("Unsupported classifier configuration"); if (input.byteLength > imageClassifier.maxBytes) throw new RangeError("Classification preview exceeds byte limit"); - await acquire(wait, signal); + const admitted = acquireInferenceSlot(wait, signal); + const bytes = Uint8Array.from(input); + const candidates = [...options.labels]; + await admitted; try { - const bytes = Uint8Array.from(input); - const candidates = [...options.labels]; + signal?.throwIfAborted(); const { data, info } = await decodePreview(bytes); signal?.throwIfAborted(); const { RawImage } = await import("@huggingface/transformers"); @@ -112,6 +83,6 @@ export async function classifyImage( labels: labels as ClassificationResult["labels"], }; } finally { - release(); + releaseInferenceSlot(); } } diff --git a/packages/core/src/images/image-processor.ts b/packages/core/src/images/image-processor.ts index c6fef6d..78550fc 100644 --- a/packages/core/src/images/image-processor.ts +++ b/packages/core/src/images/image-processor.ts @@ -107,7 +107,11 @@ export const imageQueue = createQueue({ type OutputFile = { name: string; type: string; bytes: Buffer }; -async function runSharp(input: string | Buffer | Blob, opts: ImageOptions[]): Promise { +/** Convert sibling outputs and retain their exact encoded bytes for optional classification. */ +async function runSharp( + input: string | Buffer | Blob, + opts: ImageOptions[], +): Promise { const sharpInstance = sharp(); void exhaustAsyncIterableToWritable(toSharpInput(input), sharpInstance); return Promise.all( diff --git a/packages/core/src/images/inference-slot.spec.ts b/packages/core/src/images/inference-slot.spec.ts new file mode 100644 index 0000000..0ad994f --- /dev/null +++ b/packages/core/src/images/inference-slot.spec.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from "bun:test"; +import { + acquireInferenceSlot, + maxInferenceWaiters, + releaseInferenceSlot, +} from "./inference-slot.js"; + +describe("inference slot admission", () => { + test("bounds waiters, rejects overflow synchronously and drains admitted callers in order", async () => { + await acquireInferenceSlot(false); + const order: number[] = []; + const admitted = Array.from({ length: maxInferenceWaiters }, (_, i) => + acquireInferenceSlot(true).then(() => { + order.push(i); + }), + ); + let overflow: unknown; + + try { + acquireInferenceSlot(true); + } catch (error) { + overflow = error; + } + releaseInferenceSlot(); + for (const pending of admitted) { + await pending; + releaseInferenceSlot(); + } + await acquireInferenceSlot(false); + releaseInferenceSlot(); + + expect(String(overflow)).toContain("wait queue is full"); + expect(order).toEqual(Array.from({ length: maxInferenceWaiters }, (_, i) => i)); + }); + + test("cancelled waiters free capacity without stealing or releasing active inference", async () => { + await acquireInferenceSlot(false); + const controller = new AbortController(); + const cancelled = acquireInferenceSlot(true, controller.signal).then( + () => "unexpected", + (error: Error) => error.name, + ); + const admitted = Array.from({ length: maxInferenceWaiters - 1 }, () => + acquireInferenceSlot(true), + ); + let busy: unknown; + + controller.abort(); + const replacement = acquireInferenceSlot(true); + try { + acquireInferenceSlot(false); + } catch (error) { + busy = error; + } + const aborted = await cancelled; + releaseInferenceSlot(); + for (const pending of [...admitted, replacement]) { + await pending; + releaseInferenceSlot(); + } + await acquireInferenceSlot(false); + releaseInferenceSlot(); + + expect(aborted).toBe("AbortError"); + expect(String(busy)).toContain("Classifier is busy"); + }); + + test("rejects an already aborted request without acquiring the idle slot", async () => { + const controller = new AbortController(); + controller.abort(); + let rejected: unknown; + + try { + acquireInferenceSlot(true, controller.signal); + } catch (error) { + rejected = error; + } + await acquireInferenceSlot(false); + releaseInferenceSlot(); + + expect(rejected).toBeInstanceOf(DOMException); + }); +}); diff --git a/packages/core/src/images/inference-slot.ts b/packages/core/src/images/inference-slot.ts new file mode 100644 index 0000000..758cc44 --- /dev/null +++ b/packages/core/src/images/inference-slot.ts @@ -0,0 +1,35 @@ +/** At most 64 MiB of bounded preview snapshots may wait behind active inference. */ +export const maxInferenceWaiters = 8; +let busy = false; +const waiting: (() => void)[] = []; + +/** Reserve synchronously before callers copy their input; wait in FIFO order or reject admission. */ +export function acquireInferenceSlot(wait: boolean, signal?: AbortSignal): Promise { + signal?.throwIfAborted(); + if (!busy) { + busy = true; + return Promise.resolve(); + } + if (!wait) throw new Error("Classifier is busy"); + if (waiting.length >= maxInferenceWaiters) throw new Error("Classifier wait queue is full"); + return new Promise((resolve, reject) => { + const turn = () => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }; + const onAbort = () => { + const index = waiting.indexOf(turn); + if (index >= 0) waiting.splice(index, 1); + reject(signal!.reason); + }; + waiting.push(turn); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** Transfer ownership to the next admitted waiter, or mark inference idle. */ +export function releaseInferenceSlot() { + const next = waiting.shift(); + if (next) next(); + else busy = false; +} diff --git a/packages/server/src/images/process-image-handler.spec.ts b/packages/server/src/images/process-image-handler.spec.ts index d484515..af91b6e 100644 --- a/packages/server/src/images/process-image-handler.spec.ts +++ b/packages/server/src/images/process-image-handler.spec.ts @@ -308,10 +308,28 @@ describe("/process with classification", () => { it("rejects an unsupported classifier before reading the input", async () => { const options = { format: "jpeg", classify: { ...classify, labels: ["only-one"] } }; + let pulls = 0; + const body = new ReadableStream( + { + pull(controller) { + pulls++; + controller.enqueue(new Uint8Array([1])); + controller.close(); + }, + }, + { highWaterMark: 0 }, + ); + const request = new Request("http://m4k/images/process", { + method: "POST", + body, + headers: { "X-Options": JSON.stringify(options) }, + }); - const response = await post(options); + const response = await processImageHandler(request); expect(response.status).toBe(400); + expect(request.bodyUsed).toBe(false); + expect(pulls).toBe(0); }); it("streams the classification and maps later files onto their own names after a discard", async () => {