Retry transient 503s and tolerate isolated unprocessable media during vectorization #28
Loading…
Reference in a new issue
No description provided.
Delete branch "fix/vectorize-error-tolerance"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary of Changes
This MR fixes the embedding generation failure observed in Job #94 (
Encoder returned HTTP 503; verify service and model cache), which caused the vectorize worker to fail and crash-loop indefinitely at media ID 364096.src/vector.ts):encoderRequestnow retries transient 503 and 429 status codes with bounded exponential backoff (up to 3 attempts), while honoring abort signals.scripts/encoder-server.py): Configuredslots.acquire(timeout=10)instead ofblocking=Falseso concurrent requests queue briefly rather than failing immediately. HandledOSError(and Pillow decode failures) as HTTP 422 rather than generic 503s.src/jobs.ts):vectorizeHandlercatches isolated per-file embedding failures, incrementsjobs.error_count, appends tocheckpoint.skipped_media(bounded at 20 entries), and advancescursor = row.idso a bad file does not permanently stall the batch. If 5 consecutive file errors occur, the job aborts with an error to prevent silently skipping the whole library when the encoder is down.Encoder model changed,invalid or non-normalised vectors,Index model changed) continue to fail immediately without advancing the cursor or deleting indexed work.tests/vectorize-error-tolerance.test.mjscovering all 3 behaviors (skip isolated failure, retry transient 503, abort on 5 consecutive failures), and updatedREQUIREMENTS-TRACE.mdunderSEARCH-01.2.7.1-dev2.Automated code review
Reviewed commit:
8f4b2eccb934856528610a26b8c6909f22de80ecVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The change adds a bounded 3-attempt retry for HTTP 503/429 in encoderRequest, reclassifies unprocessable encoder inputs as 422 and lets the server wait up to 10s for a slot, and makes vectorizeHandler tolerate isolated per-file embedding failures with a 5-consecutive-error abort while recording skips in the checkpoint. Version/CHANGELOG/package metadata are consistent (2.7.1-dev1 -> 2.7.1-dev2), and the new test file matches the
node --test tests/*.test.mjsglob in package.json. The substantive defects are in the new error-classification boundary: the server's 409 'model changed' response is now silently reclassified as an isolated file error (a behavior regression against the previous rethrow-everything path), and the consecutive-error abort counter is per-run only, so it resets on every resume. Secondary issues are retry scope (shared by user-facing routes), an unreachable branch in the new fetch catch, an unwrapped SQLite update, and an over-broad exception class moved into the permanent 422 bucket.Blocking findings
None.
Important findings
Server-side 409 'Encoder model changed' is now treated as an isolated per-file skip instead of a systemic failure (src/jobs.ts:924; high confidence)
scripts/encoder-server.py:136 responds
409 {'error': 'Encoder model changed; re-index required'}, but src/vector.ts:132 discards the body for any non-ok status and throws onlyEncoder returned HTTP ${response.status}; verify service and model cache. That text matches none of the whitelisted substrings at src/jobs.ts:924-926, so the new catch records the media in skippedMedia, increments error_count (src/jobs.ts:930), advancescursor = row.id(src/jobs.ts:935) and continues. The client-side guard that would produce a matching message (src/vector.ts:148 'Encoder model changed; re-index required') is unreachable for a 409 because encoderRequest throws before encode() inspects the body.Impact: A model swap mid-job, which previously failed the job immediately, now permanently skips up to four media per run and reports them as unprocessable, and the eventual abort message ('verify encoder service') misattributes a model change to a service fault. The checkpoint also stores
model_identity: model.identity(src/jobs.ts:899), so a later run considers the same model current and never re-attempts those skipped ids.Suggested fix: Preserve the encoder status/error body in encoderRequest (e.g. throw a typed error carrying
response.statusand the parsed error body) and classify systemic conditions in vectorizeHandler on that status/code rather than on free-text message substrings.Consecutive-error abort counter is not checkpointed, so the skip limit is per run and resets on every resume (src/jobs.ts:935; high confidence)
let consecutiveErrors = 0;(src/jobs.ts:896) is local to the handler run and is never written into the checkpoint:report(src/jobs.ts:897-900) emits only phase, last_media_id, model_identity, skipped_unsafe_files, skipped_media. The catch advancescursor = row.id(src/jobs.ts:935) past every failed row, and fetchBatch (src/jobs.ts:902-907) selectsWHERE v.media_id IS NULL AND ... m.id>?, so skipped rows below the restored cursor are never re-selected. src/worker.ts:246 restorespendingCheckpointfromcheckpoint_json, so each resumed run restarts the counter at 0 and can skip four more media before theconsecutiveErrors >= 5abort (src/jobs.ts:937) fires again.Impact: With an encoder that serves /metadata but fails /embed, repeated deliberate resumes skip four more media each time and can end with
phase: 'complete'(the batch loop exits when fetchBatch returns no rows) while a large share of the library is silently un-indexed for the current model - the coverage hazard the change states it is trying to prevent.Suggested fix: Persist the consecutive-error count (or a cumulative skip count) in the checkpoint alongside last_media_id and compare the restored value against the abort threshold, or re-queue ids recorded in skipped_media for a retry pass instead of only advancing the cursor.
Suggestions
Retry now applies to user-facing encoder routes, multiplying worst-case request latency (src/vector.ts:113; medium confidence)
maxAttempts = 3is inside encoderRequest, which is shared by encode/embedImage and by encoderMetadata/embedTextQuery. src/app.ts:960-962 (GET /api/media/search-by-text) callsawait encoderMetadata()andawait embedTextQuery(qs.q, model)with no signal, so the retry guard!signal?.abortedat src/vector.ts:128 is true and each attempt re-creates a freshREVIEW_V2_EMBED_TIMEOUT_MSdeadline (default 120000, src/vector.ts:111/116). The route's documented 503 response (src/app.ts:966) is only reached after up to three sequential attempts plus backoff.Impact: A busy or down encoder makes the browser text-search path hang for minutes instead of returning the documented 503; the retry appears intended for the vectorize worker path only.
Suggested fix: Scope retries to the vectorize call path (an opt-in retry parameter) or enforce a total retry/timeout budget shared across attempts rather than a fresh per-attempt deadline.
Dead branch in the new fetch catch: transport-level failures are never retried (src/vector.ts:125; medium confidence)
The new catch is
catch (err) { if (signal?.aborted) throw err; throw err; }- both branches behave identically, so the catch block only re-throws. The retry condition at src/vector.ts:128 covers only status codes 503/429, so an aborted fetch (per-attempt deadline expiry or socket failure) still fails the call on the first attempt.Impact: The stated goal of retrying transient encoder unavailability is implemented only for explicit 503/429 responses; the equally transient connection-abort and timeout paths remain single-shot, and the duplicated throw suggests an unintended condition.
Suggested fix: Remove the duplicated throw and decide explicitly whether fetch-level aborts other than the caller's
signalshould consume a retry attempt; if so, retry them under the sameattempt < maxAttemptsbound.error_count update is not guarded against SQLite contention, unlike the equivalent purge path (src/jobs.ts:930; medium confidence)
The new failure path runs
UPDATE jobs SET error_count = error_count + 1 WHERE id = ?directly (src/jobs.ts:930), whereas the analogous per-file failure path in the purge handler wraps the same statement inretrySqliteBusy(src/jobs.ts:637, imported at src/jobs.ts:13). Multi-worker concurrency is a documented configuration (REVIEW_V2_WORKER_CONCURRENCY).Impact: A SQLITE_BUSY raised while recording a tolerated per-file failure propagates out of the new catch and fails the whole vectorize job instead of tolerating the isolated un-vectorizable media.
Suggested fix: Wrap the error_count update (and the surrounding skip bookkeeping) in
retrySqliteBusyas the purge handler does.OSError is folded into the permanent 422 'unprocessable input' class (scripts/encoder-server.py:140; medium confidence)
The changed handler maps
(ValueError, KeyError, TypeError, OSError)to422 {'error': 'Invalid or unprocessable embedding input'}(scripts/encoder-server.py:140-141). The client never retries 422 (only 503/429 at src/vector.ts:128) and vectorizeHandler records it as a skipped media while advancing the cursor (src/jobs.ts:930-935). OSError covers service-level I/O faults (model-cache reads, asset reads, transient disk errors), not only input-decoding failures.Impact: A service-level I/O fault is reported as bad media, so the affected files are permanently skipped for the current model rather than retried or reported as a service outage under the 503 branch (scripts/encoder-server.py:143).
Suggested fix: Narrow the 422 mapping to input-decoding exceptions (e.g. explicit ValueError on decode plus PIL.UnidentifiedImageError) and leave generic OSError in the 503 'service failure' branch so it remains retryable.
Tests and validation
Questions
Review limitations
node --test tests/*.test.mjsglob in package.json.Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Review Feedback Resolution
All feedback from the automated code review has been implemented and validated:
Server-side 409 'Encoder model changed' systemic failure:
EncoderErrorcarryingstatusand parsed error body.vectorizeHandlercheckserror instanceof EncoderError && error.status === 409(in addition to message matching) and immediately rethrows without advancing the cursor or recording skipped media.server-side 409 model changed aborts immediately without advancing cursor or recording skipverifyinglast_media_idremains 0, error count is not incremented, and no skips are recorded.Checkpointed consecutive-error abort counter:
consecutive_errors: consecutiveErrorsin the job checkpoint emitted byreportProgressand restored it upon resuming an interrupted run with the same model.consecutive_errors is retained across checkpoint resumesverifying an interrupted run resuming with 4 previous consecutive errors immediately aborts upon the next failure.Scoped retries for background worker vs interactive queries:
encoderRequestaccepts{ retries?: number }, defaulting to0so user-facing text search queries fail fast with 503.embedImageexplicitly specifies{ retries: 2 }(3 attempts total with exponential backoff).Cleaned fetch error handling:
if (signal?.aborted) throw err; throw err;and retried transient network-level fetch failures across attempts when!signal?.aborted.Contention safety for error_count update:
UPDATE jobs SET error_count = error_count + 1 WHERE id = ?inretrySqliteBusy, matching the purge worker pattern.Narrowed 422 error classification in encoder server:
scripts/encoder-server.pynow maps only(ValueError, KeyError, TypeError)and PillowUnidentifiedImageErrorto HTTP 422, leaving generalOSError(I/O, memory, GPU runtime faults) to fall through to HTTP 503.Validation Evidence
tests/vectorize-error-tolerance.test.mjs: all 5 tests passed.tests/vectorize-pipeline.test.mjs: all 10 tests passed.npm test: all 223 tests passed.python3 -B -m unittest discover -s tests: all 60 tests passed.nix build --no-link --print-build-logs .#redview: passed.2.7.1-dev3viapython3 scripts/version.py bump fix.Automated code review
Reviewed commit:
67a22cf8a02611aa483b1a548439394057b53decVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Validated the initial review against the checked-out code. One blocking defect is confirmed: the new per-file error_count update in src/jobs.ts:932 calls the async retrySqliteBusy helper without await, while every other call site in the repository awaits it. Two behavioural consequences of the change are confirmed by supplied evidence: exhausted 503/429 retries are routed through the same permanent-skip path as unprocessable media (the cursor-based batch query makes those media unreachable again), and the server's validate_embedding ValueErrors are now mapped to 422 and therefore take the per-file skip path instead of the systemic failure path. One minor resource concern (abort listeners accumulating on the long-lived job signal across retries) is retained as a suggestion. Line numbers from the initial review were corrected against the checked-out files.
Blocking findings
src/jobs.ts:932 is
retrySqliteBusy(() => ctx.db.prepare('UPDATE jobs SET error_count = error_count + 1 WHERE id = ?').run(ctx.jobId));with noawait.retrySqliteBusyisexport async function retrySqliteBusy<T>(operation: () => T): Promise<T>(src/sqlite-contention.ts:11) and rethrows after 4 bounded retries when the error is not SQLITE_BUSY. Every other call site awaits it (src/jobs.ts:546, 627, 637, 675, 676; src/worker.ts:67, 103, 300, 303, 308, 309). The promise returned at 932 is discarded.Impact: In the un-contended case the operation still runs synchronously before the first await, which is why tests/vectorize-error-tolerance.test.mjs observes error_count = 1; under SQLITE_BUSY the retry awaits, the update is abandoned, and a rejection becomes an unhandled rejection that terminates the worker process — reintroducing the crash-loop behaviour this MR is meant to remove, and understating the job's error_count for the skipped media.
Suggested fix: Await the call (
await retrySqliteBusy(...)) to match the established pattern, or wrap it in a try/catch if a lost error_count update should be non-fatal. The new test suite does not exercise the SQLITE_BUSY path for this call site, so it cannot catch this defect.Important findings
The failure handler sets
cursor = row.id(src/jobs.ts:937) andcontinues. The batch query at src/jobs.ts:907 selects... LEFT JOIN vec_media v ... WHERE v.media_id IS NULL AND m.is_video=0 AND m.id>? ORDER BY m.id, so a media row below the new cursor is never offered again for the same model identity. This path is reached afterembedImageexhausts its retries ({ retries: 2 }, src/vector.ts:200) on 503/429, which the server emits for ordinary contention (self.respond(503, {'error': 'Encoder busy'})afterslots.acquire(timeout=10), scripts/encoder-server.py) rather than for an unprocessable file (422).Impact: Media that failed only because the service was momentarily busy or unavailable are recorded in
skipped_mediaand left un-indexed for the rest of the run; the 5-consecutive guard only catches a wholly dead encoder, not intermittent contention, so a job can report 'complete' while leaving scattered gaps in the index.Suggested fix: Distinguish the two conditions the server already distinguishes: treat 422 (and client-side decode/size errors) as the permanent skip, and on exhausted 503/429 either fail/pause without advancing the cursor, or record the media id for a later retry pass.
Suggestions
Server-side embedding validation failures are reclassified from systemic to per-file skips (scripts/encoder-server.py:140; medium confidence)
validate_embeddingraisesValueError('Invalid embedding dimensions or values')andValueError('Embedding must have unit length')(scripts/encoder-server.py:39-42) for a systemic model-output defect. The broadened handlerexcept (ValueError, KeyError, TypeError) as exc: self.respond(422, ...)(scripts/encoder-server.py:140) routes those through the client's isolated-failure branch, since src/jobs.ts:925-928 treats onlyEncoder model changed,invalid or non-normalisedandIndex model changedas systemic. The client's own equivalent check throwsEncoder returned invalid or non-normalised vectors(src/vector.ts:186), which is systemic — the same invariant is now systemic client-side and per-file server-side.Impact: A degraded encoder producing non-unit-length or wrong-dimension vectors would skip up to 5 media permanently (cursor advanced, error_count incremented) before the consecutive-error guard aborts, weakening the stated requirement that systemic model invariants fail immediately without advancing the cursor.
Suggested fix: Return a distinct status (e.g. 500/503) for
validate_embeddingfailures, or keep them out of the 422 mapping, so they remain systemic rather than per-file skips.Abort listeners accumulate on the long-lived job signal during retries (src/vector.ts:103; medium confidence)
sleepperformssignal?.addEventListener('abort', ..., { once: true })(src/vector.ts:101-105) and is called once per retry attempt (src/vector.ts:142, 148). Thesignalpassed throughembedImageis the per-jobctx.signal(src/worker.ts passescontroller.signal), which lives for the whole library run; aonce: truelistener is only removed when the abort actually fires.Impact: For a full-library vectorization with many transient 503s, listeners (each retaining its
timerclosure) accumulate on the same AbortSignal for the duration of the job, growing with retry count.Suggested fix: Remove the listener explicitly after the sleep resolves (
const listener = () => ...; try { await ... } finally { signal?.removeEventListener('abort', listener) }), or implement the delay withnode:timers/promisesas src/sqlite-contention.ts does.Tests and validation
Questions
UnidentifiedImageErrorby class name (scripts/encoder-server.py:143); a generic OSError (e.g. Pillow's 'image file is truncated') still falls through to the 503 branch and therefore takes the 3-attempt retry path before being skipped. Was broad OSError handling intended and left unimplemented?Review limitations
nix build --no-link --print-build-logs .#redviewpackage check, which does not demonstrate the new test outcomes.Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Review Round 2 Feedback Resolution
All items from the second automated review have been resolved and verified:
Awaited
retrySqliteBusyin vectorize skip path:await retrySqliteBusy(() => ctx.db.prepare('UPDATE jobs SET error_count = error_count + 1 WHERE id = ?').run(ctx.jobId));insrc/jobs.tssoSQLITE_BUSYcontention is properly retried and never results in an unhandled promise rejection.Distinguished exhausted 503/429 service outage from isolated file skips:
vectorizeHandler, if anEncoderErrorwith HTTP 503 or 429 persists after exhausting retries, it is treated as a service outage and rethrown immediately without advancingcursor = row.idor recording media skips.exhausted 503 from encoder fails the job immediately without advancing cursor or recording skipverifying thatlast_media_idremains 0 and no skips are recorded.Preserved systemic failure on server-side embedding validation:
scripts/encoder-server.py,validate_embeddingfailures (Invalid embedding dimensions or values,Embedding must have unit length) now return HTTP 503 rather than 422, ensuring degraded model output remains a systemic failure rather than a per-file skip.Prevented AbortSignal listener accumulation:
src/vector.ts,sleepremoves itsabortevent listener when the timer fires so listeners do not accumulate on the long-lived job signal across retries.Validation Evidence
tests/vectorize-error-tolerance.test.mjs: all 6 tests passed.tests/vectorize-pipeline.test.mjs: all 10 tests passed.npm test: all 224 tests passed.python3 -B -m unittest discover -s tests: all 60 tests passed.nix build --no-link --print-build-logs .#redview: passed.2.7.1-dev4viapython3 scripts/version.py bump fix.Automated code review
Reviewed commit:
1392bf572f49f35a1a258a2f47a6a0f3b94deb76Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The change set is internally consistent: VERSION, package.json and CHANGELOG all move to 2.7.1-dev4, the SEARCH-01 trace row cites the new files, and the new test file matches the
node --test tests/*.test.mjsglob in package.json. The classification logic added to vectorizeHandler and encoderRequest matches the trace text for the HTTP cases the six tests exercise (422 skip, transient 503/429 retry, exhausted 503/409 systemic, consecutive-error abort, consecutive_errors resume). Two gaps are demonstrable from the supplied code: (1) failures that never carry an HTTP status — transport errors and the per-attempt REVIEW_V2_EMBED_TIMEOUT_MS abort — are rethrown raw by encoderRequest and therefore fall into the new tolerant per-file branch, which increments error_count and permanently advances the cursor past media that failed only because the encoder was unreachable; (2) the server's 422 branch keys on an exact exception class-name string, so any other Pillow decode exception type returns 503 and is treated as systemic. A third, lower-severity point is that the retry loop retries every fetch failure and restarts a full per-attempt deadline, tripling the worst-case per-image cost. I did not run the tests or the encoder, so the trace's claim that all six cases pass is unverified here.Blocking findings
None.
Important findings
src/vector.ts:140-148 rethrows the raw fetch error when retries are exhausted (
throw err;), and src/vector.ts:134 creates a fresh AbortSignal.timeout deadline per attempt, so an unreachable encoder (ECONNREFUSED/'fetch failed') or a per-attempt timeout abort is a plain error, not an EncoderError and its message contains no 'HTTP 503'/'HTTP 429'. The new classification at src/jobs.ts:924-933 only rethrows for EncoderError status 409/503/429 or those literal message substrings, so such errors fall through to src/jobs.ts:934-943, which increments jobs.error_count, records skipped_media, setscursor = row.idand continues. fetchBatch (src/jobs.ts:903-908) selects onlym.id>?over that cursor, so those media are never revisited on a later resume. The six cases in tests/vectorize-error-tolerance.test.mjs all drive the mock service with HTTP statuses (422, 503, 409); none exercises a connection-level failure.Impact: With the encoder service down or an image exceeding REVIEW_V2_EMBED_TIMEOUT_MS, the job now silently skips media and advances the cursor past them (bounded by the 5-consecutive-error abort at src/jobs.ts:941) instead of failing without cursor movement. After the service recovers, those rows are permanently excluded from vec_media and never re-indexed, which is the outage behavior this change is meant to survive.
Suggested fix: Restrict the tolerant skip path to responses that actually carry an unprocessable-media status (e.g. EncoderError with status 422/413), and treat errors with no HTTP status as systemic: wrap fetch failures and deadline aborts in EncoderError with a distinct sentinel status in encoderRequest, or rethrow anything that is not an EncoderError, so the cursor is not advanced past media that failed only because the service was unreachable.
Suggestions
Server 422 classification keys on an exact exception class-name string (scripts/encoder-server.py:146; medium confidence)
The new handler branches on
exc.__class__.__name__ == 'UnidentifiedImageError'(scripts/encoder-server.py:146) and otherwise responds 503 with 'Encoder inference failed; inspect server runtime' (line 148). Encoder.encode (scripts/encoder-server.py:78-84) obtains images viaImage.open(...)andoriginal.convert('RGB'), so any decode failure whose type is not exactly the base UnidentifiedImageError class name reaches the 503 branch. jobs.ts:925 then treats 503 as systemic and rethrows without advancing the cursor.Impact: A single corrupt or truncated image whose decode failure is reported as anything other than the exact base class (a subclass name, or a plain OSError) returns 503, so the vectorize job fails and stalls at the same cursor on every resume rather than being recorded as an isolated skip.
Suggested fix: Test the exception structurally rather than by name, e.g.
from PIL import UnidentifiedImageErrorandisinstance(exc, UnidentifiedImageError)for the 422 branch, keeping genuine inference/runtime faults (RuntimeError, torch errors) in the 503 branch.Retry loop retries every fetch failure and restarts the full per-attempt timeout (src/vector.ts:145; medium confidence)
The fetch catch retries any thrown error (
if (attempt < maxAttempts) { await sleep(attempt * 100, signal); continue; }, src/vector.ts:145-147), not only 503/429, and a freshAbortSignal.timeout(...)deadline is created inside the attempt loop (src/vector.ts:134). embedImage passes{ retries: 2 }(src/vector.ts:204), so a hung or persistently slow encoder costs up to 3 x REVIEW_V2_EMBED_TIMEOUT_MS (6 minutes at the 120000 ms default) plus backoff per image before the media is skipped or the consecutive-error abort fires.Impact: The worst case for a failing vectorize batch is materially longer than before (three full timeouts per image), and permanent connection errors such as ECONNREFUSED/ENOTFOUND are retried even though they are not transient.
Suggested fix: Limit retries to transient conditions (HTTP 503/429 and explicitly retryable connection errors) and bound total retry elapsed time with a shared deadline or cumulative budget instead of restarting the full per-attempt timeout.
Tests and validation
Questions
Review limitations
ps.pillow), so the exception types Pillow raises for corrupt or truncated images are inferred rather than observed in supplied material; finding 2's mechanism is evidenced in the diff, its trigger conditions are not.Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Response to Review Round 3 (Addressing commit
1392bf5->ebed715)All findings from the latest review round have been addressed:
Restrict per-file skips to unprocessable media and fs errors (Important Finding):
src/jobs.ts, invertedvectorizeHandlererror handling from a blacklist to an explicit whitelist of isolated file errors:ECONNREFUSED, timeouts, 503/429/409, and vector validation errors are rethrown immediately without advancingcursoror recording inskipped_media.src/vector.ts, network drops and timeout aborts are wrapped inEncoderError(..., 503).tests/vectorize-error-tolerance.test.mjsverifying that connection refused / transport drops fail immediately with no cursor advance, zerojobs.error_count, and no skip recorded.Server-side Image decode error classification (Suggestion):
scripts/encoder-server.py, wrappeddata = base64.b64decode(...)andImage.open(...)insideencode()to raiseValueError(f'Invalid or unprocessable image: {exc}'), which maps to 422 indo_POST.exc.__class__.__name__ == 'UnidentifiedImageError'withisinstance(exc, IMAGE_DECODE_ERRORS)containing(UnidentifiedImageError, DecompressionBombError, OSError)with safe fallback when PIL is not loaded.test_image_decode_errors_includes_pil_exceptionsintests/test_encoder_server.py.Shared timeout budget across retries (Suggestion):
src/vector.ts, moved deadline instantiationconst deadline = AbortSignal.timeout(timeout)outside the retry loop inencoderRequest, ensuring the 3 retry attempts share the overall timeout budget rather than multiplying it.Test Evidence
nix develop --command node tests/vectorize-error-tolerance.test.mjs: 7/7 passed.nix develop --command python3 -B -m unittest discover -s tests: 61/61 passed.nix develop --command npm test: 225/225 passed.nix build --no-link --print-build-logs .#redview: passed cleanly.2.7.1-dev5viascripts/version.py bump fixand refreshed OpenAPI spec.Automated code review
Reviewed commit:
ebed7154c2e3fa70f0799c7c197c547a33d62f7cVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Re-validated the initial review against the checked-out head state. Four findings survive: (1) the encoder server's new
except Exception/isinstance(exc, IMAGE_DECODE_ERRORS)branch cannot catch image-decode failures (Encoder.encode re-raises them as ValueError and the earlier clause already handles them), so its only real effect is to map inference-time OSError to HTTP 422, which src/jobs.ts treats as a permanent per-file skip that advances the cursor; (2) thegetattr(Image, 'DecompressionBombError', ())fallback embeds a non-type in the isinstance tuple; (3) the new 'network transport failure' test fails at/metadata(retries 0) and never exercises the embedImage retry/skip path it names; (4) the SEARCH-01 trace row states 'all 6 cases' while the supplied test file defines 7test(...)cases and attributes the behaviour to 2.7.1-dev4 while VERSION/package.json/CHANGELOG are at 2.7.1-dev5. Version metadata is self-consistent (VERSION, package.json, CHANGELOG head all read 2.7.1-dev5, afixincrement per AGENTS.md). The retry path is bounded (3 attempts, shared deadline, abort-aware sleep) and text queries remain fast-fail; 409, invalid-vector and transport failures still throw systemically without advancing the cursor.Blocking findings
None.
Important findings
Encoder.encode (lines 87-88) already converts every image-decode failure into
ValueError('Invalid or unprocessable image: ...'), which is handled by the earlier clause at lines 151-155; therefore the newexcept Exception as exc: if IMAGE_DECODE_ERRORS and isinstance(exc, IMAGE_DECODE_ERRORS): self.respond(422, ...)at lines 156-159 is only reachable for exceptions raised bymodel.encode/inference. IMAGE_DECODE_ERRORS (line 28) includes bareOSError, so an OSError raised during inference is answered 422. src/jobs.ts:924 classifieserror instanceof EncoderError && error.status === 422asisFileError, then incrementserror_count, records the skip and setscursor = row.id(line 936); the batch query at src/jobs.ts:907 selects onlym.id>?, so that media is never offered again.Impact: A service-level fault surfacing as OSError during inference is reported as 'Invalid or unprocessable embedding input' and silently drops media from the index instead of failing the job; because the cursor advances, those media are never re-attempted after the service is repaired. The sibling clause at line 151 also selects 503 vs 422 by substring matching on the message, so a decode failure whose wrapped text contains 'embedding' would be reported as 503 and abort the job instead.
Suggested fix: Classify by provenance, not by message text or an OSError-inclusive isinstance tuple: keep the outer
except Exceptionhandler at 503, and have the decode wrapper raise a dedicated marker type (e.g.UnprocessableInput) that the handler maps to 422; keepvalidate_embeddingfailures at 503.Suggestions
IMAGE_DECODE_ERRORS fallback embeds a tuple element, making isinstance raise TypeError (scripts/encoder-server.py:28; medium confidence)
IMAGE_DECODE_ERRORS = (UnidentifiedImageError, getattr(Image, 'DecompressionBombError', ()), OSError)- if Pillow lacksImage.DecompressionBombError, the default()becomes an element of the tuple, soisinstance(exc, IMAGE_DECODE_ERRORS)at line 157 raisesTypeErrorinside the exception handler, leaving the request with no HTTP response. The added test in tests/test_encoder_server.py only asserts the tuple is truthy and thatUnidentifiedImageErroris a member, so it would still pass in that configuration.Impact: Latent handler crash instead of a clean 503/422 response on a Pillow version without that attribute; the new test does not cover the fallback shape.
Suggested fix: Build the tuple conditionally, e.g.
bomb = getattr(Image, 'DecompressionBombError', None); IMAGE_DECODE_ERRORS = tuple(t for t in (UnidentifiedImageError, bomb, OSError) if isinstance(t, type)), and assert every element is a type in the test.The 'network transport failure' test never reaches embedImage, so it does not exercise the behaviour it names (tests/vectorize-error-tolerance.test.mjs:302; high confidence)
The fixture points REVIEW_V2_ENCODER_URL at a port with no listener, and vectorizeHandler calls
await encoderMetadata(ctx.signal)before any embed request (src/jobs.ts:881), so the first/metadatafetch fails and encoderRequest (retries 0) throwsEncoder request failed. The assertions oncheckpoint.last_media_id,error_countandskipped_mediatherefore restate the initial state; theretries: 2path in embedImage (src/vector.ts:216) and theisFileErrordecision at src/jobs.ts:924 are not exercised.Impact: A regression that turned an embedImage transport drop into a per-file skip, or that advanced the cursor on a transport drop, would not be caught by this suite despite its title.
Suggested fix: Serve a working
/metadatahandler (as the other cases do via createEncoderService) and make only the/embedconnection fail, so the test exercises the retry-then-systemic path for embedImage.SEARCH-01 trace row undercounts the new suite and attributes the behaviour to an earlier dev version (REQUIREMENTS-TRACE.md:60; high confidence)
The updated SEARCH-01 row states 'Focused regression in tests/vectorize-error-tolerance.test.mjs passes all 6 cases', but the supplied file defines 7
test(...)cases (lines 51, 105, 151, 191, 230, 269, 302). The row attributes the behaviour to '2.7.1-dev4', while VERSION and package.json are at 2.7.1-dev5 and CHANGELOG.md's head entry describes the dev5 change ('whitelist isolated file errors for skips, treat transport and service failures as systemic, and share timeout budget'), which is not described in the row. The file header (line 17) states 'Update a row when code or evidence changes.'Impact: The acceptance-evidence entry understates what is covered and leaves the head change untraced, so the review record does not match the code supplied with this change.
Suggested fix: Update the row to the head version (2.7.1-dev5), state the actual case count, and describe the transport/systemic classification and shared timeout budget the head change introduces.
Tests and validation
Questions
error_counthas already been incremented once per skipped file (src/jobs.ts:931) and the worker's failJob adds one more on the throw (src/worker.ts:326) - is the extra increment intended, or should the aborting throw avoid double counting?cursor = row.id(src/jobs.ts:936) and the batch filterm.id>?(src/jobs.ts:907), a 422 skip is permanent for the current index model, which is why the service-fault misclassification in encoder-server.py becomes silent data loss.slots.acquire(timeout=10)(scripts/encoder-server.py:135) sized against the client budget? Withretries: 2(src/vector.ts:216) and the default REVIEW_V2_EMBED_TIMEOUT_MS of 120000, three attempts can each wait up to 10s at the server while multiple workers contend for the 8 slots.Review limitations
Image.DecompressionBombError) and the runtime exception types actually raised by the torch/sentence-transformers inference path were not observable from the supplied material, so findings 1 and 2 rest on the code shape rather than an observed failure.Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Response to Review Round 4 (Addressing commit
ebed715->95095e5)All findings from the latest review round have been addressed:
Provenance-based input classification (
scripts/encoder-server.py) (Important Finding):UnprocessableMediaError(Exception)dedicated marker type.Encoder.encode(), decoding exceptions (corrupt images, unsupported formats, decompression bombs, invalid base64, invalid query text) raiseUnprocessableMediaError.Handler.do_POST(), onlyUnprocessableMediaErroris mapped to HTTP 422.torch, CUDA faults,validate_embeddingfailures, inference-timeOSError) fall intoexcept Exceptionand respond HTTP 503 as systemic failures, preventing silent media drops from inference faults.IMAGE_DECODE_ERRORStuple and itsgetattr(Image, 'DecompressionBombError', ())fallback entirely.Exercising embedImage transport failure (
tests/vectorize-error-tolerance.test.mjs) (Suggestion):network transport failure on embedImagetest to serve a working/metadataendpoint viacreateEncoderService, destroying the socket only on/embed.embedImage's 3-attempt retry loop with backoff, wrapping intoEncoderError(..., 503), andvectorizeHandler's whitelist check rethrowing systemically without advancing cursor or recording skips.Updated REQUIREMENTS-TRACE.md (Suggestion):
2.7.1-dev6, all 7 passing cases intests/vectorize-error-tolerance.test.mjs, and documented the provenance-basedUnprocessableMediaErrorand systemic transport classification.Test Evidence
nix develop --command node tests/vectorize-error-tolerance.test.mjs: 7/7 passed.nix develop --command python3 -B -m unittest discover -s tests: 61/61 passed.nix develop --command npm test: 225/225 passed.nix build --no-link --print-build-logs .#redview: passed cleanly.2.7.1-dev6viascripts/version.py bump fixand refreshed OpenAPI spec.Automated code review
Reviewed commit:
95095e5958fdb415b68ce9babc9f15d42fb05047Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The supplied changes are internally consistent with their stated goal: encoderRequest gains a bounded retry loop for 503/429 and transport failures, encoder-server.py separates unprocessable input (422) from inference faults (503), and vectorizeHandler whitelists per-file failures while keeping model/transport failures systemic. Four concrete issues are visible in the changed files: the 5-consecutive-error guard aborts after the cursor has already been advanced past the failing files (so a resumed job never re-embeds them), HTTP 400 is whitelisted as a per-file skip although the server uses 400 only for request/protocol faults rather than unprocessable media, the job-start encoderMetadata call is not covered by the retry path, and the consecutive-error counter is neither reset by unsafe-file skips nor reconciled with the worker's own error_count increment. Retry coverage is narrower than the trace wording implies (metadata and text queries are not retried; the delay is linear 100/200 ms).
Blocking findings
None.
Important findings
The 5-consecutive-error abort commits the cursor past files that were never successfully embedded (src/jobs.ts:936; high confidence)
In the new catch block,
cursor = row.id;andreport('vectorizing')(src/jobs.ts:936-937) run before the guardif (consecutiveErrors >= 5) { throw ... }(src/jobs.ts:938-940). src/worker.ts flushes the pending checkpoint before recording the failure (try { await retrySqliteBusy(flushProgress); }at src/worker.ts:308, thenfailJobat 309), andfailJobre-persists that checkpoint (src/worker.ts:319-331). The batch query only selects media withm.id>?(src/jobs.ts:907), and app.ts:3414 accepts resuming a 'failed' job, so the advanced cursor is restored on resume.Impact: On the outage path this MR targets, the five media that failed only because the encoder was unavailable are recorded in
skipped_media, the persisted cursor moves past them, and a resumed job after the outage never re-embeds them; those media stay permanently unindexed for the current model identity (the test 'repeated consecutive encoder failures abort the job...' asserts the abort but does not check the cursor).Suggested fix: Track the first failing media_id of the current consecutive run and roll
cursorback to it (dropping those entries fromskipped_media) before throwing the systemic error, so a resumed job retries them once the encoder recovers.HTTP 400 is whitelisted as an isolated per-file failure although the server reserves 400 for request/protocol faults (src/jobs.ts:925; high confidence)
isFileErroracceptserror instanceof EncoderError && (error.status === 422 || error.status === 413 || error.status === 400). In scripts/encoder-server.py, 400 is emitted only for request-level faults —Invalid JSON payload: {exc}and'Expected text or image and model identity'— i.e. client/server contract problems; 422 is the unprocessable-media status (UnprocessableMediaError). The REQUIREMENTS-TRACE row for SEARCH-01 describes the whitelist as 'isolated un-vectorizable media (422/413) and fs read errors', with no 400.Impact: A payload-contract drift between client and server is silently converted into up to four per-file skips with the cursor advanced past them (those media remain unindexed for the model identity) instead of failing systemically, and the code does not match the documented whitelist.
Suggested fix: Restrict the whitelist to 422/413 plus the fs codes and the client-side transport-limit message, treating 400 as systemic; if 400 must remain tolerated, update the trace wording to say so.
Suggestions
The job-start metadata request is not covered by the new retry path (src/vector.ts:184; high confidence)
encoderMetadatacallsencoderRequest('/metadata', undefined, signal)with no options, soretriesdefaults to 0 (src/vector.ts:134) and no 503/429 retry occurs. vectorizeHandler calls it at job start (src/jobs.ts:880), and a non-ok status there throwsEncoder returned HTTP <status>...(src/vector.ts:177), which is not in the per-file whitelist and is rethrown by the handler.Impact: If the transient outage hits the /metadata request rather than an /embed request, the vectorize job still fails immediately, so the added tolerance covers only part of the failure mode the trace describes ('transient 503, connection drops').
Suggested fix: Pass bounded retry options to the metadata call made from the worker job path (keeping text-query routes fast-fail as the trace intends), or retry the whole job-start metadata probe under the shared deadline.
Retry delay budget (100 ms + 200 ms) is far shorter than the server's own 10 s slot-wait window (src/vector.ts:148; medium confidence)
Both retry branches use
await sleep(attempt * 100, combined)(src/vector.ts:148 and 160), i.e. 100 ms then 200 ms for the{ retries: 2 }passed by embedImage (src/vector.ts:217). scripts/encoder-server.py now blocks up to 10 s for a semaphore slot (if not slots.acquire(timeout=10)) before answering 503 'Encoder busy'.Impact: A busy or starting service that returns 503 for more than ~0.3 s exhausts the client retries and routes the failure into the systemic path (job failure, or the 5-consecutive guard), so the added tolerance is much narrower than the server's own queueing behaviour.
Suggested fix: Size the retry budget against the server's slot-wait window (e.g. a capped exponential or a total delay budget derived from REVIEW_V2_EMBED_TIMEOUT_MS), keeping it inside the shared deadline that is already shared correctly.
Unsafe-file skips do not reset the consecutive-error counter, and the aborting file is counted twice in error_count (src/jobs.ts:915; high confidence)
The
if (!await safeFile(row)) { skippedUnsafe++; }branch (src/jobs.ts:914-915) neither resets nor incrementsconsecutiveErrors, so encoder-error counts accumulate across unrelated unsafe-file skips and the guard can fire for failures that are not adjacent. Separately, the failing file incrementserror_countat src/jobs.ts:931, and when the guard throws, src/worker.ts:309failJobrunserror_count = error_count + 1(src/worker.ts:326) for the same file.Impact: The abort can fire for a pattern that is not actually five consecutive file errors, and the reported error_count overstates the number of failed files by one on the abort path.
Suggested fix: Reset
consecutiveErrors = 0in the unsafe-file branch (or count it consistently in both branches), and avoid the per-file increment when the same error is about to be recorded byfailJob.Tests and validation
Questions
skipped_mediaever be revisited? Withcursor = row.idandWHERE ... m.id > ?, a file that failed during a transient outage or that becomes processable later is never re-embedded for the current model identity; is that acceptable, or should skips be re-tried on a later pass?consecutive_errorsbe reset when a failed job is deliberately resumed via POST /api/jobs/:id/resume? The added test asserts it is retained, which means a resume after an encoder outage aborts on the first failing file.error_count; is the user expected to seecheckpoint.skipped_mediaandconsecutive_errors, since the trace describes the skip list as 'for review'?Review limitations
Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Round 6 Response to Automated Review
Changes implemented in
fix/vectorize-error-tolerance(version2.7.1-dev7):Cursor & Skipped Media Rollback on Consecutive-Error Abort:
runStartCursorandrunStartIndexduring vectorize processing.cursorrolls back torunStartCursor, failing entries are removed fromskippedMedia, anderror_countis decremented by the failing items sofailJobdoes not double-count them.Removed HTTP 400 from File Skip Whitelist:
ENOENT,EACCES,EISDIR). HTTP 400 is reserved for protocol/payload validation faults and fails immediately.Job-Start Metadata Probe Retries:
encoderMetadata(signal, options)to accept retry options and passed{ retries: 2 }at the start ofvectorizeHandler, avoiding spurious job failures during encoder start-up or transient slot waits.Sized Retry Delay to Encoder Slot Window:
Math.min(attempt * 500, 2000)(500ms, 1000ms), providing sufficient headroom during encoder contention.Safe File Skips Reset Consecutive Error Counter:
consecutiveErrors = 0and advancesrunStartCursor, avoiding interleaving safe-file skips with encoder errors into a premature 5-error abort.Validation Evidence:
npm test: 225 passing tests (including consecutive error rollback and metadata retry tests).python3 -B -m unittest discover -s tests).nix build --no-link --print-build-logs .#redviewsucceeded cleanly.Automated code review
Reviewed commit:
e7512996448f1f1d6fe6ccf502dafd3b0b2323eaVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The supplied diff advances the vectorize path to 2.7.1-dev7: src/vector.ts adds an EncoderError type and a bounded 503/429 retry loop in encoderRequest under a single per-call AbortSignal deadline (retries: 2 only for embedImage and the job-start encoderMetadata probe, leaving embedTextQuery fast-fail), src/jobs.ts adds a per-file error whitelist (422/413, the 128 MiB transport guard, ENOENT/EACCES/EISDIR) with per-file error_count increments, a bounded 20-entry skipped_media list, consecutive_errors checkpointing, and a cursor/error_count rollback on the 5-consecutive abort, and scripts/encoder-server.py adds UnprocessableMediaError -> 422 ahead of the generic 503 handler plus slots.acquire(timeout=10). VERSION, package.json and the CHANGELOG head entry agree at 2.7.1-dev7, and tests/vectorize-error-tolerance.test.mjs contains the 7 cases the updated SEARCH-01 row cites. I verified two real consistency defects in the rollback path (src/jobs.ts:936-948): the rollback derives the count to subtract from the capped skipped_media list, so error_count is left unreconciled once that list reaches its 20-entry bound, and the aborted run persists consecutive_errors: 5 together with the rewound cursor, so every subsequent resume of the failed job aborts after a single file while failJob (src/worker.ts:326) adds another error_count. The new Python test only asserts the exception class exists, so the 422/503 routing it introduces is unexercised. I did not run npm run build, npm test, or the Python unittest discovery, so no test-pass claim is verified here.
Blocking findings
None.
Important findings
Consecutive-error rollback under-decrements error_count once skipped_media reaches its 20-entry bound (src/jobs.ts:940; high confidence)
src/jobs.ts:936-942: the 5-consecutive abort computes
removedCount = skippedMedia.length - runStartIndexand only runs theerror_count = MAX(0, error_count - ?)update whenskippedMedia.length > runStartIndex. But src/jobs.ts:948 records a skip onlyif (skippedMedia.length < 20), while src/jobs.ts:947 incrementserror_countunconditionally for every whitelisted file error. Once the checkpoint list is at its 20-entry bound,runStartIndex(set fromskippedMedia.lengthat src/jobs.ts:907/963 after each success) equalsskippedMedia.length, so a run of 4 errors incrementserror_count4 times and the abort decrements 0. The same bounded-list-plus-unconditional-counter convention is used in tagHandler (src/jobs.ts:865-866), which treatserror_countas an exact per-file tally.Impact: After such an abort the persisted checkpoint has the cursor rewound before those files but keeps their
error_countincrements; on resume the same files are re-attempted and incrementerror_countagain, so the reported error total (web/src/vector-panel.tsx:50 and web/src/job-activity.tsx:85 renderjob.error_count) overstates real errors and grows with each resume past the 20-skip bound. No media or index data is lost, but the job's reported error count becomes wrong and unreconcilable.Suggested fix: Count the per-file errors attributed to the current run independently of the bounded display list (e.g. a
runErrorCountreset alongsiderunStartCursor/runStartIndex) and decrementerror_countby that count on the 5-consecutive abort, instead of deriving it fromskippedMedia.length - runStartIndex.Aborted run persists consecutive_errors: 5 with its errors rolled back, so every resume of the failed job aborts after one file (src/jobs.ts:944; high confidence)
src/jobs.ts:937-944: on the 5-consecutive abort the code rewinds
cursor = runStartCursor, splicesskippedMediaback torunStartIndexand decrementserror_count, then callsreport('vectorizing')(src/jobs.ts:901-903, which persistsconsecutive_errors: consecutiveErrors) before throwing. src/worker.ts:309 flushes that checkpoint and src/worker.ts:318-326failJobstores it unchanged with state 'failed' anderror_count = error_count + 1. src/app.ts:3414-3437 re-queues such a job on resume, and src/jobs.ts:897 restoresconsecutiveErrors = checkpoint?.consecutive_errors ?? 0= 5, so the first re-attempted failing file makes it 6 and hitsconsecutiveErrors >= 5again at src/jobs.ts:937 withrunStartIndex == skippedMedia.length(the list was emptied by the rollback), leaving the cursor unmoved and adding anothererror_countvia failJob.Impact: The persisted
consecutive_errorsdescribes errors that the same rollback removed fromskipped_mediaanderror_count, so the two halves of the checkpoint disagree. A library region containing five or more consecutive unvectorizable media can never be advanced past by repeated resumes: each resume aborts on the first file and inflateserror_count, which the Settings panel shows as growing errors. This is a reachable state, not only a down-encoder state.Suggested fix: Make the rollback self-consistent: when the run's skips and
error_countare rewound, also rewind the consecutive counter (persistconsecutive_errorsas the count of errors still represented beforecursor, i.e. 0 after a full rollback), or persistrunStartCursor/runStartIndexin the checkpoint so the counter and the rewound position always describe the same run.Suggestions
tests/test_encoder_server.py:35-36 adds only
self.assertTrue(issubclass(self.module.UnprocessableMediaError, Exception)). The behaviour actually changed in scripts/encoder-server.py is the routing:raise UnprocessableMediaError(...)in Encoder.encode (image decode and text-length paths), theexcept UnprocessableMediaError as exc: self.respond(422, ...)handler ordered before the genericexcept Exception as exc:503 branch, andslots.acquire(timeout=10). None of these are exercised; the existing tests in that file only callmodel_metadata,validate_embeddingand readMAX_BODY. The client-side suite tests/vectorize-error-tolerance.test.mjs mocks the status codes itself (e.g. lines 60-61, 163-164) and would still pass if the server routed these inputs to 503.Impact: A regression in the 422/503 routing - for example reordering the
exceptclauses, or the conditional message expression in the 503 branch - would not be caught by the Python suite, while the client suite would stay green; AGENTS.md:5 asks for a focused test of changed behaviour and REQUIREMENTS-TRACE.md now cites this suite as evidence for SEARCH-01.Suggested fix: Add a handler-level case in tests/test_encoder_server.py that feeds an undecodable image payload and an over-length text payload and asserts 422 responses, plus an inference-fault case still asserting 503, following the existing unittest style in that file (this may require exposing the Handler or its classification so it can be driven without a live CUDA model).
Tests and validation
Questions
consecutive_errors: 5is persisted (src/jobs.ts:944, src/worker.ts:326), so every resume re-aborts on the first file of that stretch; if that hard stop is intended, the REQUIREMENTS-TRACE.md wording ('tolerate isolated un-vectorizable media') could state the limit explicitly.error_countintended to remain an exact per-file tally regardless of the 20-entryskipped_mediadisplay bound (as tagHandler does at src/jobs.ts:865-866), or is it meant to track only the displayed skips? The vectorize rollback currently mixes the two conventions (src/jobs.ts:940-942).Review limitations
npm run build,npm test, the Python unittest discovery, ornix build; there is no dist/ in the checked-out tree, so I could not confirm that the new TypeScript (includingcheckpoint.skipped_mediaaccess afterArray.isArray(checkpoint?.skipped_media)at src/jobs.ts:894-896) compiles, nor that the 7 new cases and the existing suites pass. Those claims come only from the supplied material.slots.acquire(timeout=10)contention behaviour, and sqlite-vec host acceptance remain unverified, as the trace itself notes.Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Round 7 Response to Automated Review
Changes implemented in
fix/vectorize-error-tolerance(version2.7.1-dev8):Independent
runErrorCountTracking on Rollback:runErrorCountacross the current run, reset alongsiderunStartCursorandrunStartIndexon successful embeddings and safe-file skips.error_countis decremented byrunErrorCountdirectly in SQLite (MAX(0, error_count - ?)). This decouples error total rollback fromskippedMedia.length, ensuring accurate error accounting even when the 20-entryskipped_mediadisplay cap has been reached.Self-Consistent
consecutive_errors: 0Checkpoint on Abort:consecutiveErrors = 0prior to callingreport('vectorizing')during the 5-consecutive-error abort.Encoder Server Handler Routing & Payload Validation Tests:
make_handler(encoder, slots=None)inscripts/encoder-server.pyso the HTTP server can be cleanly tested with mock encoders.test_handler_routes_unprocessable_and_runtime_errorsintests/test_encoder_server.pyexercising HTTP 422 (UnprocessableMediaError), HTTP 503 (inferenceRuntimeError), HTTP 409 (identity mismatch), and HTTP 200 responses.test_encode_payload_validation_raises_unprocessableverifyingUnprocessableMediaErroron empty text, over-length text, invalid base64, and invalid image bytes.Validation Evidence:
npm test: 226 tests pass (added test assertingerror_countrollback withskipped_mediaat the 20-entry bound andconsecutive_errors: 0).python3 -B -m unittest discover -s tests).nix build --no-link --print-build-logs .#redviewsucceeded cleanly.Automated code review
Reviewed commit:
6b457244a6ed7666b086b502d4e4b8f462e05f1bVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The supplied changes add bounded 503/429 retry logic plus a typed EncoderError in src/vector.ts, per-file error tolerance with a 5-consecutive abort and run-rollback bookkeeping in vectorizeHandler (src/jobs.ts), an UnprocessableMediaError -> 422 classification in scripts/encoder-server.py, and two new test suites. I inspected the checked-out head of src/jobs.ts, src/vector.ts, scripts/encoder-server.py, src/worker.ts and the new tests. The main systemic paths behave as documented: 409, exhausted 503, transport drops and non-file faults throw before
cursor = row.id(src/jobs.ts:973), so the cursor is not advanced; text search still calls encode() with no options, so retries stay 0. The defects I can support are bookkeeping and classification-fragility issues in the new tolerance logic: the consecutive-error run anchors are not persisted alongsideconsecutive_errors, per-file classification still depends on a message substring for the client-side 128 MiB guard, unrelated unsafe-file skips reset the outage guard, and the server 503/422 bodies interpolate arbitrary exception text.Blocking findings
None.
Important findings
src/jobs.ts:897 restores
consecutiveErrorsfrom the checkpoint (checkpoint?.consecutive_errors ?? 0), but src/jobs.ts:898-900 re-initialise the rollback anchors run-local on every handler invocation:let runStartCursor = cursor; let runStartIndex = skippedMedia.length; let runErrorCount = 0;. The abort at src/jobs.ts:939-949 rewinds only that run (cursor = runStartCursor,skippedMedia.splice(runStartIndex),error_count - runErrorCount). The checkpoint type at src/jobs.ts:884-889 carries no run anchors. The added test 'consecutive_errors is retained across checkpoint resumes' (tests/vectorize-error-tolerance.test.mjs) seedsconsecutive_errors: 4and asserts onlyassert.rejects(... /consecutive file errors/), with no cursor, error_count or skipped_media assertion. Because fetchBatch (src/jobs.ts:908) selects only media withv.media_id IS NULL AND m.id>?, media skipped in an earlier run and left unindexed are re-selected after the partial rewind, so theirerror_count + 1increments (src/jobs.ts:952) are applied again on re-attempt.Impact: After an interruption, a resumed run starting with
consecutive_errors = N > 0aborts on the very next failing file but rewinds only the current run: the N earlier failures keep their cursor advance and theirerror_countincrements, and because those media are still unindexed they are re-processed and counted a second time.error_countthen over-counts distinct failures and the guard's 'roll back the consecutive run' invariant holds only within a single handler invocation.Suggested fix: Persist the run anchors with
consecutive_errorsin the checkpoint (e.g.run_start_media_id,run_start_skip_index,run_error_count) and restore them at src/jobs.ts:898-900 whensameModelis true, so the rewind covers the whole consecutive run across resumes; alternatively derive the rewind fromconsecutive_errors. Extend the cross-resume test to assert the cursor,error_countandskipped_mediarollback for the seededconsecutive_errors: 4case.Suggestions
Oversized-image skip is recognised by matching an error message substring instead of the typed status (src/jobs.ts:932; medium confidence)
The per-file whitelist at src/jobs.ts:931-934 is
(error instanceof EncoderError && (error.status === 422 || error.status === 413)) || msg.includes('Image exceeds encoder transport limit') || .... That oversized-image case is produced in src/vector.ts:214 as a plainthrow new Error('Image exceeds encoder transport limit (128 MiB)'), so it is matched only by that literal substring, even though the new typedEncoderError(src/vector.ts:114-120) exists to carry a status.Impact: Any rewording of the vector.ts:214 message (or of the '128 MiB' limit text) silently reclassifies every oversized image as a systemic fault, failing the whole vectorize job at the first such file instead of skipping it; the new tests only exercise the server-side 422/413 path, so they would not catch that drift.
Suggested fix: Throw
new EncoderError('Image exceeds encoder transport limit (128 MiB)', 413)inembedImageand drop the message-substring clause fromisFileError, so per-file classification depends only on the typed status.Unsafe-file skips reset the consecutive-error counter, so an encoder outage interleaved with missing files never aborts (src/jobs.ts:919; medium confidence)
The
!await safeFile(row)branch at src/jobs.ts:917-922 setsconsecutiveErrors = 0and re-anchors the run for files that are merely missing or outside their folder, which are unrelated to the encoder. The abort guard at src/jobs.ts:939 only fires on 5 consecutive embedding errors.Impact: During a mid-run encoder outage on a library where unsafe/missing files alternate with encoder-failing files, the job can skip a large fraction of the media - each incrementing
error_countat src/jobs.ts:952 - without ever reaching 5 in a row and without aborting, which is the unbounded-skip case the 5-consecutive guard was added to prevent.Suggested fix: Keep the encoder-outage guard independent of unrelated safe-file skips: track embedding failures since the last successful embedding (or since job start) and abort on that counter, while leaving the run anchors and the 'same file twice' notion reset by safe-file skips.
Server 503 body is selected by a substring heuristic and echoes arbitrary exception text into the response (scripts/encoder-server.py:157; medium confidence)
except Exception as exc: self.respond(503, {'error': f'Encoder inference failed: {exc}' if 'embedding' in str(exc).lower() or 'unit length' in str(exc).lower() else 'Encoder inference failed; inspect server runtime'}). Any exception whose text happens to contain 'embedding' or 'unit length' - e.g. a torch/sentence-transformers traceback - has its full message echoed into the body, which src/vector.ts:172 embeds verbatim into theEncoderErrormessage and src/worker.ts:309/326 (failJob) stores incheckpoint_jsonand the job error report.Impact: Unbounded, library-internal exception text can be surfaced into the job checkpoint and job error report, and the systemic-vs-input classification is incidental to the wording rather than intentional.
Suggested fix: Raise a dedicated typed exception for inference/validation faults (mirroring
UnprocessableMediaError, e.g.InvalidEmbeddingError) and respond with a fixed 503 message, keeping the raw exception in the server log only; do not interpolatestr(exc)into the response body.Tests and validation
Questions
slots.acquire(timeout=10)(scripts/encoder-server.py:133) intended to be bounded by the client's shared REVIEW_V2_EMBED_TIMEOUT_MS budget, given that 3 attempts plus backoff can now consume most of the 120 s deadline for a single image under contention?skipped_mediaremain capped at 20 entries (src/jobs.ts:953) as the only record of per-file skips, or is a bounded summary of omitted media ids wanted so that rolled-back versus permanently-skipped files stay distinguishable in the checkpoint?Review limitations
Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Round 8 Response to Automated Review
Changes implemented in
fix/vectorize-error-tolerance(version2.7.1-dev9):Persist Run Anchors Across Checkpoint Resumes:
run_start_cursor,run_start_index, andrun_error_countto the checkpoint metadata alongsideconsecutive_errors.sameModelis true so that an abort occurring after a job resume rolls back the entire consecutive run rather than only the current process invocation.last_media_id,skipped_media,consecutive_errors, andjobs.error_countroll back correctly across resumes.Typed Status 413 for Oversized Images:
embedImagenow throwsnew EncoderError('Image exceeds encoder transport limit (128 MiB)', 413)instead of a genericError.isFileErrorinvectorizeHandler, relying strictly on typed HTTP statuses (422, 413) and filesystem error codes.Preserve Consecutive Error Counting Across Unsafe Files:
!await safeFile(row)) recordskipped_unsafe_fileswithout resettingconsecutiveErrorsor re-anchoring the run, ensuring encoder outages interleaved with missing files still trigger the 5-consecutive abort.Typed
InvalidEmbeddingErrorand Fixed 503 Status Messages:InvalidEmbeddingError(ValueError)inscripts/encoder-server.pyand raised it fromvalidate_embedding.'Encoder returned invalid or non-normalised vectors'forInvalidEmbeddingErrorand'Encoder inference failed; inspect server runtime'for other runtime faults) without interpolating arbitrary exception text into responses.tests/test_encoder_server.pyverifying the 503 response and exact error body.Validation Evidence:
npm test: 227 passing tests.python3 -B -m unittest discover -s tests).nix build --no-link --print-build-logs .#redviewpassed install checks cleanly.Automated code review
Reviewed commit:
5dbf5f5b1cd775246235285f4cb487c32c768e3dVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
I re-checked the supplied diff against the checked-out sources. The version metadata (VERSION, package.json, CHANGELOG top entry) is self-consistent at 2.7.1-dev9, and the new server/client/job error paths match the behaviour described in the REQUIREMENTS-TRACE row. Two defects are supportable from the supplied evidence: (1) the new 5-consecutive-error rollback rewinds the cursor, skipped_media and error_count but not skipped_unsafe_files, so unsafe-file skips are re-counted on resume; (2) the new client retry policy retries every 503, including the two deterministic 503 responses the server now emits for validation/inference faults, which wastes encoder passes (the outcome is still correct, so this is a suggestion). I did not reproduce the earlier reviewer's 'live skipped_media array vs snapshot-valued run anchors' concern: in src/jobs.ts every mutation of skippedMedia (the push at 957, the splice at 941) is immediately followed by a report() call that re-captures run_start_index/run_error_count and builds a new checkpoint object, so the object the worker stores in pendingCheckpoint (src/worker.ts:262) is internally consistent at the point it is serialized.
Blocking findings
None.
Important findings
src/jobs.ts:922 increments skippedUnsafe for every row that fails safeFile(), and that count is persisted at src/jobs.ts:905 (skipped_unsafe_files: skippedUnsafe). The new abort branch at src/jobs.ts:938 rewinds cursor = runStartCursor (939), truncates skippedMedia via splice(runStartIndex) (941) and decrements the job's error_count by runErrorCount (944), but never adjusts skippedUnsafe; unsafe rows also never reset runStartCursor, so they always lie between runStartCursor and the abort point. The new test 'unsafe-file skips do not reset consecutive encoder errors' (tests/vectorize-error-tolerance.test.mjs) asserts checkpoint.skipped_unsafe_files === 1 in the same checkpoint whose cursor was rolled back to 0, and the resume path is real: src/app.ts:3432-3443 re-queues a job whose state is 'failed', and web/src/job-activity.tsx:94 offers a Resume button for paused/failed jobs.
Impact: After a consecutive-error abort and resume, unsafe files between runStartCursor and the abort point are re-scanned and counted again, so the persisted skipped_unsafe_files counter drifts above the number of distinct unsafe files actually skipped and grows with each abort/resume cycle. This is checkpoint-accounting drift introduced by the new rollback logic; it does not lose or duplicate embeddings (the fetch query excludes rows already in vec_media).
Suggested fix: Apply the same run-anchor discipline to unsafe-file skips as is used for skippedMedia and error_count: persist a run_start_unsafe anchor (or count unsafe skips since the last success in a runUnsafe counter) and subtract it in the abort branch at src/jobs.ts:938-948, so the reported counter always corresponds to the persisted cursor.
Suggestions
The server now emits 503 for three distinct conditions: slot contention at scripts/encoder-server.py:139 ('Encoder busy'), the new InvalidEmbeddingError path at scripts/encoder-server.py:162 ('Encoder returned invalid or non-normalised vectors'), and the trailing except Exception at scripts/encoder-server.py:164 ('Encoder inference failed'). The new client retries on status alone - src/vector.ts:158 retries any 503/429 - and embedImage opts into { retries: 2 } (src/vector.ts:216), so a deterministic model/validation fault costs three full encoder passes before the exhausted 503 is rethrown as EncoderError(..., 503) and treated as systemic in vectorizeHandler (isFileError at src/jobs.ts:932 matches only 422/413).
Impact: No incorrect outcome (the exhausted 503 still fails the job systemically, as the trace states), but deterministic faults are retried pointlessly against the serialised CUDA workload, adding up to two extra encoder passes and extra semaphore-slot holds per image before the job fails.
Suggested fix: Separate transient from permanent conditions on the wire: keep 503 for 'Encoder busy' and use a non-retryable status (e.g. 500/502) for the InvalidEmbeddingError and inference-fault responses, or honour a retryable flag in the JSON error body at src/vector.ts:158.
Tests and validation
Questions
Review limitations
Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Round 9 Response to Automated Review
Changes implemented in
fix/vectorize-error-tolerance(version2.7.1-dev10):Roll Back
skipped_unsafe_fileson Consecutive Abort:run_unsafe_countto checkpoint metadata alongsiderun_error_count.runUnsafeCountonsafeFileskips, and reset it to 0 on successful embeddings.skippedUnsafeis decremented byrunUnsafeCount(Math.max(0, skippedUnsafe - runUnsafeCount)), ensuring unsafe file skips within the rewound run are not double-counted when the job is resumed.tests/vectorize-error-tolerance.test.mjsverifying thatcheckpoint.skipped_unsafe_filesrolls back to match the rewound cursor.Return HTTP 500 for Deterministic Validation & Inference Faults:
scripts/encoder-server.pyto respond with HTTP 500 forInvalidEmbeddingErrorand generic runtime exceptions, keeping HTTP 503 strictly reserved for transient slot contention (slots.acquire(timeout=10)).tests/test_encoder_server.pyto assert status code 500 forInvalidEmbeddingErrorand runtime errors.Validation Evidence:
npm test: 227 passing tests.python3 -B -m unittest discover -s tests).nix build --no-link --print-build-logs .#redviewpassed install checks cleanly.Automated code review
Reviewed commit:
3cd0756d804870913cce836c051261b0664f580bVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Strict validation pass over the vectorize error-tolerance change (src/vector.ts retry/typed EncoderError, src/jobs.ts skip/rollback/anchor bookkeeping, scripts/encoder-server.py error classification, plus the two new suites). The two findings from the initial review that survive validation are: (1) the 5-consecutive guard is fed by deterministic per-file faults (422/413), so a run of 5 or more permanently unprocessable media can never be passed because the cursor rollback makes every resume re-fail identically; (2) the server's catch-all
except Exception:now answers 500, which the client never retries, so non-deterministic runtime faults (e.g. CUDA OOM) lose the bounded backoff this MR adds. The initial review's 20-entry skipped_media finding was dropped: the identical bound already exists in unchanged code (src/jobs.ts:866, tag handler), so it is an established convention, not a defect introduced by this change. Its test-scaffolding finding (mutating UnprocessableMediaError to reach InvalidEmbeddingError) was dropped as test-style only, with no demonstrated defect. The initial review's claims about retry budget, 409/400/503 paths, and checkpoint restore math were re-checked against the checked-out source and are consistent with the code and the 9 new .mjs cases.Blocking findings
None.
Important findings
src/jobs.ts:935-936 puts permanent per-file conditions in the same counter as transient ones:
(error instanceof EncoderError && (error.status === 422 || error.status === 413)). Both are deterministic per the supplied diff: src/vector.ts:214 throwsnew EncoderError('Image exceeds encoder transport limit (128 MiB)', 413)for any file over 128 MiB, and scripts/encoder-server.py:159 maps every undecodable image (base64/Image.open/convertfailure) to 422. On the 5th consecutive error, src/jobs.ts:943 setscursor = runStartCursor, andrunStartCursoris only advanced after a successful insert (src/jobs.ts:976runStartCursor = row.id;), whilefetchBatchre-selectsWHERE ... m.id>? ORDER BY m.id(src/jobs.ts:916). worker.ts:308-309 shows the rolled-back checkpoint is flushed beforefailJob, and onlykind IN ('rip','tag')jobs are auto-requeued (src/worker.ts:70), so a manual resume restarts the identical 5 rows withconsecutive_errorsreset to 0.Impact: For a library with 5 adjacent corrupt/undecodable images, or 5 adjacent files above 128 MiB, the vectorize job can never complete: every resume re-fetches the same rows, aborts with 'Vectorize stopped after 5 consecutive file errors', and each attempt adds
error_count + 1(src/worker.ts:326) while the cursor stays put. The tolerance the MR introduces therefore only holds for runs of 4 or fewer, and the operator has no way to get past a permanent bad run without hand-editing checkpoint_json.last_media_id.Suggested fix: Separate the two causes: keep the consecutive guard and cursor rollback for transient/service causes (503, 429, transport drops), but for deterministic per-file faults (422, 413, ENOENT/EACCES/EISDIR) advance past the failing run and record it in a permanent-skip counter so the batch can complete; alternatively document and surface in the job result that a run of >=5 permanently-bad files requires manual intervention.
Suggestions
scripts/encoder-server.py:163
except Exception:->self.respond(500, {'error': 'Encoder inference failed; inspect server runtime'})is the fall-through for anything raised insideEncoder.encode, including a torch CUDA memory error raised byself.model.encode(...)underself.lock(scripts/encoder-server.py:110). The client retries onlyresponse.status === 503 || response.status === 429(src/vector.ts:158), and src/jobs.ts:938 rethrows any error whose status is not 422/413 immediately, so a single 500 fails the whole vectorize job with no backoff. Only slot contention (slots.acquire(timeout=10), scripts/encoder-server.py:138) still yields 503.Impact: A transient GPU/resource fault becomes an immediate systemic job failure that bypasses the bounded retry this MR adds, so the classification boundary between retryable and non-retryable encoder faults is wider than the CHANGELOG's intent ('HTTP 500 for deterministic validation and inference faults').
Suggested fix: Catch known transient resource faults (e.g. torch.cuda.OutOfMemoryError) separately and answer 503/429 so the client's bounded backoff applies, reserving 500 for deterministic model/protocol faults; or include a machine-readable retryable marker in the 500 body and honour it in encoderRequest.
Tests and validation
Questions
Review limitations
Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Response to automated review round 9 (review id 104)
We have addressed the review feedback and updated the codebase in commit
3547993(version bumped to2.7.1-dev11):Transient GPU Memory/Resource Faults (Suggestion):
scripts/encoder-server.py, catchMemoryErrorand exceptions with nameOutOfMemoryErrororCudaError(or containing "out of memory") during inference and map them to HTTP 503 (Encoder resource temporarily exhausted).encoderRequest's bounded exponential retry backoff, reserving HTTP 500 strictly for deterministic model, contract, and validation failures.tests/test_encoder_server.pyasserting that transient memory exhaustion yields HTTP 503 with the expected payload.5-Consecutive-Error Guard and Operator Remediation Path (Important Finding & Questions):
runStartCursorso that once the operator fixes the mount or unlinks/inspects the bad media, deliberate resume retries the block cleanly.src/jobs.ts, clarified the abort error message fromverify encoder service: ...toVectorize stopped after 5 consecutive file errors; operator inspection required for media starting at ${runStartCursor}: ${msg}. The operator can inspect the failing media starting atrunStartCursor. If the mount was broken, repairing it allows resume to succeed immediately. If the media items are permanently corrupt or unvectorizable, removing or deleting them from disk allowssafeFileto classify them asskipped_unsafe_fileson resume and advance past them without requiring direct database modifications.skipped_mediaat 20 sample entries in the checkpoint matches the established convention intagHandler(src/jobs.ts:866), bounding checkpoint and progress payload sizes whileerror_counttracks the exact aggregate tally of all skipped media.Validation Evidence:
nix develop --command npm test: 227 tests passed (including all 9 cases intests/vectorize-error-tolerance.test.mjs).nix develop --command python3 -B -m unittest discover -s tests: 63 tests passed (including new OOM 503 test case intests/test_encoder_server.py).nix build --no-link --print-build-logs .#redview: passed with exit code 0.2.7.1-dev11.Automated code review
Reviewed commit:
35479934718136f1a615dba52ad6c3266f34a40bVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Validated the supplied diff against the checked-out tree. Confirmed one categorization defect in scripts/encoder-server.py: the new broad
except Exceptionaround base64/PIL decode converts every failure in that block intoUnprocessableMediaError(HTTP 422), which src/jobs.ts:936 treats as an isolated file error (skip + cursor advance + error_count++), so a decode-timeMemoryErrornever reaches the 503 branch at encoder-server.py:163/166 that the round-9 CHANGELOG entry and the SEARCH-01 trace row claim to provide. The rest of the control flow checks out against the tests: exhausted 503/429 and transport failures becomeEncoderErrorwith status 503 and are re-thrown as systemic (tests 5 and 9 assert cursor/skip/error_count are untouched); 409 stays systemic; 422/413 plus ENOENT/EACCES/EISDIR are the only whitelisted skips; the 5-consecutive rollback re-reads the in-memoryrunErrorCount/runUnsafeCount/runStartCursor/runStartIndex(jobs.ts:944-956) and the nine .mjs cases match that code path for path, bound, and cross-resume anchors. Version (2.7.1-dev11), package.json, CHANGELOG and the trace row are mutually consistent; the trace's 'all 9 cases' count matches the ninetest(...)calls in tests/vectorize-error-tolerance.test.mjs. I did not run the suites or the build; the only gate evidence supplied is the claim of package-checks success.Blocking findings
None.
Important findings
The new decode block wraps every failure of the whole base64+PIL sequence:
try: data = base64.b64decode(...); with Image.open(...) as original: image = original.convert('RGB'); image.thumbnail((512, 512)) except Exception as exc: raise UnprocessableMediaError(f'Invalid or unprocessable image: {exc}') from exc(encoder-server.py:82-90).MemoryErroris a subclass ofException, so a MemoryError raised while PIL decodes/converts a large image is re-raised asUnprocessableMediaError, which the handler routes to 422 at encoder-server.py:159 (except UnprocessableMediaError as exc: self.respond(422, ...)) and never reaches the 503 branches at encoder-server.py:163 (except (MemoryError,)) or 166 ('out of memory' in str(exc).lower()). On the client, src/jobs.ts:936 classifieserror instanceof EncoderError && error.status === 422asisFileError, which incrementsjobs.error_count(line 959), records the item incheckpoint.skipped_media(line 961) and advancescursor = row.id(line 962).Impact: A recoverable resource condition during image decode is reported as a permanent 'un-vectorizable media' skip: the cursor moves past that media and it stays un-indexed for the remainder of the run, rather than being retried under the new 503/backoff path in src/vector.ts:158. This contradicts the 2.7.1-dev11 CHANGELOG entry and the SEARCH-01 trace claim ('maps transient resource/OOM faults to HTTP 503 to allow client backoff'), which only holds for faults raised inside the inference block, not the decode block. The 5-consecutive counter is the only thing that would eventually surface it, and only if five such failures happen back-to-back.
Suggested fix: Re-raise resource faults before the broad decode handler, e.g. add
except MemoryError: raise(and any torch OOM type if it can surface during preprocessing) immediately ahead ofexcept Exception as exc: raise UnprocessableMediaError(...), so the handler's 503 branch and the client's retry/backoff apply. Keep 422 reserved for genuine decode/protocol faults (bad base64, undecodable image bytes).Suggestions
Each isolated file error increments the job column with its own awaited write (
await retrySqliteBusy(() => ctx.db.prepare('UPDATE jobs SET error_count = error_count + 1 WHERE id = ?').run(ctx.jobId))at src/jobs.ts:959), whereas the matchingrun_error_countis persisted only viareport('vectorizing')->ctx.reportProgress(src/jobs.ts:906-911), which src/worker.ts:260-268 flushes only whennow - lastReported >= PROGRESS_INTERVAL_MS(250 ms, worker.ts:14) and otherwise defers to the interval flusher at worker.ts:277-287. A subsequent abort subtracts the checkpoint-restoredrunErrorCount(src/jobs.ts:904 -> 948error_count = MAX(0, error_count - ?)). Fast failures (fs ENOENT/EACCES, or a local 422 round-trip) can produce several increments inside one 250 ms window; if the checkpoint write for that window is lost (e.g.flushProgressthrows 'Job ownership lost' at worker.ts:256, or the worker is killed), the persistedrun_error_countlags the persistederror_count.Impact: Within a single uninterrupted run the rollback is exact, because the in-memory
runErrorCountis authoritative. Across an interruption that loses a flush, the next resume's rollback under-subtracts, leaving a residual over-count injobs.error_count(and the same shape applies toskipped_unsafe_filesviarun_unsafe_countat src/jobs.ts:950), so the reported error count no longer matches the recordedskipped_mediaentries.Suggested fix: Make the two writes agree by construction: perform the per-error increment and the checkpoint update in one sqlite transaction (as the insert path does with
db.transaction(...).immediate()at src/jobs.ts:972-980), or derive the rollback amount by re-reading the persisted checkpoint delta atomically instead of trusting the in-memory counter.Tests and validation
Questions
error_countincrement and the checkpointedrun_error_countbe persisted atomically, given that worker.ts throttles checkpoint writes at 250 ms while the error_count write is immediate?skipped_mediabound (src/jobs.ts:960) means media IDs beyond the bound are counted inerror_countbut not recorded; the 5-consecutive abort message (src/jobs.ts:956) names onlyrunStartCursor. Is an operator expected to re-derive the unrecorded IDs from the cursor range, or should the checkpoint carry a count of them?MemoryError('CUDA out of memory')routing (503) but no decode-time resource fault, so the round-9 intent is only half covered by the supplied tests.Review limitations
Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata
Response to automated review round 10 (review id 105)
We have addressed the review feedback and updated the codebase in commit
6e9a26e(version bumped to2.7.1-dev12):Decode-Time MemoryError and OOM Re-raising (Important Finding & Question 3):
scripts/encoder-server.py, added explicit handling forMemoryErrorandOutOfMemoryError/CudaErrorduring base64 decode and Pillow processing to re-raise before the broadexcept Exception:block catches them.make_handler's HTTP 503 branch (Encoder resource temporarily exhausted), ensuring that transient decode-time resource exhaustion engages client-side bounded retry with backoff instead of being swallowed into HTTP 422 per-file skips.tests/test_encoder_server.pyconfirming both decode-time and inference-timeMemoryErrorreturn HTTP 503.Reasoned Dismissal on Immediate
error_countWrite (Suggestion & Question 1):runErrorCountis authoritative for the 5-consecutive error rollback calculation.worker.ts:308explicitly callsawait retrySqliteBusy(flushProgress)beforefailJob, ensuring all buffered progress and checkpoint state are flushed to SQLite before the job entersfailed.worker.tsduring rapid filesystem skips.Validation Evidence:
nix develop --command npm test: 227 tests passed.nix develop --command python3 -B -m unittest discover -s tests: 63 tests passed.nix build --no-link --print-build-logs .#redview: passed with exit code 0.2.7.1-dev12.Automated code review
Reviewed commit:
6e9a26e0d1100f10025fc2912219106d6b9e6d2aVerdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
Validated the three candidate findings against the checked-out sources. Line references in scripts/encoder-server.py (92/170), src/jobs.ts (917/959/960/963) and src/vector.ts (139) are accurate, and src/worker.ts confirms flushProgress runs before failJob (worker.ts:308/309), so the 5-consecutive rollback checkpoint is persisted as the tests assert. Finding 3 was corrected: the initial claim that a malformed REVIEW_V2_ENCODER_URL 'burns retries on every media row' and that the message 'omits the actual misconfiguration' is not supported — src/jobs.ts:882 calls encoderMetadata with { retries: 2 } before any row is fetched, so the job fails at start, and src/vector.ts:152 embeds the original error text in the EncoderError message. The residual, still-evidenced part of that finding is only that a deterministic URL-configuration TypeError is caught by the transport retry handler and re-labelled HTTP 503. No blocking defect was found in the supplied changes; the retained items are classification/observability concerns introduced by this change.
Blocking findings
None.
Important findings
None.
Suggestions
Transient-vs-permanent classification is still decided from free-form error text in the encoder (scripts/encoder-server.py:92; medium confidence)
The decode guard (line 92) and the handler's generic except clause (line 170) both use
type(exc).__name__ in ('OutOfMemoryError', 'CudaError') or 'out of memory' in str(exc).lower(). Any deterministic per-file decode fault whose message happens to contain 'out of memory' is re-raised instead of being converted to UnprocessableMediaError, so the handler answers 503 (line 168/171). src/vector.ts:163 retries that status (encode(..., { retries: 2 })), and src/jobs.ts:935 whitelists onlyEncoderErrorwith status 422/413 plus ENOENT/EACCES/EISDIR, so an exhausted 503 is re-thrown systemically and the cursor is not advanced.Impact: A permanently unprocessable image can be reported as a transient resource outage: the vectorize job fails without advancing the cursor and every resume repeats the same three attempts on the same file, instead of the file being recorded in skipped_media and skipped. The classification is therefore only as correct as the error text, which the change did not fully decouple from exception type.
Suggested fix: Decide the transient case from the exception type (MemoryError, torch.cuda.OutOfMemoryError) and keep the message substring only as a documented last-resort fallback for encoder classes that cannot be matched by type; alternatively have the decode stage tag confirmed input faults with UnprocessableMediaError before any text heuristic runs.
Isolated vectorize skips advance the cursor and are capped at 20 entries, so skipped media are never revisited or fully enumerated (src/jobs.ts:960; medium confidence)
The new isolated-failure path increments error_count (line 959), records the skip only under
if (skippedMedia.length < 20)(line 960), and then setscursor = row.id(line 963). fetchBatch selectsWHERE v.media_id IS NULL AND m.is_video=0 AND m.id>?(line 917), so ids at or below the cursor are never re-fetched, and no per-media marker records the skip. The same 20-entry cap exists in the pre-existing tag handler (src/jobs.ts:866), but the cursor-advance-on-skip behaviour is new in this diff: the previous vectorize path re-threw every error and left the cursor unmoved.Impact: After 20 recorded skips, later un-vectorizable media raise error_count with no record of which media they are, and a media that fails once (e.g. a decode fault not mapped to OOM) stays permanently unindexed even after the encoder recovers; the only recovery implied by the code is a model change, which drops the whole index. web/src/vector-panel.tsx:50-51 renders only completed_units, error_count and checkpoint_json.error, so the skipped set is not visible in the Settings panel.
Suggested fix: Either persist skipped media ids durably for accounting/retry (e.g. a per-media flag or an uncapped checkpoint list, with the 20-entry cap applied only to the rendered detail), or state in REQUIREMENTS-TRACE.md/README that isolated vectorize skips are one-shot and re-attempting them requires a model change.
A malformed REVIEW_V2_ENCODER_URL is retried and re-labelled as an encoder 503 (src/vector.ts:139; medium confidence)
new URL(path, base)is evaluated inside the try aroundfetch(line 139), so a synchronous URL-construction TypeError from a badprocess.env.REVIEW_V2_ENCODER_URL(line 134) is caught by the transport handler at line 144, which sleeps and retries up tomaxAttemptsbefore throwingnew EncoderError('Encoder request failed: ...', 503)(line 152). In src/jobs.ts:882 this is the first encoder call (encoderMetadata(ctx.signal, { retries: 2 })), so the job fails at start with status 503, which is not in the isolated-error whitelist at src/jobs.ts:935.Impact: A permanent configuration error is indistinguishable from a transient service outage in the reported status: the worker waits through the backoff (up to 2.5s) before failing, and the failure is recorded as HTTP 503 rather than a misconfiguration. The underlying message text is preserved in the EncoderError message, so this is a mislabelling/wasted-retry concern, not a lost-cause one.
Suggested fix: Construct the request URL once before the retry loop (or validate REVIEW_V2_ENCODER_URL at startup) so configuration errors fail fast with their original type and only network failures are retried.
Tests and validation
Questions
UPDATE jobs SET error_count = error_count + 1 WHERE id = ?(src/jobs.ts:959) intentionally unguarded byworker_token, while the matching checkpoint write (src/worker.ts:253WHERE id = ? AND worker_token = ?) is guarded? If ownership is lost between the two writes, error_count can be incremented without the cursor/skipped_media checkpoint, and the 5-consecutive rollback subtracts onlyrunErrorCountfor the current run. The same unguarded pattern exists in the pre-existing purge/tag paths (src/jobs.ts:637, 865), so this may be deliberate convention.skipped_mediaentries are reachable only via the raw job checkpoint; was surfacing them intended to stay out of scope for this change?Review limitations
Diff coverage
CHANGELOG.md: reviewed — included in a context-limited batchREQUIREMENTS-TRACE.md: reviewed — included in a context-limited batchVERSION: reviewed — included in a context-limited batchpackage.json: reviewed — included in a context-limited batchscripts/encoder-server.py: reviewed — included in a context-limited batchsrc/jobs.ts: reviewed — included in a context-limited batchsrc/vector.ts: reviewed — included in a context-limited batchtests/test_encoder_server.py: reviewed — included in a context-limited batchtests/vectorize-error-tolerance.test.mjs: reviewed — included in a context-limited batchReview metadata