Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

perf(sprites): memoize the degenerate-frame probe on frame content (#6004)

Adam Eivye54f0de60096
diff --git a/server/lib/README.md b/server/lib/README.md
index 58d27d2276..772ced803d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -247,7 +247,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
| `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity); `createKeyedFileWriteQueue()` → `queueKeyedWrite(key, fn)` that collapses the pipeline stage stores' hand-rolled `Map` + per-key `createFileWriteQueue` factory (falsy keys → shared `'__unknown__'` tail; self-pruning via `createKeyCachedQueue`). |
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |
-| `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). |
+| `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). A **buffer** verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a **path** is never memoized (the file behind it can change), so hand it bytes you already read. `__resetFrameStatsCache()` drops the memo in tests. |
| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
diff --git a/server/lib/imageFrameStats.cache.test.js b/server/lib/imageFrameStats.cache.test.js
new file mode 100644
index 0000000000..e9b9782690
--- /dev/null
+++ b/server/lib/imageFrameStats.cache.test.js
@@ -0,0 +1,134 @@
+/**
+ * Content-addressed memo for `describeFrameStats` (issue #6004).
+ *
+ * A separate file from `imageFrameStats.test.js` — which pins the CLASSIFIER
+ * and builds every fixture with the real sharp — because counting decodes needs
+ * sharp wrapped for the whole module graph, and the classifier suite must keep
+ * measuring through the unwrapped one.
+ *
+ * The decode count is the point: `sharp().stats()` costs ~4ms regardless of
+ * pixel count (libvips pipeline setup, not pixels), and the sprite compiler
+ * re-probes the same frame bytes dozens of times per run. A regression here is
+ * invisible in behavior and only shows up as CI wall time, so it is asserted
+ * directly rather than left to a timing threshold.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const probe = vi.hoisted(() => ({ calls: 0 }));
+
+vi.mock('sharp', async (importOriginal) => {
+ const actual = await importOriginal();
+ const real = actual.default;
+ const counted = Object.assign((...args) => {
+ probe.calls += 1;
+ return real(...args);
+ }, real);
+ return { ...actual, default: counted };
+});
+
+const sharp = (await import('sharp')).default;
+const {
+ describeFrameStats, __resetFrameStatsCache, FRAME_REASON,
+} = await import('./imageFrameStats.js');
+
+const SIDE = 64;
+
+// Synthesized here; no binary fixture is committed and no image from the
+// running instance is ever read.
+const flatPng = (level) => sharp({
+ create: { width: SIDE, height: SIDE, channels: 3, background: { r: level, g: level, b: level } },
+}).png().toBuffer();
+
+const gradientPng = (offset = 0) => {
+ const raw = Buffer.alloc(SIDE * SIDE * 3);
+ for (let y = 0; y < SIDE; y++) {
+ for (let x = 0; x < SIDE; x++) {
+ const i = (y * SIDE + x) * 3;
+ raw[i] = (x * 4 + offset) % 256;
+ raw[i + 1] = (y * 4 + offset) % 256;
+ raw[i + 2] = ((x + y) * 2 + offset) % 256;
+ }
+ }
+ return sharp(raw, { raw: { width: SIDE, height: SIDE, channels: 3 } }).png().toBuffer();
+};
+
+beforeEach(() => {
+ __resetFrameStatsCache();
+ probe.calls = 0;
+});
+
+describe('describeFrameStats memo', () => {
+ it('decodes a buffer once and answers repeat probes from the memo', async () => {
+ const bytes = await gradientPng();
+ probe.calls = 0;
+
+ const first = await describeFrameStats(bytes);
+ const decodesForFirst = probe.calls;
+ const second = await describeFrameStats(bytes);
+
+ expect(first.ok).toBe(true);
+ expect(second).toEqual(first);
+ expect(decodesForFirst).toBeGreaterThan(0);
+ expect(probe.calls).toBe(decodesForFirst);
+ });
+
+ it('keys on content, not buffer identity — equal bytes hit, different bytes miss', async () => {
+ const bytes = await gradientPng();
+ const twin = Buffer.from(bytes);
+ const flat = await flatPng(90);
+ probe.calls = 0;
+
+ const original = await describeFrameStats(bytes);
+ const afterCopy = probe.calls;
+ const fromTwin = await describeFrameStats(twin);
+ const afterTwin = probe.calls;
+ const fromFlat = await describeFrameStats(flat);
+
+ expect(fromTwin).toEqual(original);
+ expect(afterTwin).toBe(afterCopy);
+ // A distinct image must not be answered by the memo: its verdict differs,
+ // which a key on length (or on identity) would get wrong.
+ expect(fromFlat.ok).toBe(false);
+ expect(fromFlat.reason).toBe(FRAME_REASON.SOLID_FILL);
+ expect(probe.calls).toBeGreaterThan(afterTwin);
+ });
+
+ it('never memoizes a PATH, whose file can change under the same key', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'frame-stats-memo-'));
+ const framePath = join(dir, 'frame.png');
+ writeFileSync(framePath, await flatPng(120));
+ // libvips keeps its own operation cache keyed on the file, which would
+ // answer the second read with the first image and hide whichever layer is
+ // actually re-measuring. Off for this test so the assertion is about OUR
+ // memo — and note libvips' cache is per-process and short-lived, unlike an
+ // hour-long path-keyed memo, which is why one is tolerable and the other
+ // would be a correctness bug.
+ sharp.cache(false);
+
+ const degenerate = await describeFrameStats(framePath);
+ writeFileSync(framePath, await gradientPng());
+ const rewritten = await describeFrameStats(framePath);
+
+ sharp.cache(true);
+ expect(degenerate.ok).toBe(false);
+ expect(rewritten.ok).toBe(true);
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('hands out a copy, so a caller mutating a verdict cannot poison the memo', async () => {
+ const bytes = await gradientPng(7);
+
+ const first = await describeFrameStats(bytes);
+ first.ok = false;
+ first.reason = 'tampered';
+ first.perChannel[0].stdev = -1;
+ const second = await describeFrameStats(bytes);
+
+ expect(second.ok).toBe(true);
+ expect(second.reason).toBeNull();
+ expect(second.perChannel[0].stdev).toBeGreaterThan(0);
+ });
+});
diff --git a/server/lib/imageFrameStats.js b/server/lib/imageFrameStats.js
index 01fa9a333b..dd44a19378 100644
--- a/server/lib/imageFrameStats.js
+++ b/server/lib/imageFrameStats.js
@@ -32,6 +32,8 @@
*/
import sharp from 'sharp';
+import { createHash } from 'crypto';
+import { createBoundedStateMap } from './boundedStateMap.js';
// Per-channel stdev, in 8-bit levels, under which a channel counts as flat.
// A genuinely flat fill reports exactly 0. Half of one 0-255 level is below
@@ -82,6 +84,40 @@ export const DEGENERATE_FRAME_REASONS = [
const result = (ok, reason, perChannel = null) => ({ ok, reason, perChannel });
+/**
+ * Content-addressed verdict memo (issue #6004).
+ *
+ * The verdict is a pure function of the encoded bytes, and `sharp().stats()` is
+ * a full decode plus a greyscale-histogram entropy pass — ~4 ms even for a 40x40
+ * frame, because the cost is libvips pipeline setup rather than pixel count.
+ * Sprite compiles re-probe the SAME bytes constantly: an eight-direction walk
+ * set re-verifies all 48 frames on every (idempotent) recompile, and a set whose
+ * directions share frame images probes each identical image eight times. Keying
+ * on the sha256 of the buffer makes the repeat probes free while keeping the
+ * verdict byte-exact.
+ *
+ * Buffers ONLY. A path string is not content — the file behind it can change
+ * between calls, so a path-keyed entry would answer for bytes it never saw.
+ * Hashing is worth it on a miss too: sha256 runs at GB/s, an order of magnitude
+ * under the decode it guards.
+ *
+ * `null` (could-not-measure) verdicts are cached the same way: undecodable bytes
+ * stay undecodable, and re-warning once per unique bad buffer is the signal —
+ * re-warning per call is noise.
+ */
+const verdictCache = createBoundedStateMap({ maxSize: 2000, ttlMs: 60 * 60 * 1000 });
+
+// Callers never mutate a verdict today; hand out a copy anyway so a cached entry
+// can't become shared mutable state the day one does.
+const copyVerdict = ({ ok, reason, perChannel }) => ({
+ ok,
+ reason,
+ perChannel: perChannel ? perChannel.map((channel) => ({ ...channel })) : null,
+});
+
+/** Test seam: drop every memoized verdict. */
+export const __resetFrameStatsCache = () => verdictCache.clear();
+
/**
* Classify a decoded image as having content or being degenerate.
*
@@ -89,6 +125,19 @@ const result = (ok, reason, perChannel = null) => ({ ok, reason, perChannel });
* @returns {Promise<{ ok: boolean|null, reason: string|null, perChannel: Array<{ mean: number, stdev: number, min: number, max: number }>|null }>}
*/
export async function describeFrameStats(input) {
+ const cacheKey = Buffer.isBuffer(input) && input.length
+ ? createHash('sha256').update(input).digest('hex')
+ : null;
+ if (cacheKey) {
+ const memo = verdictCache.get(cacheKey);
+ if (memo) return copyVerdict(memo);
+ }
+ const verdict = await measureFrameStats(input);
+ if (cacheKey) verdictCache.set(cacheKey, verdict);
+ return copyVerdict(verdict);
+}
+
+async function measureFrameStats(input) {
// One sharp instance per read — `metadata()` and `stats()` both consume the
// pipeline, so sharing an instance between them is not safe.
// Most callers run outside the Express request lifecycle (child-process
diff --git a/server/services/sprites/normalize.js b/server/services/sprites/normalize.js
index 04aaff7ca1..b837ebf0af 100644
--- a/server/services/sprites/normalize.js
+++ b/server/services/sprites/normalize.js
@@ -29,6 +29,7 @@
import sharp from 'sharp';
import { copyFile } from 'fs/promises';
+import { tryReadFile } from '../../lib/fileUtils.js';
import { hexToRgb, keyChannelSplit, keyShareFn } from './chromaKey.js';
import { describeFrameStats, isDegenerateFrame } from '../../lib/imageFrameStats.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -85,9 +86,17 @@ export async function assertFrameHasContent(src) {
}
export async function analyzeForeground(src, maskKeyHex) {
- await assertFrameHasContent(src);
+ // Read a path ONCE and hand the same bytes to the content gate and the decode
+ // it guards, the read-once-verify-in-memory seam the compiler already keeps
+ // (atlas.js): passing the path twice re-reads the file between the check and
+ // the use, and also defeats `describeFrameStats`'s content-addressed memo,
+ // which only keys on buffers (a path is not content). A read that fails falls
+ // through to the path unchanged so sharp still raises its own decode error —
+ // the existing INVALID_IMAGE surface, not a new ENOENT.
+ const source = Buffer.isBuffer(src) ? src : (await tryReadFile(src, null)) ?? src;
+ await assertFrameHasContent(source);
const key = hexToRgb(maskKeyHex);
- const { data, info } = await sharp(src)
+ const { data, info } = await sharp(source)
.flatten({ background: { r: 255, g: 255, b: 255 } })
.raw()
.toBuffer({ resolveWithObject: true });