You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat: conform uploaded videos to one web-playable format, accept the common containers (#84) - #85
webReady is now a conform step. Every finished video is served in the one format the Pulse app records (CONFORM_TARGET), and a Pulse upload is left byte-for-byte. Containers from a host's file picker (.mov, .m4v, .webm, .mkv, .3gp, .avi) are accepted by default and become an .mp4 at the same artifact URL.
What it does
The upload
What happens
action
Already in the target (a Pulse upload)
nothing, bytes untouched
none
MP4 with the moov at the end
lossless -c copy faststart remux
remuxed
MP4 with an off-target stream
one ffmpeg run, in place
transcoded
Another container
one ffmpeg run into a new <id>.mp4 (a stream copy when the streams already conform)
conformed
No ffmpeg, unreadable, failed or timed out
nothing, the original serves
skipped + reason
Target: faststart MP4, H.264 8-bit yuv420p (limited range) with even dimensions, longest edge ≤ maxEdge (1920) with aspect ratio and orientation kept, rotation applied, AAC or silent. HDR (PQ/HLG) is tone-mapped to BT.709; an SDR source keeps its own colour tags (BT.709 or BT.601). A re-encode touches only the streams that are off.
Also in this PR:
webReady.timeoutSeconds: a guard against hung runs. The default is 60 + 10 × the duration counted in 1080p30 seconds, so a 4K120 second counts 16.
createVideoValidator({ maxDurationSeconds }), which refuses with 422 That file isn't a video. / That video is longer than the limit of …. Pictures don't count as video: PNG, JPEG, GIF, HEIC and one-frame clips are refused.
While a video is converting, its URL is served with max-age=0 instead of the configured (possibly immutable) cache.
CI installs ffmpeg (Ubuntu's FFmpeg 6.x with zscale). Before this, every web-ready/conform test was skipped in CI.
413 That file is larger than 500 MB.
The migrate script conforms existing artifacts the same way.
Invariants and failure cases
One persisted state per artifact, as before: converted (plus the new webReady result and, after a container change, ext/sourceExt) is written in one sidecar write. The replay rule is unchanged: a ready video that isn't converted is converted.
Failure
Result
Crash while ffmpeg runs
tmp file only; the original serves; replay redoes it
Crash after <id>.mp4 is written, before the sidecar switch
the original serves; replay converts again and its rename overwrites the .mp4 (run)
Crash after the switch, before the original is deleted
the .mp4 serves; the leftover original is deleted by remove (sourceExt)
Artifact deleted mid-conversion
remove runs under the in-process sidecar lock: either it goes first and the patch finds no sidecar (the runner drops the written file), or it removes the switched file (test: 50-round race; the pre-fix code failed 300/300 rounds of it)
Second instance on the same disk with the old extension cached
a converted video is always at <id>.mp4; resolve falls back to it, and re-reads the sidecar once if neither file exists (test)
A queued conversion whose artifact was removed or converted elsewhere meanwhile
re-read when its slot comes; does nothing; a failed run never records over a finished one
Run hangs
killed at timeoutSeconds, original kept, skipped: timed out after N s recorded (test)
Two instances on one disk: an acknowledgement on one written from a copy older than the other's switch
no cross-instance lock (as on main: the last sidecar write wins). The old copy names the deleted original, so resolve/getLocalPath fall back to <id>.mp4, the next conversion pass records ext again, and remove deletes <id>.mp4 too (test: a pre-conversion sidecar written back; fails without the fallback. test: the WebM test's replay repairs it; fails without the repair). A delete racing a write on another instance can leave the metadata behind, as on main; OPERATIONS.md says to use S3 for strict multi-instance guarantees
A conversion that outlives its upload (removed, then the id reserved again)
each reservation has a generation; the conversion is installed by one patch (in-process lock) conditioned on it, else its file is dropped (test, fails on the commit before)
A queued conversion whose upload is removed and its id reserved again before its turn
the job requires the generation it was scheduled for; settle and acknowledgement are per reservation (test, fails on the commit before)
A removal racing a new reservation of the same id
reserve runs under the in-process lock; remove deletes the sidecar last (from code reading: didn't reproduce on the commit before; regression test added)
A failed run racing another pass's finished conversion
unlessConverted is checked under the in-process lock; the runner then makes the files match whichever record stands (test)
GET racing the switch
waits for the file to open before headers; on ENOENT resolves once more (test)
ffprobe hangs on a malformed upload
every ffprobe run is bounded by probeTimeoutSeconds (test)
Client re-sends the final PATCH after a container change
204, as without a conversion: the local adapter's tus store reads the replaced upload as complete and takes its empty tail without a write (test: HEAD reports complete, the retry gets 204, the hook isn't fired again; fails on the commit before)
Decisions where I went beyond, or differ from, the issue
A .mov/.m4v that already conforms is remuxed to .mp4: the rule is "container conforms = .mp4 with an ftyp". Otherwise such a file would stay video/quicktime. The remux is a lossless stream copy.
Rotation alone triggers a re-encode, as the target says ("rotation metadata applied").
The content check is an opt-in helper (createVideoValidator), like createMp4Sniffer. PulseVault still doesn't run a validatePayload by default. It checks kind: "video" only.
SDR colour tags are kept, not converted to BT.709 (Copilot thread open for you). Re-encoding BT.601-tagged videos, which some Android phones record, would break "a Pulse upload is served byte-for-byte". Browsers honour the tags.
conformAvailable() is an async method, not a capabilities.conform property, because availability is found by spawning ffmpeg.
A failed or timed-out conversion is recorded and not retried, as before (only an unrecorded one is resumed).
S3 stays without conversion; the S3 adapter refuses the new ext/webReady patch fields.
Tested
npm test: 238/238 pass at 63a3606 on Homebrew FFmpeg 9.0.2, and protocol:check passes. Earlier, 230/230 at 61e68a4 also on FFmpeg 7.1.5 with zscale, the same shape as Debian/Ubuntu packages (Homebrew ffmpeg@7, run via PATH), with protocol:compat passing; not re-run on 7.1.5 since. CI runs the conform tests (ffmpeg installed there).
Real-file sweep: every file in the conform corpus (14 iPhone/Android/Pulse recordings: 4K60, 4K120, 10-bit HLG, full-range screen recordings, rotated exports) went through ensureWebReady under both FFmpeg versions. Each output was checked for: H.264 yuv420p, even size ≤ 1920, orientation and aspect ratio kept, no rotation tag, AAC when there was audio, no HDR transfer left, duration within 0.15 s, moov at the front, and a full decode with no errors.
FFmpeg 7.1: 14/14.
FFmpeg 9: 13/14 before the timeout fix. The failure was the 4K120 clip, killed at the old default; under FFmpeg 7.1 with the new default it converts in 520 s and passes.
The Pulse app export: none, same bytes.
HDR colour: frame from an iPhone HLG clip compared across the naive conversion (washed out), FFmpeg 9's scale and FFmpeg 7's zscale. Both tone-mapped outputs have correct colour.
Edge cases:
Refused with That file isn't a video.: PNG/JPEG/GIF/HEIC renamed as video, a one-frame clip, audio-only, a truncated MP4 and an empty file.
Converted and checked: MJPEG/PCM AVI with odd dimensions, Xvid/MP3 AVI, H.263/AMR 3GP, MKV with two audio tracks, 5.1 Opus WebM, full-range and 10-bit H.264, a VP8 WebM with spaces and ü in its name.
An MKV with only a cover picture and audio is accepted (MKV doesn't record a frame count).
Browser playback (Playwright on macOS: installed Google Chrome, Playwright Firefox 151, Playwright WebKit 26.5): 8 converted artifacts served by a local PulseVault with webReady: true (Pulse export, browser WebM VP9/Opus, iPhone HLG .mov, landscape 4K, rotation tag, PCM .mov, MJPEG AVI with odd size, 5.1 Opus WebM). 24/24 play. Each is served as video/mp4, has the expected size and orientation, and its playback clock advances.
Control, the same originals unconverted: on macOS most play as well, including iPhone HEVC in Chrome and Firefox, because macOS provides hardware HEVC decoding. Only the MJPEG AVI fails, in Chrome and Firefox. So on a Mac the visible gains are the AVI, 4K served at 1080p, and HDR shown as SDR. The HEVC gain the issue describes is for systems without HEVC decoding (Windows without the HEVC extension, Linux), which wasn't tested.
Through the fastify-demo (webReady: true): Pulse export none, browser WebM and iPhone HLG .movconformed, served as video/mp4. No 4xx/5xx.
Crash between writing <id>.mp4 and the switch (replay finishes it), two instances sharing a disk, delete mid-conversion: scratch scripts, not committed.
Found and fixed by these runs
Full-range video (iPhone screen recordings, yuvj420p) came out still full range and was converted again on every pass.
A picture renamed as video was accepted and turned into a one-frame MP4.
The default timeout killed a legitimate 4K120 clip.
Copilot's first six comments (replied inline): five fixed in code or docs; the BT.709 one is answered with a docs correction.
Copilot's second review: after a container change, replay and status built tus's upload id from the new ext. Fixed: sourceExt on the metadata plus uploadIdOf(meta), so a replayed hook's ext/uploadId match filename. Copilot rounds 3–5: three inline findings and nine "previously missed" ones, all addressed in 88a8d72 (summary in a PR comment). Round 6 (generations, reserve under the lock): eb5c298. Round 7 (owned and renewed locks, streamed packet scan, the 413 for deferred-length uploads, transcode: false → skipped): c995986. Round 8 (GET checks it opened the file its headers describe, one stale-lock takeover at a time, exact limit wording): 877d4d7. Round 9 (completion work belongs to the reservation it was scheduled for; the test fails on the commit before): 0b5e03c. Round 10 (fresh local path, bounded capability queries, observer failures, migrate rerun cleanup): 61e68a4. Round 11 (the lock file's lease couldn't fence a paused holder): the cross-instance lock is removed instead of fenced, and a converted video's file is always <id>.mp4 so a stale sidecar still finds it: 3d31bb0. A conversion that loses its record hands back a result only for its own reservation (3d31bb0). Main (with feat: https pairing links — buildUploadLink form: 'https' (protocol 2.4) #86) merged in: f7a2b5a. Round 12: CodeQL path check (fc6cfef), custom extensions keep sourceExt (e7fc74d), the default timeout capped at an hour (e25b8fd), a retried final PATCH after a container change gets 204 and conversions need a generation (63a3606).
Not tested
Playback on Windows, Linux, Android or iOS browsers; Safari itself (only Playwright's WebKit build).
The demo server (Debian 13) still has no ffmpeg installed.
…common containers (#84)
webReady becomes a conform step. Every finished video is brought to
CONFORM_TARGET, the format the Pulse app records: faststart MP4, H.264 8-bit
yuv420p with even dimensions, SDR, longest edge at most maxEdge (1920),
rotation applied, AAC or no audio. A file already in it keeps its bytes
(none); a moov at the end is a lossless remux; otherwise one ffmpeg run
re-encodes only the off-target streams (HEVC, 10-bit HDR tone-mapped, 4K
scaled, Opus/PCM to AAC). Another container (.mov, .m4v, .webm, .mkv, .3gp,
.avi) becomes a new <id>.mp4 (conformed): the sidecar switches ext,
converted and webReady in one write, then the original is deleted;
sourceExt lets remove() clean up a crash leftover.
- webReady.timeoutSeconds (default 60 + 10 x duration) kills a stuck run;
the original serves and skipped is recorded with the reason.
- The result is recorded on the artifact and reported by the status route
as webReady { action, reason } (protocol 2.4).
- core.conformAvailable() for a host's health check.
- createVideoValidator(): content check by ffprobe (video stream, duration
> 0, optional maxDurationSeconds) with plain 422 reasons; sniffVideo
fallback without ffprobe.
- 413 "That file is larger than 500 MB." instead of tus's message.
- Default video allowedExtensions: the seven containers above.
- Local resolve() re-reads the sidecar once when the cached file is gone
(another instance switched it).
- web-ready-migrate.mjs conforms existing artifacts the same way.
From a local run over real files (the conform corpus, edge cases, FFmpeg
9.0 and 7.1) and Copilot's review of #85:
- Full-range video (an iPhone screen recording's yuvj420p) came out still
full range, and was converted again on every pass: scale to limited
range (out_range=tv) before format=yuv420p.
- A picture renamed as a video (PNG, JPEG, GIF, an iPhone HEIC) passed the
validator and was "converted": an image demuxer or a one-frame stream is
not a video.
- remove() raced a conversion's switch to a new file and could write the
sidecar back after a delete (0/300 clean before, 300/300 after): it now
runs under the sidecar lock and reads the sidecar itself.
- A conversion queued behind others re-reads the artifact when its turn
comes (removed, or converted by another instance meanwhile), and a
failed run never records over a finished one.
- While a video converts, its URL is served with max-age=0 instead of the
configured (possibly immutable) cache.
- Sizes round down to even, so an odd maxEdge stays a cap.
- Docs: SDR sources keep their colour tags (only HDR is converted to
BT.709); transcode:false still runs lossless remuxes.
- CI installs ffmpeg so the conform tests run there (they all skipped).
#84)
An iPhone 4K 120 fps HDR clip (38 s, 4,520 frames) was killed at the old
default (60 + 10 x duration = 437 s) and served unconverted, though nothing
was wrong with it: it needs ~450-520 s on an M-series Mac. The default now
counts the duration in 1080p30 seconds (a 4K120 second counts 16), keeping
it a guard against a hung run rather than a speed limit.
…returns
The test checked acknowledged right after the hook ran; the flag is written
once the hook has returned. It never ran in CI before (no ffmpeg there) and
lost that race on the node 22 runner.
Eliminate TOCTOU between sidecar metadata and artifact resolution
src/core.ts:856
There is still a TOCTOU gap because the path is resolved before the fresh conversion metadata is read. On another instance, resolve can return its cached .webm while that file still exists just after the sidecar switched to .mp4; describeArtifact then reports converted: true, so the old bytes can be served with the immutable cache (or disappear before send and produce a transient 404). Resolve the file and cache state from the same fresh sidecar generation, or detect an extension change and re-resolve/retry.
Provide a default logger for security degradation warnings
src/lib/magic.ts:223
When no logger is supplied, this optional call suppresses the promised one-time warning, so the validator silently falls back from content validation to a 12-byte container sniff. Use a default logger so this security-relevant degradation is observable.
Apply timeouts to all ffprobe and duration fallback operations
src/lib/web-ready.ts:255
The wall-clock guard only wraps ffmpeg; this ffprobe invocation and the packet-duration fallback run without any timeout. Because both consume untrusted uploads, a malformed file can hold a conversion queue slot indefinitely, and createVideoValidator can hold the client's final PATCH indefinitely before conversion even starts. Apply a bounded timeout/kill to every ffprobe subprocess and report probe timeout separately.
Sanitize persisted FFmpeg errors to avoid filesystem disclosure
src/lib/web-ready.ts:440
This raw ffmpeg stderr is now persisted and returned by the status route. FFmpeg failures commonly include absolute input or temporary output paths, exposing server filesystem details and producing text that is not the documented person-readable reason. Keep the full error in the existing server log and persist a stable sanitized message instead.
🧠 Review effort: Balanced
Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.
…84)
After a container change `meta.ext` is the stored file's (`.mp4`), but
tus's record of the upload and `filename` keep the uploaded one (`.webm`).
describeArtifact now reports it as `sourceExt`, and `uploadIdOf(meta)`
names the upload by it, so a replayed hook's `ext` and `uploadId` match
`filename` and the status route asks tus for the right upload.
The pre-check does not make the following patch conditional. A failed run can read converted === false, then another instance records a successful conversion, and finally this unconditional patch overwrites its webReady result with skipped. This contradicts the stated “failed run never records over a finished one” invariant; make the check-and-patch atomic (for example, patch only while converted is still false).
Skip HDR conversion when no tone-mapping support exists
src/lib/web-ready.ts:531
When neither scale tone-mapping support nor zscale is available, toneMapper is null, but the code still publishes a plain-scaled output and retags it as BT.709 below. That produces incorrect HDR colours while reporting a successful conform, contrary to the target and fail-open behavior. Keep the original and report skipped when HDR cannot actually be tone-mapped.
🧠 Review effort: Balanced
Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.
Retry resolution when source conversion replaces the input
src/core.ts:856
The resolution and conversion state are read separately. If conversion switches the sidecar and removes the source between resolve() and send(), this request still tries the old .webm/.mov path and returns a transient 404 or an aborted stream even though the new MP4 is ready. Re-resolve and retry once on an ENOENT/404 during this cutover, or otherwise coordinate source deletion with active readers.
Skip HDR conversion when no tone mapper is available
src/lib/web-ready.ts:531
When an HDR input is encountered on a build with neither supported tone mapper, this falls through to ordinary scaling and then forcibly tags the unchanged HDR transfer as BT.709. That produces incorrectly coloured pixels while reporting a successful conversion, contrary to CONFORM_TARGET. Fail open with skipped unless a real tone mapper is available.
🧠 Review effort: Balanced
Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.
Prevent artifact GET failures during sidecar switching
src/lib/completion.ts:306
Unlinking the source immediately after switching the sidecar can transiently break an artifact GET that already resolved and stated the old path but has not yet opened it in serveResolution; that request receives 404 even though the artifact exists at the new extension. Make the GET path retry resolution once on an ENOENT during this switch (or serve from an already-open handle) before deleting the source.
Reject one-frame videos when nb_frames is unavailable
src/lib/web-ready.ts:279
nb_frames is optional and is commonly absent for containers such as MKV. In that case Number(undefined) is NaN, so a one-frame stream with a positive container duration is accepted, contradicting this API's promise that one-frame clips are not videos. Count/read up to two video packets when the frame count is unavailable and reject if fewer than two exist.
Validate ensureWebReady options at the public API
src/lib/web-ready.ts:476
The exported ensureWebReady API bypasses validateCompletionOptions, so invalid new options are accepted here: for example maxEdge: 1 produces a 2-pixel edge (breaking the cap), while a non-positive timeout is silently clamped to 1 ms. Validate maxEdge and timeoutSeconds at this public entry point, ideally through the same shared validator used by the core.
Conformity check ignores full-range color_range
src/lib/web-ready.ts:503
The conformity check never reads color_range. H.264 can be reported as pix_fmt=yuv420p with color_range=pc; such a faststart MP4 reaches none here even though CONFORM_TARGET requires limited range. Include color_range in probeVideo and treat full-range (pc) video as off-target so the existing out_range=tv filter is applied.
🧠 Review effort: Balanced
Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.
Cross-instance (shared workspace, a documented deployment):
- The local adapter changes a sidecar under a per-artifact lock file
(`<id>.json.lock`, created with wx; taken over after 30 s from a crashed
holder) as well as its in-process lock, and remove() runs under it. Two
adapters on one workspace racing a delete or an acknowledgement against a
conversion's switch: the pre-fix code failed this 3/3, now passes.
- Patch field `unlessConverted`: a failed run never records over another
pass's conversion; the runner then makes the files match whichever
record stands (the original goes only once the record names the new file).
GET: wait for the file stream to open before sending headers; on ENOENT
(a conversion just replaced the file) resolve once more instead of a 404 or
a cut-off response. Bytes resolved under an extension storage no longer
names are served with max-age=0.
ffprobe: every run over an upload is bounded (probeTimeoutSeconds, default
60); the validator refuses with "That video couldn't be checked in time."
and defaults its logger to console. A stream without a frame count (MKV,
WebM) is checked for two packets, so a one-frame MKV isn't a video.
color_range=pc counts as off-target.
ensureWebReady validates maxEdge/timeoutSeconds/probeTimeoutSeconds itself;
a failed run records "ffmpeg exited with code N", never ffmpeg's output
(server paths); HDR on an ffmpeg without tone mapping is left as uploaded
(skipped) instead of converted with wrong colours. webReady needs
describeArtifact.
Replies to the findings Copilot listed under "Previously missed" in its review summaries (they have no thread to answer in). All are in 88a8d72 unless noted.
GET racing a conversion's switch (core.ts:856, completion.ts:306): fixed. The route now waits for the file stream to open before sending headers, since an open file survives being replaced. On ENOENT it resolves once more and serves the new file instead of a 404 or a cut-off response. Bytes this instance resolved under an extension storage no longer names are served with max-age=0, never immutable. Test: "GET resolves again once when the resolved file is gone".
Validator warning with no logger (magic.ts): fixed. The logger defaults to console.
ffprobe without a timeout (web-ready.ts:255): fixed; see the inline thread.
ffmpeg stderr persisted (web-ready.ts:440): fixed. The recorded reason is conversion failed: ffmpeg exited with code N (or the timeout), and ffmpeg's output goes only to the server log. Test: a failing fake ffmpeg that prints a path gives exactly that reason.
Atomic check-and-patch (completion.ts:289): fixed. The new patch field unlessConverted is checked under the sidecar lock. Afterwards the runner re-reads the artifact and makes the files match whichever record stands: the original goes only once the record names the new file, and an output the record doesn't name goes. Test: "a conversion record with unlessConverted never replaces one already made".
HDR with no tone mapper (web-ready.ts:531): fixed. The original is left as uploaded, with skipped: HDR (…) needs tone mapping, which this ffmpeg can't do: FFmpeg 8 or later, or a build with zscale. Test: a fake ffmpeg that reports neither filter.
One-frame video without nb_frames (web-ready.ts:279): fixed. When the container has no frame count, ffprobe reads only the first two packets (-read_intervals %+#2), and fewer than two means it isn't a video. Test: a one-frame MKV.
ensureWebReady option validation (web-ready.ts:476): fixed. The shared validateWebReadyOptions runs in ensureWebReady and in the core's boot check. Test: maxEdge: 1, timeoutSeconds: 0 and probeTimeoutSeconds: -1 are refused.
color_range ignored (web-ready.ts:503): the probe now reads color_range, and pc counts as off-target ("full range"). Untested for this exact case: I couldn't produce yuv420p + color_range=pc. Full-range H.264 and HEVC encoded with x264/x265 report yuvj420p on FFmpeg 7.1 and 9.0, which the pixel-format check already catches, and the corpus covers that.
Tested at 88a8d72: 219/219 on FFmpeg 9.0.2, 219/219 on FFmpeg 7.1.5 (zscale), and 219/219 in three parallel runs; the sample sweep has 0 failures on both versions.
…e under the sidecar lock (#84)
Copilot round 6 on #85:
- Each reservation gets a `generation`; the runner converts into a temp
.mp4 (`install: false`) and installs it with one locked patch (`file`,
`ext`, result) conditioned on that generation and on no other pass having
recorded a conversion. A conversion that outlived its upload (removed,
then the id reserved again) can no longer record onto, or rename its file
over, the new upload. patchArtifact resolves false when a condition
doesn't hold; the runner then drops its file.
- reserveUpload runs under the sidecar lock and remove() deletes the
sidecar last, so a new upload of a removed id never loses its bytes to
the old removal.
STORED_EXT (/^\.[a-z0-9]+$/) was stricter than the allowedExtensions rule,
so a custom extension like .my-video lost its sourceExt on re-read after a
conversion (replay, uploadIdOf and remove then used .mp4), and storedExt
refused to serve such a video at all. Use options.ts's EXTENSION_REGEX in
all three places; storedPath still keeps the path in its kind directory.
It's computed from the upload's own duration, size and frame rate, so a
crafted file could advertise values worth a days-long run and hold the
queue. Capped at an hour (the unknown-duration default), and an hour when
the computed value isn't finite; an explicit timeoutSeconds still wins.
Preserve or reject non-right-angle rotation metadata
src/lib/web-ready.ts:229
Rounding every display matrix to a quarter turn can distort valid videos with non-90° rotation metadata. For example, 45° is stored as 90° here, so targetSize computes portrait dimensions while ffmpeg applies the actual 45° matrix before the forced scale, violating the promised aspect-ratio preservation. Preserve the actual angle and compute its displayed bounds, or explicitly reject unsupported rotations instead of silently changing their geometry.
Clamp sub-millisecond probe timeouts to 1 ms
src/lib/web-ready.ts:319
A positive sub-millisecond probeTimeoutSeconds rounds to 0; Node treats an execFile timeout of zero as no timeout, so the advertised hang guard can be disabled by an accepted option value. Clamp the converted timeout to at least 1 ms (as the ffmpeg timeout path already does).
Limit recovery claims to replayable completion bookkeeping
OPERATIONS.md:60
This claim is too broad: acknowledgement and conversion records can be replayed, but an outcome lost to a concurrent last-writer-wins sidecar update has no replay source and is permanently lost. Limit the recovery statement to completion bookkeeping so operators understand the shared-filesystem consistency tradeoff.
Handle singular byte size wording
src/lib/pulsevaultTus.ts:572
For a valid maxUploadSize of 1, this produces the user-facing error “larger than 1 bytes.” Handle the singular byte label.
Correct misleading claim that no data is permanently lost
src/storage/local.ts:320
“Nothing is lost for good” is incorrect for fields such as outcome, which replay cannot reconstruct after a stale cross-instance write wins. Describe only acknowledgement/conversion bookkeeping as recoverable; otherwise this comment can lead future changes to rely on a guarantee the adapter does not provide.
…ions need a generation (#84)
- The local adapter's tus store answers for an upload a conversion
replaced: tus kept its record, the file is gone, and a client re-sending
the final PATCH got 410. It now reads as complete and its empty tail is
taken without a write, so the retry reaches onUploadFinish's
already-finished branch (204).
- A conversion runs only with a generation; an adapter offering
getLocalPath without one has its videos recorded skipped, since a
queued conversion couldn't tell its upload from a later one of the id.
The local adapter's markReady gives one to an upload reserved before
generations were kept.
Tests (each fails on the previous commit): the WebM retry/HEAD, a
generation-less adapter, an older sidecar at markReady.
…est recovery claims (#84)
- A display matrix more than a degree off a quarter turn was rounded to
one, so a 45° video would be scaled as portrait and distorted. Such a
video is now skipped with the reason and served as uploaded; phones
only record quarter turns.
- A sub-millisecond probeTimeoutSeconds rounded to 0, which Node treats
as no timeout: at least 1 ms, as the ffmpeg timeout already was.
- "larger than 1 bytes" → "1 byte".
- OPERATIONS.md and the local adapter's comment no longer say nothing is
lost across instances: completion bookkeeping recovers, a host's
outcome lost to a stale write does not.
Test: a 45° rotation is skipped and its bytes kept (fails on the previous
commit). 239/239.
Copilot's review of e25b8fd listed five previously missed findings with no thread. All fixed in 578d5f7:
Non-right-angle rotation (web-ready.ts): a display matrix more than a degree off a quarter turn is no longer rounded to one. probeVideo reports the angle itself, and ensureWebReady records skipped ("rotation 45° isn't a quarter turn") and serves the upload as it is. Test: a 45° clip is skipped with its bytes untouched (fails on the previous commit).
Sub-millisecond probe timeout (web-ready.ts): probeVideo's timeout is at least 1 ms, as the ffmpeg timeout already was. From code reading; no new test.
Recovery claim (OPERATIONS.md) and comment (local.ts): both now say only the completion bookkeeping recovers (acknowledgement and conversion records, and the converted file at <id>.mp4), and that a host's outcome lost to a stale cross-instance write isn't redone.
"1 bytes" (pulsevaultTus.ts): formatBytes(1) is "1 byte". From code reading; no new test.
The two other items in that review (the retried final PATCH and optional generations) were already fixed in 63a3606; both threads are resolved. 239/239 pass locally.
Compute clip duration from packet PTS span, not absolute end timestamp
src/lib/web-ready.ts:290
This returns the absolute end timestamp as the clip duration. For durationless streams whose packet PTS starts above or below zero, maxDurationSeconds and the computed conversion timeout are therefore wrong (including possible limit bypasses for negative starts). Track the minimum packet PTS and return the timestamp span instead.
…imestamp (#84)
packetDuration returned the last packet's end, and clamped negative
timestamps to zero, so a WebM without a header duration whose
timestamps start above zero read as longer, and one starting below zero
could read as shorter than it is (slipping under maxDurationSeconds).
It now returns last end minus first start, over every numeric
timestamp.
Test: a piped WebM starting at 100 s measures 1 s (fails on the previous
commit). 240/240.
Copilot's review of 63a3606 had no open threads and one previously missed finding, fixed in 3588d81:
Durationless videos with non-zero packet timestamps (web-ready.ts, packetDuration): it returned the last packet's end and clamped negative timestamps to zero, so a WebM with no header duration whose timestamps start above zero read as longer, and one starting below zero could read as shorter (slipping under maxDurationSeconds and shortening the computed timeout). It now returns the span — the latest packet end minus the earliest packet start — over every numeric timestamp, negative included. Test: a WebM piped from ffmpeg with -output_ts_offset 100 (no duration in its header) measures 1 s; it fails on the previous commit. 240/240 pass.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Valid trailing-slash tus URLs bypass the new plain maximum-size error mapping.
0 open findings
Previously missed (1)
In code that hasn't changed since last review
Handle trailing slash in tus file ID parsing
src/lib/pulsevaultTus.ts:281
The tus file-id parser accepts one trailing slash (mirrored by tusLastUrlSegment in src/core.ts:396-399), but split('/').pop() returns an empty string for that valid form. A deferred-length upload that exceeds maxUploadSize through /upload/<id>/ therefore misses this mapping and gets tus's generic error instead of the promised plain size message. Strip at most one trailing slash before extracting the final segment.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Conversion concurrency is bounded, but the pending queue remains unbounded under sustained uploads.
0 open findings
Previously missed (1)
In code that hasn't changed since last review
Bound createQueue to prevent unbounded backlog and delayed conversions
src/lib/completion.ts:350
This still submits every completed video to createQueue, whose waiting array and running set are unbounded (completion.ts:209-227). Because the new conform runs can each last up to an hour and the default completeAfter: false lets uploads finish while jobs accumulate, sustained uploads can retain arbitrarily many contexts/promises, delay conversions indefinitely, and make shutdown drain the entire backlog. Add a bounded pending/admission limit (for example, leave excess artifacts converted: false for replay) or apply explicit backpressure.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #84.
webReadyis now a conform step. Every finished video is served in the one format the Pulse app records (CONFORM_TARGET), and a Pulse upload is left byte-for-byte. Containers from a host's file picker (.mov,.m4v,.webm,.mkv,.3gp,.avi) are accepted by default and become an.mp4at the same artifact URL.What it does
actionnonemoovat the end-c copyfaststart remuxremuxedtranscoded<id>.mp4(a stream copy when the streams already conform)conformedskipped+ reasonTarget: faststart MP4, H.264 8-bit
yuv420p(limited range) with even dimensions, longest edge ≤maxEdge(1920) with aspect ratio and orientation kept, rotation applied, AAC or silent. HDR (PQ/HLG) is tone-mapped to BT.709; an SDR source keeps its own colour tags (BT.709 or BT.601). A re-encode touches only the streams that are off.Also in this PR:
webReady.timeoutSeconds: a guard against hung runs. The default is60 + 10 ×the duration counted in 1080p30 seconds, so a 4K120 second counts 16.webReady: { action, reason }(protocol 2.5, additive; 2.4 is the https pairing link from feat: https pairing links — buildUploadLink form: 'https' (protocol 2.4) #86, merged into this branch).core.conformAvailable().createVideoValidator({ maxDurationSeconds }), which refuses with422 That file isn't a video./That video is longer than the limit of …. Pictures don't count as video: PNG, JPEG, GIF, HEIC and one-frame clips are refused.max-age=0instead of the configured (possiblyimmutable) cache.zscale). Before this, every web-ready/conform test was skipped in CI.413 That file is larger than 500 MB.Invariants and failure cases
One persisted state per artifact, as before:
converted(plus the newwebReadyresult and, after a container change,ext/sourceExt) is written in one sidecar write. The replay rule is unchanged: a ready video that isn'tconvertedis converted.<id>.mp4is written, before the sidecar switch.mp4(run).mp4serves; the leftover original is deleted byremove(sourceExt)removeruns under the in-process sidecar lock: either it goes first and the patch finds no sidecar (the runner drops the written file), or it removes the switched file (test: 50-round race; the pre-fix code failed 300/300 rounds of it)<id>.mp4;resolvefalls back to it, and re-reads the sidecar once if neither file exists (test)timeoutSeconds, original kept,skipped: timed out after N srecorded (test)resolve/getLocalPathfall back to<id>.mp4, the next conversion pass recordsextagain, andremovedeletes<id>.mp4too (test: a pre-conversion sidecar written back; fails without the fallback. test: the WebM test's replay repairs it; fails without the repair). A delete racing a write on another instance can leave the metadata behind, as on main; OPERATIONS.md says to use S3 for strict multi-instance guaranteesgeneration; the conversion is installed by one patch (in-process lock) conditioned on it, else its file is dropped (test, fails on the commit before)removedeletes the sidecar last (from code reading: didn't reproduce on the commit before; regression test added)unlessConvertedis checked under the in-process lock; the runner then makes the files match whichever record stands (test)ENOENTresolves once more (test)probeTimeoutSeconds(test)PATCHafter a container change204, as without a conversion: the local adapter's tus store reads the replaced upload as complete and takes its empty tail without a write (test: HEAD reports complete, the retry gets204, the hook isn't fired again; fails on the commit before)Decisions where I went beyond, or differ from, the issue
.mov/.m4vthat already conforms is remuxed to.mp4: the rule is "container conforms =.mp4with anftyp". Otherwise such a file would stayvideo/quicktime. The remux is a lossless stream copy.createVideoValidator), likecreateMp4Sniffer. PulseVault still doesn't run avalidatePayloadby default. It checkskind: "video"only.conformAvailable()is an async method, not acapabilities.conformproperty, because availability is found by spawning ffmpeg.ext/webReadypatch fields.Tested
npm test: 238/238 pass at 63a3606 on Homebrew FFmpeg 9.0.2, andprotocol:checkpasses. Earlier, 230/230 at 61e68a4 also on FFmpeg 7.1.5 withzscale, the same shape as Debian/Ubuntu packages (Homebrewffmpeg@7, run viaPATH), withprotocol:compatpassing; not re-run on 7.1.5 since. CI runs the conform tests (ffmpeg installed there).ensureWebReadyunder both FFmpeg versions. Each output was checked for: H.264yuv420p, even size ≤ 1920, orientation and aspect ratio kept, no rotation tag, AAC when there was audio, no HDR transfer left, duration within 0.15 s,moovat the front, and a full decode with no errors.none, same bytes.scaleand FFmpeg 7'szscale. Both tone-mapped outputs have correct colour.That file isn't a video.: PNG/JPEG/GIF/HEIC renamed as video, a one-frame clip, audio-only, a truncated MP4 and an empty file.üin its name.webReady: true(Pulse export, browser WebM VP9/Opus, iPhone HLG.mov, landscape 4K, rotation tag, PCM.mov, MJPEG AVI with odd size, 5.1 Opus WebM). 24/24 play. Each is served asvideo/mp4, has the expected size and orientation, and its playback clock advances.webReady: true): Pulse exportnone, browser WebM and iPhone HLG.movconformed, served asvideo/mp4. No 4xx/5xx.<id>.mp4and the switch (replay finishes it), two instances sharing a disk, delete mid-conversion: scratch scripts, not committed.Found and fixed by these runs
yuvj420p) came out still full range and was converted again on every pass.ext. Fixed:sourceExton the metadata plusuploadIdOf(meta), so a replayed hook'sext/uploadIdmatchfilename. Copilot rounds 3–5: three inline findings and nine "previously missed" ones, all addressed in 88a8d72 (summary in a PR comment). Round 6 (generations, reserve under the lock): eb5c298. Round 7 (owned and renewed locks, streamed packet scan, the 413 for deferred-length uploads,transcode: false→skipped): c995986. Round 8 (GET checks it opened the file its headers describe, one stale-lock takeover at a time, exact limit wording): 877d4d7. Round 9 (completion work belongs to the reservation it was scheduled for; the test fails on the commit before): 0b5e03c. Round 10 (fresh local path, bounded capability queries, observer failures, migrate rerun cleanup): 61e68a4. Round 11 (the lock file's lease couldn't fence a paused holder): the cross-instance lock is removed instead of fenced, and a converted video's file is always<id>.mp4so a stale sidecar still finds it: 3d31bb0. A conversion that loses its record hands back a result only for its own reservation (3d31bb0). Main (with feat: https pairing links — buildUploadLink form: 'https' (protocol 2.4) #86) merged in: f7a2b5a. Round 12: CodeQL path check (fc6cfef), custom extensions keepsourceExt(e7fc74d), the default timeout capped at an hour (e25b8fd), a retried finalPATCHafter a container change gets204and conversions need a generation (63a3606).Not tested