When a Valid Photo Fails Before AI Ever Sees It
A valid photo was making it all the way from the phone into private storage and then failing before the AI ever saw it.
That was the problem behind Media Pipeline v3 in Physara.
The Physique Analyzer already had a durable job system. A user could upload photos, start an analysis, leave the screen, come back, and reconnect to the same job. The backend had retries, leases, validation, cleanup, and a clear completed or failed result.
On paper, it looked solid.
Then I tested it with a real photo.
The upload succeeded.
The MIME type was correct.
The byte size matched.
The image had already been resized and converted to JPEG on the client.
But the analysis still failed.
Gemini was not rejecting the image.
Gemini was never called.
The server was rejecting a valid JPEG during its own decode check.
That changed the question from:
How do I retry the AI request?
to:
How do I build an image boundary I can actually trust?
Media Pipeline v3 became much more than replacing one broken function. It became a full server-side normalization layer between user uploads and AI inference, with its own lifecycle, security boundary, integrity checks, retry rules, cleanup system, and deployment process.
Why I Built It
The release requirement for the Physique Analyzer is simple:
Take the photos.
Tap Analyze once.
Get one dependable analysis.
A user should not have to tap the button several times because one request disappeared, a valid photo was rejected, or a temporary provider error left the interface stuck.
The v2 job system had already solved a large part of that problem. It made the analysis durable instead of tying everything to one screen or one long request.
But the image decoder was still a weak point.
The server-side validation path used createImageBitmap() inside the Supabase Edge runtime. That worked for some images, but it was not reliable across the range of JPEGs real phones and image tools can produce.
A photo can be completely valid and still contain details the decoder has to handle correctly:
- EXIF orientation
- progressive JPEG encoding
- CMYK color
- embedded ICC profiles
- metadata and GPS information
- large dimensions
- unusual but valid compression
- a file extension or MIME type that does not match the actual bytes
The live smoke test proved that I could not treat browser-style decoding inside the Edge runtime as the final image trust boundary.
If the decoder rejects a good image, the analyzer never starts.
If it accepts a bad one without enough limits, the system can waste memory or process something unsafe.
I needed one controlled format between the uploaded file and Gemini.
The Architecture Decision
I decided to keep Supabase responsible for the durable job, the database, private storage, retries, Gemini, result validation, and final persistence.
I moved only the work Supabase Edge was not suited to do: full image decoding and normalization.
That work now runs in a Vercel Node function using Sharp and libvips.
Client photo ↓ Private Supabase upload ↓ Durable analysis job ↓ Node + Sharp normalization ↓ Canonical private JPEG ↓ Supabase worker verifies media ↓ Gemini analysis ↓ Physara validation ↓ Completed result + cleanup
That separation matters.
The Node worker does not call Gemini.
It does not decide whether a muscle group is assessable.
It does not create recommendations.
Its only job is to turn an untrusted uploaded image into a predictable, private, verified image that the rest of Physara can safely use.
That kept the change focused and reversible. I did not have to move the entire analyzer to another platform just to get a dependable decoder.
What the Normalizer Produces
Every accepted image is converted into the same canonical media contract.
The worker:
- verifies the file signature instead of trusting only the MIME type
- rejects files over the source-size limit
- reads the real image metadata
- blocks decompression bombs and extreme dimensions
- applies EXIF orientation
- converts the color space to sRGB
- removes EXIF, GPS, ICC, thumbnails, and other metadata
- resizes the longest edge to a maximum of 2048 pixels
- flattens the output into a baseline JPEG
- calculates a SHA-256 checksum
- stores the normalized file in private storage
Gemini no longer receives whatever format happened to come from the device.
It receives a Physara-controlled JPEG.
That means the inference path does not need to understand every strange camera format, color profile, metadata block, or orientation flag. The normalizer deals with that once, then hands the rest of the system something predictable.
The Job Lifecycle Had to Change
Adding a media worker created a real new stage in the analysis.
I did not want to hide that stage inside a generic queued status because then the database could not tell the difference between:
- photos still uploading
- photos currently being normalized
- normalized media ready for Gemini
- Gemini actively processing
- a temporary provider retry
- a completed or failed job
The lifecycle became:
uploading
↓
normalizing
↓
ready
↓
processing
↓
completed | failed
Provider retries still use the existing retry path.
Media retries stay inside the normalization stage.
That separation lets each type of failure have its own attempt count, lease, timeout, and recovery rule.
A temporary storage download failure should retry.
A spoofed file signature should not.
A corrupt image should fail clearly.
A Gemini timeout should not cause the image to be normalized again.
The database remains the source of truth through all of it.
One Tap Still Had to Mean One Job
The user-facing requirement did not change just because the backend became more complicated.
One tap should start one analysis.
That required idempotency at several points.
If the client sends the start request twice, the second request cannot create a second analysis.
If the scheduler and the interactive request reach the same job close together, they cannot both take ownership.
If a worker times out after doing the work but before the response reaches the caller, the next attempt has to determine what already committed instead of blindly repeating everything.
The first version used separate leases for media normalization and AI processing.
A lease is temporary ownership recorded in the database. The worker receives a token and an expiration time. It can only change the job if that token still matches and has not expired.
That prevents an old worker from waking up late and overwriting a newer attempt.
It was a good foundation.
It was not the end of the problem.
The First Adversarial Review Found Real Races
After the initial implementation passed its tests, I reviewed the system as if I were trying to break it.
That review found several situations the happy path did not cover.
A worker could upload some canonical images and then fail before finishing the rest.
A late worker could try to report success after its lease expired.
The 24-hour photo expiration could occur while the longer-lived job record still existed.
The cleanup process could trust an incomplete manifest and leave an uploaded object behind.
A storage download failure and a checksum mismatch needed different retry behavior.
A duplicate start needed to begin immediately after confirmed uploads, while the background recovery scan still needed to respect the upload grace period.
Those were not theoretical details anymore. Each one represented a way to leave data behind, process the wrong bytes, duplicate work, or move a job into the wrong state.
I fixed them and added regression tests for each case.
Then I reviewed it again.
The Hardest Problem Was Promotion
The normalizer does not write directly into the final canonical path anymore.
Each invocation first writes into its own random staging location.
That change came from a race that looked small at first.
Two invocations could share a job lease and write to the same temporary location. Even if only one result was accepted by the database, their storage writes could still collide.
The database can reject a stale update.
It cannot reach backward in time and cancel a storage write that already started.
So each invocation needed its own identity and its own staging path.
Once normalization finishes, the worker asks the database for permission to promote that exact staged result.
The promotion now happens in two phases:
- The database atomically admits one invocation as the winner while the job remains in
normalizing. - That winner copies the staged files to the deterministic canonical paths, downloads them again, verifies their sizes and SHA-256 checksums, and only then finalizes the job into
ready.
This prevents ready from becoming visible before the canonical files actually exist and have been verified.
A losing invocation can delete only its own staging files.
It never touches the winner's files.
Then Cleanup Became a Coordination Problem
Cleanup sounds simple until work is happening at the same time.
Delete the source files.
Delete the canonical files.
Delete the staging files.
Mark cleanup complete.
But what if a worker is still writing while cleanup runs?
What if an account is being deleted while a normalization attempt is in flight?
What if cleanup checks the folder, finds it empty, marks the job complete, and then a delayed storage write lands afterward?
The fix was a media writer quarantine.
When the database revokes a worker's authority, it starts a 300-second quarantine based on the database clock. That window matches the maximum worker execution window.
During quarantine:
- no new writer generation can be leased
- cleanup cannot be marked complete
- account deletion cannot finish
- reclaim waits before assigning another writer
- the storage prefix is swept and verified again after the window closes
Account deletion also became a fenced, retryable lifecycle instead of one optimistic pass.
That is more work than simply calling delete on a folder.
It is also the difference between hoping temporary files disappear and having a system that can prove the writer is gone before cleanup is considered finished.
Failure Reporting Had to Be Idempotent Too
There was another subtle failure mode.
The Node worker could report a failure to the database, the database could commit it, and the network response could disappear.
From the worker's point of view, the outcome would be unknown.
Sending a brand-new failure report could spend another attempt or produce a different result.
So each failure report now has its own generated ID.
If the response is lost, the worker retries the same report ID.
The database returns the persisted disposition:
- retry
- terminal
- rejected
The worker does not guess based only on the local error.
The durable job record stays authoritative.
Security Between the Workers
The Supabase function and the Node media worker communicate over a signed request.
The request includes:
- the job ID
- the media lease token
- a timestamp
- an HMAC signature
The signature is bound to that specific job and request time.
The Node endpoint rejects:
- missing signatures
- invalid signatures
- stale timestamps
- malformed job identifiers
- unsupported methods
- requests larger than the allowed body size
The private storage service key remains server-side.
No image bytes, base64 data, storage paths, prompts, model output, secrets, or raw exception text are written to operational logs.
The telemetry records only what is needed to operate the system: stage, outcome, typed error code, attempt count, and duration.
The Error Taxonomy Became More Specific
Before this work, several different image problems could collapse into one unsupported-image result.
Media Pipeline v3 separates the internal cause from the simple message shown to the user.
Examples include:
MEDIA_DOWNLOAD_FAILED
MEDIA_UPLOAD_FAILED
MEDIA_NORMALIZATION_FAILED
MEDIA_SIGNATURE_INVALID
MEDIA_DECODE_FAILED
MEDIA_DIMENSION_LIMIT
MEDIA_PIXEL_LIMIT
MEDIA_CHECKSUM_MISMATCH
The internal code decides whether the failure should retry.
The user still gets plain language.
A temporary storage problem can recover automatically.
A corrupt or spoofed image fails permanently.
A checksum mismatch is treated as an integrity problem and Gemini is never called.
One important behavior stayed exactly the same:
NOT_ASSESSABLE is a valid completed result.
If Physara cannot confidently assess the photos, that is not a broken pipeline. It is the system correctly refusing to invent an answer.
The Issues That Came Up During Deployment
The code was only one part of the work.
The first Vercel preview attempts were blocked or failed.
The media worker also hit TypeScript and ESM import problems after moving into the actual Vercel build environment.
Those failures mattered because local TypeScript resolution and a serverless production bundle are not always the same thing.
I fixed the imports, added direct import tests, and redeployed.
The preview became ready in the intended region.
A direct GET request to the media endpoint returned 405 Method Not Allowed, which was the expected result. The route existed, the function loaded, and it was correctly refusing the wrong method.
The branch was then released to main and deployed to production.
After release, I added a server-side gate so new physique starts could be restricted to a controlled production smoke test. That let me verify the real path without opening the new pipeline to everyone at once.
This was not a flip-the-switch-and-hope release.
It was a controlled rollout with a clear boundary for who could start new work.
How Much Work It Took
I did not run a stopwatch for every minute, so I do not want to pretend the number is more exact than it is.
The documented implementation, adversarial review, reliability fixes, deployment debugging, and release work represents roughly 10 to 12 concentrated hours across two main work sessions.
The first Phase 1 implementation commit and the release commit were separated by just under 29 elapsed hours.
The architecture decision itself started five days earlier, on September 9.
The first implementation pass alone ran for about one hour before the wider review and hardening work began.
The important part is where the time went.
The normalizer was not the majority of the difficulty.
Most of the work went into everything around it:
- defining the architecture before changing production behavior
- adding database states, leases, constraints, and service-only functions
- making retries bounded and stage-specific
- reviewing duplicate-worker races
- building the two-phase promotion fence
- coordinating cleanup and account deletion with in-flight writers
- making failure reports idempotent
- writing hostile image fixtures
- repairing deployment-only import problems
- validating the release in preview and production
- documenting the runbook and rollback behavior
That is why a feature that can be described as "resize the image before sending it to AI" became a multi-day reliability project.
What Was Tested
The test work covered the media layer, Edge functions, database lifecycle, and failure recovery.
The Node tests used real Sharp-encoded binary fixtures, not only mocked objects.
They covered:
- EXIF orientations 1 through 8
- CMYK conversion
- progressive JPEG input
- metadata removal
- spoofed MIME types
- truncated JPEG and PNG files
- large dimensions and decompression-bomb limits
- checksum generation
- HMAC verification
- duplicate invocations
- losing and winning promotion attempts
- partial uploads
- lost database responses
- idempotent failure reports
- staging cleanup
The Deno tests covered dispatch, canonical loading, integrity verification, provider retries, terminal failures, cleanup, and account deletion.
The database tests covered state transitions, expired leases, photo expiration, one-winner promotion, quarantine timing, RLS, cross-user access, and service-only boundaries.
By the final verification pass, the focused suites included:
- 179 Deno tests passing
- 76 Node tests passing
- both database suites passing, including 42 and 82 assertions
- TypeScript and production builds passing
The broader app test suite also remained green through the implementation.
The number matters, but the kind of tests matters more.
A normal JPEG working once would not have proven this pipeline reliable.
The useful tests were the ones that reproduced the situations most likely to break ownership, integrity, cleanup, or recovery.
What We Actually Built
Media Pipeline v3 is a boundary between untrusted user media and AI inference.
It gives Physara:
- reliable native image decoding
- one canonical image format
- private temporary storage
- checksum verification before Gemini
- separate media and provider retries
- durable job recovery
- duplicate-worker protection
- two-phase canonical promotion
- writer quarantine
- coordinated account deletion
- typed operational telemetry
- a controlled production rollout
The original problem was one valid JPEG failing inside createImageBitmap().
The finished system is much larger because the real requirement was never just "make this image decode."
The requirement was:
Make the analyzer dependable enough that a user can tap once and trust what happens next.
That is the difference between getting an AI feature to work and building the system around it well enough to release.