diff --git a/examples/egocap/CALIBRATION_TOOLS.md b/examples/egocap/CALIBRATION_TOOLS.md index b671c0fd5f..94f4baa51a 100644 --- a/examples/egocap/CALIBRATION_TOOLS.md +++ b/examples/egocap/CALIBRATION_TOOLS.md @@ -1550,15 +1550,36 @@ start its children with. What that leaves unknown: `wrist_left` and `wrist_right` entries and the wrist intrinsics files are in place for it. The camera sender is not part of this tree: where it corrects a wrist picture itself, that has to be switched off first, because a picture corrected twice is bent again. -- **Calibration takes are ordinary takes.** They pass the recorder's checks, are kept, and appear in the day's - recordings and in the end-of-day report like any other. One in which no tracking row was recorded fails those - checks and is not kept. Their task text is `Calibration: head camera` (or `left wrist camera`, - `right wrist camera`, `controller–glove offset`), which is how to tell them apart; the operator's own task text - is put back when the take ends. One that was interrupted stays on disk unfinished and holds the next take, like - any interrupted take, until a new batch is started on the recording page. The tool says so of its own take (*the - take was interrupted and stays on disk unfinished; start a new batch on the recording page to go on*) and - refuses to start another meanwhile (*an interrupted take is waiting; start a new batch on the recording page - first*). +- **Calibration takes are the recorder's takes, exempt from the capture checks.** A take either tool records is + never judged by the capture checks: a board waved at one camera and hands held still are what those checks + reject or set aside. It is never rejected for its camera's rate, flagged or quarantined; its record says why + (`capture_checks_exempt` in its manifest, `capture_qc_exempt` in its metadata), and the recording page shows it + as kept with *The capture checks did not run on this take.* The tools start their takes that way themselves: + nothing a request carries decides it, and no take started from the recording page is exempt. In every other + respect they are takes like any other: kept, counted, handed to time alignment, and listed in the day's + recordings and in the end-of-day report. Their task text is `Calibration: head camera` (or + `left wrist camera`, `right wrist camera`, `controller–glove offset`), which is how to tell them apart; the + operator's own task text is put back when the take ends. +- **A calibration take can still fail, and then it waits on the recording page.** Storage integrity is checked + as for any take: one in which no tracking row was recorded fails it and is not kept, and the tool says so (*no + tracking was recorded: ...; its data stays on disk and can be discarded on the recording page*), followed by + the recording page's own sentence for what the check found. The page lists such a take, with Discard, while + the session it was recorded in is the one open for recording. One that was interrupted waits unfinished and + holds the next take, like any interrupted take, until it is recovered or discarded on the recording page. The + tool says so of its own take (*the take was interrupted and waits unfinished; recover or discard it on the + recording page to go on*) and refuses to start another meanwhile (*an interrupted take is waiting; recover or + discard it on the recording page first*). A take recovered there is finished exempt, as it was started, and + kept; the tool that recorded it does not take it up afterwards, so record the calibration take again. +- **A take that waits from before rectification was switched on is resolved in a run started without it.** A + session of a run that corrects a camera carries that run's files, and the recorder reopens a session to recover + or discard a take only as it was recorded. A take that waits from a run that corrected nothing is listed on the + recording page of a run that corrects a camera, and both of its buttons are refused there (*This take's session + cannot be reopened under the current settings: ...*). Recover or discard what waits before the capture stack is + started with a correction, or start it once with `--no-rectify` to do so. +- **A refusal of the recorder is said as the recording page says it.** When the recorder will not start or end a + calibration take, the tool answers with the sentence a refused Record or Stop gets: the readiness reason the + page shows, a recordings disk that is full or read-only named in words, and for anything unexpected *the take + could not be started; see the backend log* (or *ended*). What the recorder raised stays in the backend log. - **A camera that arrives over LiveKit is guided only while a take records.** The backend holds no picture of it before the take's first frame. The Rectification preview of such a camera is made on a frame of a recorded take. - **The camera's lag is found only as well as the take shows it.** It is found from the take to within a 10 ms diff --git a/examples/egocap/DESIGN.md b/examples/egocap/DESIGN.md index 46ba584c1e..720d1c1cee 100644 --- a/examples/egocap/DESIGN.md +++ b/examples/egocap/DESIGN.md @@ -57,8 +57,8 @@ stale blocks a new take rather than starting one against outdated data. Recording itself is a short loop: start an episode, perform the demonstration, then either keep the take or discard it. The operator can edit the task description between takes without interrupting the session, and can rotate to a fresh batch of episodes when moving on to a new -block of work. A kept take is checked automatically once it finishes writing, and any problem -found is reported to the operator. +block of work. Every take is checked automatically once it finishes writing, and the operator is +told what became of it and why. The station's time is observed, not entered. The backend logs through the day whether the station could record or was down, and why, and counts active and down time between the first and last take @@ -67,7 +67,7 @@ kept as a blocker with its reason, in a daily log written on the station. A take and waits to be recovered or discarded counts as down, as does time the backend could not observe. At the end of the day a report lists every take of the day by session with what became of it: kept, -flagged, rejected, discarded, or still pending after an interruption. It is read from the recording +flagged, quarantined, rejected, discarded, or still pending after an interruption, with the reason. It is read from the recording service's own record of each take, so a take that was not kept is counted rather than left out, and each take belongs to the day it was actually recorded rather than the day its session was opened. The report shows the station's active and down time with its blockers and the operator's notes, and @@ -125,16 +125,31 @@ A kept episode is written to the station's local storage as one MP4 video file p camera, numeric tracking data — headset and controller pose, hand skeleton — stored in Zarr, and metadata: the task description and the operator who recorded it. -An automatic check runs once a take finishes recording and marks it kept, flagged, or rejected, -with the result and reason in the session status the backend reports back. A measured tracking -problem flags the take but keeps it, letting downstream consumers decide for themselves whether to -use it. A measured camera failure rejects the take and removes its media, since a recording -missing its camera content is not useful; a storage-integrity failure also rejects the take, but -keeps its data and reports its path for inspection. A take interrupted mid-recording, including by -a station restart, is retained as a pending episode that blocks a new take at that station. The -recording service exposes `recover_episode`/`discard_pending` to resolve it, but the browser page -has no command that calls either one yet -- clearing a pending episode today needs a direct call -into the service, not the page. +An automatic check runs once a take finishes recording and marks it kept, flagged, quarantined or +rejected, with the result and the reason in the session status the backend reports back: which +camera or stream, what was measured against which limit, and what to check. A measured tracking +problem marks the take bad but keeps it, letting downstream consumers decide for themselves whether +to use it; by a station switch that is on by default it is quarantined, set apart from its session +under the recording output, and otherwise it stays with its session, flagged. Either way it is not +time-aligned. A measured camera failure rejects the take and removes its media, since a recording +missing its camera content is not useful: a camera whose rate while it ran was under its minimum, or +that recorded too few frames for the take's length. A storage-integrity failure also rejects the take, but +keeps its data and reports where it is for inspection. The thresholds are deployment policy, read +from a documented defaults file that a site or a station can override, and each take's metadata +records the ones it was judged by. + +A take interrupted mid-recording, including by a station restart, is retained as a pending episode. +In the session open for recording it holds the next take until the operator recovers or discards it +from the page; one left behind by an earlier session, recorded under any name the station has had, +holds nothing and is listed in the end-of-day report's dialog with the same two commands. A session +that a recorder still has open is not listed: the recorder marks it about once a second, which a +backend on another machine sharing the recordings folder can see without a shared lock, and when the +recorder cannot write that marker it refuses a new take and says so, without interrupting one that +is being recorded. Recover finishes the take and runs its checks, and is +offered only for a take that was completely written, while the station is set up as when it was +recorded. Discard removes the take's recorded media for good, so the page asks once before sending +it. A take the integrity check rejected is listed with Discard only while its session is the one +open for recording; afterwards its data stays on disk and is removed there. Whichever of the station's calibration files are actually installed — the head camera's intrinsics and extrinsics, each wrist camera's intrinsics, and the controller-to-glove wrist @@ -202,7 +217,9 @@ to a new batch, available as on-screen buttons and keyboard shortcuts alike, usa demonstrating a task. Buttons and keyboard shortcuts use the same readiness checks. A command that cannot run — no operator entered, no camera ready, no task set — is rejected with the specific reason, and a take's outcome is -reported once its check actually completes, not assumed from the stop command alone. +reported once its check actually completes, not assumed from the stop command alone. The outcome +stays above the cameras until the next take starts, in the backend's own sentences, and an outcome +the page does not recognise is shown as unknown rather than as kept. If a browser tab reconnects mid-session, it is brought back to the same live state, since the recording session itself lives in the backend, not in any one tab. The task description opens into @@ -233,12 +250,15 @@ It is a separate thing from the controller-to-glove wrist offsets below. The station's calibration files — the head camera's intrinsics and extrinsics, each wrist camera's intrinsics, and the controller-to-glove wrist offsets — are made from the recording page, by the -calibration tools under Settings, Devices. Each tool records an ordinary take, solves from it, and -installs the result into the station's calibration directory. `recording/tools/calibrate_station.py -camera --install` runs the same camera solve on a recorded take without the backend; the wrist -offsets are made on the page only. The backend copies whichever of those files exist into each -session as it opens, so a take can be related back to the calibration active when it was recorded; -an install from the page ends the open batch, so that the next take's session holds the new files. +calibration tools under Settings, Devices. Each tool records a take of its own through the recorder, +solves from it, and installs the result into the station's calibration directory. Such a take is +exempt from the automatic check of capture quality, which a board waved at one camera or hands held +still would fail; its storage integrity is checked like any take's. +`recording/tools/calibrate_station.py camera --install` runs the same camera solve on a recorded +take without the backend; the wrist offsets are made on the page only. The backend copies whichever +of those files exist into each session as it opens, so a take can be related back to the calibration +active when it was recorded; an install from the page ends the open batch, so that the next take's +session holds the new files. The recorder applies none of them to the data it stores. One of them is applied before the video reaches it: a camera's lens calibration drives the correction of that camera's video into the @@ -324,8 +344,10 @@ reconstructed per tab. The recording session stays in the backend when a browser reconnecting tabs receive its current state. Rotating to a new batch ends the current batch; the next take starts a new recording session, independent of the underlying capture connection, which keeps running under it the whole time. The backend writes accepted samples to local storage, runs -the automatic check once a take stops, and reports the outcome — kept, flagged, or rejected — back -to every connected viewer, with the specific reason behind any failure. +the automatic check once a take stops, and reports the outcome — kept, flagged, quarantined or +rejected — back to every connected viewer, with the specific reason behind any failure. It also +lists the takes waiting to be recovered or discarded, of the open session and of earlier ones, and +carries out those two commands; removing a take's media stays in the recording service. ### Recordings browser (PoC demo, not part of the final design) diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 089a481712..f76596b9c2 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -84,6 +84,273 @@ backend printed at startup — both are required before any recording command is [`frontend/README.md`](frontend/README.md) for the full station-file and environment-variable reference. +A take recorded this way is judged when it stops, like any other; see [Capture checks](#capture-checks) for what +the page then says and for the mock faults that show each outcome. + +## Capture checks + +Every take is judged once, when it stops, from what was recorded. The page says what became of it above the +cameras, and why in a sentence: which camera or stream, what was measured against which limit, and what to check. +The end-of-day report carries the same sentence for each take. + +| The page says | What happened | Where the take's data is | +| --- | --- | --- | +| Kept | The checks passed. A kept take the checks did not run on says so. | `//episode_`, or its slot in a routed group | +| Kept, but flagged | A tracking check marked the take bad, on a station with quarantine off. | The same place, marked `bad_episode` in its metadata. Not time-aligned. | +| Quarantined | The same, on a station with quarantine on (the default). | `/_quarantine//episode_`. Not time-aligned. | +| Rejected, and its media removed | A camera recorded below its minimum rate, or too few frames for the take's length. | Nowhere: the take's video and tracking are removed. Its record keeps what was measured, and the day's report lists it. | +| Rejected, its data left on disk | The stored data failed the integrity check. | `//episode_.pending`, for inspection, until it is discarded | +| Discarded | The operator discarded it. | Removed | +| Interrupted | A capture source stopped during the take, or writing or finishing it failed. | `//episode_.pending`, until it is recovered or discarded | + +### What is checked + +The limits are the documented defaults in +[`recording/egocap/config/data_check/data_check_config.yaml`](recording/egocap/config/data_check/data_check_config.yaml); +that file is the authority, and this table follows it. + +| Check | Shipped limit | What it does to the take | +| --- | --- | --- | +| Camera minimum rate, for each recorded camera | An average below 0.86 of the camera's expected rate (25.8 fps of 30), or fewer than 0.86 of the frames a take of that length holds | Rejects it and removes its media | +| Frozen stream: the headset and each controller, and each glove where `gloves_expected` is set | No change for 1 s | Marks it bad: flagged or quarantined | +| Tracking gap: a tracking source that sent no data | 1 s | Warning; marks it bad with `tracking_gap_marks_bad` | +| Take length | Outside 1 s to 600 s | Warning; marks it bad with `duration.marks_bad` | +| Dropped camera frames | More than 6 within any 2 s | Warning | +| Camera rate far from the expected one | 10 % above or below | Warning | +| A stream that barely moved | 2 s | Warning | +| A stream unchanged for the whole take, a zeroed pose, a video encoded at another size than declared | | Warning | +| Camera frame counts that differ across cameras | Off | Rejects it and removes its media, when switched on | +| Storage integrity: readable files of the declared shape, every required source present, as many video frames as timestamps | Always on | Rejects it and keeps its data | + +A camera's expected rate is the one the capture session declares for it, unless the station file states another +(`guardrails.camera_expected_fps`). A warning never decides: it is listed with the take and counted on the page. +A take marked bad is not time-aligned, whichever of the two it becomes. + +The camera rate rule asks two things of each camera, with the same share of its expected rate: its rate while it +ran, and how much of the take it recorded. A camera that fails either has its take rejected, and the page names the +camera with what was measured. [What to know before relying on it](#what-to-know-before-relying-on-it) states the +rule exactly and says what it leaves unjudged. + +A take started as exempt from the capture checks is otherwise an ordinary saved take: it is checked for storage +integrity only, counts as kept and is handed to time alignment, and its metadata says `capture_qc_exempt: true`. +That is for a calibration recording, which holds still on purpose. The calibration tools under Settings, +Devices record every take of theirs that way (the headset calibration and the controller–glove offset), and +the page says of such a take that the capture checks did not run on it. No recording command can ask for it: +a take started with Record is always judged. A calibration take that is interrupted, or that the integrity +check rejects, waits on the recording page like any other; see +[`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#what-the-tools-do-not-do). + +### Quarantine + +`guardrails.quarantine` is one switch per station, on by default. On, a take marked bad is finished under +`/_quarantine//episode_`, outside every session and studio folder, and counted as quarantined. +Off, it is finished where a kept take would be, marked bad, and counted as flagged. The session itself is never +moved. Nothing on the page releases or deletes a quarantined take. + +The quarantine folder must be a plain folder on the recordings disk: not a link, not a file, not on another disk. +Otherwise Record is refused, before anything is recorded, with a sentence that says which it is. + +```yaml +# In the station file (EGOCAP_STATION_CONFIG), under the station: +data_check: + guardrails: + quarantine: false # keep a take marked bad with its session, flagged +``` + +### Thresholds + +The defaults file is read once when the backend starts. `EGOCAP_QC_CONFIG` names another file for a site, and the +station file's `data_check` section, of the same shape, changes any subset of its keys for one station. An unknown +key, a value of the wrong type or one out of range holds every take until the file is fixed and the backend +restarted; the preview keeps running and the page gives the reason (`quality-check configuration is invalid; see +backend logs`, or `station configuration is invalid; see backend logs` for the station's section). Settings, +Advanced, *Capture checks* shows the thresholds in force, the defaults file's name and SHA-256 and what the station +changed. They are deployment policy: nothing on the page edits them. + +A station's file can switch the checks or the camera rate rule off, or weaken the rule: `guardrails.enabled: false`, +`guardrails.camera_min_fps_enabled: false`, a low `guardrails.camera_min_fps_ratio`, or a low +`guardrails.camera_expected_fps`. A take whose camera lost frames is then kept, counted as kept and time-aligned, +with at most a warning. Only the file on the recording PC can do this; no message from the page can. The *Capture +checks* card says so in a sentence at its top whenever a station runs that way, since nothing else on the page does. + +### Interrupted takes + +An interrupted take holds Record for its session until the operator recovers or discards it, with the buttons the +take is given, beside its outcome. + +- **Recover** finishes the take: it runs the checks if they did not run, and the take then ends as its checks + decide (kept, flagged or quarantined, or rejected). It is offered only for a take that was completely written, + and only while the station is set up as when the take was recorded, with the same cameras and settings. The + page says what Recover would do before it is pressed, or what the take needs; while no camera is connected it + says that this is not known yet. +- **Discard** removes the take's recorded video and tracking for good, so the page asks once first, naming the + take. + +Record works again in the same session once the take is resolved. Other takes that wait hold nothing; the page +counts them in one line, and End of day lists each with the buttons it is given, whatever day it was recorded on: + +- A take an earlier session left behind, after a backend restart or after New batch was used past it. The + sessions listed are those recorded under any name the station has had, and those recorded before it had one. +- A take the integrity check rejected, with Discard only, while its session is the one open for recording. + [What to know before relying on it](#what-to-know-before-relying-on-it) says what becomes of it afterwards. +- A session folder copied or renamed by hand is shown and left alone: neither button is offered for its records, + and the row says to delete the copy, or to give a renamed folder its old name back, on the recordings disk. + +A session that some recorder has open is never listed and never acted on. On one machine the session's lock says +so at once. For a reader anywhere else, a recorder marks its open session by rewriting the session's lock file about +once a second, and a backend lists a session's takes only after two looks 2.5 s apart found that file unchanged. +This needs neither file locks that work across machines nor clocks that agree. Takes left by an earlier run +therefore appear a few seconds after the backend starts, and a Recover or Discard of one can take a few seconds +longer to answer. + +The recorder watches its own marker. When it has not been able to write it for 2.5 s, Record is refused with a +sentence about the recordings disk until the marker is written again. A take being recorded at that moment is not +interrupted: the status bar goes on showing it as recording, with that sentence beside it, Stop works as always, and +the finished take carries a note saying that the recorder could not write for a while. + +A full recordings disk, a used-up quota, and a read-only or unwritable recordings folder are said in words on the +page: when Record is refused, when a take is interrupted, and when finishing one fails. They are said only for a +failure on a file in the recordings folder; any other failure gets a general sentence that points to the backend +log. + +The two buttons are the commands `recover_pending` and `discard_pending` on `WS /api/session`; see +[`backend/README.md`](backend/README.md). + +### Seeing each outcome without hardware + +The mock CaptureServer of the [Quickstart](#quickstart-mock-data-no-hardware) records a healthy take, which is +kept. Two named faults show the others; start the backend after the capture server each time. + +```bash +uv run capture-server --mock --fault camera_stall # every camera delivers for 1.0 s, then withholds frames for + # 1.5 s, and repeats: a take of a few seconds is rejected and + # its media removed +uv run capture-server --mock --fault sample_freeze # every tracking pose stops changing: the take is quarantined, + # or flagged where the station sets quarantine: false +``` + +Stopping the mock capture server during a take interrupts the take; it was cut off while being written, so it +can only be discarded. + +### What to know before relying on it + +How the checks and the two commands behave where it is easy to assume otherwise. This is for whoever puts a station +into use and for whoever changes this code. + +**Every way a take's recorded video and tracking are removed.** + +- The camera rate rule rejects the take, when it stops or when Recover runs its checks. There is no trial mode: on + a station that runs the rule, a take it rejects is gone. +- Discard of a take that waits, from its banner or its row in End of day, after the page asked once. That includes + a complete take that Recover would have finished. +- Discard of the take being recorded. The button and its key act at once, without a question. +- Shutting the backend down while a take is being recorded discards that take. That is how the backend shuts + down, whatever the checks would have said of the take: stop the take before stopping the backend. + +A take marked bad keeps its data, flagged or quarantined. So does a take rejected for integrity, and an interrupted +take keeps what was written until someone decides. + +**The camera rate rule, exactly.** Each camera is asked two things, both with `camera_min_fps_ratio` (0.86) of its +expected rate. First, its rate over its own frames, from its first frame to its last, once those frames span ten +frame intervals (0.33 s at 30 Hz). Second, how many frames it recorded against how many a take of that length holds, +less three frame intervals for a camera's ordinary start and stop; this is asked in a take of thirteen intervals or +more (0.43 s at 30 Hz), and the take's length is that of its longest source. The count is what rejects a camera +that delivered one frame, a burst at one end, or ran well for a part of the take: the page then says how many frames +the camera recorded and about how many the take holds. Left unjudged: a take too short for both questions is not +rejected for a camera's rate, and gets a warning that says so; in a take of ten to thirteen intervals the frames are +not counted, so a camera whose frames span fewer than ten intervals passes with that warning; and a take is as long +as its data, so when every source stopped early the take counts as short however long the operator recorded, and +the take-length warning and the tracking checks are what speak then. + +**One recordings folder per machine.** The recorder is built for a recordings folder that one machine writes to. If +machines share one, give each its own station name: a backend with no configured name uses the deployment's default +label, which every unconfigured backend shares, and a station lists the takes left under its own names. What tells +a backend that a session is open is the session's lock where that lock reaches, which is on the same machine, and +otherwise the marker its recorder rewrites every second, watched for 2.5 s. The marker fails for a recorder that is +stopped or suspended, and for one whose disk stalls or refuses the write for 2.5 s: its session then looks closed +to another machine, which can list the take being recorded and discard it. A recorder that is still running notices +this itself, refuses Record until the marker is written again and notes it on the take; a stopped one says nothing. +Two backends that no lock separates can find the same leftover take and act on it at the same moment, and a session +recorded before the station had a name is listed by every station that shares the folder. Read from the code and +not seen in a run: letting a session go, at New batch or at shutdown, waits for a marker write that is stuck. + +**What the page says about the disk.** Four causes are named in words: the recordings disk is full, its quota is +used up, the recordings folder is read-only, the backend may not write to it. They are named from the system's +error number, and only when the failing file is in the recordings folder. Everything else gets a general sentence +that points to the backend log: a failure elsewhere on the machine, such as a calibration file that cannot be read +or an encoder program that cannot be run; a failure that names no file, unless one of the recorder's own writers +raised it; and a full disk that the video encoder is the first to meet. + +**Takes rejected for integrity stay on the disk.** Such a take is listed, with Discard only, while its session is +the one open for recording. After New batch or a backend restart nothing on the page lists it. Its data stays at +`//episode_.pending` until it is removed there, and the day's report counts the take as +rejected with its data kept. + +**A take that waits from before a camera's video was corrected.** A session of a run that corrects a camera's +video carries that run's files (see [`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#how-recordings-get-the-files)), +and a session is reopened to resolve a take only as it was recorded. In a run that corrects a camera, a take that +a run without correction left behind is listed and neither command works on it: both answer that its session +cannot be reopened under the current settings, and the take is left on disk. Recover or discard what waits before +starting the capture stack with a correction, or start it once with `--no-rectify` to do so. The calibration takes +recorded before a station's first corrected run are the usual case. + +**Which station names are followed.** The list of waiting takes holds the sessions recorded under any name the +station has had. A rename made from the page is recorded whether or not the station is in use at that moment, and +also on a day it recorded nothing, so the takes left under the old name stay listed. Not followed: a name changed +by editing the registry file by hand. Takes left under the deployment's default label, or under another station's +name, are listed only while that label or that station is the one in use, since choosing a station is not a rename. +A name that one station gave up and another then took belongs to both, and each lists the takes left under it. + +**The first read of a large recordings folder is slow.** Earlier sessions are read in the background once per +backend start, and their takes appear only when that read is done: about half a minute for some twelve thousand +take records where it was measured. Later reads are cheap, because a session read as finished is not opened again +until the backend restarts, the station's names change or the folder is replaced. A take that another tool leaves +in such a session later is not listed until then. + +### Not yet verified on hardware + +Everything in this section has been exercised against the mock capture server and synthetic takes only. + +**The camera rate rule has not met a real camera**, on either camera path, read by CaptureServer or published +through LiveKit: not its rate, not its first frames after Record, not its last ones before Stop. The mock camera +records at its declared rate. Until a station's cameras have been measured, the rule can remove a take whose camera +was healthy. A camera that loses no frame and runs at its expected rate is rejected by the count once it misses, at +the two ends of the take together, more than 14 % of the take plus 2.6 frame intervals: + +| Take length | Frames it holds at 30 Hz | Frames needed | Such a camera may miss, at both ends together | +| --- | --- | --- | --- | +| 0.43 s | 13 | 8.6 | 0.15 s | +| 1 s | 30 | 23.2 | 0.23 s | +| 3 s | 90 | 74.8 | 0.51 s | +| 10 s | 300 | 255.4 | 1.49 s | +| 100 s | 3000 | 2577.4 | 14.1 s | + +So a first frame more than half a second after Record rejects a three-second take, and one more than a quarter of a +second after Record rejects a one-second take. A camera that also runs under its expected rate, or drops frames +inside the take, has that much less to spare, because the same 14 % covers all of it. A station that cannot trust +the rule yet switches it off in its own file with `guardrails.camera_min_fps_enabled: false` +(`guardrails.enabled: false` switches every capture check off), or weakens it with a lower `camera_min_fps_ratio` +or a lower `camera_expected_fps` for a camera; see [Thresholds](#thresholds). Settings, Advanced, *Capture checks* +says at its top when a station runs with the rule off or weakened. + +- **What real tracking looks like when it stops.** Whether a headset, controller or glove that loses tracking + repeats its last pose (a frozen stream) or sends nothing (a tracking gap), and whether a device at rest ever + reads as frozen, is only known for the mock. +- **Gloves.** Their streams are judged only where `gloves_expected` is set, and no take with real gloves has been + judged. +- **Interrupted takes of real devices.** Recover and Discard were exercised on takes interrupted by stopping the + mock and by a session folder made read-only during a take, not by a camera unplugged during one. How long a real + camera can send nothing before its take is interrupted has not been measured. +- **A recordings folder shared between machines.** No network share was used: the lock that does not reach another + machine was a stand-in on one disk. Not tried either: a file server that shows one machine an old copy of + another's marker, and a machine that goes to sleep while it holds a session. +- **The quarantine folder on another disk.** That refusal was exercised with a stand-in; no second disk was mounted. +- **What the tests do not show.** A recorder was stopped by killing its process, or by imitating that inside one + process at each step; the power was never cut. Most backend tests of the list of waiting takes run with the wait + between its two looks switched off, and those that keep it use far shorter times than the 1 s and 2.5 s a station + runs with. The marker's own tests run in real time with shortened times, so one can fail on a machine that stalls + at the wrong moment. The page was run against the mock stack only. + ## One command for the whole stack `tools/start_system.py` deploys the camera sender to the Orin, then starts LiveKit, CaptureServer, the backend @@ -187,6 +454,7 @@ an environment variable: | Variable | Affects | | --- | --- | | `EGOCAP_STATION_CONFIG` | Path to the deployment station file described above. See [`backend/README.md`](backend/README.md). | +| `EGOCAP_QC_CONFIG` | Path to a site's own capture-check thresholds, in place of the shipped defaults file. See [Capture checks](#capture-checks). | | `EGOCAP_CAPTURE_SERVER_URL` | Where to connect for tracking/camera data. See [`frontend/README.md`](frontend/README.md). | | `EGOCAP_DATA_DIR`, `EGOCAP_CALIBRATION_DIR` | Where configuration/calibration defaults live. See [`recording/README.md`](recording/README.md); the calibration files are made and installed with the [calibration tools](CALIBRATION_TOOLS.md). | | `EGOCAP_STREAMS_STATE` | The file in which `tools/start_system.py` tells the backend it starts what each bridged camera is published as, rectification included. Not set by hand in normal use. See [`backend/README.md`](backend/README.md). | diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index 6efcf768ca..fdca87d3b1 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -26,19 +26,19 @@ or restarts it. | Route | Purpose | | --- | --- | -| `WS /api/session` | The main live connection: capture-status snapshots, sampled binary tracking frames, and recording commands/replies/snapshots. One socket per browser tab; see [`frontend/README.md`](../frontend/README.md) for the full message shapes. | +| `WS /api/session` | The main live connection: capture-status snapshots, sampled binary tracking frames, and recording commands/replies/snapshots. One socket per browser tab; see [`frontend/README.md`](../frontend/README.md) for the full message shapes and [Take outcomes and pending takes](#take-outcomes-and-pending-takes) for what the recording snapshot says about a take. | | `GET /stream{id}` | MJPEG camera preview, bound to the backend/session identity advertised in the `/api/session` snapshot. | | `GET /api/capture-status` | Thin HTTP inspection endpoint mirroring the latest snapshot; the frontend does not poll this during normal operation. | -| `GET /api/settings` | The backend's effective configuration (CaptureServer URL, sources, station file, recording root, 3D view, origin policy), read-only and gated by the `X-Control-Token` header; the page's Advanced settings tab shows it. Secrets are reported as present or absent, never by value. | +| `GET /api/settings` | The backend's effective configuration (CaptureServer URL, sources, station file, recording root, capture-check thresholds, 3D view, origin policy), read-only and gated by the `X-Control-Token` header; the page's Advanced settings tab shows it. `quality_checks` holds the thresholds in force (`effective`), the defaults file's base name and SHA-256, what the station's `data_check` section changed (`station_overrides`), `notices` (a sentence for each way the station runs the checks or the camera rate rule switched off or loosened; empty otherwise), or `error` when they could not be read. Secrets are reported as present or absent, never by value. | | `GET`/`PUT /api/operator-settings` | The operator's station setup: the camera type (`sensing_gmsl` or `oak_d`), camera roles (`ego`, `wrist_left`, `wrist_right`), the task catalog the recording panel's picker offers (`task_file`), the task it preselects (`preselected_task`) and whether calibration files are required before recording (`require_calibration`, a boolean, `false` by default; see [Start-of-day flow](#start-of-day-flow)). Kept in `.egocap/operator_settings.json` under the recording output (hidden from the recordings browser) (`EGOCAP_OPERATOR_SETTINGS_FILE` overrides the path) so every browser sees the same values. `PUT` names only the fields it changes and uses `X-Control-Token`; legacy JSON `control_token` remains accepted. A wrong token is 403 and bodies above 16 KiB are rejected with 413 before parsing. | | `GET`/`POST /api/stations`, `PUT`/`DELETE /api/stations/{id}`, `POST /api/stations/select` | The station registry: the stations an operator chooses between and the one in use. A station is a name, a camera type, the camera filling each role and the capture host address last given to its headset. Kept in `stations.json` beside the operator settings. Every change uses `X-Control-Token` and answers with the new listing; a refusal is a 400 with the specific reason (a duplicate name, a camera in two roles, an unknown field), and an unknown id is 404. The station in use cannot be selected, edited or deleted while a take is being written, and a change that would start a new batch (selecting another station or none, renaming or deleting the station in use) is refused with `recover or discard the interrupted take first` while an interrupted take waits. A station's headset address is listed only when the `GET` carries the token. See [Stations](#stations). | | `GET`/`POST /api/station-uptime` | What the station in use is doing now (`ready`, `recording`, or `down` with the reason) and its active and down time between today's first and last take, with each down period as a blocker (`end` is `null` for one that has not ended). It is observed by the backend, never set: `POST` (`X-Control-Token`) only saves the day's notes, with the body `{"station": , "notes": }`; when that is no longer the station in use the reply is a 409 and nothing is written. `GET` is open, and returns `notes` as an empty string unless it carries `X-Control-Token`: the notes are the operator's free text, and the end-of-day report, which needs the token, is where the page reads them. See [Stations](#stations). | | `GET /api/setup` | The start-of-day flow: the four steps' states, the live station checklist (`checks`, each with a `status` of `pass`, `fail`, `warn` or `skip`), `enforced` (whether the checklist gates recording or only advises), `blocked_reason` (why station setup holds a take; only a failed item does) and, when the request carries `X-Control-Token`, `headset`: the capture host address to enter in the headset, the one remembered for the station in use, and whether that one stopped being valid. Everything in one reply describes one station: if the station in use keeps changing while it is gathered the reply is a 503 (`the station in use is changing; try again`). Read-only. See [Start-of-day flow](#start-of-day-flow). | -| `GET /api/day-report`, `POST /api/day-report/save`, `POST /api/day-report/correct` | The end-of-day report, all with `X-Control-Token`. `GET` returns today's takes for the station in use by session, with a count and duration per disposition (kept, flagged, rejected, discarded, pending, recording) read from the recording service's manifests, plus the station's time (`uptime`). `save` writes `__report.json` beside the daily log and refreshes that log's recorded time. `correct` rewrites the task of one take or a range of a session's takes (`session`, `episodes`, `task`). Each take carries `location`, where its data is under the recording output. See [End-of-day report](#end-of-day-report). | +| `GET /api/day-report`, `POST /api/day-report/save`, `POST /api/day-report/correct` | The end-of-day report, all with `X-Control-Token`. `GET` returns today's takes for the station in use by session, with a count and duration per disposition (kept, flagged, quarantined, rejected, discarded, pending, recording) read from the recording service's manifests, plus the station's time (`uptime`). `save` writes `__report.json` beside the daily log and refreshes that log's recorded time. `correct` rewrites the task of one take or a range of a session's takes (`session`, `episodes`, `task`). Each take carries `location`, where its data is under the recording output, its `reasons` and `warnings` as the sentences the page shows after the take, and `media_removed`. See [End-of-day report](#end-of-day-report). | | `POST /api/task-files/import`, `DELETE /api/task-files/{name}` | Import a task catalog the operator supplies — by `name` + `content` (text uploaded from the browser) — into the imported-catalog directory beside the operator settings, once it parses; and remove an imported one. `POST` and `DELETE` use the `X-Control-Token` header (legacy JSON tokens remain accepted for `POST`); `DELETE` refuses removal of the selected catalog (409); imports also refuse replacement of that catalog until it is deselected. Imports appear in `GET /api/task-files` (as `imported`) and shadow a shipped catalog of the same name. | | `GET /api/tools` | The operator tools the Settings dialog's Devices tab lists (`headset_calibration`, `glove_offset`, `rectification`), each with a name, a one-sentence description and whether this build can launch it. Each of them can; they are the `/api/calibration` routes below. | | `GET /api/calibration` | The calibration tools' overview, with `X-Control-Token` like every `/api/calibration` route, reads included (they return camera pictures and who calibrated what; without it 403, before startup 503). `files`: each calibration file the station keeps, whether it is present and readable, when it was made, its headline figure (`quality`), when its solve stamped one the `camera` it was solved for, and, on the head camera's position file or the wrist-offsets file that is not stamped with the tracking it was made with (`"pose_source": "openxr"`), `problem`, the sentence that says so; the files live in one calibration directory that belongs to this backend (`EGOCAP_CALIBRATION_DIR`), so every station of the registry put in use on it shares them; `ledger`: who last installed each kind and when; `cameras`: per role (`ego`, `wrist_left`, `wrist_right`) the camera the station in use assigns (the stored operator settings' with no station in use), whether the backend holds a live picture of it (only cameras CaptureServer delivers directly have one), its intrinsics file, the lens model a solve uses when the page names none (`default_model`: `fisheye` for the `sensing_gmsl` camera type, `pinhole` for `oak_d` and for a station that names no type) and whether the camera's video is being corrected in this run (`rectified`, from the launcher's streams state: true, false, or null when the launcher named a report that could not be read; see the rectification routes below); `board`: the ChArUco board last used on this station, else the default; `recording`, `camera_job`, `glove_session`: whatever is in progress, in the shapes of the routes below, so a reopened dialog resumes; `last_camera_take`: the camera take kept last since the backend started with what it was recorded for (`take`, `role`, `mode`, `model`), whatever was recorded after it, else null; and `rectification`: `restart_needed`, whether, for any camera, starting the capture stack again would change the rectification applied (each `cameras` row says it for its own camera as `rectification_waits`), `streams_reported`, whether the launcher's report of the streams is at hand, and `notes`, sentences for every calibration tool about this run's streams (the report could not be read, so no take is recorded; else each role the launcher took another camera for than the station assigns it). | -| `POST`/`GET /api/calibration/recording`, `POST /api/calibration/recording/stop`, `POST /api/calibration/recording/cancel` | The calibration take, shared by the headset tool (`{"tool": "camera", "role", "mode": both\|intrinsic\|extrinsic, "operator", "board", "model": pinhole\|fisheye\|null}`; wrist roles solve `intrinsic` only; `model` is the lens model the take is for, null or absent meaning the camera type's default, and means nothing for `extrinsic`) and the glove tool (`{"tool": "glove", "operator"}`). It is an ordinary take through the recording coordinator under the task `Calibration: `; the operator's own task text is put back when it ends, whoever ends it. `POST` refuses with 409 while a take is recording, an interrupted take waits or station setup holds a take (a missing calibration file never holds a calibration take), when the role has no camera the session offers, when the calibration the take builds on is not installed or was solved for another camera than the one now in the role (the glove tool and `extrinsic` need the head camera's), when the glove tool's head-camera position file is not stamped with the tracking it was made with (`calibrate the headset first: head_camera_extrinsics.json was made with another tracking source or another tool: calibrate again`), for a take that solves a lens (`both`, `intrinsic`) of a camera whose video is being corrected in this run (`this camera's video is being corrected; start the capture stack without rectification to calibrate its lens`) or in a run whose launcher report could not be read (`whether this camera's video is being corrected is not known, ...`), and, in a run that corrects a camera, when a file its sessions must carry cannot be had (see the rectification routes below); 400 for a malformed board, operator or model. A refusal of the recorder's own never reaches the page in the recorder's words: the take's start and end answer `the take could not be started; see the backend log` and `the take could not be ended; see the backend log`. `GET` (about 3 Hz while recording; 404 before any) answers `phase` (`recording`, `stopping`, `saved` with `take` relative to the recording output, or `failed` with `problem`), `model` (the lens model the take was started for, the default filled in; null for `extrinsic` and for the glove tool), `elapsed_s`, the live `guide` (`available`, `ready`, `hints` and the tool's own figures) and `preview` (the newest live picture with the guide's overlay, base64 JPEG). The guide looks at the JPEG CaptureServer delivers for the camera, else at the newest decoded frame the take itself is fed over LiveKit (`calibration_frames` notes each on its way into the take and forgets them when the take ends; recording is unchanged), either while it is under two seconds old. While there is no such picture the guide is `available: false` with `unavailable_reason` (`waiting for the first live picture`, `there is no live picture from this camera`) and the take records without guidance. Where the camera tool's take solves the position (`both`, `extrinsic`), each look that has a new picture also hands the guide every head pose that arrived since the last such look (`head_track`), oldest first. The backend keeps a short history of tracking samples for it (`TRACKING_HISTORY_SECONDS`, bounded in count and bytes), places each pose by the capture server's own time with one fixed offset for the whole take, so two poses are as far apart for the guide as they were captured, and leaves out a sample of a moment the take does not store, one with no head pose, and one stamped no later than the pose before it. A take that solves the lens alone and the glove tool's guide get no head track. The camera guide's record is the library's, passed on whole: beside the figures the page draws it carries `board_corners`, `coverage.density`, `coverage.asked`, `evidence.asked`, `head.asked` and `head.health` ([`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#live-guidance) describes them). The camera guide is told the lens model: it asks for the same number of views (`views_needed`) under each, a frame covers cells only when it shows as many corners as that model's solve can use (five for fisheye, four for pinhole), and a fisheye take's guide measures no tilt variety (`evidence.tilt_spread` is null there). While a camera's video is corrected the glove guide projects through the corrected camera. Every guide, with or without a picture, also says whether the take is getting the tracking it needs to be kept (`tracking_recorded`, `headset_tracked`, `controllers_tracked` per side): the recorder stores a tracking row only while the headset and both controllers are tracked, and a take without any is rejected, whatever the tool or mode. While no row is being recorded `ready` is false and the first hint names what is not tracked. A guide counts only what the take will hold for its solve: where the position is solved (`both`, `extrinsic`) a picture taken while no tracking row is recorded adds no view, no coverage and no head motion, though the board in it is still found and drawn (an `intrinsic` take keeps counting, since its solve uses every frame); the glove guide counts a hand only while the recorder stores both a tracking row and a glove row, and a glove row holds both hands or is left out, so it needs both gloves' wrist joints. While a guide counts nothing a hint says so, after the hints that name the cause (what is not tracked, a glove that sends no joints). Those hints are said from the newest tracking sample, which every poll reads with or without a new picture, so they never contradict `tracking_recorded` between two pictures; everything else in the guide is of the last picture. A take rejected for holding no tracking says so in `problem`. `stop` keeps the take, `cancel` discards it (`failed`, `problem: "cancelled"`, or the interrupted-take problem when the recorder could not remove it); both are 409 when nothing is recording. An interrupted take is cleared with New batch on the recording page, which is what both of its messages say. | +| `POST`/`GET /api/calibration/recording`, `POST /api/calibration/recording/stop`, `POST /api/calibration/recording/cancel` | The calibration take, shared by the headset tool (`{"tool": "camera", "role", "mode": both\|intrinsic\|extrinsic, "operator", "board", "model": pinhole\|fisheye\|null}`; wrist roles solve `intrinsic` only; `model` is the lens model the take is for, null or absent meaning the camera type's default, and means nothing for `extrinsic`) and the glove tool (`{"tool": "glove", "operator"}`). It is a take through the recording coordinator under the task `Calibration: `, started exempt from the capture checks (`start_episode(..., exempt_from_capture_checks=True)`; no field of the request is read for it), so it is kept unjudged where the same frames from Record would be rejected or quarantined, and its storage integrity is still checked; the operator's own task text is put back when it ends, whoever ends it. `POST` refuses with 409 while a take is recording, an interrupted take waits or station setup holds a take (a missing calibration file never holds a calibration take), when the role has no camera the session offers, when the calibration the take builds on is not installed or was solved for another camera than the one now in the role (the glove tool and `extrinsic` need the head camera's), when the glove tool's head-camera position file is not stamped with the tracking it was made with (`calibrate the headset first: head_camera_extrinsics.json was made with another tracking source or another tool: calibrate again`), for a take that solves a lens (`both`, `intrinsic`) of a camera whose video is being corrected in this run (`this camera's video is being corrected; start the capture stack without rectification to calibrate its lens`) or in a run whose launcher report could not be read (`whether this camera's video is being corrected is not known, ...`), and, in a run that corrects a camera, when a file its sessions must carry cannot be had (see the rectification routes below); 400 for a malformed board, operator or model. A refusal of the recorder's own never reaches the page in the recorder's words. A recorder that is not ready refuses the start with the readiness reason the recording snapshot publishes (`not_ready_reason`); a refusal of the coordinator or the recording service at the take's start or end is answered with the sentence a refused recording command gets (`recording_command.refusal_sentence`); a recordings disk that is full, over quota, read-only or unwritable is named; and any other failure answers `the take could not be started; see the backend log` or `the take could not be ended; see the backend log`. `GET` (about 3 Hz while recording; 404 before any) answers `phase` (`recording`, `stopping`, `saved` with `take` relative to the recording output, or `failed` with `problem`), `model` (the lens model the take was started for, the default filled in; null for `extrinsic` and for the glove tool), `elapsed_s`, the live `guide` (`available`, `ready`, `hints` and the tool's own figures) and `preview` (the newest live picture with the guide's overlay, base64 JPEG). The guide looks at the JPEG CaptureServer delivers for the camera, else at the newest decoded frame the take itself is fed over LiveKit (`calibration_frames` notes each on its way into the take and forgets them when the take ends; recording is unchanged), either while it is under two seconds old. While there is no such picture the guide is `available: false` with `unavailable_reason` (`waiting for the first live picture`, `there is no live picture from this camera`) and the take records without guidance. Where the camera tool's take solves the position (`both`, `extrinsic`), each look that has a new picture also hands the guide every head pose that arrived since the last such look (`head_track`), oldest first. The backend keeps a short history of tracking samples for it (`TRACKING_HISTORY_SECONDS`, bounded in count and bytes), places each pose by the capture server's own time with one fixed offset for the whole take, so two poses are as far apart for the guide as they were captured, and leaves out a sample of a moment the take does not store, one with no head pose, and one stamped no later than the pose before it. A take that solves the lens alone and the glove tool's guide get no head track. The camera guide's record is the library's, passed on whole: beside the figures the page draws it carries `board_corners`, `coverage.density`, `coverage.asked`, `evidence.asked`, `head.asked` and `head.health` ([`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#live-guidance) describes them). The camera guide is told the lens model: it asks for the same number of views (`views_needed`) under each, a frame covers cells only when it shows as many corners as that model's solve can use (five for fisheye, four for pinhole), and a fisheye take's guide measures no tilt variety (`evidence.tilt_spread` is null there). While a camera's video is corrected the glove guide projects through the corrected camera. Every guide, with or without a picture, also says whether the take is getting the tracking it needs to be kept (`tracking_recorded`, `headset_tracked`, `controllers_tracked` per side): the recorder stores a tracking row only while the headset and both controllers are tracked, and a take without any is rejected by the integrity check, whatever the tool or mode. While no row is being recorded `ready` is false and the first hint names what is not tracked. A guide counts only what the take will hold for its solve: where the position is solved (`both`, `extrinsic`) a picture taken while no tracking row is recorded adds no view, no coverage and no head motion, though the board in it is still found and drawn (an `intrinsic` take keeps counting, since its solve uses every frame); the glove guide counts a hand only while the recorder stores both a tracking row and a glove row, and a glove row holds both hands or is left out, so it needs both gloves' wrist joints. While a guide counts nothing a hint says so, after the hints that name the cause (what is not tracked, a glove that sends no joints). Those hints are said from the newest tracking sample, which every poll reads with or without a new picture, so they never contradict `tracking_recorded` between two pictures; everything else in the guide is of the last picture. What became of a take is read from the description the recording page gets (`take_outcome.describe_result`): `saved` only for the outcome `kept`, and for any other outcome `problem` is the tool's lead followed by that description's `reasons`, whole sentences only (an interrupted take's reason is left to the recording page, which shows it beside the buttons that resolve the take). A take rejected for holding no tracking says so in `problem`, and that its data stays on disk and can be discarded on the recording page, where it is a row of `pending_takes`. `stop` keeps the take, `cancel` discards it (`failed`, `problem: "cancelled"`, or the interrupted-take problem when the recorder could not remove it); both are 409 when nothing is recording. An interrupted calibration take is a row of `pending_takes` like any other and is resolved from the recording page with `recover_pending` or `discard_pending`, which is what both of its messages say; one that is recovered is finished exempt, as it was started. | | `POST /api/calibration/camera/solve`, `GET /api/calibration/camera/job`, `POST /api/calibration/camera/job/cancel`, `GET /api/calibration/camera/job/picks/{n}`, `POST /api/calibration/camera/install` | The headset tool's solve. `solve` (`role`, `mode`, `take` or null for the take the last camera recording saved, `camera_latency_ms`, `board`, `model`: `pinhole`, `fisheye`, or null or absent for the camera type's default; 400 for anything else) starts one background solve of a finalized take inside the recording output (aligned or rectified copies and pending takes are refused) and answers with the job; 409 while a solve runs or a take is being written, when the take's recorded data cannot be opened, for a position-only solve when the installed intrinsics were solved for another camera than the one now in the role, and for a lens solve (`both`, `intrinsic`) of a camera whose video is being corrected in this run or in a run whose launcher report could not be read, whichever take is named, or of a take recorded corrected (its session's `rectification.json` lists the camera; a record that cannot be read refuses every solve of the take, and so does a session that holds a lens file under a lens name and no record, and a record that states another picture size than the take's video). A position-only solve is made against the camera as the take saw it: the corrected pinhole camera its session's record describes when the take was recorded corrected (the installed lens file then takes no part), else the installed lens. A lens solved for a camera the launcher reported is stamped with its stream (`"stream": {"divisor", "source_size_wh"}` in the intrinsics file) when the take's picture is that stream's published one, so the launcher later scales the lens by a declared number; the solve's `log` says which. The board is looked for in a bounded number of the take's frames, however long the take; the video between those frames is still read through, so a longer take still takes longer to solve. `camera_latency_ms` is how far the camera's frame times lag the tracking: a number solves the position at that lag; null or absent leaves it to the solve, which tries lags up to 200 ms either side of none and adopts one only when the board clearly stands stiller under it (the extrinsics figures carry `camera_lag_ms`, the lag used, and `camera_lag_found`, true when the search adopted one). `job` is `idle`, `running` (`progress`, `message`), `failed` (`error`, in words for the operator) or `done` with `result`; whenever there is one it carries `role`, `mode`, `model` (the lens model solved; null for `extrinsic`), `take` and `id`, which tells this solve from the one that replaces it. The `result` holds the intrinsics and extrinsics figures (either null when not solved, `extrinsics_problem` saying why a run of both solved only the intrinsics; the intrinsics figures carry `model`, four `dist_coeffs` for a fisheye solve and five for a pinhole one, and `field_angle_deg`: `seen`, how far from the optical axis a used corner was seen, and `picture_corner`, the angle of the picture's own corner under the solved model, null when the model does not reach it), the `grade`, per part whether the policy allows installing it (`install`), the picked frames (`picks`) and the `log`; a finished job is replaced by the next solve. `job/cancel` tells the running solve to stop (409 when none runs): the job stays `running`, with the message `Stopping`, until the solve has left at its next progress report, and is `idle` after. `picks/{n}` is the n-th picked frame with its corners drawn (`image/jpeg`; 404 otherwise); with `?solve=` it is 409 once the backend holds another solve than the one named. `install` (`operator`, `what`: `intrinsics`, `extrinsics` or both, and optionally `solve`: the `id` of the solve the page shows, 409 when the backend holds another) writes the station's calibration files, archived and ledger-stamped; 400 without an operator name or with one the station store's rule refuses (longer than 128 characters, or holding a control character or half of a surrogate pair), the rule every install shares, so the ledger spells a name as the takes carry it; 409 with the reason when the policy refuses a part that was asked for, and nothing is installed then. A position solved in the same run as intrinsics (`install.extrinsics.with_intrinsics`) is only right under them: asking for `extrinsics` installs that run's intrinsics with it, unless they were already installed from this job, and it is refused when those intrinsics may not be installed. A position-only run is installed on its own. The recorder copies the calibration files into a session when the session opens, so a successful `install` also ends the recording batch when a session is open and no take is being written, as a change of station does, and the next take opens a session that holds the installed files; its reply carries `recording_batch`: `ended` (this install ended the batch), `new_batch_needed` (a session stays open that does not hold the files, because a take is being written, an interrupted take waits or the recorder refused) and `note`, the sentence for the operator (null when no session was open). A take in progress is never interrupted. When a later part fails to be written after an earlier one was installed, the batch is ended for the part that went in all the same, and the refusal (503 for a write that failed, 409 for a record the store refuses) says so: its `detail` names the file that was installed and what became of the batch, and it carries `installed` and `recording_batch` beside it. A file that went live before the calibration log could be written is installed: it is counted, the batch is ended for it, and the refusal (503) says ` is installed, but the calibration log was not updated`, with which file went in before that and which was not installed. An install answers with the solve that was installed, whatever solve the backend holds by then. The extrinsics file states `tracking_latency_s`, the latency the recorder had taken off the take's tracking times, beside `camera_latency_s`, when the take says it: the glove tool and the time aligner move the lag by what that latency has changed by since. It also states the tracking its head poses came from (`"pose_source": "openxr"`), which every reader of a position asks for, and what became of the take's head tracking (`head_tracking`: whether the headset lost its position, what that cost, and the take's lowest and median reading of how the position followed the turning). Work files go under `/runs/`, named as the command line names its runs, never into a recording. | | `GET /api/calibration/rectification`, `POST /api/calibration/rectification/preview`, `PUT /api/calibration/rectification/plan` | The rectification tool, with `X-Control-Token` on every route. Nothing here corrects video: the camera bridge does, from a table the launcher builds when the capture stack starts, out of the choices saved here and the installed lens calibrations. What the launcher applied is read once at startup from the file it names in `EGOCAP_STREAMS_STATE`, so a saved choice takes effect at the next start. With no file named there are no stream facts and no camera is taken for corrected. A file that was named and cannot be used (missing, damaged, of another version, or one that corrects a camera as no role or two cameras as one role) leaves the run unknown, which is never read as "nothing corrected": the log says why, the recording readiness check holds every take for the whole run (`the launcher's report of the camera streams could not be read, so a take could not say whether its video is corrected; start the capture stack again`), lens takes and lens solves are refused, a preview uses no live picture, and the overview and the listing say so in `notes`. The file also says whether the run was started with rectification switched off (`no_rectify`, the launcher's `--no-rectify`); the backend logs that at startup and the listing says it in a note. `GET` lists each role: `role`, `camera` (the camera the launcher bridges as the role, where it bridges one, else the one the station assigns), `intrinsics_file`, `installed`, `model` (what the installed file states, else null), `problems` (why the installed calibration cannot be corrected with, one sentence each: the planner's gates, a file solved for another camera than the one now in the role, a calibration that is not for the picture the bridge receives by the divisor it declares), `plan` (what is saved: `enabled`, `output_size_wh`, `balance`, `fov_scale`, `allow_border`, `K`, `oversample`; else null), `plan_problem` (the planner's refusal of the saved, switched-on choice for a calibration that is sound, else null; the card keeps its controls, since changing the choice is the cure), `applied` (what this run applies to the camera, else null: `plan_matches`, whether it is the saved choice, the oversample included; `calibration_matches`, whether it was built from the calibration installed now; `output_size_wh`, `balance`, `fov_scale`, `explicit_K`, true when the applied view was a stated camera matrix, in which case `balance` and `fov_scale` are null; `K`, that matrix as a plan entry carries it, null when the view was fitted from a balance or when the record's matrix is not one a reply can carry; `oversample`, `outside_share`, `field_of_view_deg`), `stream` (what the launcher reported: `source_size_wh`, `divisor`, which for a corrected stream is the plan's oversample, and `published_size_wh`; null for a camera it did not report), `preview_source` (`live`, `take` or null: where a preview's picture would come from; never `live` for a camera whose video this run corrects), `warnings` (the planner's warnings for the saved, switched-on choice, planned as a save plans it; empty when nothing is saved, it is off, or it cannot be planned) and `restart_needed` (whether starting the capture stack again would change what is applied to this camera: false for a camera with no `stream`, when the launcher's report could not be read, and for a switched-on choice whose calibration is not installed or has `problems`, or that has a `plan_problem`, on which the launcher refuses to start; otherwise true when the saved choice differs from what this run applies). Beside the cameras the listing carries `restart_needed` (true when any camera's is), `plan_file_usable` (false while the plan file is there and cannot be understood), `streams_reported` (whether the launcher's report of the streams is at hand) and `notes`: sentences about the station's rectification as a whole, shown by the page as sent and never among a camera's `problems`, since the page takes a camera's controls away over those (the plan file cannot be understood and saving replaces it; the launcher's report could not be read, so what this run applies is unknown and no take is recorded; the run was started with rectification switched off; the backend was given no report of the camera streams; the launcher took another camera for a role than the station assigns it). `preview` (`role`, `output_size_wh`, `balance`, `fov_scale`, `allow_border`, `K`, and optionally `oversample`, 1 when absent) plans as the launcher will, for the picture the bridge receives with the divisor the calibration file declares, and answers `tiles` (`received`, with the area kept outlined, and `corrected`; base64 JPEG, sent no larger than 1280 pixels a side), `received_size_wh` and `corrected_size_wh` (the pictures' own sizes), the planner's `figures` (with `oversample`, `table_size_wh` and `suggested_oversample`) and `warnings` as it gives them, and `source`. The corrected tile is the picture as it would be published: one pass through the plan's maps, then the box filter by the oversample. The picture is the newest live picture when CaptureServer delivers the camera directly, else the middle frame of the take changed last that holds the camera's video as received at the size the calibration was solved at (takes recorded corrected, takes of another size, aligned or rectified copies and pending takes are passed over; the listing's `preview_source` is chosen by the same search), enlarged by the declared divisor to stand for the bridge's picture. 409 with the planner's own sentence when it builds no plan, and when there is no camera in the role, no usable calibration or no picture; 400 for an unknown role. `plan` (`{"cameras": {role: choice or null}}`; a role that is not named keeps what is saved, null removes its entry, a choice with `enabled` false is kept with its values for the day it is switched on, and a choice without `oversample` is saved with 1) checks every choice and plans each one that is switched on, then writes `/rectification/plan.json` whole and atomically and answers with the listing. A choice that cannot be planned refuses the save with 409, the planner's sentence as `detail` and the `role` beside it, and nothing is written; 400 when `cameras` is not an object or names an unknown role; 503 when the file cannot be written. A plan file the launcher refuses to start on (one that cannot be read, is not valid JSON, is not a version 1 plan with a `cameras` object, or holds an entry that is not an object with a real true or false `enabled`) reads here as nothing saved for every role, and an entry whose geometry is not well formed is left out; the log says which, the listing says so in `notes` with `plan_file_usable` false, and the next save writes the file again whole. The plan file, the streams state and the session's record are named, laid out and read by the library (`egocap.calibration.rectification_files`), which the launcher and the command line use as well. Listing, preview, save and the overview's restart check run one at a time on a worker of their own. When a camera is corrected in this run every session carries, copied and hashed like the calibration files and required for a session to open, `rectification.json` (`{"version": 1, "cameras": {name: what was applied}}`), the corrected camera under the role's intrinsics file name, and the station's lens file byte for byte under the role's lens name (`egocap.calibration.files.ROLE_LENS_INTRINSICS`), so a recording's files describe its pictures. The backend writes the run's copies beside the launcher's file at startup and looks for them again when a session opens and before each calibration take; the lens is copied only while it is still the file the correction was built from. When a copy cannot be had no take is recorded, from the tools or the recording page: `the record of this run's rectification is missing, so no take can be recorded; start the capture stack again`, or ` is no longer the lens calibration this run's correction was built from, so no take can be recorded; start the capture stack again`. | | `POST`/`GET /api/calibration/glove/session`, `GET /api/calibration/glove/session/samples/{i}`, `GET /api/calibration/glove/session/samples/{i}/frame` | The controller–glove offset tool's labelling session, with `X-Control-Token` on every route. `POST` (`take` or null for the take the last glove recording saved, `samples`: 10 to 80, 40 when absent) reads the head camera's video and the tracking of a finalized take and samples frames that show a gloved hand; it replaces the earlier session once it is ready. 409 while a take is being written or another session is being prepared, when the station has no head camera, when the head camera's intrinsics or extrinsics are not installed (`calibrate the headset first`) or were solved for another camera than the one now in the role, when the position file is not stamped with the tracking it was made with, when the take's `rectification.json` cannot be read, lists the camera without describing the corrected one or states another picture size than the take's video, when the take cannot be labelled (no tracking, glove joints or head-camera video at its frames, glove rows that are not the 25-joint hand, a video that is not the calibrated picture at some scale, or too few frames showing a hand), when the stored camera lag cannot be carried over to the take because the take does not say which tracking latency it was recorded under, and when a calibration file or the take changed while the frames were being prepared; 400 for a malformed body. `GET` is the session (404 when there is none): `id` (each session has its own, which tells it from the session that replaces it), `take`, `samples`, `image_size_wh`, `fingers`, `bones`, `start` (`installed` when the fit began from the station's offsets, else `zero`; offsets that are not stamped with the tracking they were made with are not started from), `warnings` (sentences the operator reads before clicking: a glove whose recorded skeleton is not in the expected joint order, and installed offsets the fit does not start from), `camera` (`rectified`, `model`: which description of the head camera the hands are projected with: the corrected pinhole camera the take's session describes when the take was recorded corrected, in which case the installed lens file takes no part, else the installed lens), `camera_lag_ms` (the camera lag under which the samples' tracking was read: the one the installed head-camera extrinsics record, moved, when that file also states the tracking latency it was measured under, by what the recorder's tracking latency has changed by between that calibration's take and this one), the `offsets` as they stand, each hand's last fit (`fits`: `rms_px`, `clicks`, `frames`, the distinct frames those clicks were placed on, and `at_translation_limit`, true when the fit stopped at the furthest offset the tool fits), `install` (`allowed`, `reason`), `installed` and `stale`: null, or why the session can no longer be fitted or installed (the head camera's calibration, the offsets it started from, the take or the calibration directory is no longer what it was prepared from). `GET` looks at those again, so a reopened tool learns that its session is over; `install.reason` then carries the same sentence. `samples/{i}` is one sampled frame's `index`, its `frame_index` in the take and the `overlay` to draw over it under the offsets as they stand now (per hand `valid`, `joints_px`, `tips_px`, `wrist_axes_px`, `controller_axes_px`), so it is read again after a fit; `samples/{i}/frame` is that frame as recorded (`image/jpeg`); 404 for a sample the session does not have. A sample read may name the session it means (`?session=`) and is then 409 once a newer session has replaced that one, so one session's overlay is never drawn over another's frame. | @@ -79,8 +79,7 @@ A site usually has several stations, and an operator picks the one they are at. moment it is applied (`the station is being changed`), so none can open a session under the outgoing name or record against cameras being reassigned; the batch rotates only when the label changes. While an interrupted take waits to be recovered or discarded, a change that would rotate the batch is refused (`recover or discard - the interrupted take first`): a new batch would leave that take on disk with nothing on the page to resolve - it. Which cameras CaptureServer is asked for stays a deployment + the interrupted take first`): a new batch would leave that take behind as an earlier session's. Which cameras CaptureServer is asked for stays a deployment setting (the station file); restarting the backend is the only way to change that. - **The station in use holds the camera setup.** `GET /api/operator-settings` returns its camera type and roles, and they are changed through the station routes; a `PUT` of those two fields to the operator settings is refused @@ -88,11 +87,68 @@ A site usually has several stations, and an operator picks the one they are at. - **Names.** Two names that would share one daily log file (they differ only in case or punctuation) are one name. Renaming the station in use carries its day over: its timeline, its daily log and its saved report move to the new name, and takes recorded under the old name stay part of its report. Once another station records under - the old name, that name's takes are that station's. + the old name, that name's takes are that station's. A rename is recorded for every station of the registry, + also one that is not in use and on a day it recorded nothing, so the takes a station left under its old name + are still listed for it ([`station_uptime.py`](egocap_web/station_uptime.py)). A name changed by editing the + registry file by hand is not a recorded rename, and choosing another station is not one either. - **Headset address.** The backend remembers, per station, the capture host address its headset was given. It does so by itself, once a headset is connected, and replaces the remembered one only when the host no longer has it and the station and its saved address are still the ones that were looked at. +### Take outcomes and pending takes + +Every take is judged when it stops, by the thresholds of the defaults file and the station's `data_check` section +(see the example's [`README.md`](../README.md#capture-checks) for the checks and what each does to a take), except +a take a calibration tool starts, which is exempt from the capture checks and is reported as `kept` with the +`qc_decision` `SKIPPED`. The +recording snapshot carries the result, and every sentence in it is composed in +[`take_outcome.py`](egocap_web/take_outcome.py): fixed text around measured numbers and configured names, never a +directory path. The recorder's own notes can hold raw error text, so each is replaced by the sentence for its kind +and the note stays in the backend log. + +- `last_result.outcome` is what to show: `kept`, `flagged`, `quarantined`, `rejected` (media removed), + `rejected_data_kept`, `discarded` or `interrupted`. Beside it are the recorder's `disposition`, the checks' + `qc_decision`, `reasons`, `warnings`, `media_removed` and `location` (relative to the recording output). + A camera rejection has one reason per camera: its average rate against the minimum when its rate while it ran + was what failed, otherwise how many frames it recorded and about how many a take of that length holds. +- `saved_count` counts good takes only; `flagged_count`, `quarantined_count` and `rejected_count` count the rest + of the batch. A take of an earlier session resolved from the page sets `last_result` and adds to no count. +- `pending_takes` lists every take that waits for the operator: the open session's unresolved one (`current`), + which holds Record; takes of the open session that the integrity check rejected whose data is still on disk + (`phase` `REJECTED`), which hold nothing and are rows only while that session is open; then what earlier + sessions left behind, which the backend finds by reading their manifests at start, after New batch, after each + resolution and every few seconds. The sessions listed are those recorded under any name the station has had and + those that carry no station name. A session some recorder has open is never listed or acted on: a recorder + rewrites its session's lock file about once a second, and a session's takes are listed only after two looks + 2.5 s apart found that file unchanged, so rows of earlier sessions arrive a few seconds after a backend start. + The recorder watches its own marker: when it has not been written for 2.5 s, `ready_to_record` is false, + `not_ready_reason` and a refused `start_episode` carry a sentence about the recordings folder, and the snapshot + is pushed when that begins and when it ends. A take being recorded then is not interrupted; `not_ready_reason` + carries the sentence while `episode_phase` stays `RECORDING`, and the take's `issues` say so afterwards. + A record found in a session folder it was not written for (a folder copied or renamed by hand) is listed too, + with neither command offered. Each row has the `reason` it waits, a `recover_note` saying what Recover would do or what the take + needs, and which commands it is given: `recoverable`, `discardable`, and `recoverable_known`, which is false + while no camera has been accepted and nothing can be said either way. +- `recover_pending` and `discard_pending` take `{batch_id, episode_id}`, the current batch and the take's id from + `pending_takes`. "ok" means the recording service ran the step; what became of the take is `last_result`, which + can again be `interrupted`. Both are refused while a take is being recorded or another recording command runs. + A take of an earlier session is resolved by reopening its session for that one step; when its frozen source + declarations or calibration files no longer match, the command is refused and the take is left on disk. + Before reopening an earlier session the backend looks at it once more, so such a command can take a few + seconds longer or be refused because another recorder holds the session. Removing a take's media happens only + in the recording service. +- Every reason a recording command is refused with is a sentence written for the operator: fixed text, with no + directory, no recorder state name and nothing a lower layer raised, which stays in the backend log. A full + recordings disk, a used-up quota and a read-only or unwritable recordings folder each have a sentence of their + own, given only for a failure on a file under the recording output; a failure elsewhere on the machine, or + one that names no file and did not come from one of the recorder's own writers, keeps the general sentence. +- Shutting the backend down while a take is being recorded discards that take; the capture checks are not + asked. +- `start_episode` is refused while the quarantine folder of the recording output is a link, a file or on another + disk, before anything is recorded, with a sentence that says which. +- A take marked bad, flagged or quarantined, is not submitted for time alignment. +- No command releases or deletes a quarantined take. + ### Station time Nobody marks a station active or blocked. Every two seconds the backend asks whether the station in use is @@ -162,16 +218,25 @@ take is counted with what became of it: | Disposition | Meaning | | --- | --- | | kept | Finalized, and capture quality did not mark it bad. | -| flagged | Finalized and kept, but capture quality marked its data bad. | -| rejected | Failed its check; a camera failure also removed its media. | -| discarded | The operator discarded it. | +| flagged | Finalized and kept with its session, but capture quality marked its data bad. | +| quarantined | Marked bad the same way, on a station with quarantine on: finalized under `_quarantine//`. | +| rejected | Failed its check. `media_removed` tells the two kinds apart: true for a camera failure, whose media is gone; false for an integrity failure, whose data is still in its pending folder. | +| discarded | The operator discarded it. A take discarded after an integrity rejection keeps its integrity reasons, with `media_removed` true. | | pending | Interrupted before it finished; it waits to be recovered or discarded. | | recording | The take being written right now. | +Each take's `reasons` are the findings that decided what became of it, worded by +[`take_outcome.py`](egocap_web/take_outcome.py) exactly as after the take, and `warnings` the findings that never +decide. For a pending take the reasons are the recorder's notes. The buttons of a pending row come from the +recording snapshot's `pending_takes`, not from the report. The daily log's recorded time still counts kept, +unflagged takes only. + A take belongs to the day in its finalized episode's `recorded_at`, else the day its manifest was last checkpointed. A session whose name says it was opened on a later day than the report's is passed over without being read; one opened on that day or earlier, or with no date in its name, is always read, since it may hold the day's takes. -A manifest that cannot be read, or that holds values of the wrong shape, is reported with its session, never dropped. +A manifest that cannot be read, or that holds values of the wrong shape, is reported with its session, never dropped; +the line names the record's file, never a directory. A record found in a session folder it was not written for is +such a line too, not a take, so a copied session does not count its takes twice. A correction ([`day_report_routes.py`](egocap_web/day_report_routes.py)) accepts only a recorded session inside the recording output: a recording-service session directly under it, or a studio's group one level below that carries @@ -191,6 +256,7 @@ every take was corrected. Nothing is ever moved. | Variable | Default | Meaning | | --- | --- | --- | | `EGOCAP_STATION_CONFIG` | unset (development default) | Path to the deployment station YAML described above. | +| `EGOCAP_QC_CONFIG` | the shipped `recording/egocap/config/data_check/data_check_config.yaml` | A site's own capture-check thresholds file. Read once at start, then the station file's `data_check` section is applied over it. A file that cannot be read, an unknown key, a wrong type or a value out of range holds every take (`quality-check configuration is invalid; see backend logs`); the preview keeps running. | | `EGOCAP_CAPTURE_SERVER_URL` | `ws://127.0.0.1:8082` | Where to connect for tracking/camera data. | | `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` | unset | The LiveKit server's key pair. The backend signs two viewer tokens with it (subscribe and data messages, no media publishing): viewer tokens for `GET /api/livekit-token`, and the recorder's own token. LiveKit recording will not start without both variables; see [`LIVEKIT_PREVIEW.md`](../LIVEKIT_PREVIEW.md). | | `EGOCAP_CALIBRATION_DIR` | `/calibration` | The calibration directory: the station's calibration files, their history and ledger, the calibration tools' work files and the saved rectification plan. See [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#the-calibration-directory). | diff --git a/examples/egocap/backend/egocap_web/app.py b/examples/egocap/backend/egocap_web/app.py index b04b3cdcf7..f38ee8c912 100644 --- a/examples/egocap/backend/egocap_web/app.py +++ b/examples/egocap/backend/egocap_web/app.py @@ -26,7 +26,12 @@ from fastapi.staticfiles import StaticFiles from egocap.core.data_root import calibration_dir -from egocap.recording.capture_qc import CaptureQcConfig +from egocap.recording.capture_qc_policy import ( + CaptureQcPolicy, + CaptureQcPolicyError, + capture_config_for, + load_policy, +) from recording_service import ( CalibrationAsset, ConfigurationError, @@ -37,6 +42,7 @@ VideoSourceSpec, ) +from . import readiness_text from .auto_align import AutoAligner from .calibration_frames import NewestFrames, WatchedLiveKitSource from .calibration_routes import router as calibration_router @@ -62,7 +68,9 @@ from .preview_routes import router as preview_router from .recording_adapter import ( MANUS_GLOVE_SPEC, + MANUS_POSE_STREAMS, PICO_CONTROLLER_SPEC, + PICO_POSE_STREAMS, RecordingAdapterError, validate_tracking_descriptor, ) @@ -194,7 +202,9 @@ def _station_calibration_assets() -> tuple[CalibrationAsset, ...]: ) -def _session_calibration_assets(session_files: SessionFiles | None = None) -> tuple[CalibrationAsset, ...]: +def _session_calibration_assets( + session_files: SessionFiles | None = None, *, opens_sessions: bool = True +) -> tuple[CalibrationAsset, ...]: """The calibration files a new session copies: the station's, and in a run that corrects a camera's video the run's own (``session_files``): its record of what was done to each camera's picture and, for each corrected camera's role, the corrected camera and the lens it was built from. @@ -203,14 +213,18 @@ def _session_calibration_assets(session_files: SessionFiles | None = None) -> tu corrected role's intrinsics file then describes the recorded video. The run's files are required, unlike the station's: a session of corrected video that did not say so would be taken for raw video by everything that reads it later. + + ``opens_sessions`` False names the same files without looking for them, for a configuration that only + looks at what earlier sessions left (see ``_recording_config_factory``). """ station = _station_calibration_assets() if session_files is None: return station - # Written again here when a copy went away since the backend started. What cannot be had is the recorder's - # to refuse this session over, and holds every take after it in the tools' own words - # (``_held_without_session_files``). - session_files.ensure() + if opens_sessions: + # Written again here when a copy went away since the backend started. What cannot be had is the + # recorder's to refuse this session over, and holds every take after it in the tools' own words + # (``_held_without_session_files``). + session_files.ensure() run = { file.name: CalibrationAsset(name=file.name, path=file.source, required=True) for file in session_files.files @@ -251,6 +265,32 @@ def held() -> tuple[bool, str | None]: return held +#: Names another capture-QC defaults file for a site; unset reads the one shipped with the recording package. +QC_CONFIG_ENV = "EGOCAP_QC_CONFIG" +#: The public reason new recordings are blocked while the capture-QC thresholds cannot be read. The cause, which +#: can hold a file name and parser text, stays in the backend log. +QC_CONFIG_INVALID = "quality-check configuration is invalid; see backend logs" + + +def _qc_config_path_from_env() -> Path | None: + """The capture-QC defaults file a site configured, or None for the shipped one.""" + raw = os.environ.get(QC_CONFIG_ENV) + return Path(raw).expanduser() if raw else None + + +def _load_qc_policy(station: ResolvedStation | None) -> tuple[CaptureQcPolicy | None, str | None]: + """The station's capture-QC policy and, when it cannot be read, the public reason recording is blocked. + + A bad file is never replaced by the built-in values: thresholds decide what happens to recorded media, so a + take must not be judged by numbers nobody chose. + """ + try: + return load_policy(_qc_config_path_from_env(), station.data_check if station is not None else None), None + except CaptureQcPolicyError as exc: + logger.error("capture-QC configuration failed; new recording is blocked: %s", exc) + return None, QC_CONFIG_INVALID + + def _recorder_livekit_token(room: str) -> str: """A viewer-capability token (subscribe and data messages, no media) for the recorder's LiveKit connection.""" api_key, signing_key = os.environ.get(API_KEY_ENV, ""), os.environ.get(API_SECRET_ENV, "") @@ -267,6 +307,8 @@ def _recording_config_factory( video_encoder: str = DEFAULT_VIDEO_ENCODER, video_encoder_options: dict[str, Any] | None = None, session_files: SessionFiles | None = None, + qc_policy: CaptureQcPolicy | None = CaptureQcPolicy(), + opens_sessions: bool = True, ): """Builds the real ``ServiceConfig`` lazily, read fresh each time the coordinator actually opens/reopens a session (not once at import time) @@ -286,9 +328,22 @@ def _recording_config_factory( changes the station in use carries the new station's name. ``session_files`` are the files a session carries because this run corrects a camera's video; see - ``_session_calibration_assets``.""" + ``_session_calibration_assets``. + + ``qc_policy`` is the station's capture-QC policy, resolved once at backend start. Every camera, however it + arrives, and the tracking pose streams are judged by it, so no take is recorded as unjudged unless the + policy switches the checks off. None means the policy could not be read: no configuration is built, since + one built from other thresholds would judge takes by numbers nobody chose. + + ``opens_sessions`` False is for the configuration that looks at, and resolves, the takes earlier sessions + left pending. It names the run's files, so a take of a corrected run is found recorded under this + configuration, and does not write them again: it is built every few seconds, during a take too, and a file + found missing then would hold recording in the middle of that take. A session reopened to resolve a take + reads its own copies, never the run's.""" def factory() -> ServiceConfig: + if qc_policy is None: + raise ConfigurationError(QC_CONFIG_INVALID) livekit_streams = recordable_livekit_streams(monitor.native.started) video_sources = tuple( VideoSourceSpec( @@ -323,23 +378,26 @@ def factory() -> ServiceConfig: ) # A supported profile must record actual tracking AND the # selected cameras -- pico_controller and every configured camera - # are required for a KEPT result. manus_glove is NOT required: - # a hand legitimately going briefly untracked (the whole-row - # omission policy in recording_adapter.py) must not by itself - # invalidate an otherwise-good take. - required = (PICO_CONTROLLER_SPEC.name, *(v.name for v in video_sources)) - # A LiveKit camera must average at least 0.86 of its configured fps over the take or the take is rejected. - capture_qc = ( - CaptureQcConfig(camera_expected_fps=tuple((s.name, None) for s in livekit_streams)) - if livekit_streams - else None + # are required for a KEPT result. manus_glove is required only + # where the station expects gloves: elsewhere a hand legitimately + # going untracked (the whole-row omission policy in + # recording_adapter.py) must not by itself invalidate an + # otherwise-good take, and a station without gloves records no + # glove row at all. + gloves = (MANUS_GLOVE_SPEC.name,) if qc_policy.gloves_expected else () + required = (PICO_CONTROLLER_SPEC.name, *gloves, *(v.name for v in video_sources)) + # Which streams the checks read follows from what this session records; the thresholds are the policy's. + capture_qc = capture_config_for( + qc_policy, [v.name for v in video_sources], PICO_POSE_STREAMS, MANUS_POSE_STREAMS ) config = ServiceConfig( output_root=output_root, numeric_sources=(PICO_CONTROLLER_SPEC, MANUS_GLOVE_SPEC), video_sources=video_sources, qc=QcConfig(required_sources=required, capture=capture_qc), - calibration_assets=_session_calibration_assets(session_files), + # A take the checks mark bad is finalized apart from its session where the station says so. + quarantine=qc_policy.quarantine, + calibration_assets=_session_calibration_assets(session_files, opens_sessions=opens_sessions), station_label=station_label() if callable(station_label) else station_label, ) largest_decoded_frame_bytes = max((cam.width * cam.height * 3 for cam in video_sources), default=0) @@ -393,6 +451,7 @@ def _recording_readiness_check( monitor: CaptureStatusMonitor, station_config_error: str | None = None, capture_server_url: str | None = None, + qc_config_error: str | None = None, ): """Real backend-local capture facts, injected into the coordinator -- it never imports CaptureStatusMonitor/CaptureClient itself (see @@ -414,23 +473,26 @@ def _recording_readiness_check( ``station_config_error``, when set, unconditionally blocks new recording admission with that reason -- a configured-but-invalid station YAML must never silently fall back to a development default, but it must - also never prevent capture preview from running.""" + also never prevent capture preview from running. ``qc_config_error`` + blocks the same way when the capture-QC thresholds could not be read.""" def check() -> tuple[bool, str | None]: if station_config_error is not None: return False, station_config_error + if qc_config_error is not None: + return False, qc_config_error if monitor.tracking_descriptor is None: - return False, "tracking source not yet accepted" + return False, readiness_text.TRACKING_NOT_ACCEPTED try: validate_tracking_descriptor(monitor.tracking_descriptor) except RecordingAdapterError as exc: - return False, f"tracking descriptor unsupported for recording: {exc}" + return False, f"{readiness_text.TRACKING_UNSUPPORTED}: {exc}" if monitor.native.status is None or not monitor.native.status.running: - return False, "capture is not running" + return False, readiness_text.CAPTURE_NOT_RUNNING now = time.monotonic() tracking = monitor.preview.tracking() if tracking is None or (now - tracking.received_monotonic) > _READINESS_STALE_SECONDS: - return False, "tracking source is stale or has no sample yet" + return False, readiness_text.TRACKING_STALE # An offered LiveKit stream that cannot be recorded blocks recording by name, never silently dropped. blocked = unrecordable_reason(monitor.native.started, capture_server_url) if blocked is not None: @@ -439,11 +501,11 @@ def check() -> tuple[bool, str | None]: # A recordable LiveKit stream is a camera too; its liveness is checked when the take prepares and # while it records, not by a preview sample here. if not cameras and not recordable_livekit_streams(monitor.native.started): - return False, "no camera selected" + return False, readiness_text.NO_CAMERA_SELECTED for cam in cameras: slot = monitor.preview.camera(cam.name) if slot is None or (now - slot.received_monotonic) > _READINESS_STALE_SECONDS: - return False, f"camera {cam.name!r} is stale or has no sample yet" + return False, readiness_text.camera_stale(cam.name) return True, None return check @@ -473,6 +535,9 @@ def _station_change_blocked(coordinator: RecordingSessionCoordinator) -> str | N _UPTIME_SAMPLE_SECONDS = 2.0 #: How often a connected headset's host address is compared with the one remembered for the station. _HEADSET_MEMORY_SECONDS = 30.0 +#: How often the takes earlier sessions left behind are read again: whether one can be recovered depends on the +#: cameras accepted by now. After the first read only the sessions that still hold one are opened again. +_PENDING_TAKES_SECONDS = 5.0 def _station_state( @@ -537,8 +602,8 @@ async def _rotate_batch_for_station(coordinator: RecordingSessionCoordinator) -> """Ends the current batch so the next take opens a session under the new station label. A session's configuration is frozen when it opens, so the label can only change between sessions. - Refused while an interrupted take waits: a new batch would leave it on disk with nothing on the page to - recover or discard it, and the station would stop being logged as down for it.""" + Refused while an interrupted take waits: it belongs to the station that recorded it, and that station is + logged as down until the take is recovered or discarded, which the page can do before the change.""" if interrupted_take(coordinator.snapshot().service): raise StationError(RESOLVE_INTERRUPTED_TAKE) try: @@ -603,6 +668,9 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: except StationConfigError as exc: station_config_error = "station configuration is invalid; see backend logs" logger.error("station configuration failed; new recording is blocked: %s", exc) + # Read once, like the station file: the defaults file, then the station's own section over it. With no station + # file the defaults alone apply, so the configuration-free workflow is judged by the same rules as a station. + qc_policy, qc_config_error = _load_qc_policy(resolved_station) config = config_from_env() # The station YAML's label wins when configured, else the fixed development default. if resolved_station is not None and resolved_station.station_label: @@ -668,25 +736,45 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: # The files every session of a run that corrects a camera carries, written here once. session_files = SessionFiles(streams, calibration_dir) session_files.ensure() - coordinator = RecordingSessionCoordinator( - _recording_config_factory( + + def recording_config( + on_video_sources: Callable[[frozenset[str], frozenset[str]], None] | None, opens_sessions: bool = True + ): + """The recording configuration factory; ``on_video_sources`` is told the cameras at each build, and + ``opens_sessions`` is False for the one that only looks at what earlier sessions left.""" + return _recording_config_factory( monitor, # Read at each session open: the station service below owns the label once it exists. lambda: station_service.label(), recording_output_root, - aligner.note_video_sources if aligner is not None else None, + on_video_sources, video_encoder=resolved_station.video_encoder if resolved_station is not None else DEFAULT_VIDEO_ENCODER, video_encoder_options=resolved_station.video_encoder_options if resolved_station is not None else None, session_files=session_files, - ), + qc_policy=qc_policy, + opens_sessions=opens_sessions, + ) + + coordinator = RecordingSessionCoordinator( + recording_config(aligner.note_video_sources if aligner is not None else None), + # The same configuration for looking at and resolving takes earlier sessions left pending. It is built + # more often than a session opens, so it does not tell the aligner which cameras "the session" records + # and does not write the run's session files again. + scan_config_factory=recording_config(None, opens_sessions=False), + # Every name the station in use has had, so a take left under an earlier name is still listed. Read + # when the output is read: the station service below owns the name once it exists. + station_names=lambda: station_uptime.all_names(station_service.label()), queue_capacity=_INGRESS_QUEUE_CAPACITY, queue_bytes=lambda: _ingress_queue_bytes(monitor.native.started), readiness_check=_held_while_streams_unknown( streams, _held_without_session_files( - session_files, _recording_readiness_check(monitor, station_config_error, config.capture_server_url) + session_files, + _recording_readiness_check( + monitor, station_config_error, config.capture_server_url, qc_config_error + ), ), ), initial_context=initial_context, @@ -776,6 +864,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: visualization=visualization_config, visualization_error=visualization_error, task_file_root=task_file_root, + qc_policy=qc_policy, + qc_error=qc_config_error, ) # The station's state is sampled every few seconds for the uptime log. sampler = UptimeSampler() @@ -797,6 +887,11 @@ async def sample_uptime() -> None: "remembering the headset address", ) ), + # Its first pass finds what a previous run left behind; it reads manifests, so it stays off the startup + # path and off the event loop. Later passes open only the sessions that still hold a take. + asyncio.create_task( + _every(_PENDING_TAKES_SECONDS, coordinator.refresh_pending, "the list of pending takes") + ), ] aligner_task: asyncio.Task[None] | None = None if aligner is not None: diff --git a/examples/egocap/backend/egocap_web/auto_align.py b/examples/egocap/backend/egocap_web/auto_align.py index 0952814b5c..68e91aa1b6 100644 --- a/examples/egocap/backend/egocap_web/auto_align.py +++ b/examples/egocap/backend/egocap_web/auto_align.py @@ -6,7 +6,8 @@ One worker handles episodes in the order they were kept. Each alignment runs as a low-priority child process (the same ``recording/tools/align_episode.py`` an operator can run by hand), so its CPU and memory never compete with a -live take inside the recorder's own process, and a shutdown can stop it. An episode that cannot be aligned is +live take inside the recorder's own process, and a shutdown can stop it. A take the capture checks marked bad is +not aligned, whether it stayed with its session or was quarantined. An episode that cannot be aligned is logged with the reason and left as recorded; the raw episode is never modified. Output is published by one rename, so an alignment that is killed leaves no partial result. At startup the worker re-queues the kept episodes that still have no aligned copy. The log line of an aligned episode carries the tool's own summary: the frames kept, @@ -29,6 +30,7 @@ from pathlib import Path from egocap.recording.aligned_writer import episode_qualification +from egocap.recording.capture_qc import QcDecision from egocap.recording.episode_layout import ( FINALIZATION_KEEP, MANIFEST_DIR, @@ -101,16 +103,20 @@ def note_video_sources(self, recorded: frozenset[str], qualified: frozenset[str] self._session_alignable = alignable def submit(self, result: EpisodeResult) -> None: - """Queue a finished take for alignment; anything other than a kept episode is ignored.""" - if result.disposition is Disposition.KEPT and result.final_path is not None and self._session_alignable: + """Queue a finished take for alignment; anything other than a kept episode the checks did not mark bad + is ignored. A quarantined take is not a kept one, so it never reaches the queue either.""" + kept = result.disposition is Disposition.KEPT and result.final_path is not None + marked_bad = result.qc_decision is QcDecision.FLAGGED_BAD + if kept and not marked_bad and self._session_alignable: self._queue.put_nowait(_Job(result.session_id, result.episode_index, result.final_path)) def scan(self) -> list[_Job]: """Every kept episode, in any session, that has no aligned copy and whose evidence allows one. - Skips episodes already refused (see ``_Job.refused_marker``), and an episode recorded without qualified - timing evidence (an older recording, or a station with no tracking delay set), so history is not retried at - every start. Also removes staging directories left by a run that was killed long ago. Blocking file work. + Skips a take the capture checks marked bad, episodes already refused (see ``_Job.refused_marker``), and + an episode recorded without qualified timing evidence (an older recording, or a station with no tracking + delay set), so history is not retried at every start. Also removes staging directories left by a run + that was killed long ago. Blocking file work. """ jobs: list[_Job] = [] groups: set[Path] = set() @@ -128,6 +134,7 @@ def scan(self) -> list[_Job]: eligible = ( manifest.storage_phase == "FINALIZED" and manifest.finalization == FINALIZATION_KEEP + and manifest.qc_decision != QcDecision.FLAGGED_BAD.value and not job.aligned.exists() and not job.refused_marker.exists() and all( diff --git a/examples/egocap/backend/egocap_web/calibration_common.py b/examples/egocap/backend/egocap_web/calibration_common.py index 14fab4eb69..b90b7adfa0 100644 --- a/examples/egocap/backend/egocap_web/calibration_common.py +++ b/examples/egocap/backend/egocap_web/calibration_common.py @@ -17,7 +17,7 @@ import json import math import re -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from pathlib import Path from typing import Any, Protocol @@ -82,6 +82,22 @@ def bounded(value: Any) -> str: return str(value)[:_MAX_DETAIL_CHARS] +def with_sentences(lead: str, sentences: Iterable[str]) -> str: + """A refusal's ``lead`` followed by the whole ``sentences`` that explain it, as many as a dialog shows. + + A sentence is added whole or not at all: cut short, it would read as another finding than the one made. + The lead is cut like any refusal text. + """ + said, joint = bounded(lead), ". " + for sentence in sentences: + # The first that does not fit ends the list: a later one would be read as following the one before it. + if len(said) + len(joint) + len(sentence) > _MAX_DETAIL_CHARS: + break + # The sentences end in their own full stop, so only the lead needs one put after it. + said, joint = f"{said}{joint}{sentence}", " " + return said + + def finite(value: Any) -> Any: """A JSON value with every number JSON cannot carry (a NaN, an infinity) replaced by None, so one such number in a solve, a guide or a plan cannot make every later reply fail.""" diff --git a/examples/egocap/backend/egocap_web/calibration_service.py b/examples/egocap/backend/egocap_web/calibration_service.py index 682afb9486..a992912680 100644 --- a/examples/egocap/backend/egocap_web/calibration_service.py +++ b/examples/egocap/backend/egocap_web/calibration_service.py @@ -5,8 +5,11 @@ """The calibration tools' state for one station: the calibration take and its live guide, the camera solve and its install, the board last used, and which take a tool means. -A calibration take is an ordinary take recorded through the recording coordinator, under a task text of its own. -The operator's task text is put back when the take ends, whoever ends it. Everything here is kept in memory: a +A calibration take is recorded through the recording coordinator like any other take, under a task text of its +own and exempt from the capture checks: a board waved at one camera or hands held still would be rejected or set +aside as a bad take. Its storage integrity is still checked. The operator's task text is put back when the take +ends, whoever ends it. What became of a take is read in the recording page's own words (take_outcome.py), and a +refusal of the recorder is worded as the page's commands are answered. Everything here is kept in memory: a restarted backend has no calibration recording and no solve. The recorder's state is read on the event loop only. Decoding, detection, solving and file work run in worker @@ -70,8 +73,8 @@ from egocap.calibration.wrist_offset import SIDES from egocap.recording.constants import PENDING_SUFFIX from egocap.recording.episode_layout import write_json_atomic -from recording_service import StateError +from . import take_outcome from .calibration_common import ( DERIVED_SUFFIXES, EPISODE_DIR, @@ -88,6 +91,7 @@ other_camera_problem, sendable, size_wh, + with_sentences, ) from .calibration_frames import DecodedFrame, NewestFrames from .capture_preview import TrackingSlot @@ -100,7 +104,7 @@ convert_hand_pose, convert_head_pose, ) -from .recording_command import interrupted_take, normalize_operator +from .recording_command import RECORDER_REFUSALS, interrupted_take, normalize_operator, refusal_sentence from .recording_session import CoordinatorBusyError from .rectification_service import ( RECTIFIED_NOW, @@ -141,8 +145,8 @@ ALREADY_RECORDING = "a calibration recording is already in progress" ALREADY_ENDING = "the calibration take is already being stopped" TAKE_BEING_WRITTEN = "finish the take being recorded first" -#: The recording page offers one way out of an interrupted take, a new batch, which leaves the take on disk. -INTERRUPTED_TAKE_WAITS = "an interrupted take is waiting; start a new batch on the recording page first" +#: An interrupted take holds the recorder until the operator resolves it, which the recording page does. +INTERRUPTED_TAKE_WAITS = "an interrupted take is waiting; recover or discard it on the recording page first" CALIBRATE_HEADSET_FIRST = "calibrate the headset first" INTRINSICS_FIRST = "the head camera's intrinsics must be installed before its position is solved alone" RECORD_A_TAKE_FIRST = "record a calibration take first" @@ -151,8 +155,10 @@ TAKE_DAMAGED = "the take could not be opened: its recorded data is damaged" CANCELLED = "cancelled" TAKE_INTERRUPTED = ( - "the take was interrupted and stays on disk unfinished; start a new batch on the recording page to go on" + "the take was interrupted and waits unfinished; recover or discard it on the recording page to go on" ) +#: Said in place of a readiness reason the recorder did not give. +SOURCES_NOT_READY = "required sources are not ready" OUTCOME_UNKNOWN = "the take ended outside the calibration tool and its outcome is not known" SOLVE_RUNNING = "a solve is already running" SOLVE_FAILED = "the solve failed unexpectedly; see the backend log" @@ -189,11 +195,20 @@ "The batch that is open does not carry this calibration: start a new batch on the recording page, and the " "takes after it will." ) -#: How a take that was not kept ended, by the recorder's disposition. +#: Said of a take whose outcome is a word this tool does not know: never taken for a kept one. +NOT_KEPT = "the take was not kept" +#: What becomes of a take the integrity check rejected: its data is left where it was until someone removes it. +DATA_KEPT = "its data stays on disk and can be discarded on the recording page" +#: How a take that was not kept ended, by the outcome the recording page shows for it. A calibration take is +#: exempt from the capture checks, so only the integrity check can reject one; the checks' other outcomes are +#: worded for a take that was judged all the same. _ENDINGS = { - "REJECTED": "the take was rejected by the recorder's checks", - "DISCARDED": "the take was discarded", - "RECOVERY_REQUIRED": TAKE_INTERRUPTED, + take_outcome.REJECTED_DATA_KEPT: f"the integrity check rejected it; {DATA_KEPT}", + take_outcome.REJECTED: "the capture checks rejected it and removed its media", + take_outcome.FLAGGED: "the capture checks marked it bad", + take_outcome.QUARANTINED: "the capture checks marked it bad and set it aside", + take_outcome.DISCARDED: "the take was discarded", + take_outcome.INTERRUPTED: TAKE_INTERRUPTED, } #: How old the newest picture may be and still count as live; the window recording readiness uses. @@ -270,13 +285,14 @@ class LiveTracking: @dataclass(frozen=True) class _Outcome: - """What the recorder says became of a take.""" - - disposition: str - #: Where a kept take is. - final_path: Path | None - #: What the recorder and its checks found, in their own words. - findings: tuple[str, ...] + """What became of a take, as the recording page is told (``take_outcome.describe_result``).""" + + #: The outcome word the page shows; one of ``take_outcome.OUTCOMES``. + word: str + #: Where the take's data is, relative to the recording output; None once it is gone. + location: str | None + #: Why it ended that way: the page's own sentences, which hold no path and no recorder text. + reasons: tuple[str, ...] #: Tracking rows the take holds, when the recorder's result says; None when only the page's record is left. tracking_rows: int | None = None @@ -516,15 +532,18 @@ def untracked_hint(tracking: LiveTracking) -> str | None: return f"{subject[0].upper()}{subject[1:]} {verb} not tracked: {ROWS_NEED_ALL_THREE}." +def described_outcome(described: Mapping[str, Any], tracking_rows: int | None = None) -> _Outcome: + """The outcome the tool settles from, read from a take's description as the recording page gets it: the + record ``take_outcome.describe_result`` makes, which the recording context keeps of the last take.""" + reasons = tuple(reason for reason in described.get("reasons", ()) if isinstance(reason, str)) + return _Outcome(described.get("outcome", ""), described.get("location"), reasons, tracking_rows) + + def outcome_of(result: Any) -> _Outcome: - """A recording-service result as the outcome the tool settles from.""" - findings = list(result.issues) - # A take the checks reject carries their findings in the reports, not among its issues. - for report in (result.quality, result.capture_quality): - if report is not None: - findings += report.issues + """A recording-service result as the outcome the tool settles from, worded once for the page and the tool: + the recorder's own notes can hold a directory or an exception's text, and stay in the backend log.""" rows = next((count.accepted for count in result.counts if count.source_name == PICO_CONTROLLER_SOURCE), None) - return _Outcome(result.disposition.value, result.final_path, tuple(findings), rows) + return described_outcome(take_outcome.describe_result(result), rows) def _no_guide(reason: str) -> dict[str, Any]: @@ -1066,31 +1085,31 @@ def _installed_prerequisites( async def _begin_take( self, request: RecordingRequest, camera: str, head: tuple[Intrinsics, np.ndarray] | None, model: str | None ) -> _Recording: - """Put the calibration task text in place and start the take; the operator's text goes back if the - start is refused.""" + """Put the calibration task text in place and start the take, exempt from the capture checks; the + operator's text goes back if the start is refused.""" coordinator = self._context.coordinator + # Asked as Record on the recording page asks it: the reason is the backend's own sentence for the + # operator, where the coordinator's refusal of a start it is not ready for is worded for the log. + ready, reason = coordinator.readiness() + if not ready: + raise CalibrationRefusal(409, bounded(reason or SOURCES_NOT_READY)) before = coordinator.snapshot().context what = GLOVE_PHRASE if request.tool == GLOVE_TOOL else ROLE_PHRASES[request.role] swap = _TaskSwap(f"Calibration: {what}", before.task_text, before.task_details) try: coordinator.set_task(swap.calibration_text, task_details="") except CoordinatorBusyError as exc: - raise CalibrationRefusal(409, bounded(exc)) from None + raise CalibrationRefusal(409, self._recorder_refusal(exc, "started", TAKE_NOT_STARTED)) from None self._swap = swap # The coordinator announces no task change of its own; viewers are sent one when this advances. self._context.revision += 1 try: - episode = await coordinator.start_episode(request.operator) - except (CoordinatorBusyError, StateError) as exc: - # The coordinator's own reasons are written for the operator. + # Exempt, for every take either tool starts: a board waved at one camera and hands held still are + # what the capture checks reject or set aside. The flag is this code's own: no request names it. + episode = await coordinator.start_episode(request.operator, exempt_from_capture_checks=True) + except Exception as exc: # noqa: BLE001 -- a refusal or a full disk: the task text must go back self._restore_task() - raise CalibrationRefusal(409, bounded(exc)) from None - except Exception: # noqa: BLE001 -- e.g. a full disk; the task text must go back whatever failed - # A refused configuration among them: the recording service words those for a log, with the - # directory of whatever it could not find. - logger.exception("A calibration take could not be started") - self._restore_task() - raise CalibrationRefusal(409, TAKE_NOT_STARTED) from None + raise CalibrationRefusal(409, self._recorder_refusal(exc, "started", TAKE_NOT_STARTED)) from None # The head track is of the take: what arrived before it began is not handed to its guide. newest = self._monitor.preview.tracking() return _Recording( @@ -1105,6 +1124,15 @@ async def _begin_take( track_handed=None if newest is None else newest.sequence, ) + def _recorder_refusal(self, exc: Exception, doing: str, otherwise: str) -> str: + """The sentence for a take the recorder would not have ``doing`` (started, ended), as the recording page + words a refused command. What was raised names recorder states, ids and directories: it goes to the log.""" + # A refusal on purpose is an expected answer; anything else is a fault and keeps its traceback. + expected = isinstance(exc, RECORDER_REFUSALS) + level = logging.WARNING if expected else logging.ERROR + logger.log(level, "A calibration take could not be %s: %s", doing, exc, exc_info=not expected) + return refusal_sentence(self._context.coordinator, exc, otherwise) + async def _remember_board(self, spec: BoardSpec) -> None: """Keep the take's board for the station. A note that cannot be written costs a prefilled form, so it is logged and the take goes on.""" @@ -1165,16 +1193,15 @@ def _recorded_outcome(self, recording: _Recording, service: Any) -> _Outcome | N return outcome_of(result) last = self._context.last_result if last is not None and last.get("episode_id") == recording.episode_id: - # The page's record of the last take keeps no path; a kept take is its pending directory renamed. - pending = recording.pending_path - kept_at = pending.with_name(pending.name.removesuffix(PENDING_SUFFIX)) - return _Outcome(last.get("disposition", ""), kept_at, tuple(last.get("issues", ()))) + # The page's record of the last take is the same description, less the count of tracking rows. + return described_outcome(last) return None def _apply_outcome(self, recording: _Recording, outcome: _Outcome) -> None: """Settle the recording from a take's outcome: saved when it was kept, failed with why otherwise.""" - if outcome.disposition == "KEPT" and outcome.final_path is not None: - take = self.take_name(outcome.final_path) + if outcome.word == take_outcome.KEPT and outcome.location is not None: + # Named as the recording page names it: relative to the recording output, with no directory above. + take = outcome.location request = recording.request self._last_take[request.tool] = take if request.tool == CAMERA_TOOL: @@ -1188,18 +1215,14 @@ def _apply_outcome(self, recording: _Recording, outcome: _Outcome) -> None: } self._finish(recording, SAVED, take=take) return - found = "; ".join(outcome.findings) - problem = _ENDINGS.get(outcome.disposition, "the take was not kept") - if outcome.disposition == "REJECTED": - # What the recorder's checks found, in their words; those findings are kept with the take as well. - problem = f"{problem}: {found}" if found else problem - if self._without_tracking(recording, outcome): - # The checks name a source with no rows, which says nothing to an operator; this says why. - problem = f"{NO_TRACKING_RECORDED}; {problem}" - else: - # What interrupted a take can quote an exception, so it goes to the log and not to the page. - logger.info("A calibration take ended as %s: %s", outcome.disposition or "unknown", found) - self._finish(recording, FAILED, problem=bounded(problem)) + problem = _ENDINGS.get(outcome.word, NOT_KEPT) + if outcome.word == take_outcome.REJECTED_DATA_KEPT and self._without_tracking(recording, outcome): + # The integrity check names a source with no rows, which says nothing to an operator; this says why. + problem = f"{NO_TRACKING_RECORDED}; {DATA_KEPT}" + # An interrupted take waits on the recording page, which says why beside the buttons that resolve it. + # Any other take's reasons are that page's own sentences, so the tool and the page never disagree. + reasons = () if outcome.word == take_outcome.INTERRUPTED else outcome.reasons + self._finish(recording, FAILED, problem=with_sentences(problem, reasons)) @staticmethod def _without_tracking(recording: _Recording, outcome: _Outcome) -> bool: @@ -1272,17 +1295,13 @@ async def _end_take(self, *, discard: bool) -> dict[str, Any]: try: end = coordinator.discard_episode if discard else coordinator.stop_episode result = await end(recording.episode_id) - except (CoordinatorBusyError, StateError) as exc: - refusal = bounded(exc) - except Exception: # noqa: BLE001 -- the reply must say the take is still recording, whatever failed - # A refused configuration among them, which the recording service words for a log. - logger.exception("A calibration take could not be ended") - refusal = TAKE_NOT_ENDED + except Exception as exc: # noqa: BLE001 -- the reply must say the take is still recording, whatever failed + refusal = self._recorder_refusal(exc, "ended", TAKE_NOT_ENDED) else: outcome = outcome_of(result) # A discard the recorder could not carry out leaves the take with it, interrupted, and that is # what the page must hear: the recorder now refuses the next take until it is dealt with. - if discard and outcome.disposition == "DISCARDED": + if discard and outcome.word == take_outcome.DISCARDED: self._finish(recording, FAILED, problem=CANCELLED) else: self._apply_outcome(recording, outcome) @@ -1863,8 +1882,8 @@ async def after_install(self) -> dict[str, Any]: if service is None: return {"ended": False, "new_batch_needed": False, "note": None} waits = {"ended": False, "new_batch_needed": True, "note": NEW_BATCH_NEEDED} - # A take being written is never interrupted. An interrupted one would be left on disk by a new batch - # with nothing on the page to say so, so ending that batch stays the operator's own step. + # A take being written is never interrupted. An interrupted one waits for the operator, who recovers or + # discards it on the recording page: ending the batch under it stays their own step. if interrupted_take(service) or self.take_in_progress() is not None: return waits try: diff --git a/examples/egocap/backend/egocap_web/day_report_routes.py b/examples/egocap/backend/egocap_web/day_report_routes.py index 29ed03fb47..8bb35d2634 100644 --- a/examples/egocap/backend/egocap_web/day_report_routes.py +++ b/examples/egocap/backend/egocap_web/day_report_routes.py @@ -40,6 +40,7 @@ from .recording_command import MAX_TASK_DETAILS_CHARS, control_token_valid, interrupted_take from .request_body import read_authorized_json from .session_locks import ALIGNER, CORRECTION, SessionLocks +from .take_outcome import describe_manifest logger = logging.getLogger("isaaccapture.egocap.day_report_routes") @@ -87,9 +88,14 @@ def _gather(state: tuple[Any, Any, Any, Path], snapshot: Any) -> dict[str, Any]: _context, stations, uptime, root = state today = datetime.date.fromtimestamp(time.time()).isoformat() station = stations.label() - # A station renamed today recorded its earlier takes under the old name; they are still its day. + # A station renamed today recorded its earlier takes under the old name; they are still its day. Each take's + # reasons are worded as on the page after the take, so the summary and the take never disagree. report = build_day_report( - root, today, stations=uptime.names(station), active_episode_id=_active_episode_id(snapshot) + root, + today, + stations=uptime.names(station), + active_episode_id=_active_episode_id(snapshot), + describe=describe_manifest, ) return { "report": {**report, "station": station}, diff --git a/examples/egocap/backend/egocap_web/livekit_recording.py b/examples/egocap/backend/egocap_web/livekit_recording.py index c3e3fdafac..28708fe1ab 100644 --- a/examples/egocap/backend/egocap_web/livekit_recording.py +++ b/examples/egocap/backend/egocap_web/livekit_recording.py @@ -25,6 +25,7 @@ import ipaddress import logging import os +import re from collections.abc import Callable, Mapping, Sequence from typing import Any from urllib.parse import urlparse @@ -121,6 +122,39 @@ def is_loopback_url(url: str) -> bool: return False +#: A stream's name as a streams file writes it, for the sentences below that begin with one. +_STREAM = r"[A-Za-z0-9_.\-]{1,64}: " +#: Every sentence :meth:`LiveKitRecordingSource.prepare` refuses a start with. They are written here for an +#: operator; anything else a start can fail with (what the room connection raised) is not. +_START_REFUSALS = tuple( + re.compile(pattern) + for pattern in ( + _STREAM + r"the LiveKit track was lost before recording started", + _STREAM + + r"the first frame carries no capture time, so it cannot be recorded " + + r"\(the bridge publishes none while time sync is not up\)", + _STREAM + r"frames are \d+x\d+, expected \d+x\d+", + r"a LiveKit stream sent no frame before the recording could start", + r"joining the LiveKit room took longer than [0-9.]+ s", + r"the publisher did not answer clock-sync requests, so its frame times cannot be placed", + r"the publisher's clock mapping jumped before the take started", + r"the clock mapping is uncertain by [0-9.]+ ms, over the [0-9.]+ ms budget \([A-Z_]+\)", + ) +) + + +def own_start_refusal(text: str) -> str | None: + """The sentence of this module that ``text`` begins with, or None when it begins with none of them. + + For a caller that passes a refused start on to an operator: only what this module wrote is passed on. + """ + for pattern in _START_REFUSALS: + found = pattern.match(text) + if found: + return found.group(0) + return None + + def unrecordable_reason(started: Any, capture_server_url: str | None = None) -> str | None: """Why a started session's LiveKit streams cannot all be recorded, naming the first that cannot; else None. diff --git a/examples/egocap/backend/egocap_web/readiness_text.py b/examples/egocap/backend/egocap_web/readiness_text.py new file mode 100644 index 0000000000..25e57686fe --- /dev/null +++ b/examples/egocap/backend/egocap_web/readiness_text.py @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The sentences the backend writes for why capture cannot be recorded right now. + +The readiness check composes them, and the same sentences are the only capture reasons passed on when a take +is interrupted: a reason that reaches the recorder from anywhere else (an error raised inside CaptureServer, a +device's own message) is not one of these and never leaves the log. +""" + +from __future__ import annotations + +import re + +__all__ = [ + "CAPTURE_NOT_RUNNING", + "NO_CAMERA_SELECTED", + "TRACKING_NOT_ACCEPTED", + "TRACKING_STALE", + "TRACKING_UNSUPPORTED", + "camera_stale", + "readiness_sentence", +] + +TRACKING_NOT_ACCEPTED = "tracking source not yet accepted" +#: Followed, in the readiness check, by a colon and what the descriptor lacks. +TRACKING_UNSUPPORTED = "tracking descriptor unsupported for recording" +CAPTURE_NOT_RUNNING = "capture is not running" +TRACKING_STALE = "tracking source is stale or has no sample yet" +NO_CAMERA_SELECTED = "no camera selected" + +_FIXED = (TRACKING_NOT_ACCEPTED, CAPTURE_NOT_RUNNING, TRACKING_STALE, NO_CAMERA_SELECTED) +#: A stale camera, named as the station file names it: letters, digits and the three marks used in such names. +_CAMERA_STALE = re.compile(r"camera '[A-Za-z0-9_.\-]{1,64}' is stale or has no sample yet") + + +def camera_stale(name: str) -> str: + """The sentence for a camera that stopped delivering, or has not delivered yet.""" + return f"camera {name!r} is stale or has no sample yet" + + +def readiness_sentence(text: str) -> str | None: + """The readiness sentence that ``text`` begins with, or None when it does not begin with one. + + What follows the sentence is dropped: the recorder appends its own notes to a reason, and an unsupported + descriptor is followed by detail that is not written for the page. + """ + for sentence in (*_FIXED, TRACKING_UNSUPPORTED): + if text.startswith(sentence): + return sentence + found = _CAMERA_STALE.match(text) + return found.group(0) if found else None diff --git a/examples/egocap/backend/egocap_web/recording_adapter.py b/examples/egocap/backend/egocap_web/recording_adapter.py index 6b36ee5f0c..abbdb31b8c 100644 --- a/examples/egocap/backend/egocap_web/recording_adapter.py +++ b/examples/egocap/backend/egocap_web/recording_adapter.py @@ -83,6 +83,17 @@ ) +def _pose_streams(spec: NumericSourceSpec) -> tuple[tuple[str, str], ...]: + """The (source, field) of every field of ``spec`` that holds 4x4 transforms, alone or as an array of them.""" + return tuple((spec.name, f.name) for f in spec.fields if tuple(f.shape[-2:]) == (4, 4)) + + +#: The pose fields the capture checks judge, read off the schemas above so the two cannot drift apart. A trigger +#: is a float too, but it rests at one value for a whole take, so only transforms are poses. +PICO_POSE_STREAMS = _pose_streams(PICO_CONTROLLER_SPEC) +MANUS_POSE_STREAMS = _pose_streams(MANUS_GLOVE_SPEC) + + class RecordingAdapterError(ValueError): """Raised when the actually-offered tracking descriptor doesn't match the fixed contract this adapter was written against -- a real diff --git a/examples/egocap/backend/egocap_web/recording_command.py b/examples/egocap/backend/egocap_web/recording_command.py index 3b921f0587..8169bf9d7e 100644 --- a/examples/egocap/backend/egocap_web/recording_command.py +++ b/examples/egocap/backend/egocap_web/recording_command.py @@ -34,24 +34,181 @@ from dataclasses import dataclass, field from typing import Any -from recording_service import ConfigurationError, Disposition, EpisodeResult, RecordingPhase, StateError +from recording_service import ConfigurationError, EpisodeResult, RecordingPhase, StateError +from .livekit_recording import own_start_refusal from .recording_session import ( + MISPLACED_TAKE, + RECORDING_IN_THE_WAY, + REJECTED_TAKE_NOT_RECOVERABLE, + SESSION_OPEN_ELSEWHERE, CoordinatorBusyError, CoordinatorSnapshot, + PendingTake, RecordingSessionCoordinator, SessionStatus, ) +from .take_outcome import ( + FLAGGED, + KEPT, + NEEDS_SAME_SETUP, + QUARANTINED, + REJECTED, + REJECTED_DATA_KEPT, + SETUP_NOT_KNOWN_YET, + STORAGE_SENTENCES, + describe_pending, + describe_result, +) + +#: Which of the batch's counts a take's outcome adds to; an outcome not listed (discarded, interrupted) adds to +#: none. "Saved" is good takes only: one the checks marked bad is counted as flagged or quarantined instead. +_COUNT_OF_OUTCOME = { + KEPT: "saved_count", + FLAGGED: "flagged_count", + QUARANTINED: "quarantined_count", + REJECTED: "rejected_count", + REJECTED_DATA_KEPT: "rejected_count", +} + +#: What a quarantine folder that cannot take a take needs, said wherever the recorder refuses because of it. +_QUARANTINE_FOLDER = { + "quarantine location is a link": "is a link", + "quarantine location is not a directory": "is a file, not a folder", + "quarantine location is on another file system": "is on another disk than the recordings", +} +_QUARANTINE_FIX = "Make it a plain folder on the recordings disk." + +#: Why a pending take could not be resolved, by what the recording service said. The service's own text names +#: directories and ids, so it stays in the log and the operator gets the sentence for its kind. A take that is +#: complete is never said to need discarding: the sentence says what it needs instead. +_PENDING_REFUSALS = ( + ( + "still marked WRITING", + "This take was cut off while it was being written and cannot be recovered; discard it.", + ), + ("different configuration", NEEDS_SAME_SETUP), + ( + "a discard of episode", + "A discard of this take was started, so its data may be incomplete; discard it again to finish.", + ), + ("rejected by the integrity check", REJECTED_TAKE_NOT_RECOVERABLE), + ("owned by another recorder", SESSION_OPEN_ELSEWHERE), + ("is still running", "Work on this take is still running; try again in a moment."), + ("no pending episode", "That take is no longer pending."), + *( + ( + marker, + f"This take cannot be set aside: the quarantine folder in the recording output {problem}. " + f"{_QUARANTINE_FIX} The take was left as it is; it can also be discarded.", + ) + for marker, problem in _QUARANTINE_FOLDER.items() + ), +) +#: A session that cannot be reopened: its frozen source declarations or required calibration files differ now. +_CANNOT_REOPEN = ( + "This take's session cannot be reopened under the current settings: its source declarations or calibration " + "files have changed. The take was left on disk." +) +_CANNOT_RESOLVE = "The take could not be resolved; see the backend log." +_NOT_PENDING = "That take is no longer pending." -#: recording_service.Disposition values the existing frontend wire -#: contract can actually represent as a last_result.disposition (see -#: useCaptureSession.ts's DISPOSITIONS set, unchanged -- any backend/ -#: protocol change to extend it is explicitly out of scope here and needs -#: separate approval). RECOVERY_REQUIRED is a real, valid disposition now -#: that interrupt_episode exists, but is NOT one of these -- see -#: RecordingContext._apply_result for how that case is handled without -#: ever serializing an unsupported value. -_WIRE_COMPATIBLE_DISPOSITIONS = frozenset({Disposition.KEPT, Disposition.REJECTED, Disposition.DISCARDED}) +#: A take that waits blocks the next one; said for every way the recorder reports it. +_TAKE_WAITING = ( + "A take is waiting to be recovered or discarded. Resolve it, or start a new batch, before recording." +) +_STILL_WRITING = "The take is still being written; try again in a moment." +#: The sentence for each refusal of a recording command, by a part of what the coordinator or the recording +#: service said. Their own texts are written for the log: they name recorder states, ids and directories, and +#: several end in whatever a lower layer raised. None of that is passed on. +_COMMAND_REFUSALS = ( + ("recording session is closing", "The recorder is shutting down; no recording command is accepted."), + ("service is closing or closed", "The recorder is shutting down; no recording command is accepted."), + ("already in progress", "Another recording command is still running; try again in a moment."), + ("already has a", "Another recording command is still running; try again in a moment."), + ("recording session failed", "The recording session failed; use New batch before recording again."), + ("a recording session (", "The recording session did not close; use New batch before recording again."), + ("did not fully release", "The previous session did not close; restart the backend before recording again."), + ("has not yet settled", _STILL_WRITING), + ("did not settle", _STILL_WRITING), + ("start was superseded", "Capture stopped being ready while the take was starting; try again."), + ("no matching active episode", "That take is not the one being recorded."), + ("no active episode", "That take is not the one being recorded."), + (RECORDING_IN_THE_WAY, "Finish or discard the take being recorded first."), + ("an episode is active", "Stop or discard the take being recorded first."), + ("while RECOVERY_REQUIRED", _TAKE_WAITING), + ("needs recovery", _TAKE_WAITING), + ("unresolved pending episodes", _TAKE_WAITING), + ( + "unreadable episode manifests", + "This session holds a take record that cannot be read; start a new batch to record.", + ), + ("cannot start an episode while", "A take is still being started, recorded or finished."), + ("cannot stop while", "That take is not being recorded any more."), + ("cannot discard while", "That take is not being recorded any more."), + ("no open recording session", "No recording session is open."), + ("no open session", "No recording session is open."), + ("no frozen source declarations", "This session cannot record; start a new batch."), + ("owned by another recorder", "That session is open in another recorder."), + ("calibration asset", "A calibration file this station requires is missing or changed; see the backend log."), + ("quality-check configuration is invalid", "The quality-check configuration is invalid; see the backend log."), + *( + ( + marker, + f"The quarantine folder in the recording output {problem}, so a take marked bad could not be set " + f"aside. {_QUARANTINE_FIX}", + ) + for marker, problem in _QUARANTINE_FOLDER.items() + ), +) +_REFUSED = "The recorder refused the command; see the backend log." +_CONFIGURATION_REFUSED = "The recording configuration is not valid; see the backend log." +_COMMAND_FAILED = "The recording command failed; see the backend log." +#: How the coordinator begins its refusal of a start whose LiveKit video is not flowing; the reason follows. +_LIVEKIT_NOT_READY = "LiveKit video is not ready" + + +def _public_refusal(exc: Exception) -> str: + """The sentence an operator reads for a refused recording command; what was raised stays in the log.""" + text = str(exc) + if text.startswith(_LIVEKIT_NOT_READY): + # The reason is passed on when the LiveKit recording code wrote it, and only as far as it wrote it: + # what a room connection raised is not for the page. + reason = own_start_refusal(text.removeprefix(_LIVEKIT_NOT_READY).removeprefix(": ")) + return f"{_LIVEKIT_NOT_READY}: {reason}." if reason else f"{_LIVEKIT_NOT_READY}; see the backend log." + known = next((sentence for marker, sentence in _COMMAND_REFUSALS if marker in text), None) + if known is not None: + return known + return _CONFIGURATION_REFUSED if isinstance(exc, ConfigurationError) else _REFUSED + + +def _public_failure(disk_problem: str | None, otherwise: str) -> str: + """The sentence for a command that failed with something unexpected. + + A recordings disk that is full, over quota, read-only or not writable is said in words: it is the one + failure an operator can act on. ``disk_problem`` is the recorder's word for it, which it gives only for a + failure on a file under the recording output. Anything else gets ``otherwise``. + """ + return STORAGE_SENTENCES.get(disk_problem or "", otherwise) + + +#: What the coordinator and the recording service raise on purpose to refuse a command. Anything else that +#: comes out of one is a failure. +RECORDER_REFUSALS = (CoordinatorBusyError, StateError, ConfigurationError) + + +def refusal_sentence(coordinator: RecordingSessionCoordinator, exc: BaseException, otherwise: str) -> str: + """The sentence an operator reads when the coordinator would not start, stop or discard a take. + + For backend code that records takes of its own through the coordinator (the calibration tools): it words a + refusal as the page's commands are answered, so a recorder's refusal is never worded a second way. A + refusal raised on purpose is worded by its kind; anything else is a failure, named when the recordings disk + caused it and ``otherwise`` when not. What was raised is the caller's to log and is never returned. + """ + # Raised on purpose, it is of a kind that has a sentence. Anything else is told by what the disk refused. + if isinstance(exc, RECORDER_REFUSALS): + return _public_refusal(exc) + return _public_failure(coordinator.recordings_disk_problem(exc), otherwise) _logger = logging.getLogger(__name__) @@ -153,6 +310,10 @@ def _validate_episode_target(payload: dict[str, Any]) -> None: "stop_episode": _validate_episode_target, "discard_episode": _validate_episode_target, "new_batch": _validate_batch_target, + # A pending take is named by its episode id, which holds its session: one of the open session and one of + # an earlier session are resolved by the same two commands. + "recover_pending": _validate_episode_target, + "discard_pending": _validate_episode_target, } @@ -248,7 +409,14 @@ class RecordingContext: #: Keyword-only, so the fields after it keep their places for a caller that passes them by position. settle_tools: Callable[[], None] | None = field(default=None, repr=False, kw_only=True) batch_id: str = field(default_factory=_new_batch_id) + #: The batch's takes by outcome. ``saved_count`` is good takes only; a take the checks marked bad adds to + #: ``flagged_count`` or ``quarantined_count``, a rejected one (media removed or data kept) to + #: ``rejected_count``. A take of an earlier session resolved from the page adds to none: it was not + #: recorded in this batch. saved_count: int = 0 + flagged_count: int = 0 + quarantined_count: int = 0 + rejected_count: int = 0 last_result: dict[str, Any] | None = None #: Monotonic clock basis (time.monotonic()) the current episode started #: at, or None when idle -- process-local, never serialized directly; @@ -271,9 +439,9 @@ class RecordingContext: #: _observe() runs (each viewer's sender loop calls refresh() on every #: iteration; see preview_routes.py). revision: int = field(default=0, repr=False) - #: The last (status, phase, active_operation, ready, reason) tuple - #: snapshot() observed -- compared on every call so a real change with - #: no dedicated callback still advances ``revision``. None before the + #: The last (status, phase, active_operation, ready, reason, pending + #: takes) tuple snapshot() observed -- compared on every call so a real + #: change with no dedicated callback still advances ``revision``. None before the #: first snapshot() call, so that call always counts as a real first #: observation (not implicitly "no change"). _last_decision_state: tuple[Any, ...] | None = field(default=None, repr=False) @@ -296,39 +464,22 @@ def _on_episode_started(self) -> None: self.revision += 1 def _on_episode_result(self, result: EpisodeResult) -> None: + """Publish what became of a take: one just stopped, discarded or interrupted, or a pending one resolved. + + An interrupted take is published too, with the reason it waits, so the page can offer to recover or + discard it instead of showing the previous take's outcome in its place. + """ self._episode_started_monotonic = None - if result.disposition not in _WIRE_COMPATIBLE_DISPOSITIONS: - # The interrupted take has no wire form (see below); keep the - # previous take's outcome from standing in for it. - self.last_result = None - if result.disposition in _WIRE_COMPATIBLE_DISPOSITIONS: - self.last_result = { - "episode_id": result.episode_id, - "disposition": result.disposition.value, - "issues": list(result.issues), - "duration_ms": int(result.duration_seconds * 1000), - } - if result.disposition is Disposition.KEPT: - self.saved_count += 1 - # else: RECOVERY_REQUIRED (from interrupt_episode -- a real - # pipeline failure, whether operator-stopped or automatically - # interrupted mid-recording) is NOT serialized into last_result, - # since the existing frontend wire contract's EpisodeDisposition - # parser only accepts KEPT/REJECTED/DISCARDED and would reject the - # WHOLE snapshot as malformed on an unrecognized value. The real - # recovery state is still visible through episode_phase - # (RECOVERY_REQUIRED is an already-supported phase value), but the - # specific failure reason text has no existing place to go in the - # current wire contract -- a real, acknowledged protocol gap, not - # silently patched around here; extending the frontend's - # EpisodeDisposition/DISPOSITIONS set (or adding a dedicated - # surfaced-issue field) is a deliberate follow-up decision, not - # made unilaterally in this backend-only change. + self.last_result = describe_result(result) + counted = _COUNT_OF_OUTCOME.get(self.last_result["outcome"]) + # A take of an earlier session, resolved from the page, was not recorded in this batch. + if counted is not None and result.session_id == self.coordinator.open_session_id(): + setattr(self, counted, getattr(self, counted) + 1) self.revision += 1 def _on_batch_rotated(self) -> None: self.batch_id = _new_batch_id() - self.saved_count = 0 + self.saved_count = self.flagged_count = self.quarantined_count = self.rejected_count = 0 self.last_result = None self._episode_started_monotonic = None self.revision += 1 @@ -343,7 +494,27 @@ def _decision_state( docstring).""" service_snapshot = coordinator_snapshot.service phase_value = service_snapshot.phase.value if service_snapshot is not None else "IDLE" - return (coordinator_snapshot.status, phase_value, coordinator_snapshot.active_operation, ready, reason) + # The pending takes change with no callback either: a read of earlier sessions' manifests finds one, or + # finds that one can be recovered now that the cameras are accepted. + pending = tuple( + ( + take.episode.episode_id, + take.episode.storage_phase, + take.episode.recoverable, + take.episode.discard_requested, + take.current, + take.cameras_known, + ) + for take in self.coordinator.pending_takes() + ) + return ( + coordinator_snapshot.status, + phase_value, + coordinator_snapshot.active_operation, + ready, + reason, + pending, + ) def _settle_tools(self) -> None: """Lets another tool put back what it holds over the recorder (see ``settle_tools``), when one does.""" @@ -378,7 +549,7 @@ def refresh(self) -> None: def snapshot(self) -> dict[str, Any]: """The current recording facts, in the wire shape the frontend's RecordingSnapshot parser expects.""" coordinator_snapshot, decision_state = self._observe() - status, phase_value, active_operation, ready, reason = decision_state + status, phase_value, active_operation, ready, reason, _pending = decision_state service_snapshot = coordinator_snapshot.service current_episode_id = None if service_snapshot is not None and service_snapshot.episode is not None: @@ -401,7 +572,17 @@ def snapshot(self) -> dict[str, Any]: # explicit "Set operator" action; this never means auto-commit. "auto_fill_operator_name": self.auto_fill_operator_name, "saved_count": self.saved_count, + "flagged_count": self.flagged_count, + "quarantined_count": self.quarantined_count, + "rejected_count": self.rejected_count, "last_result": self.last_result, + # Every take that waits for the operator: the open session's unresolved one (it blocks Record), takes + # rejected for integrity whose data is still on disk, and what earlier sessions left behind. The same + # two commands act on all of them; each row says which of the two it takes. + "pending_takes": [ + describe_pending(take.episode, current=take.current, cameras_known=take.cameras_known) + for take in self.coordinator.pending_takes() + ], # Real command-admission readiness: the same phase==IDLE/no- # active-operation/not-closing conditions start_episode itself # enforces, PLUS the real injected readiness_check result (so @@ -452,9 +633,9 @@ async def apply(self, command: RecordingCommand) -> tuple[str, str | None]: exception. Checked first, before any other validation: a missing or wrong - ``control_token`` is rejected before admission, for every one of - the five actions reaching this point (no per-action allowlist to - keep in sync -- every admitted command already mutates). + ``control_token`` is rejected before admission, for every action + reaching this point (no per-action allowlist to keep in sync -- + every admitted command already mutates). This method itself does NOT update any projection state (no ``last_result``/``saved_count``/``batch_id``/elapsed-basis writes @@ -510,6 +691,10 @@ async def apply(self, command: RecordingCommand) -> tuple[str, str | None]: blocked = self.setup_block() if blocked is not None: return "rejected", blocked + # The readiness reason is the backend's own sentence, the one the snapshot already publishes. + ready, reason = self.coordinator.readiness() + if not ready: + return "rejected", reason or "required sources are not ready" await self.coordinator.start_episode(operator) return "ok", None if command.action == "stop_episode": @@ -526,15 +711,57 @@ async def apply(self, command: RecordingCommand) -> tuple[str, str | None]: # the coordinator itself). await self.coordinator.new_batch() return "ok", None + if command.action in ("recover_pending", "discard_pending"): + return await self._resolve_pending(command) except (CoordinatorBusyError, StateError, ConfigurationError) as exc: - return "rejected", str(exc) + _logger.warning("recording command %s was refused: %s", command.action, exc) + return "rejected", _public_refusal(exc) except Exception as exc: # noqa: BLE001 -- e.g. a full disk or an unwritable output directory # Anything else must still reach the viewer as a reply; letting it escape would end the receiver - # and close the socket with no answer. + # and close the socket with no answer. What was raised can name a directory, so it stays in the log. _logger.exception("recording command %s failed", command.action) - return "rejected", f"recording failed: {exc}" + return "rejected", _public_failure(self.coordinator.recordings_disk_problem(exc), _COMMAND_FAILED) raise AssertionError(f"unhandled recording action: {command.action}") + async def _resolve_pending(self, command: RecordingCommand) -> tuple[str, str | None]: + """Recover or discard one pending take, and answer with a deliberate reason when it is refused. + + "ok" means the recording service ran the step; what became of the take is in ``last_result``, which can + again be an interrupted take when the step failed part-way. + """ + episode_id = command.payload["episode_id"] + listed: PendingTake | None = next( + (take for take in self.coordinator.pending_takes() if take.episode.episode_id == episode_id), None + ) + if listed is None: + return "rejected", _NOT_PENDING + resolve = ( + self.coordinator.recover_episode + if command.action == "recover_pending" + else self.coordinator.discard_pending + ) + try: + await resolve(episode_id) + except CoordinatorBusyError as exc: + _logger.warning("%s of %s was refused: %s", command.action, episode_id, exc) + # Two of the coordinator's refusals are sentences about this take; the rest are worded like any + # other refused command. + own = str(exc) in (MISPLACED_TAKE, REJECTED_TAKE_NOT_RECOVERABLE, SESSION_OPEN_ELSEWHERE) + return "rejected", str(exc) if own else _public_refusal(exc) + except (StateError, ConfigurationError) as exc: + _logger.warning("%s of %s was refused: %s", command.action, episode_id, exc) + if isinstance(exc, ConfigurationError): + return "rejected", _CANNOT_REOPEN + if "different configuration" in str(exc) and not listed.cameras_known: + # With no camera accepted there is nothing to compare the take's setup with. + return "rejected", SETUP_NOT_KNOWN_YET + known = next((reason for marker, reason in _PENDING_REFUSALS if marker in str(exc)), None) + return "rejected", known or _CANNOT_RESOLVE + except Exception as exc: # noqa: BLE001 -- e.g. a full disk; the reply must still reach the viewer + _logger.exception("%s of %s failed", command.action, episode_id) + return "rejected", _public_failure(self.coordinator.recordings_disk_problem(exc), _CANNOT_RESOLVE) + return "ok", None + async def handle_recording_command(command: RecordingCommand, context: RecordingContext) -> dict[str, Any]: """Builds the real reply for one parsed command: applies its effect to diff --git a/examples/egocap/backend/egocap_web/recording_session.py b/examples/egocap/backend/egocap_web/recording_session.py index e0d79e381d..345bae8b1d 100644 --- a/examples/egocap/backend/egocap_web/recording_session.py +++ b/examples/egocap/backend/egocap_web/recording_session.py @@ -46,6 +46,22 @@ whatever operation is already in flight under one overall deadline, so shutdown can always actually settle in-progress work rather than either racing it or waiting forever. + +A take left pending (interrupted, or stopped part-way through its checks) is resolved from the page with +``recover_episode`` or ``discard_pending``. One left by the session open for recording is resolved by the open +service, which then returns to idle. One left by an earlier session (the usual case after a restart, or after New +batch) is listed from its manifest by ``refresh_pending`` and resolved by a second service opened on that +session for the one step and closed again, inside one owned operation. Either way only the recording service +finishes, removes or discards anything: this module deletes nothing. + +The same list holds a take of the open session that the integrity check rejected, for as long as its data is on +disk (it blocks nothing and can only be discarded), and a record found in a session directory it was not written +for, which no command acts on. Reading the list never fails an operation: a read that cannot be done keeps the +last list, and what a resolution did is always reported. + +A session some recorder has open is never listed and never acted on. Its lock says so where the lock reaches; +everywhere else its beat does (see ``recording_service.OutputScan``): this module looks at a session twice, a +few seconds apart, before it lists a take of it, and looks once more before it reopens the session for a command. """ from __future__ import annotations @@ -53,7 +69,7 @@ import asyncio import contextlib import logging -from collections.abc import Callable, Coroutine +from collections.abc import Callable, Collection, Coroutine from dataclasses import dataclass, replace from enum import Enum from functools import partial @@ -67,9 +83,12 @@ Disposition, EpisodeInfo, EpisodeResult, + OutputScan, PendingEpisode, RecordingPhase, ServiceConfig, + StateError, + storage_problem, ) if TYPE_CHECKING: @@ -79,6 +98,8 @@ _T = TypeVar("_T") +logger = logging.getLogger("isaaccapture.egocap.recording_session") + #: Overall bound on close()'s own settlement work (joining an in-flight #: operation, draining the current ingress, closing the service) -- #: deliberately distinct from ServiceConfig.close_deadline_seconds (the @@ -134,6 +155,39 @@ class TaskContext: task_text: str operator: str = "" task_details: str = "" + #: Set only on the copy frozen for one take, like the operator: that take is not judged by the capture + #: checks. The committed context never holds it, so it cannot carry over to the next take. + exempt_from_capture_checks: bool = False + + +#: Why a command for a listed take is refused before any service is asked. Written for the operator. +MISPLACED_TAKE = ( + "This take's record was written for another session: its folder was copied or renamed by hand. " + "Nothing was changed." +) +REJECTED_TAKE_NOT_RECOVERABLE = ( + "This take failed its integrity check and cannot be recovered. It can only be discarded." +) +RECORDING_IN_THE_WAY = "finish or discard the take being recorded first" +SESSION_OPEN_ELSEWHERE = "That take's session is open in another recorder." +#: Why Record is refused while the recorder's own sign that its session is open has stopped being written (see +#: ``SessionLock``): a take recorded now could look left behind to another machine that shares the recordings. +SESSION_BEAT_STOPPED = ( + "The recorder has not been able to write to the recordings folder for a few seconds. " + "Check the recordings disk; if this stays, finish any take in progress and restart the backend." +) + + +@dataclass(frozen=True) +class PendingTake: + """A take that waits for the operator. ``current`` is True for an unresolved take of the session open for + recording, which blocks the next take until it is resolved; any other blocks nothing. ``cameras_known`` is + False when the take was last looked at while no camera had been accepted, so that whether its settings match + could not be told.""" + + episode: PendingEpisode + current: bool + cameras_known: bool = True @dataclass(frozen=True) @@ -193,12 +247,38 @@ def __init__( initial_context: TaskContext | None = None, livekit_source: LiveKitRecordingSource | None = None, tracking_latency: dict[str, float] | None = None, + scan_config_factory: Callable[[], ServiceConfig] | None = None, + station_names: Callable[[], Collection[str]] | None = None, + watch_seconds: float | None = None, capture_facts: Callable[[], dict[str, Any] | None] | None = None, ) -> None: self._config_factory = config_factory # Reads the capture session's own facts when a take stops; injected because this coordinator must not # import the capture client. self._capture_facts = capture_facts + # Every name the station in use has had, so that what it left under an earlier name is still listed. + # It may read files, so it is asked in the worker thread that reads the output. Without it the scanning + # configuration's own station name is the only one. + self._station_names = station_names + # The same configuration without the side effects of opening a session for recording: it is built to + # look at, and to resolve, takes earlier sessions left pending. Defaults to the recording one. + self._scan_config_factory = scan_config_factory if scan_config_factory is not None else config_factory + #: Pending takes of sessions other than the open one, as last read from their manifests; None until the + #: first read, which is the one that finds what a previous run of the backend left behind. + self._earlier_pending: tuple[PendingEpisode, ...] | None = None + #: Whether that read was made with a camera accepted: without one no take's settings can be compared. + self._earlier_cameras_known = True + # What earlier reads learned, so that reading again opens only the sessions that can still change, and + # the looks at each session's beat that tell an open session from one left behind. ``watch_seconds`` is + # how far apart two looks must be; the default spans the recorder's one-second beat. + self._output_scan = OutputScan() if watch_seconds is None else OutputScan(watch_seconds=watch_seconds) + # The one read that follows a read which saw a session for the first time, a watch time later. + self._second_look: asyncio.Task[None] | None = None + # The kind of failure of the last read that could not be done, so that a read repeated every few + # seconds reports a standing problem once. + self._scan_failure: str | None = None + # One read at a time, so a read that started earlier can never overwrite the result of a later one. + self._scan_lock = asyncio.Lock() # Optional LiveKit video for each take: joined before storage opens, fed after the ingress starts, left # before the ingress is retired. self._livekit_source = livekit_source @@ -401,7 +481,7 @@ def set_task(self, task_text: str, task_details: str = "") -> None: raise CoordinatorBusyError("cannot edit task while recording") self._context = replace(self._context, task_text=task_text, task_details=task_details) - async def start_episode(self, operator: str = "") -> EpisodeInfo: + async def start_episode(self, operator: str = "", *, exempt_from_capture_checks: bool = False) -> EpisodeInfo: """The one place real storage is opened: requires current readiness (so the schema it opens with reflects actually accepted sources, not a guess made too early) and a committed task, then @@ -415,15 +495,23 @@ async def start_episode(self, operator: str = "") -> EpisodeInfo: state shared with ``set_task``, and admission can still be rejected after this point (e.g. a duplicate start while already RECORDING, inside the real service's own state machine) -- so a - rejected attempt must never leak its operator into shared state.""" + rejected attempt must never leak its operator into shared state. + + ``exempt_from_capture_checks`` starts a take the capture checks do + not judge. It is for backend code that records a calibration take + through this method. The page's start command has no field for it + and the command handler never passes it, so an operator's take is + always judged.""" if self._closing: raise CoordinatorBusyError("recording session is closing") if self._service is not None and self._status is SessionStatus.FAILED: raise CoordinatorBusyError("recording session failed; use New batch before recording again") - ready, reason = self._readiness_check() + ready, reason = self.readiness() if not ready: raise CoordinatorBusyError(reason or "required sources are not ready") - frozen_context = replace(self._context, operator=operator) + frozen_context = replace( + self._context, operator=operator, exempt_from_capture_checks=exempt_from_capture_checks + ) return await self._run_operation(OperationKind.STARTING, partial(self._start_episode_impl, frozen_context)) async def _start_episode_impl(self, frozen_context: TaskContext) -> EpisodeInfo: @@ -461,7 +549,10 @@ async def _start_episode_with_storage(self, frozen_context: TaskContext) -> Epis if not ready or self._closing: raise CoordinatorBusyError("start was superseded while storage was opening") episode = await service.start_episode( - frozen_context.task_text, frozen_context.operator, task_details=frozen_context.task_details + frozen_context.task_text, + frozen_context.operator, + task_details=frozen_context.task_details, + exempt_from_capture_checks=frozen_context.exempt_from_capture_checks, ) # Recheck readiness AND the service's own phase after the await: # start_episode can succeed at the storage level after something @@ -749,26 +840,207 @@ def _require_matching_active_episode(self, service: _RecordingService, episode_i raise CoordinatorBusyError("no matching active episode") async def recover_episode(self, episode_id: str) -> EpisodeResult: - service = self._require_open() - return await self._run_operation( - OperationKind.RECOVERING, partial(self._recover_episode_impl, service, episode_id) + """Finish a pending take: of the session open for recording, or of an earlier session.""" + return await self._resolve_pending(episode_id, discard=False) + + async def discard_pending(self, episode_id: str) -> EpisodeResult: + """Remove a pending take's unfinished data: of the session open for recording, or of an earlier one.""" + return await self._resolve_pending(episode_id, discard=True) + + async def _resolve_pending(self, episode_id: str, *, discard: bool) -> EpisodeResult: + """Route one resolution to the service that can perform it, as one owned operation.""" + if self._closing: + raise CoordinatorBusyError("recording session is closing") + kind = OperationKind.DISCARDING_PENDING if discard else OperationKind.RECOVERING + listed = next( + (take.episode for take in self.pending_takes() if take.episode.episode_id == episode_id), None + ) + if listed is not None: + # Said here, before any service is asked: these two are refused whatever the service would do. + if listed.misplaced: + raise CoordinatorBusyError(MISPLACED_TAKE) + if listed.storage_phase == "REJECTED" and not discard: + raise CoordinatorBusyError(REJECTED_TAKE_NOT_RECOVERABLE) + # Nothing is resolved beside a take that is being written: a discard of a rejected take would run in the + # recording service's own session, and a second service would be finishing files next to it. + writing = self._service is not None and self._service.snapshot().phase not in ( + RecordingPhase.IDLE, + RecordingPhase.RECOVERY_REQUIRED, ) + in_open_session = self._service is not None and any( + waiting.episode_id == episode_id + for waiting in (*self._service.pending_episodes(), *self._service.retained_rejections()) + ) + earlier = next((p for p in self._earlier_pending or () if p.episode_id == episode_id), None) + if in_open_session or earlier is None: + if in_open_session and (writing or self._current_ingress is not None): + raise CoordinatorBusyError(RECORDING_IN_THE_WAY) + # The open service answers for its own takes, and refuses an id it does not know. + service = self._require_open() + return await self._run_operation( + kind, partial(self._resolve_in_open_session_impl, service, episode_id, discard) + ) + if writing or self._current_ingress is not None: + raise CoordinatorBusyError(RECORDING_IN_THE_WAY) + return await self._run_operation(kind, partial(self._resolve_in_earlier_session_impl, earlier, discard)) + + async def _resolve_in_open_session_impl( + self, service: _RecordingService, episode_id: str, discard: bool + ) -> EpisodeResult: + """Resolve inside the owned operation, so a cancelled caller cannot skip telling what became of it.""" + result = await (service.discard_pending(episode_id) if discard else service.recover_episode(episode_id)) + self._emit_result(result) + return result - async def _recover_episode_impl(self, service: _RecordingService, episode_id: str) -> EpisodeResult: - """Recover inside the owned operation, so a cancelled caller cannot skip the kept notification.""" - result = await service.recover_episode(episode_id) - self._emit_kept(result) + async def _resolve_in_earlier_session_impl(self, pending: PendingEpisode, discard: bool) -> EpisodeResult: + """Open a second service on the take's own session, resolve the take there, and close it again. + + The session is reopened under the current configuration, so the service refuses it when its frozen + source declarations or required calibration files no longer match, and the take stays untouched. + + Before it is reopened its beat is looked at once more. Unchanged since a look a watch time ago or + longer, the step runs at once, which is the usual case for a take that has been listed for a while. + Otherwise the step waits for its own second look, and is refused when a recorder turns out to have the + session open. + """ + session_path = pending.pending_path.parent + quiet, wait = await asyncio.to_thread(self._output_scan.judge, session_path) + if quiet is None: + await asyncio.sleep(wait) + quiet, _wait = await asyncio.to_thread(self._output_scan.judge, session_path) + if not quiet: + raise CoordinatorBusyError(SESSION_OPEN_ELSEWHERE) + service = _RecordingService(self._scan_config_factory()) + # Whether the beat that stops when this service closes was this process's own. It was not when the + # session's lock was refused: then another recorder holds it, and its beat goes on. + own_beat = True + try: + try: + await service.open_session(pending.session_id) + except StateError: + own_beat = False + raise + episode_id = pending.episode_id + result = await ( + service.discard_pending(episode_id) if discard else service.recover_episode(episode_id) + ) + finally: + # The second service exists for this one step: it is closed whatever happened, and the list is read + # again so it shows what the take is now. Neither may hide what the step did. + try: + closed = await service.close() + if not closed.released: + logger.error("an earlier session did not fully release: %s", "; ".join(closed.issues)) + self._last_issue = "an earlier session did not fully release" + elif own_beat: + # The session was at rest before this process took it, so it is at rest again now: without + # this its own beat would hide the session's other takes for a watch time. + self._output_scan.note_closed(session_path) + finally: + await self.refresh_pending() + # What the step did is reported whatever became of the read. + self._forget_earlier(result) + self._emit_result(result) return result - async def discard_pending(self, episode_id: str) -> EpisodeResult: - service = self._require_open() - return await self._run_operation( - OperationKind.DISCARDING_PENDING, partial(service.discard_pending, episode_id) + def _forget_earlier(self, result: EpisodeResult) -> None: + """Take a resolved take off the list of earlier sessions' takes. + + The read after a resolution does this too. When that read could not be done the list would otherwise go + on showing a take that is gone. + """ + if result.disposition is Disposition.RECOVERY_REQUIRED or self._earlier_pending is None: + return + self._earlier_pending = tuple(p for p in self._earlier_pending if p.episode_id != result.episode_id) + + def pending_takes(self) -> tuple[PendingTake, ...]: + """Every take that waits for the operator. + + The open session's unresolved takes first (they block Record), then its takes rejected for integrity + whose data is still on disk, then the unresolved takes earlier sessions left behind. An earlier + session's take that was rejected for integrity is not listed: its data stays on disk, as it always did. + """ + current = self._service.pending_episodes() if self._service is not None else () + rejected = self._service.retained_rejections() if self._service is not None else () + listed = {waiting.episode_id for waiting in (*current, *rejected)} + earlier = tuple(p for p in self._earlier_pending or () if p.episode_id not in listed) + known = self._earlier_cameras_known + return ( + tuple(PendingTake(p, True) for p in current) + + tuple(PendingTake(p, False) for p in rejected) + + tuple(PendingTake(p, False, known) for p in earlier) ) + def recordings_disk_problem(self, exc: BaseException) -> str | None: + """What the recordings disk refused, when ``exc`` failed on a file under the recording output. + + The recorder's word for it (full, quota, read-only, denied), or None: for a failure anywhere else, + for one that names no file, and when the recording output is not known because the configuration + cannot be built. + """ + try: + root = self._scan_config_factory().output_root + except Exception: # noqa: BLE001 -- with no configuration there is no output to hold the failure against + return None + return storage_problem(exc, root) + def pending_episodes(self) -> tuple[PendingEpisode, ...]: + """The pending takes of the session open for recording.""" return self._service.pending_episodes() if self._service is not None else () + def open_session_id(self) -> str | None: + """The id of the session open for recording, or None when there is none.""" + session = self._service.snapshot().session if self._service is not None else None + return session.session_id if session is not None else None + + async def refresh_pending(self) -> None: + """Read again which takes earlier sessions of this station left behind, from their manifests. + + Called at backend start, after New batch (which leaves an interrupted take behind), after each + resolution, and from time to time, since whether a take can be recovered depends on the cameras accepted + by now and another recorder's session may have ended. After the first read only the sessions that still + hold a take, and the ones that appeared since, are opened again. The file reading runs in a worker thread. + + A session is listed from the second look at it on, once its beat was found unchanged a watch time + apart: a take a previous run left behind appears a few seconds after the backend starts, not at once. + A read that saw a session for the first time is followed by one more, a watch time later, so that this + does not wait for the next periodic read. + + Best effort, and it never raises: a configuration that cannot be built yet, or an output that cannot be + read, keeps the last list. An operation that reads the list afterwards must not fail because of it. + """ + async with self._scan_lock: + try: + config = self._scan_config_factory() + scanner = _RecordingService(config) + skip = self.open_session_id() + + def read() -> tuple[PendingEpisode, ...]: + """The blocking part: the station's names (a file read) and the output itself.""" + names = self._station_names() if self._station_names is not None else None + return scanner.pending_under_output_root( + skip_session=skip, scan=self._output_scan, stations=names + ) + + found = await asyncio.to_thread(read) + except Exception as exc: # noqa: BLE001 -- e.g. the capture-QC policy could not be read + kind = type(exc).__name__ + if kind != self._scan_failure: + self._scan_failure = kind + logger.warning("takes left by earlier sessions were not read: %s", exc) + return + self._scan_failure = None + self._earlier_pending = found + self._earlier_cameras_known = bool(config.video_sources) + if self._output_scan.first_looks() and (self._second_look is None or self._second_look.done()): + self._second_look = asyncio.create_task(self._look_again(self._output_scan.watch_seconds)) + + async def _look_again(self, delay: float) -> None: + """Read the output once more after ``delay``: the second look at the sessions just seen for the first + time, which is the one that can list their takes.""" + await asyncio.sleep(delay) + await self.refresh_pending() + async def new_batch(self) -> None: """Releases the current storage session, if any, and rotates the batch -- it does NOT eagerly open a replacement. @@ -778,10 +1050,12 @@ async def new_batch(self) -> None: schema before anything has committed to actually recording with it. If no storage session exists yet (New batch used before any recording this process), this only rotates local batch/task - facts -- there is nothing to close. It is also how an interrupted - take (RECOVERY_REQUIRED) or a failed session is cleared: the old - session is closed, the take stays on disk as pending, and the - next ``start_episode`` opens a fresh session.""" + facts -- there is nothing to close. It is also how a failed + session is cleared, and it may be used past an interrupted take + (RECOVERY_REQUIRED): the old session is closed, the take stays on + disk as pending and stays listed for recovery or discard as an + earlier session's, and the next ``start_episode`` opens a fresh + session.""" if self._closing: raise CoordinatorBusyError("recording session is closing") if self._current_ingress is not None: @@ -802,6 +1076,7 @@ async def new_batch(self) -> None: async def _new_batch_impl(self) -> None: service = self._service if service is not None: + session = service.snapshot().session close_result = await service.close() if not close_result.released: # self._service deliberately stays pointing at the @@ -812,6 +1087,12 @@ async def _new_batch_impl(self) -> None: raise CoordinatorBusyError(self._last_issue) self._service = None self._status = SessionStatus.CLOSED + if session is not None: + # The beat that just stopped was this process's own, so the session needs no second look. + self._output_scan.note_closed(session.session_path) + # A take the closed session left pending is now an earlier session's, reachable only by this list. + # The read is best effort: the batch rotates whether or not the output could be read. + await self.refresh_pending() if self.on_batch_rotated is not None: self.on_batch_rotated() @@ -829,6 +1110,8 @@ async def close(self, *, final: bool = False) -> CloseResult: reopens when the close finishes.""" if self._closing and self._close_task is not None: return await asyncio.shield(self._close_task) + if self._second_look is not None: + self._second_look.cancel() self._closing = True self._final_close = final self._close_task = asyncio.create_task(self._close_impl()) @@ -906,7 +1189,15 @@ def readiness(self) -> tuple[bool, str | None]: ``start_episode`` itself runs, exposed read-only so a caller publishing state (e.g. ``RecordingContext``) can report "not ready, because X" without duplicating or guessing at the - underlying source/freshness logic.""" + underlying source/freshness logic. + + An open session whose beat stopped is not ready either, whatever the + sources say: the recorder watches its own beat, and a take started + while it is missing could look left behind to another machine. A + take already being recorded is not interrupted for it; the recorder + notes it on the take.""" + if self._service is not None and self._service.beat_silence() is not None: + return False, SESSION_BEAT_STOPPED return self._readiness_check() # --- capture callbacks (synchronous, called directly from CaptureStatusMonitor) --- diff --git a/examples/egocap/backend/egocap_web/rectification_service.py b/examples/egocap/backend/egocap_web/rectification_service.py index 4b1ee660d7..d46b4a729d 100644 --- a/examples/egocap/backend/egocap_web/rectification_service.py +++ b/examples/egocap/backend/egocap_web/rectification_service.py @@ -722,7 +722,8 @@ def newest_uncorrected_takes(output_root: Path, cameras: Mapping[str, tuple[int, changed = os.stat(episode / f"{name}.mp4").st_mtime except OSError: continue - # A pending take is renamed once it is finalized, so only a kept one has this name and this file. + # A pending take is renamed once it is finalized, so only a finalized one has this name and this + # file: a kept take, or one the capture checks set aside in quarantine, whose video is as received. if os.path.isfile(episode / "zarr.json"): takes.append((changed, str(episode))) newest: dict[str, Path] = {} diff --git a/examples/egocap/backend/egocap_web/settings_routes.py b/examples/egocap/backend/egocap_web/settings_routes.py index a5da81219d..c98a5d77f9 100644 --- a/examples/egocap/backend/egocap_web/settings_routes.py +++ b/examples/egocap/backend/egocap_web/settings_routes.py @@ -21,6 +21,8 @@ from fastapi import APIRouter, Request from fastapi.responses import JSONResponse +from egocap.recording.capture_qc_policy import CaptureQcPolicy, effective_mapping + from . import recordings from .config import CaptureStatusConfig, VisualizationConfig from .preview_protocol import CAMERA_SAMPLE_HZ, TRACKING_SAMPLE_HZ @@ -39,6 +41,36 @@ def _enum_name(value: Any) -> Any: return name.lower() if isinstance(name, str) else value +def camera_rule_notices(policy: CaptureQcPolicy) -> list[str]: + """What an operator should know when this station does not run the camera rate rule as it is built in. + + The rule rejects a take whose camera averaged under 0.86 of its expected rate. A station's file, or the + defaults file of a site, can switch it off, lower the fraction, or replace a camera's expected rate; the + take is then kept and counted as saved with at most a warning. One sentence per way it was changed, and none + when the rule runs as built in. + """ + built_in = CaptureQcPolicy() + if not policy.enabled: + return ["Capture checks are switched off for this station: no take is judged, rejected or marked bad."] + notices = [] + if not policy.camera_min_fps_enabled: + notices.append( + "The camera rate rule is switched off for this station: no take is rejected for a low camera rate." + ) + elif policy.camera_min_fps_ratio < built_in.camera_min_fps_ratio: + notices.append( + f"The camera rate rule is relaxed for this station: a camera may fall to " + f"{policy.camera_min_fps_ratio:g} of its expected rate (built in: {built_in.camera_min_fps_ratio:g})." + ) + if policy.camera_expected_fps: + rates = ", ".join(f"{name} at {fps:g} Hz" for name, fps in policy.camera_expected_fps) + notices.append( + f"This station sets its own expected camera rate ({rates}): the camera rate rule judges against " + "that rate, not the camera's declared one." + ) + return notices + + @dataclass(frozen=True) class EffectiveSettings: """What the backend is running with, resolved once at startup by the application lifespan.""" @@ -54,6 +86,40 @@ class EffectiveSettings: visualization: VisualizationConfig | None visualization_error: str | None task_file_root: Path + #: The capture-QC policy takes are judged by; ``None`` when it could not be read, and ``qc_error`` then holds + #: the public (path-free) reason. + qc_policy: CaptureQcPolicy | None = None + qc_error: str | None = None + + def _quality_checks(self) -> dict[str, Any]: + """The thresholds in force, the defaults file they started from and what the station changed. + + The file is named by base name and digest only: the page shows where the numbers came from, not where + the file is. ``notices`` says in sentences when this station does not run the camera rate rule as built + in, since nothing else on the page shows that a take is no longer rejected for a low camera rate. + """ + policy = self.qc_policy + if policy is None: + return { + "error": self.qc_error, + "defaults_file": None, + "defaults_sha256": None, + "station_overrides": {}, + "effective": None, + "notices": [], + } + overrides = { + key: dict(value) if isinstance(value, tuple) else value + for key, value in policy.source.station_overrides + } + return { + "error": self.qc_error, + "defaults_file": policy.source.defaults_file, + "defaults_sha256": policy.source.defaults_sha256, + "station_overrides": overrides, + "effective": effective_mapping(policy), + "notices": camera_rule_notices(policy), + } def to_json(self) -> dict[str, Any]: """The wire form: plain JSON types, enum names instead of numbers, secrets as booleans.""" @@ -86,6 +152,7 @@ def to_json(self) -> dict[str, Any]: else None, }, "recording": {"output_root": str(self.recording_output_root)}, + "quality_checks": self._quality_checks(), "visualization": { "error": self.visualization_error, "enabled": viz.enabled if viz is not None else False, diff --git a/examples/egocap/backend/egocap_web/station_config.py b/examples/egocap/backend/egocap_web/station_config.py index 6548bf8eed..e2e7bb0054 100644 --- a/examples/egocap/backend/egocap_web/station_config.py +++ b/examples/egocap/backend/egocap_web/station_config.py @@ -6,7 +6,8 @@ ``EGOCAP_STATION_CONFIG`` points at a YAML file describing this station's identity, operator, initial task, recording output root, the writer every camera is recorded with (``recording.video_encoder`` and -``recording.video_encoder_options``) and the cameras to request from CaptureServer. Unset +``recording.video_encoder_options``), its overrides of the capture-QC thresholds (``data_check``) and the cameras +to request from CaptureServer. Unset preserves the existing configuration-free development workflow (the deployment station label, freeform task editing, no cameras requested). Set but unreadable or invalid is a hard recording-configuration failure, never a silent fallback to a development default -- see @@ -19,7 +20,7 @@ visualization, or any other section) is read by nobody here and never passed downstream. The ``cameras`` field is itself a small ``name``/``type`` projection of ``video_sources`` -- the fuller per-source declaration (``frame_type``, ``params``) is reference data for other tooling, not consumed -here; the one exception is the ``alignment`` section. +here; the exceptions are the ``alignment`` and ``data_check`` sections. """ from __future__ import annotations @@ -32,6 +33,7 @@ import yaml from capture_server import protocol as p +from egocap.recording.capture_qc_policy import CaptureQcPolicyError, validate_section from egocap.recording.video_writer_backends import VideoEncoderKind, resolve_video_encoder_options STATION_CONFIG_ENV = "EGOCAP_STATION_CONFIG" @@ -76,6 +78,9 @@ class ResolvedStation: #: ``recording.video_encoder_options`` (crf, preset, pix_fmt), validated for ``video_encoder``; None keeps the #: writer's defaults. video_encoder_options: dict[str, Any] | None = None + #: The station's ``data_check`` section as written: its overrides of the capture-QC defaults, validated key by + #: key at load. None when the station sets none. + data_check: dict[str, Any] | None = None class _DuplicateKeyLoader(yaml.SafeLoader): @@ -208,6 +213,22 @@ def _resolve_video_encoder(station_id: str, recording: dict) -> tuple[str, dict[ return encoder, (dict(options) if options else None) +def _resolve_data_check(station_id: str, entry: dict) -> dict[str, Any] | None: + """The station's ``data_check`` section, refused whole when one key is unknown, mistyped or out of range. + + A bad threshold fails station load rather than the first take: it would otherwise decide what happens to + recorded media. + """ + section = entry.get("data_check") + if section is None: + return None + try: + validate_section(section, station=True) + except CaptureQcPolicyError as error: + raise StationConfigError(f"station {station_id!r}: data_check: {error}") from error + return section + + def _resolve_one_station(station_id: str, entry: Any, config_dir: Path) -> ResolvedStation: """Build a :class:`ResolvedStation` from one station's parsed mapping.""" if not isinstance(entry, dict): @@ -245,6 +266,7 @@ def _resolve_one_station(station_id: str, entry: Any, config_dir: Path) -> Resol alignment_index=_resolve_alignment_index(station_id, entry), video_encoder=video_encoder, video_encoder_options=video_encoder_options, + data_check=_resolve_data_check(station_id, entry), ) diff --git a/examples/egocap/backend/egocap_web/station_service.py b/examples/egocap/backend/egocap_web/station_service.py index ad13986470..cf5a612a83 100644 --- a/examples/egocap/backend/egocap_web/station_service.py +++ b/examples/egocap/backend/egocap_web/station_service.py @@ -46,7 +46,8 @@ async def rotate_batch(self) -> None: :class:`StationError` when the session cannot rotate now.""" def renamed(self, previous: str, name: str) -> None: - """The station in use was renamed: carry its day (time and notes) over to the new name.""" + """A station was renamed, in use or not: carry its day (time and notes) over to the new name and + remember the old one, so that what it recorded under the old name stays its own.""" class StationService: @@ -195,12 +196,9 @@ async def _persist( candidate = apply(self._registry) label = self._label_of(candidate) relabelled = label != self._label - # A rename keeps the same station in use; anything else that changes the label is a different station. - renamed = ( - relabelled - and candidate.selected_id is not None - and candidate.selected_id == self._registry.selected_id - ) + # A station that keeps its place in the registry under another name was renamed, whether or not it is + # the one in use. Anything else that changes the label is a different station. + names_before = {station.station_id: station.name for station in self._registry.stations} # Held across the awaits below, for every change to the station in use: a take admitted between them # would open a session under the old label, or record against camera assignments being replaced. self._applying = touches_station_in_use @@ -213,13 +211,15 @@ async def _persist( self._registry = after self._warning = None if relabelled: - previous, self._label = self._label, self._label_of(after) + self._label = self._label_of(after) # The label is live from here; what follows only keeps the day's records in step with it. self._session.show_label(self._label) finally: self._applying = False - if renamed: - await self._carry_day(previous, self._label) + for station in after.stations: + previous = names_before.get(station.station_id) + if previous is not None and previous != station.name: + await self._carry_day(previous, station.name) return after async def _carry_day(self, previous: str, name: str) -> None: diff --git a/examples/egocap/backend/egocap_web/station_uptime.py b/examples/egocap/backend/egocap_web/station_uptime.py index 90df35c315..8abe2f8754 100644 --- a/examples/egocap/backend/egocap_web/station_uptime.py +++ b/examples/egocap/backend/egocap_web/station_uptime.py @@ -142,6 +142,9 @@ def __init__(self, directory: Path, clock: Callable[[], float] = time.time) -> N #: Why the station is down right now. A segment keeps the reason it began with; this is the current one. self._live_reason: str | None = None self._full_warned = False + #: The renames recorded in the stored day files, with the day they were read on: they are read again + #: when the day changes, and today's own are always read live. + self._renames: tuple[str, list[tuple[str, frozenset[str]]]] | None = None #: Stations whose daily log is behind the timeline: a take ended and the log has not been written since. self._owed_logs: set[str] = set() @@ -295,11 +298,14 @@ def _write(self, payload: dict[str, Any]) -> None: """Replace the day file atomically, once the day has something worth keeping. Time is counted from the first take, so until then the timeline lives in memory only: a backend that - is merely running, or a test that starts one, leaves no file behind. + is merely running, or a test that starts one, leaves no file behind. Notes are worth keeping, and so + is a rename: the names a station has had are followed through these files on any later day. """ self._written_at = self._clock() path = self._path(payload["date"]) - worth_keeping = any(record["notes"] or _took(record) for record in payload["stations"].values()) + worth_keeping = any( + record["notes"] or record["aliases"] or _took(record) for record in payload["stations"].values() + ) # A file already written is kept current, or notes cleared before the first take would return. if not worth_keeping and not path.exists(): return @@ -374,13 +380,18 @@ def _has_room(self, record: dict[str, Any]) -> bool: def rename(self, previous: str, name: str) -> None: """Move today's timeline of a station to its new name, remembering the old one so the day's takes, - recorded under either name, are reported together.""" + recorded under either name, are reported together. + + The old name is recorded also for a station with no timeline today, in use or not: a take left under + it on an earlier day is still this station's to resolve (see :meth:`all_names`). + """ with self._lock: payload, now = self._today() self._carry_files(previous, name, payload["date"]) record = payload["stations"].pop(previous, None) if record is None: - return + # Nothing was observed under the old name today. The rename is the day's one fact about it. + record = {"segments": [], "notes": "", "aliases": []} existing = payload["stations"].get(name) if existing is not None: # The new name was used earlier today: the two histories are one station's day. @@ -470,6 +481,44 @@ def names(self, station: str) -> frozenset[str]: record = self._today()[0]["stations"].get(station) return frozenset({station, *(record["aliases"] if record is not None else ())}) + def all_names(self, station: str) -> frozenset[str]: + """Every name the station has had on any day this log holds, the one it has now included. + + For what outlives a day: a take left to be resolved under an earlier name is still this station's. Each + day's timeline records the names a station was renamed from that day, so the names are followed back + through the days, one rename at a time. Reads every stored day once a day: call it off the event loop. + """ + with self._lock: + today = self._today()[0] + if self._renames is None or self._renames[0] != today["date"]: + self._renames = (today["date"], self._stored_renames()) + links = [*self._renames[1], *self._renames_of(today)] + names, grew = {station}, True + while grew: + before = len(names) + for name, aliases in links: + if name in names: + names |= aliases + grew = len(names) > before + return frozenset(names) + + @staticmethod + def _renames_of(payload: dict[str, Any]) -> list[tuple[str, frozenset[str]]]: + """The renames one day's timeline records: each station's name that day with the names it came from.""" + return [(name, frozenset(record["aliases"])) for name, record in payload["stations"].items()] + + def _stored_renames(self) -> list[tuple[str, frozenset[str]]]: + """The renames of every stored day, read from the day files; an unusable file records none.""" + renames: list[tuple[str, frozenset[str]]] = [] + try: + files = sorted(self._directory.glob("*_timeline.json")) + except OSError: + return renames + for path in files: + day = path.name.removesuffix("_timeline.json") + renames += [link for link in self._renames_of(self._load(day)) if link[1]] + return renames + # --- the daily log and the saved report ------------------------------------------------------------------ def _log_path(self, station: str, day: str) -> Path: diff --git a/examples/egocap/backend/egocap_web/take_outcome.py b/examples/egocap/backend/egocap_web/take_outcome.py new file mode 100644 index 0000000000..2afda86ddc --- /dev/null +++ b/examples/egocap/backend/egocap_web/take_outcome.py @@ -0,0 +1,497 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What became of a take, in the words the operator reads. + +The recording service reports a take's disposition, its reports and the recorder's own notes. This module turns +them into the outcome the page shows and into sentences that say which stream, what was measured against which +limit, and what to check. One wording serves the page after a take, the list of pending takes and the day's +summary, so the three never disagree. + +Every sentence here is fixed text around measured numbers and configured names. A recorder note can hold raw +error text with a directory path in it, so none is ever passed on: each is replaced by the sentence for its +kind, and the note itself stays in the backend log. The one part of a note that is passed on is the reason a +capture source stopped, and only when it is one of the sentences the backend's own readiness check writes. +""" + +from __future__ import annotations + +import logging +import re +from collections.abc import Iterable, Mapping +from typing import Any + +from egocap.recording.capture_qc import QcDecision, advisory_results, deciding_results +from egocap.recording.dataset_check import CheckResult, Outcome, QualityReport, report_from_dict +from egocap.recording.episode_layout import ( + FINALIZATION_KEEP, + FINALIZATION_QUARANTINE, + FINALIZATION_REMOVE, + FINALIZATION_RETAIN, + UNRESOLVED_PHASES, + EpisodeManifest, +) +from recording_service import Disposition, EpisodeResult, PendingEpisode + +from .readiness_text import readiness_sentence +from .recording_adapter import MANUS_GLOVE_SOURCE, PICO_CONTROLLER_SOURCE + +__all__ = [ + "OUTCOMES", + "STORAGE_SENTENCES", + "describe_manifest", + "describe_pending", + "describe_result", + "public_notes", +] + +_logger = logging.getLogger("isaaccapture.egocap.take_outcome") + +#: The outcomes the page shows, in the order of their headlines. +KEPT, FLAGGED, QUARANTINED, REJECTED, REJECTED_DATA_KEPT, DISCARDED, INTERRUPTED = OUTCOMES = ( + "kept", + "flagged", + "quarantined", + "rejected", + "rejected_data_kept", + "discarded", + "interrupted", +) + +#: How the page names each pose stream, in the vocabulary of its tracking view. +_STREAM_LABELS = { + (PICO_CONTROLLER_SOURCE, "head_pose"): "headset", + (PICO_CONTROLLER_SOURCE, "left_pose"): "left controller", + (PICO_CONTROLLER_SOURCE, "right_pose"): "right controller", + (MANUS_GLOVE_SOURCE, "left_hand_pose"): "left glove", + (MANUS_GLOVE_SOURCE, "right_hand_pose"): "right glove", +} +_SOURCE_LABELS = {PICO_CONTROLLER_SOURCE: "headset and controllers", MANUS_GLOVE_SOURCE: "gloves"} +#: What to check when a stream of this source stops changing or stops arriving. +_SOURCE_HINTS = { + PICO_CONTROLLER_SOURCE: "Check that the headset and both controllers are on, charged and in view.", + MANUS_GLOVE_SOURCE: "Check the glove's battery and connection.", +} + + +def _stream(item: str) -> tuple[str, str]: + """The label and the hint for a ``/`` check item; an unknown stream is named as recorded.""" + source, _, field = item.partition("/") + label = _STREAM_LABELS.get((source, field), item) + return label, _SOURCE_HINTS.get(source, "") + + +def _source(item: str) -> tuple[str, str]: + """The label and the hint for a check item that is a whole tracking source.""" + return _SOURCE_LABELS.get(item, item), _SOURCE_HINTS.get(item, "") + + +def _with_hint(sentence: str, hint: str) -> str: + """A finding followed by what to check, when there is something to check.""" + return f"{sentence} {hint}" if hint else sentence + + +def _gap_sentence(item: str, m: Mapping[str, Any]) -> str: + """A tracking source that went without data, or that recorded next to nothing.""" + label, hint = _source(item) + if m["rows"] < 2: + rows = "1 row" if m["rows"] == 1 else "no row" + return _with_hint(f"The {label} recorded {rows} in the whole take.", hint) + found = f"The {label} sent no data for {m['longest_gap_s']:.1f} s (limit {m['limit_s']:g} s)." + return _with_hint(found, hint) + + +def _duration_sentence(m: Mapping[str, Any]) -> str: + """A take shorter or longer than the configured limits.""" + return f"The take lasted {m['duration_s']:.1f} s; the limits are {m['min_s']:g} s to {m['max_s']:g} s." + + +def _camera_rate_sentence(item: str, m: Mapping[str, Any]) -> str: + """A camera below its minimum rate: the measured rate, the minimum and what it is a fraction of. + + Or, for a camera whose rate while it ran was not what failed (it ran for a part of the take, or too briefly + for a rate): how many frames it recorded and how many a take of that length holds. + """ + if "fps" in m and m["fps"] < m["minimum_fps"]: + ratio = m["minimum_fps"] / m["expected_fps"] + return ( + f"Camera {item} averaged {m['fps']:.1f} fps, below the minimum of {m['minimum_fps']:.1f} fps " + f"({ratio:.2f} of {m['expected_fps']:g} fps). Check the camera's cable and the load on this PC, " + "then record the take again." + ) + frames = "1 frame" if m["frames"] == 1 else f"{m['frames']:.0f} frames" + return ( + f"Camera {item} recorded {frames}; a take of {m['take_s']:.1f} s holds about {m['take_frames']:.0f}. " + "Check the camera's cable and the load on this PC, then record the take again." + ) + + +def _freeze_sentence(item: str, m: Mapping[str, Any]) -> str: + """A pose stream that stopped changing for longer than the limit.""" + label, hint = _stream(item) + found = f"The {label} did not move for {m['longest_still_s']:.1f} s (limit {m['limit_s']:g} s)." + return _with_hint(found, hint) + + +def _flat_sentence(item: str, m: Mapping[str, Any]) -> str: + """A pose stream that barely moved: a warning, so it says nothing of what to check.""" + label, _hint = _stream(item) + return f"The {label} barely moved for {m['longest_still_s']:.1f} s (limit {m['limit_s']:g} s)." + + +def _zero_sentence(item: str, m: Mapping[str, Any]) -> str: + """Rows of a pose stream that hold a zeroed pose.""" + label, _hint = _stream(item) + return f"The {label} has a zeroed pose in {m['zero_rows']:.0f} of {m['rows']:.0f} rows." + + +def _drops_sentence(item: str, m: Mapping[str, Any]) -> str: + """Frames a camera dropped, at worst within one window and over the whole take.""" + return ( + f"Camera {item} dropped {m['window_max']:.0f} frames within {m['window_s']:g} s " + f"({m['total']:.0f} in the whole take)." + ) + + +def _unmeasured_sentence(item: str, m: Mapping[str, Any]) -> str: + """A camera whose frames span too little time for a rate: the rate rule said nothing about this take.""" + frames = "1 frame" if m["frames"] == 1 else f"{m['frames']:.0f} frames" + return ( + f"Camera {item} recorded {frames} in {m['span_s']:.2f} s, too short to measure its rate " + f"(that takes {m['needed_s']:.2f} s), so the camera rate rule did not judge this take." + ) + + +def _deviation_sentence(item: str, m: Mapping[str, Any]) -> str: + """A camera whose average rate is far from the one declared for it, in either direction.""" + side = "below" if m["fps"] < m["expected_fps"] else "above" + return ( + f"Camera {item} averaged {m['fps']:.1f} fps, {m['deviation_pct']:.0f}% {side} its declared " + f"{m['expected_fps']:g} fps." + ) + + +def _resolution_sentence(item: str, m: Mapping[str, Any]) -> str: + """A camera file encoded at another size than the one declared.""" + return ( + f"Camera {item} was encoded at {m['width']:.0f}x{m['height']:.0f}, not the declared " + f"{m['expected_width']:.0f}x{m['expected_height']:.0f}." + ) + + +def _dead_sentence(item: str, _m: Mapping[str, Any]) -> str: + """A pose stream that never changed over the whole take.""" + label, _hint = _stream(item) + return f"The {label} did not change for the whole take." + + +#: The sentence for a failed check, by the check's name. Each reads only the measurements its check stores. A +#: check without an entry is described by its own finding, which is written by the checker and holds no path. +_SENTENCES = { + "camera_min_fps": _camera_rate_sentence, + "sustained_freeze": _freeze_sentence, + "tracking_gap": _gap_sentence, + "tracking_gap_warning": _gap_sentence, + "duration": lambda _item, m: _duration_sentence(m), + "duration_warning": lambda _item, m: _duration_sentence(m), + "flat_motion": _flat_sentence, + "dead_stream": _dead_sentence, + "zero_pose": _zero_sentence, + "frame_drops": _drops_sentence, + "camera_rate_measurable": _unmeasured_sentence, + "camera_fps_deviation": _deviation_sentence, + "resolution": _resolution_sentence, +} + + +def _finding(result: CheckResult) -> str: + """One check's result as the operator reads it.""" + kind, _, item = result.name.partition(":") + if result.outcome is Outcome.ERROR: + # What the check raised can be anything, a path included, so only the check and its item are named. + return f"The {kind} check could not run for {item}." if item else f"The {kind} check could not run." + sentence = _SENTENCES.get(kind) + if sentence is not None: + try: + return sentence(item, result.measurements) + except (KeyError, TypeError, ValueError, ZeroDivisionError): + # A report stored by an earlier version may lack a measurement this wording reads. + pass + return "; ".join(result.issues) or f"The {kind} check failed." + + +def _reasons( + integrity: QualityReport | None, capture: QualityReport | None, decision: QcDecision | None +) -> tuple[list[str], list[str]]: + """Why a take ended as it did and what it was warned about, as (reasons, warnings). + + A failed integrity check is the whole reason: capture quality is not judged on data that failed it. + """ + if integrity is not None and integrity.outcome is Outcome.FAILED: + return [f"The recorded data failed an integrity check: {issue}." for issue in integrity.issues], [] + decided = deciding_results(capture, decision) if decision is not None else () + return [_finding(result) for result in decided], [_finding(result) for result in advisory_results(capture)] + + +#: What a row of the pending list is, when it is not an ordinary interrupted take. Each is also the sentence for +#: the recorder's own note of that state. +_DISCARD_UNFINISHED = "A discard of this take was started and did not finish." +_REJECTED_DATA_KEPT = "This take failed its integrity check; its data was kept on disk." +_RECORD_MISPLACED = "This take's record was written for another session: its folder was copied or renamed by hand." + +#: The sentence for each kind of recorder note, by how the note begins. The recorder writes its notes for the +#: log: several end in raw error text, which can name a directory, so only the kind is passed on. +_NOTE_KINDS = ( + ("write failed", "Writing the take to disk failed; see the backend log."), + ("count mismatch", "Not every accepted sample was written, so the take is incomplete."), + ("quality check errored", "The integrity check could not read the take; see the backend log."), + ("capture quality check errored", "A capture check could not run; recover the take to run the checks again."), + ("the take was written and sealed", "The take was written but its record could not be saved."), + ( + "discard refused: the take is already in its final place", + "This take is already saved; only its last record is missing. Use Recover to finish it.", + ), + ( + "discard refused: the directory under the take's name", + "The folder under this take's name is not the take's own, so nothing was removed. It has to be looked " + "at by hand; see the backend log.", + ), + ("discard failed", "Discarding the take failed part-way; discard it again."), + ("start failed", "The take failed to start; see the backend log."), + ("interrupted while writing", "The recorder stopped while this take was being written."), + ("recorded with a different configuration", "This take was recorded under different settings."), + ("group totals were not refreshed", "The folder's totals were not refreshed; the next take recomputes them."), + ( + "session beat stopped", + "The recorder could not write to the recordings folder for a few seconds during this take. If another " + "PC shares that folder, check there that the take was not treated as left behind.", + ), + ("a discard of this take was started", _DISCARD_UNFINISHED), + ("rejected by the integrity check", _REJECTED_DATA_KEPT), + ("written for another session", _RECORD_MISPLACED), +) +_STEP_FAILED = re.compile(r"^[a-z]+ step failed") +#: The one fact about the recordings disk an operator has to act on, by the word the recorder puts into a note +#: (``write failed [storage: full]: ...``) or derives from a failed command. The recorder decides the word from +#: the system's error number; nothing here reads the system's text. +STORAGE_SENTENCES = { + "full": "The recordings disk is full. Free space, then record again.", + "quota": "The disk quota for the recordings is used up. Free space or raise the quota, then record again.", + "read-only": "The recordings folder is read-only. Make it writable, then record again.", + "denied": "The backend may not write to the recordings folder. Fix its permissions, then record again.", +} +#: The recorder's mark, right after the note's own first words and before anything the system said. +_STORAGE_MARK = re.compile(r"^[a-z ]+ \[storage: (?P[a-z-]+)\]") +_CAPTURE_LOST = "capture lost: " +_UNKNOWN_NOTE = "The recorder reported a problem; see the backend log." +#: What the recorder appends to a note when the take's video encoders did not stop cleanly. It is a problem of +#: its own, so it gets a sentence of its own after the one for the note it was appended to. +_ENCODER_NOT_RELEASED = ("; encoder release unconfirmed", "; encoder release failed") +_ENCODER_SENTENCE = "A video encoder did not confirm that it stopped; restart the backend before recording again." + + +def _capture_stopped(note: str) -> str: + """The sentence for a take interrupted because the recording pipeline failed or a capture source stopped. + + The reason is passed on only when it is one of the readiness sentences this backend writes. Any other text + after "capture lost" came from CaptureServer or a device, so it stays in the log. + """ + _before, lost, detail = note.partition(_CAPTURE_LOST) + if not lost: + return "The recording pipeline failed while the take was recording; see the backend log." + reason = readiness_sentence(detail) + if reason is None: + return "A capture source stopped while the take was recording." + return f"A capture source stopped while the take was recording: {reason}." + + +def _public_sentences(note: str) -> list[str]: + """The sentences for one recorder note; the note's own text is never returned.""" + encoder = [_ENCODER_SENTENCE] if any(marker in note for marker in _ENCODER_NOT_RELEASED) else [] + # What the note says about the disk is said after the sentence for the note's kind. + marked = _STORAGE_MARK.match(note) + storage = STORAGE_SENTENCES.get(marked.group("problem")) if marked else None + more = [*([storage] if storage else []), *encoder] + if note.startswith("recording pipeline failed"): + return [_capture_stopped(note), *more] + if note.startswith("encoder release"): + return encoder or [_ENCODER_SENTENCE] + if _STEP_FAILED.match(note): + return ["Finishing the take failed part-way; see the backend log.", *more] + for beginning, sentence in _NOTE_KINDS: + if note.startswith(beginning): + return [sentence, *more] + return [_UNKNOWN_NOTE, *more] + + +def public_notes(notes: Iterable[str]) -> list[str]: + """The recorder's notes on a take as fixed sentences, in order and without repeats.""" + return list(dict.fromkeys(sentence for note in notes for sentence in _public_sentences(note))) + + +def _outcome(disposition: str, decision: str | None, media_removed: bool) -> str: + """The outcome word for a resolved or interrupted take.""" + if disposition == Disposition.KEPT.value: + return FLAGGED if decision == QcDecision.FLAGGED_BAD.value else KEPT + if disposition == Disposition.REJECTED.value: + return REJECTED if media_removed else REJECTED_DATA_KEPT + return { + Disposition.QUARANTINED.value: QUARANTINED, + Disposition.DISCARDED.value: DISCARDED, + Disposition.RECOVERY_REQUIRED.value: INTERRUPTED, + }[disposition] + + +def _location(result: EpisodeResult) -> str | None: + """Where a take's data is, relative to the recording output; None once it is gone. + + Read off the tail of the service's path, so no directory above the recording output is ever sent: a + quarantined take and a routed one sit three levels below it, a take in its session two. + """ + if result.quarantine_path is not None: + return "/".join(result.quarantine_path.parts[-3:]) + if result.final_path is not None: + return "/".join(result.final_path.parts[-3 if result.output_index is not None else -2 :]) + if result.pending_path is not None: + return "/".join(result.pending_path.parts[-2:]) + return None + + +def describe_result(result: EpisodeResult) -> dict[str, Any]: + """The wire form of one take's result: its outcome, why, what it was warned about and where its data is.""" + decision = result.qc_decision + media_removed = result.disposition is Disposition.DISCARDED or ( + result.disposition is Disposition.REJECTED and decision is QcDecision.REJECTED_CAMERA + ) + reasons, warnings = _reasons(result.quality, result.capture_quality, decision) + notes = public_notes(result.issues) + if result.disposition is Disposition.RECOVERY_REQUIRED: + # An interrupted take was not decided by the checks: the recorder's note is the reason. + reasons, warnings = notes or [_UNKNOWN_NOTE], [] + if result.issues: + _logger.info("take %s: recorder notes: %s", result.episode_id, "; ".join(result.issues)) + return { + "episode_id": result.episode_id, + "disposition": result.disposition.value, + "outcome": _outcome(result.disposition.value, decision.value if decision else None, media_removed), + "qc_decision": decision.value if decision is not None else None, + "reasons": reasons, + "warnings": warnings, + "media_removed": media_removed, + "location": _location(result), + "issues": notes, + "duration_ms": int(result.duration_seconds * 1000), + } + + +def describe_manifest(manifest: EpisodeManifest) -> dict[str, Any]: + """The same wording for a take read back from its manifest, for the day's summary. + + Returns the fields of a take's record that the page words: its reasons, its warnings, the recorder's notes + and whether its media was removed. A take that is still pending has no decision yet; its notes say why it + waits. + """ + integrity = report_from_dict(manifest.quality) if manifest.quality else None + capture = report_from_dict(manifest.capture_quality) if manifest.capture_quality else None + decision = QcDecision(manifest.qc_decision) if manifest.qc_decision else None + reasons, warnings = _reasons(integrity, capture, decision) + notes = public_notes(manifest.issues) + if manifest.storage_phase in UNRESOLVED_PHASES: + reasons = notes or reasons + # A rejected take's data is gone when the camera check removed it, or once a discard of it was asked for. + removed = manifest.storage_phase == "DISCARDED" or ( + manifest.storage_phase == "REJECTED" + and (manifest.finalization == FINALIZATION_REMOVE or manifest.discard_requested) + ) + return {"reasons": reasons, "warnings": warnings, "issues": notes, "media_removed": removed} + + +#: What Recover does to a checked take, by the intent recorded with its checks. +_ON_RECOVER = { + FINALIZATION_KEEP: "Recover finishes saving this take.", + FINALIZATION_QUARANTINE: "Recover finishes setting this take aside in quarantine.", + FINALIZATION_REMOVE: "The camera check rejected this take. Recover finishes removing its media.", + FINALIZATION_RETAIN: "The integrity check failed. Recover closes this take and leaves its data on disk.", +} + + +#: What a take needs when it is complete and only the station's setup stands between it and being finished. It +#: never says to discard: the take passed its recording, and under the setup it was recorded with it can be saved. +NEEDS_SAME_SETUP = ( + "This take can be finished once the station is set up as when it was recorded: the same cameras and settings." +) +#: While no camera has been accepted there is nothing to compare the take's setup with, so nothing is said about +#: whether it can be finished. +SETUP_NOT_KNOWN_YET = "Whether this take can be finished is known once the cameras are connected." +#: What can be done with the three kinds of row that are not an ordinary interrupted take. +_NOTHING_FOR_MISPLACED = ( + "Nothing is done with this take from this page. On the recordings disk, delete its folder if it is a copy, " + "or give the folder back the name {written_for} if it was renamed." +) +_DISCARD_ONLY_REJECTED = "This take failed its integrity check and cannot be recovered. Discard removes its data." +_DISCARD_AGAIN = "A discard of this take was started, so its data may be incomplete. Discard it again to finish." + + +def _waits_for_setup(pending: PendingEpisode) -> bool: + """Whether a pending take is complete and held back only by the comparison of settings.""" + waiting = pending.storage_phase in ("SEALED", "CHECKED") and not pending.recoverable + return waiting and not pending.discard_requested and not pending.misplaced + + +def _recover_note(pending: PendingEpisode, cameras_known: bool) -> str: + """What Recover does to a pending take, or why it is not offered.""" + if pending.misplaced: + # The session the record names is the name a renamed folder had, and what a copy is a copy of. + return _NOTHING_FOR_MISPLACED.format(written_for=pending.written_for or "it had before") + if pending.discard_requested: + return _DISCARD_AGAIN + if pending.storage_phase == "REJECTED": + return _DISCARD_ONLY_REJECTED + if pending.storage_phase == "WRITING": + return "This take was cut off while it was being written, so it is incomplete. It can only be discarded." + if not pending.recoverable: + return NEEDS_SAME_SETUP if cameras_known else SETUP_NOT_KNOWN_YET + if pending.storage_phase == "SEALED": + return "Recover runs the checks on this take and finishes it." + return _ON_RECOVER.get(pending.finalization, "Recover finishes this take.") + + +def describe_pending(pending: PendingEpisode, *, current: bool, cameras_known: bool = True) -> dict[str, Any]: + """The wire form of one take that waits for the operator: what it is, why it waits and what can be done. + + ``current`` marks the take of the session open for recording, which blocks Record until it is resolved. + ``cameras_known`` is False while no camera has been accepted: a complete take's settings cannot be compared + with anything then, so ``recoverable_known`` is false and its ``recoverable`` is not a finding: the page + says nothing either way. ``recoverable`` itself stays a boolean, so a page that does not know the new field + still reads the row. ``discardable`` is false only for a record nothing may act on. + """ + notes = public_notes([*pending.recorded_issues, *pending.issues]) + unknown = _waits_for_setup(pending) and not cameras_known + # What the row is outranks what the recorder noted while the take was recorded. + if pending.misplaced: + reason = _RECORD_MISPLACED + elif pending.discard_requested: + reason = _DISCARD_UNFINISHED + elif pending.storage_phase == "REJECTED": + reason = _REJECTED_DATA_KEPT + else: + # One sentence fits here. When the recorder said what the disk refused, that is the one: it is the only + # note the operator can act on. + about_the_disk = next((note for note in notes if note in STORAGE_SENTENCES.values()), None) + reason = about_the_disk or (notes[0] if notes else "The take was interrupted before it was finished.") + return { + "episode_id": pending.episode_id, + "session_id": pending.session_id, + "index": pending.episode_index, + "phase": pending.storage_phase, + "recoverable": pending.recoverable, + "recoverable_known": not unknown, + "discardable": not pending.misplaced, + "current": current, + "reason": reason, + "recover_note": _recover_note(pending, cameras_known), + "task": pending.task, + "operator": pending.operator, + "duration_ms": int(pending.duration_seconds * 1000), + } diff --git a/examples/egocap/capture_server/capture_server/acquisition/depthai.py b/examples/egocap/capture_server/capture_server/acquisition/depthai.py index 46f8e063c2..d74424ce6b 100644 --- a/examples/egocap/capture_server/capture_server/acquisition/depthai.py +++ b/examples/egocap/capture_server/capture_server/acquisition/depthai.py @@ -36,6 +36,14 @@ # so a very low configured fps is not mistaken for a stalled camera). _NO_FRAME_TIMEOUT_S = 5.0 +# How many times per frame interval the encoded-frame queue is asked for a frame. Asked once per interval, a +# poll that comes a moment before a frame finds nothing, and by the next poll the frame after it is due as well: +# the device's size-one queue has then overwritten the first, and one frame is lost for good each time. Asked +# several times, a frame waits only that fraction of an interval and is taken before the next can arrive. Only +# the cadence of asking is divided; everything measured in frames (the timeout above) stays on the frame +# interval. +_POLLS_PER_FRAME = 4 + class DepthAIAdapter: """Wraps one ``Pipeline``-shaped object for the lifetime of one @@ -63,6 +71,7 @@ def __init__( self._pipeline_factory = pipeline_factory self._camera = camera self._interval = 1.0 / camera.fps + self._poll_interval = self._interval / _POLLS_PER_FRAME self._clock = clock or MonotonicClock() self._runner = ThreadRunner() self._pipeline: Any = None @@ -167,18 +176,18 @@ async def enter(self) -> None: # just returns None forever -- see _poll_sync's self._queue is # None check) rather than asserting on a deadline that only a # successful entry would otherwise have set. - self._deadline = self._clock.monotonic() + self._interval + self._deadline = self._clock.monotonic() + self._poll_interval await self._runner.run(self._enter_sync) # self._pipeline is set inside _enter_sync itself self._degraded = False self._last_error = "" def _next_deadline(self, deadline: float) -> float: - """Advance *deadline* to the next tick strictly after "now", + """Advance *deadline* to the next poll tick strictly after "now", skipping any ticks that are overdue rather than bursting to catch up. Same policy as :meth:`IsaacCaptureAdapter._next_deadline`.""" now = self._clock.monotonic() while deadline <= now: - deadline += self._interval + deadline += self._poll_interval return deadline def _poll_sync(self) -> tuple[int, bytes] | None: @@ -205,7 +214,9 @@ def _poll_sync(self) -> tuple[int, bytes] | None: self._intrinsics = self._frame_intrinsics(frame) # KNOWN LIMITATION, real hardware only: this size-one, non-blocking # queue can be overwritten by a newer encoded frame before this - # poll runs. An overwritten frame never reaches this method at + # poll runs, when this loop is held up for most of a frame + # interval (see _POLLS_PER_FRAME for why an ordinary poll is not + # late enough). An overwritten frame never reaches this method at # all, so it is invisible to every counter this adapter reports -- # it is not the same event as an empty poll (no frame ready) and # is not covered by this adapter's own sequence numbering (which @@ -311,7 +322,10 @@ async def next_camera_jpeg(self) -> tuple[int, bytes] | None: """Owns this camera's single acquisition cadence: sleeps until the next monotonic deadline (skipping overdue ticks), then polls the encoded queue -- ``MessageQueue.tryGet()``, the real SDK's own - nonblocking call -- on this adapter's dedicated thread. There is + nonblocking call -- on this adapter's dedicated thread. The + deadlines come ``_POLLS_PER_FRAME`` times per frame interval, so + most calls are empty polls and each frame is taken within a + fraction of an interval of becoming available. There is no adapter-side trigger call; the mock queue paces/fills itself independently, matching how a real encoder would only have a new frame ready at its own cadence regardless of poll frequency. diff --git a/examples/egocap/capture_server/capture_server/mock/mock_depthai.py b/examples/egocap/capture_server/capture_server/mock/mock_depthai.py index 8d843b5282..60c2b0dcde 100644 --- a/examples/egocap/capture_server/capture_server/mock/mock_depthai.py +++ b/examples/egocap/capture_server/capture_server/mock/mock_depthai.py @@ -66,7 +66,14 @@ # belongs to the created mock API/session instance, never a process- # global mutable fault registry. Each Pipeline owns its own # active set, settable at construction and live via set_faults(). -KNOWN_FAULTS = frozenset({"camera_required_failure", "camera_optional_failure"}) +KNOWN_FAULTS = frozenset({"camera_required_failure", "camera_optional_failure", "camera_stall"}) + +# "camera_stall": the camera delivers for _STALL_DELIVER_S, then withholds every frame for _STALL_WITHHOLD_S, and +# repeats. Each stall stays under the two seconds after which the backend calls a camera stale and interrupts the +# take, so the take ends normally and its recorded rate is what shows the stalls: well under half the declared +# rate over any take that spans one. +_STALL_DELIVER_S = 1.0 +_STALL_WITHHOLD_S = 1.5 class CameraBoardSocket(str, Enum): @@ -324,6 +331,8 @@ def __init__( self._resolution = _Resolution(1280, 720) self._queue: MessageQueue | None = None self._frame_num = 0 + # When the "camera_stall" cycle began: the first frame asked for while the fault is active. + self._stall_started: float | None = None def set_faults(self, names: set[str] | frozenset[str] | None) -> None: """Replace this pipeline's active fault set (``None``/empty means @@ -393,6 +402,19 @@ def stop(self) -> None: def wait(self) -> None: return None + def _stalled(self) -> bool: + """Whether the "camera_stall" fault withholds the frame due now; False while the fault is off. + + The cycle starts with a delivering stretch, so a take that begins with the fault still gets frames first. + """ + if "camera_stall" not in self._faults: + self._stall_started = None + return False + now = self._clock.monotonic() + if self._stall_started is None: + self._stall_started = now + return (now - self._stall_started) % (_STALL_DELIVER_S + _STALL_WITHHOLD_S) >= _STALL_DELIVER_S + def _produce_frame_payload(self) -> EncodedFrame | None: """This queue's own private frame source -- called by :class:`MessageQueue` itself, on its own pacing, never by the @@ -404,6 +426,8 @@ def _produce_frame_payload(self) -> EncodedFrame | None: raise RuntimeError( f"mock camera_optional_failure fault: no frame this poll ({self._requested_device_id})" ) + if self._stalled(): + return None self._frame_num += 1 data = _jpeg_bytes( width=self._resolution.width, diff --git a/examples/egocap/frontend/README.md b/examples/egocap/frontend/README.md index 25fcf88609..8155f3f4b6 100644 --- a/examples/egocap/frontend/README.md +++ b/examples/egocap/frontend/README.md @@ -21,6 +21,33 @@ the page sends one small `recording_command` JSON message at a time, and the backend answers each with a correlated `recording_reply` and pushes a `recording_snapshot` to every viewer when the shared recording state changes. +## Recording snapshot and commands + +`recordingSnapshotParser.ts` reads the recording snapshot; `recordingTypes.ts` names its fields. + +| Field | Meaning | +| --- | --- | +| `saved_count`, `flagged_count`, `quarantined_count`, `rejected_count` | The batch's takes by what became of them. `saved_count` is good takes only: one the capture checks marked bad or rejected is counted under its own name. | +| `last_result` | What became of the take that last ended, or of the pending take last recovered or discarded: `outcome` (`kept`, `flagged`, `quarantined`, `rejected`, `rejected_data_kept`, `discarded`, `interrupted`), the checks' `qc_decision`, `reasons` and `warnings` as sentences, `location` relative to the recording output, the recorder's `issues` and `duration_ms`. | +| `ready_to_record`, `not_ready_reason` | Whether Record would be admitted now, and the backend's sentence of why not. The reason can also arrive while a take is being recorded (the recorder could not write to the recordings folder for a while): that take is not interrupted, so the page keeps `REC`, its clock and Stop, and says *Still recording.* before the sentence. | +| `pending_takes` | Every take that waits for the operator: the open session's unresolved one (`current`, it holds Record), the open session's takes the integrity check rejected whose data is still on disk (`phase` `REJECTED`), and what earlier sessions of this station left behind, which can be a record found in a folder it was not written for. Each says why it waits (`reason`), what Recover would do or what the take needs (`recover_note`), and which buttons it gets: Recover when `recoverable`, Discard when `discardable`. `recoverable_known` is false while no camera has been accepted; `recoverable` is then not a finding. | + +Every sentence is composed by the backend (`backend/egocap_web/take_outcome.py`) and shown as it arrives; the page +words only the outcome's name and what follows from it (`takeOutcomeText.ts`). + +- **A report the page does not understand is never shown as kept.** `outcome` must be a word the page knows and + agree with the recorder's `disposition`, with `media_removed` and, for `kept`, with the checks' decision. Anything + else, a missing `outcome` included, is shown as *outcome not recognised* with the backend's own word. The rest of + the snapshot still applies: dropping it would leave the previous take's outcome on screen. +- **A waiting take the page cannot read costs that row its buttons, never the panel.** A `phase` it does not know + or a field it expects and does not find marks the one row unreadable, with the backend's own word for what was + wrong, and neither command is offered for it; the rest of the list and of the snapshot applies. +- A snapshot whose structure is broken is refused whole, and a `recording_reply` carrying one settles its command + as outcome unknown, since "ok" only says the step ran and the snapshot says what became of the take. +- Every reason a command is refused with is a backend sentence shown as sent. The page never matches on its text. +- `recover_pending` and `discard_pending` take `{batch_id, episode_id}` like `stop_episode`: the current batch, and + the take's id from `pending_takes`, also for a take of an earlier session. + ## WS /api/session snapshot fields Each `SNAPSHOT=3`/`version=1` message (`backend/egocap_web/preview_protocol.py`, @@ -68,13 +95,32 @@ or with a direct `/stream{id}` client instead. The page is built for an operator mid-take: the cameras fill it, and everything else is either a glance or one click away. - **Status bar (top).** A large recording indicator (`READY`, `REC` with the live take timer, `STOPPING`, `SAVING`, `SET UP`, - `NOT READY`, `RECOVERY`, `NO FEED`), the task in large type, the saved count, the last take's outcome (kept / rejected / - discarded, duration, issue count on hover), and one chip per tracking device and camera. Chips with a problem are listed - first and say why; a healthy chip is just its name. The bar is read-only and derived from the backend's recording snapshot - and capture status (`OperatorBar.tsx`, `deviceHealth.ts`). + `NOT READY`, `RECOVERY`, `NO FEED`), the task in large type, the count of kept takes with the batch's flagged, quarantined + and rejected takes counted beside it, the last take's outcome and length, and one chip per tracking device and camera. + Chips with a problem are listed first and say why; a healthy chip is just its name. The bar is read-only and derived from + the backend's recording snapshot and capture status (`OperatorBar.tsx`, `deviceHealth.ts`). Under `NOT READY` it gives the + backend's reason as sent. When the backend gives such a reason while a take is being recorded, the indicator stays `REC` + with its clock and reads *Still recording.* followed by the backend's sentence: the backend does not interrupt the take + for it, and the sentence alone reads like a failure. +- **Last take's outcome (above the cameras).** When a take ends, a banner says what became of it and stays until the next + take starts (`TakeOutcomeBanner.tsx`): a headline (*Take 3 kept*, *kept, but flagged*, *quarantined*, *rejected, and its + media removed*, *rejected, its data left on disk*, *discarded*, *interrupted*), then the backend's reasons, what the + outcome means for the take, and its warnings behind a disclosure. Each outcome has its own drawn mark as well as its + colour (`outcomeMarks.tsx`), here, in the status bar and in End of day. The banner is drawn by the recording panel, so + its buttons run through the same command state machine as the dock's, and its height is capped at a third of the + window: a take that failed for several cameras at once scrolls inside it. +- **A take that waits** carries its buttons in that banner, with the backend's note of what Recover would do or what the + take needs (`PendingTakeActions.tsx`). Only the buttons the backend gives the take are drawn: *Recover* when it can be + finished now, *Discard* when it may be removed. A button that is not offered is not drawn, so a take whose recovery is + not known yet shows no Recover that looks refused, and the page says nothing of its own about whether a take can be + recovered. For a complete take that only cannot be finished right now, Discard is drawn small and plain rather than as + the way out. Discard opens a dialog that names the take and what is removed; its focus starts on *Keep the take*, + Escape and a click outside keep the take, and nothing is sent until *Discard* is pressed there. The open session's + unresolved take stays on screen with its buttons even when the last result is about another take. Every other take + that waits is counted in one line with *Review in End of day*. - `READY` is claimed only when the backend would admit a take **and** this browser has an operator name and the control token; - until then it says `SET UP` and what is missing. A command in flight shows at once (`STOPPING` while a take is written), - because the backend's own phase only changes when the command finishes. A stale feed shows `NO FEED`, never a retained + until then it says `SET UP` and what is missing. A command in flight shows at once (`STOPPING` while a take is written, + `RECOVERING` while a pending one is finished), because the backend's own phase only changes when the command finishes. A stale feed shows `NO FEED`, never a retained `REC`. - **Start-of-day rail (under the header).** Station, Devices, Record and Wrap up, each done, needing attention, still to do, or not needed for this station, with a short reason (`StepRail.tsx`). The first step that is neither done nor @@ -84,9 +130,12 @@ The page is built for an operator mid-take: the cameras fill it, and everything recording readiness reason changes, and ten seconds after each read answers (a slow read is waited for, never cut short by the timer); it is absent when that cannot be read. - **Dialogs.** Settings, End of day and the calibration tools open over the page, so the cameras stay live behind - them. At most one is open, and while one is the page behind it is inert and the recording shortcuts and voice - commands are suspended; a calibration tool depends on that, since it records a take of its own while it is open. - A calibration tool takes Settings' place, and closing it returns to Settings on the Devices tab. + them, and so does the question before a pending take is discarded. At most one of Settings, End of day and a + calibration tool is open. While any dialog is open the page behind it is inert and the recording shortcuts and + voice commands are suspended; a calibration tool depends on that, since it records a take of its own while it is + open. A calibration tool takes Settings' place, and closing it returns to Settings on the Devices tab. Each dialog + holds keyboard focus and returns it to the control that opened it; the discard question can open over End of + day, and then only the question holds focus and answers Escape (`useModalFocus` in `settingsParts.tsx`). - **Settings (dialog).** Tabs: Station, Devices, Tasks, Display, Advanced (`SettingsPanel.tsx`). - *Station* is the Stations card (`StationsCard.tsx`): each station with a radio that puts it in use, the camera filling each role, and why it cannot record yet. *Edit* opens the row's inline editor for its name, camera type and @@ -111,6 +160,11 @@ The page is built for an operator mid-take: the cameras fill it, and everything calibration files are an advisory item and takes are allowed; on, they fail and hold recording. A change is followed by an immediate read of the checklist. The calibration tools are listed beneath it, each opening its own dialog (see "Calibration tools" below). + - *Advanced* shows what the deployment runs with, read-only. Its *Capture checks* card names the thresholds takes are + judged by: whether a take marked bad is quarantined or flagged, the camera minimum rate, the frozen-stream limit, + the defaults file's name and SHA-256, and what the station file changed. They are set in files, never from the page. + When a station runs with the checks or the camera rate rule switched off or loosened, the backend's sentences + saying so (`quality_checks.notices`) lead the card. - **Calibration tools (dialogs).** Opened from the Devices tab; each needs the control token, the tools that record a take or install a file need the operator name as well (Rectification does not), and each says what to enter when something is missing. How to use them is in [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md). @@ -179,29 +233,44 @@ The page is built for an operator mid-take: the cameras fill it, and everything then hold the corrected picture and say so. Closing over unsaved choices asks "Discard unsaved changes?" first. - **End of day (dialog).** Opened from the rail's last step (`WrapUpDialog.tsx`); it always shows today for the station - in use and needs the control token. Top to bottom: the day's takes by outcome; the station's active and down time, - the stretches that blocked it, and a notes field; each session with its takes (outcome, duration, task, operator, - issues) and a form that corrects the task of one take or a range; *Save report*, which writes the report on the - station and names the files. A session with any take routed into a group shows where each take is recorded, since - a routed take is numbered by its slot in its group and an unfinished one by its place in the session; with more - than one group the correction also names the group it changed. Notes come from the day report and are saved for - the station they were typed for: if another station is in use by then the save is refused, the dialog says "The - station in use changed; reload the report." and keeps the draft, and after *Reload* it is saved for the station - the report now shows. Each opening starts from a fresh report, so while notes are unsaved or a correction is half - typed, Escape, the backdrop and *Close* ask "Discard unsaved changes?" instead of closing. + in use and needs the control token. Top to bottom: the takes waiting to be recovered or discarded, when there are any; + the day's takes by outcome; the station's active and down time, the stretches that blocked it, and a notes field; + each session with its takes (outcome, duration, task, operator, what was wrong) and a form that corrects the task of + one take or a range; *Save report*, which writes the report on the station and names the files. + - *Takes waiting for a decision* (`PendingTakesCard.tsx`) lists every take of the recording snapshot's + `pending_takes`, not of the report: the open session's and those of earlier sessions, of any day. Which takes wait + is the backend's to say. A row is marked *Pending*; *Rejected, data kept* for a take of the open session that a + failed integrity check left on disk, which the report counts as rejected; *Left alone* for a record neither + command is offered for; or *Unknown* for one the page could not read. After a backend start the rows of earlier + sessions arrive a few seconds after the first snapshot. Each row says why the take waits and what Recover would do, and has the + same buttons as on the recording screen, with the same question before a discard. What became of a take resolved + there is shown under the rows, and the report is read again. + - The outcomes are kept, flagged, quarantined, rejected, discarded and pending, each counted on its own, and the + take being written while there is one. A rejected take says whether its media was removed or its data kept. A + take's row writes out every reason the backend gave, and its warnings open from the row. An outcome the page + does not know is listed under the backend's own word, never added to a known kind. A take record the day does + not count (one that cannot be read, or one of a session folder copied by hand) is a line over its session. + - A session with any take routed into a group shows where each take is recorded, since a routed take is numbered by + its slot in its group and an unfinished one by its place in the session; with more than one group the correction + also names the group it changed. + - Notes come from the day report and are saved for the station they were typed for: if another station is in use by + then the save is refused, the dialog says "The station in use changed; reload the report." and keeps the draft, and + after *Reload* it is saved for the station the report now shows. Each opening starts from a fresh report, so while + notes are unsaved or a correction is half typed, Escape, the backdrop and *Close* ask "Discard unsaved changes?" + instead of closing. - **Status strip (under the bar).** The station in use, its uptime chip, and the capture headline. The chip (`UptimeChip.tsx`) is read-only: the backend logs by itself when the station could record. It reads `Ready`, `Recording`, or `Down` with how long and why, and once the day has a take the active and down time and the number of blockers follow it. It is read every fifteen seconds, and at once when the recording phase, the readiness reason or - the saved count changes, so it does not lag the bar above. It is read without the control token, so it never + the number of takes of the batch changes, so it does not lag the bar above. It is read without the control token, so it never carries the day's notes, and after a change of the station in use it shows nothing until that station's own uptime has arrived. - **Camera stage (middle).** It takes every pixel the bar above and the dock below leave. The head camera (the one named `head*`, otherwise the first) takes the left two-thirds and the others stack on the right; each tile carries its name and measured / advertised Hz and latency on the picture. A live take puts a red frame around the stage. - **Control dock (bottom).** Record / Stop-Save / Discard are large; an unset operator or control-token field leads the dock, - and once set shrinks to a quiet line. The dock hides the recording panel's own header, status line and last-result line, - since the bar above shows them. + and once set shrinks to a quiet line. The dock hides the recording panel's own header and status line, since the bar + above shows them, and the panel draws the last take's outcome above the cameras, not here. - **Side panel (right).** Always showing: the 3D tracking view on top and the raw tracking tables and session details beneath it (Details scrolls inside itself, so neither is pushed off the screen). **Drag the divider** between it and the main column to choose its width -- pulling left widens the panel and narrows the cameras, status bar and controls, and the other way @@ -338,7 +407,9 @@ path or backend endpoint for this. `save recording` (deliberately not "done" -- too common in ordinary conversation with an always-on mic); `discard` / `discard recording` (opens the browser's own native `confirm()` dialog -- discarding is never a second spoken command); `task ` / `set task ` (opens - or updates the task draft); `save task`; `cancel task`; `stop listening`. + or updates the task draft); `save task`; `cancel task`; `stop listening`. These act on the take + being recorded. There is no phrase for a pending take: Recover and Discard for one are buttons, and + that Discard asks in a dialog of the page. - While the task draft is open, only task-related phrases and "stop listening" are accepted; record/stop/discard are ignored with feedback so dictated task text can't accidentally start or stop an episode. diff --git a/examples/egocap/frontend/src/App.liveRecordingWire.test.tsx b/examples/egocap/frontend/src/App.liveRecordingWire.test.tsx index 7097714b44..992aa28e3d 100644 --- a/examples/egocap/frontend/src/App.liveRecordingWire.test.tsx +++ b/examples/egocap/frontend/src/App.liveRecordingWire.test.tsx @@ -99,7 +99,11 @@ const activeSnapshot: RecordingSnapshot = { defaultOperator: null, autoFillOperatorName: false, savedCount: 0, + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, lastResult: null, + pendingTakes: [], readyToRecord: true, notReadyReason: null, revision: 0, diff --git a/examples/egocap/frontend/src/App.operatorLayout.test.tsx b/examples/egocap/frontend/src/App.operatorLayout.test.tsx index 1fb6fb45ac..9484220904 100644 --- a/examples/egocap/frontend/src/App.operatorLayout.test.tsx +++ b/examples/egocap/frontend/src/App.operatorLayout.test.tsx @@ -13,6 +13,7 @@ import { OVERVIEW_FIXTURE, RECTIFICATION_FIXTURE } from "./calibrationTestDouble import type { CalibrationDialogProps } from "./calibrationTypes"; import type { PreviewSnapshot } from "./captureProtocol"; import { DAY_REPORT_FIXTURE, UPTIME_FIXTURE } from "./dayReportTestDoubles"; +import { CAMERA_STOPPED, HEADSET_FROZEN, RECOVER_RUNS_CHECKS, SESSION, earlierTake, pendingTake, takeResult } from "./recordingTestDoubles"; import type { RecordingSnapshot } from "./recordingTypes"; import { OPERATOR_SETTINGS_FIXTURE, STATIONS_FIXTURE, TOOLS_FIXTURE } from "./settingsTestDoubles"; import { SETUP_HELD, SETUP_READY } from "./setupTestDoubles"; @@ -70,7 +71,11 @@ function recording(overrides: Partial = {}): RecordingSnapsho defaultOperator: null, autoFillOperatorName: false, savedCount: 3, + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, lastResult: null, + pendingTakes: [], readyToRecord: true, notReadyReason: null, revision: 1, @@ -176,6 +181,77 @@ function stubRoutes(routes: Record) { /** How many times a route has been read. */ const readsOf = (fetched: ReturnType, route: string) => fetched.mock.calls.filter(([url]) => url === route).length; +describe("the last take's outcome on the page", () => { + /** A snapshot with an interrupted take of the open session that can be recovered. */ + const held = () => { + const take = pendingTake({ phase: "SEALED", recoverable: true, recoverNote: RECOVER_RUNS_CHECKS, durationMs: 2000 }); + return recording({ episodePhase: "RECOVERY_REQUIRED", readyToRecord: false, lastResult: takeResult("interrupted"), pendingTakes: [take] }); + }; + + it("is drawn above the cameras, between the status and the stage, and takes no room while there is none", () => { + const { container } = mount(); + const slot = container.querySelector(".op-main > .op-outcome") as HTMLElement; + expect(slot.childElementCount).toBe(0); + expect(slot.nextElementSibling?.className).toContain("op-stage"); + cleanup(); + const flagged = mount({ recordingSnapshot: recording({ flaggedCount: 1, lastResult: takeResult("flagged") }) }); + const drawn = flagged.container.querySelector(".op-main > .op-outcome") as HTMLElement; + expect(within(drawn).getByRole("heading").textContent).toBe("Take 1 kept, but flagged0:02"); + expect(within(drawn).getByText(HEADSET_FROZEN)).not.toBeNull(); + // Not in the dock as well: the outcome is said in one place. + expect(flagged.container.querySelector(".op-dock .take-outcome")).toBeNull(); + }); + + it("offers Recover and Discard for the interrupted take where the outcome is, and sends Recover on the session's socket", async () => { + const send = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); + const { container } = mount({ sendRecordingCommand: send, recordingSnapshot: held() }); + const drawn = container.querySelector(".op-outcome") as HTMLElement; + expect(within(drawn).getByText(CAMERA_STOPPED)).not.toBeNull(); + fireEvent.click(within(drawn).getByRole("button", { name: "Recover take 1" })); + expect(send).toHaveBeenCalledWith("recover_pending", { batch_id: "b1", episode_id: `${SESSION}/episode_1` }); + // The status bar shows the command at once, before the backend's snapshot changes. + expect(await screen.findByText("RECOVERING")).not.toBeNull(); + }); + + it("makes the page behind the discard question inert, and sends Discard only after the answer", async () => { + const send = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); + const { container } = mount({ sendRecordingCommand: send, recordingSnapshot: held() }); + fireEvent.click(screen.getByRole("button", { name: "Discard take 1" })); + const question = screen.getByRole("alertdialog", { name: "Discard take 1?" }); + await waitFor(() => expect(container.querySelector(".op-body")?.hasAttribute("inert")).toBe(true)); + expect(container.querySelector(".op-body")?.contains(question)).toBe(false); + // The recording shortcuts are suspended: New batch would leave the take behind. + fireEvent.keyDown(window, { key: "r" }); + expect(send).not.toHaveBeenCalled(); + fireEvent.click(within(question).getByRole("button", { name: "Discard take 1" })); + expect(send).toHaveBeenCalledWith("discard_pending", { batch_id: "b1", episode_id: `${SESSION}/episode_1` }); + await waitFor(() => expect(container.querySelector(".op-body")?.hasAttribute("inert")).toBe(false)); + }); + + it("opens End of day from the line about earlier sessions, where their takes are rows with the same two commands", async () => { + stubRoutes({ "/api/day-report": DAY_REPORT_FIXTURE }); + const send = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); + mount({ sendRecordingCommand: send, recordingSnapshot: recording({ pendingTakes: [earlierTake()] }) }); + fireEvent.click(screen.getByRole("button", { name: "Review in End of day" })); + const dialog = screen.getByRole("dialog", { name: "End of day" }); + const card = within(dialog).getByRole("region", { name: "Takes waiting for a decision" }); + expect(within(card).getByText(RECOVER_RUNS_CHECKS)).not.toBeNull(); + fireEvent.click(within(card).getByRole("button", { name: "Recover take 7" })); + // The batch is the current one, also for a take of an earlier session. + expect(send).toHaveBeenCalledWith("recover_pending", { batch_id: "b1", episode_id: "session_20260308-170200_def456/episode_7" }); + await waitFor(() => expect(within(card).getByRole("button", { name: "Recover take 7" }).getAttribute("aria-busy")).toBe("false")); + }); + + it("holds the two commands in End of day while a take is being recorded, and says why", async () => { + stubRoutes({ "/api/day-report": DAY_REPORT_FIXTURE, "/api/setup": SETUP_READY }); + mount({ recordingSnapshot: recording({ episodePhase: "RECORDING", currentEpisodeId: "e2", currentEpisodeElapsedMs: 0, pendingTakes: [earlierTake()] }) }); + fireEvent.click(await screen.findByRole("button", { name: /Step 4, Wrap up/ })); + const card = await screen.findByRole("region", { name: "Takes waiting for a decision" }); + expect((within(card).getByRole("button", { name: "Discard take 7" }) as HTMLButtonElement).disabled).toBe(true); + expect(within(card).getByText("Finish the take being recorded first")).not.toBeNull(); + }); +}); + describe("station uptime in the status strip", () => { it("shows the station's read-only chip beside its name once today's uptime is read", async () => { stubRoutes({ "/api/station-uptime": UPTIME_FIXTURE }); diff --git a/examples/egocap/frontend/src/App.test.tsx b/examples/egocap/frontend/src/App.test.tsx index 56fe1e87e1..1dfc01fa1f 100644 --- a/examples/egocap/frontend/src/App.test.tsx +++ b/examples/egocap/frontend/src/App.test.tsx @@ -478,7 +478,7 @@ describe("Settings modal recording isolation", () => { recordingSnapshot: { batchId: "b1", episodePhase: "RECORDING", currentEpisodeId: "e1", currentEpisodeElapsedMs: 0, taskText: "Fold towel", taskDetails: "", defaultOperator: null, autoFillOperatorName: false, - savedCount: 0, lastResult: null, readyToRecord: true, notReadyReason: null, revision: 0, + savedCount: 0, flaggedCount: 0, quarantinedCount: 0, rejectedCount: 0, lastResult: null, pendingTakes: [], readyToRecord: true, notReadyReason: null, revision: 0, }, })); const { container } = render(); diff --git a/examples/egocap/frontend/src/App.tsx b/examples/egocap/frontend/src/App.tsx index 1cceb265d6..03c35c035e 100644 --- a/examples/egocap/frontend/src/App.tsx +++ b/examples/egocap/frontend/src/App.tsx @@ -45,6 +45,8 @@ import { useSetup } from "./useSetup"; import { WrapUpDialog } from "./WrapUpDialog"; import { useOperatorSettings } from "./useOperatorSettings"; import { buildRecordingActions } from "./recordingActions"; +import { computeEligibility, withOperatorGate } from "./recordingEligibility"; +import type { PendingTake, RecordingActions } from "./recordingTypes"; import type { RecordingPhase } from "./recordingUiReducer"; /** Feed health is derived from ConnectionPhase rather than a separate @@ -501,7 +503,14 @@ export default function App() { // the tool's Open button, as a dialog returns focus to the control that opened it; any other opening has none. const [leftForTool, setLeftForTool] = useState(null); const settingsOpen = dialog === "settings"; - const modalOpen = dialog !== null; + // The recording panel's own question before a pending take is discarded: it is a dialog over the page as well. + const [discardQuestionOpen, setDiscardQuestionOpen] = useState(false); + const modalOpen = dialog !== null || discardQuestionOpen; + // Where the recording panel draws the last take's outcome: above the cameras, not in its own dock. + const [outcomeSlot, setOutcomeSlot] = useState(null); + // Every take of the batch, whatever became of it: a take that was not kept changes the day's figures as well. + const takesOfBatch = + (recordingSnapshot?.savedCount ?? 0) + (recordingSnapshot?.flaggedCount ?? 0) + (recordingSnapshot?.quarantinedCount ?? 0) + (recordingSnapshot?.rejectedCount ?? 0); // The operator settings the page itself uses (camera roles). Re-read each time Settings closes, so a change // saved there reaches the tiles without a reload. const [settingsGeneration, setSettingsGeneration] = useState(0); @@ -510,7 +519,7 @@ export default function App() { // is derived from change: the backend's own readiness reason, the station in use and the saved count. The // control token goes with it, so the reply says which address the headset connects to. const [setupGeneration, refreshSetup] = useReducer((n: number) => n + 1, 0); - const setup = useSetup(`${setupGeneration}|${recordingSnapshot?.notReadyReason ?? ""}|${response?.station_label ?? ""}|${recordingSnapshot?.savedCount ?? 0}`, { controlToken, scope: response?.station_label ?? "" }); + const setup = useSetup(`${setupGeneration}|${recordingSnapshot?.notReadyReason ?? ""}|${response?.station_label ?? ""}|${takesOfBatch}`, { controlToken, scope: response?.station_label ?? "" }); /** Open Settings on the given tab, as a fresh dialog. */ const openSettings = (tab: SettingsTab) => { setSettingsTab(tab); @@ -545,6 +554,14 @@ export default function App() { setDialog(null); refreshSetup(); }, []); + /** Open End of day, where every take that waits is listed. */ + const openWrapUp = useCallback(() => setDialog("wrap_up"), []); + // Recover and Discard as the End of day dialog sends them: the same two commands the recording screen sends, + // under the same rule of when they may be sent. + const resolveBlocked = withOperatorGate(computeEligibility(recordingSnapshot, recordingActions, panelPhase), operatorToken, controlToken).resolvePending.reason; + /** One of the two commands for a pending take, against the batch that is current when it is sent. */ + const pendingCommand = (send: RecordingActions["onRecoverPending"]) => (take: PendingTake) => + send === undefined || recordingSnapshot === null ? Promise.reject(new Error("not connected")) : send({ batchId: recordingSnapshot.batchId, episodeId: take.episodeId }); /** Open the place a step of the start-of-day flow is dealt with. */ const openStep = (step: OpenableStep) => { if (step === "wrap_up") setDialog("wrap_up"); @@ -558,7 +575,24 @@ export default function App() { openSettings("station")} /> {/* Mounted only while open, so every opening starts from a fresh report and an empty notes draft. */} - {dialog === "wrap_up" && } + {dialog === "wrap_up" && ( + + )} {/* A tool is mounted only while open too: each opening reads afresh what is installed and what is in progress. */} {dialog === "headset_calibration" && } {dialog === "glove_offset" && } @@ -605,9 +639,11 @@ export default function App() { + {/* What became of the last take, where the operator is looking when it ends; filled by the recording panel. */} +
{/* The cameras are the page: they take every pixel the status bar above and the controls below leave. */}
@@ -625,6 +661,9 @@ export default function App() { clearControlToken={clearControlToken} onPhaseChange={setPanelPhase} interactionBlocked={modalOpen} + outcomeSlot={outcomeSlot} + onModalChange={setDiscardQuestionOpen} + onReviewEarlier={openWrapUp} />
diff --git a/examples/egocap/frontend/src/CalibrationRecorder.tsx b/examples/egocap/frontend/src/CalibrationRecorder.tsx index f43e889221..ef2d9981d0 100644 --- a/examples/egocap/frontend/src/CalibrationRecorder.tsx +++ b/examples/egocap/frontend/src/CalibrationRecorder.tsx @@ -5,9 +5,10 @@ /** * Records a calibration take from inside a calibration tool and guides the operator while it records. * - * The take is an ordinary one, started and ended by the backend through the recorder; this component only asks - * for it and shows where it stands. While a take records it asks again a few times a second, each time only - * after the last answer came, and draws the guide's verdict, its hints and whatever figures the tool sends. + * The take is the recorder's, started and ended by the backend, which starts it exempt from the capture checks; + * this component only asks for it and shows where it stands. While a take records it asks again a few times a + * second, each time only after the last answer came, and draws the guide's verdict, its hints and whatever + * figures the tool sends. * Opened while a take is already being recorded, it picks that take up instead of offering to start one; it * looks for one when it opens and again when a start is refused, and keeps looking for one the dialog knows of. * diff --git a/examples/egocap/frontend/src/DiscardTakeDialog.tsx b/examples/egocap/frontend/src/DiscardTakeDialog.tsx new file mode 100644 index 0000000000..680fd3828c --- /dev/null +++ b/examples/egocap/frontend/src/DiscardTakeDialog.tsx @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * The one question asked before a pending take is discarded. Discarding removes recorded media for good, so the + * dialog names the take and says what goes, and its safe answer is the one that has focus. It is part of the page: + * it holds focus, gives it back when it closes, and whoever opens it suspends the recording shortcuts and voice + * commands meanwhile. It can be opened over another dialog. + */ + +import { useEffect, useId, useRef } from "react"; +import { formatElapsed } from "./formatElapsed"; +import type { PendingTake } from "./recordingTypes"; +import { useEscapeToClose, useModalFocus } from "./settingsParts"; +import { takeNumber } from "./takeOutcomeText"; + +export interface DiscardTakeDialogProps { + /** The take the question is about. */ + take: PendingTake; + /** The operator chose to discard: send the command. */ + onDiscard: () => void; + /** The operator chose to keep the take: close and change nothing. */ + onKeep: () => void; +} + +/** Ask once whether a pending take's recorded data should be removed. */ +export function DiscardTakeDialog({ take, onDiscard, onKeep }: DiscardTakeDialogProps) { + const dialogRef = useModalFocus(true); + const keepButton = useRef(null); + const titleId = useId(); + const bodyId = useId(); + // Escape is the safe answer, as is a click outside the dialog. + useEscapeToClose(true, onKeep); + // After the dialog has taken focus, so Enter pressed out of habit keeps the take. + useEffect(() => keepButton.current?.focus(), []); + const number = takeNumber(take.episodeId); + return ( + <> +
+ {/* Good takes only: one the checks marked bad or rejected is counted beside it, under its own mark. */}
{recordingSnapshot?.savedCount ?? "—"} - saved + kept
+ {marked.length > 0 && ( +
    + {marked.map(({ shape, text }) => ( +
  • + {text} +
  • + ))} +
+ )} {last !== null && ( -
0 ? last.issues.join("; ") : undefined} - > + // The reasons are written out above the cameras; here they are only a hover away as well. +
0 ? last.reasons.join(" ") : undefined}> Last take - {last.disposition === "KEPT" ? "Kept" : last.disposition === "REJECTED" ? "Rejected" : "Discarded"} - {" · "} - {formatElapsed(last.durationMs)} - {last.issues.length > 0 && ` · ${last.issues.length} issue${last.issues.length === 1 ? "" : "s"}`} + {lastTakeLine(last)}
)} diff --git a/examples/egocap/frontend/src/PendingTakeActions.tsx b/examples/egocap/frontend/src/PendingTakeActions.tsx new file mode 100644 index 0000000000..1aee91904e --- /dev/null +++ b/examples/egocap/frontend/src/PendingTakeActions.tsx @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * What can be done with one take that waits: the backend's own sentence of what Recover would do or what the take + * needs, and the buttons the backend allows for it. Used where the take of the open session is shown on the + * recording screen and in the day's list of takes waiting. + * + * Which buttons a take gets is the backend's decision, sent with the take: Recover only when it can be finished + * now, Discard only when the take may be removed. The page adds no verdict of its own. A button that is not + * offered is not drawn, so a take whose recovery is only not known yet does not show a Recover that looks refused. + */ + +import { useId } from "react"; +import type { PendingTake } from "./recordingTypes"; +import { takeNumber } from "./takeOutcomeText"; + +/** Which of the two commands is running for a take. */ +export type PendingAction = "recover" | "discard"; + +export interface PendingTakeActionsProps { + /** The take the buttons act on. */ + take: PendingTake; + /** Why neither command can be sent now; null when they can. */ + blockedReason: string | null; + /** Which of the two is running for this take; null when neither. */ + busy: PendingAction | null; + /** What the backend answered when it refused the last of the two for this take, or why its outcome is unknown. */ + feedback: string | null; + /** Sends Recover for the take. */ + onRecover: () => void; + /** Asks to discard the take; the caller puts the question before anything is removed. */ + onDiscard: () => void; +} + +/** The note of what Recover would do, the buttons the take is given, and what the backend last answered. */ +export function PendingTakeActions({ take, blockedReason, busy, feedback, onRecover, onDiscard }: PendingTakeActionsProps) { + const noteId = useId(); + const number = takeNumber(take.episodeId); + const blocked = blockedReason !== null; + const offered = take.recoverable || take.discardable; + // A complete take that cannot be finished right now (other cameras connected, or none yet): its note says what + // it needs, so Discard is drawn small and plain there, not as the way out. + const discardIsAside = !take.recoverable && (take.phase === "SEALED" || take.phase === "CHECKED"); + /** Run `action` unless one of the two is already on its way. A running button is held, not disabled: disabling + * the control that has focus would drop focus out of the dialog it may sit in. */ + const unlessBusy = (action: () => void) => () => { + if (busy === null) action(); + }; + return ( +
+ {take.unreadable !== null && ( +

+ This page could not read this take as the backend sent it ({take.unreadable}), so it offers nothing for it. See the backend log. +

+ )} + {take.recoverNote !== "" && ( +

+ {take.recoverNote} +

+ )} + {offered && ( +
+ {take.discardable && ( + + )} + {take.recoverable && ( + + )} +
+ )} + {/* Shown as text: a reason kept in a tooltip needs a mouse to read. */} + {offered && blocked && busy === null &&

{blockedReason}

} + {feedback !== null && ( +

+ {feedback} +

+ )} +
+ ); +} diff --git a/examples/egocap/frontend/src/PendingTakesCard.tsx b/examples/egocap/frontend/src/PendingTakesCard.tsx new file mode 100644 index 0000000000..e4dae7c104 --- /dev/null +++ b/examples/egocap/frontend/src/PendingTakesCard.tsx @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * The takes that wait for the operator, as rows at the top of the day's summary: the open session's and everything + * earlier sessions of this station left behind, of any day. Which takes wait is the backend's to say (an + * interrupted one, one whose data a failed integrity check left on disk, a record found in a folder it was not + * written for), so nothing here assumes why. Each row says why the take waits and what Recover would do, in the + * backend's sentences, and carries the buttons the backend allows for it. What became of a take resolved here is + * shown under the rows, from the same result the recording screen shows. + */ + +import { useEffect, useState } from "react"; +import { createPortal } from "react-dom"; +import { DiscardTakeDialog } from "./DiscardTakeDialog"; +import { formatElapsed } from "./formatElapsed"; +import { OutcomeIcon, OutcomeMark } from "./outcomeMarks"; +import { PendingTakeActions, type PendingAction } from "./PendingTakeActions"; +import type { EpisodeResultSummary, PendingTake, RecordingCommandResult } from "./recordingTypes"; +import { Card, errorMessage } from "./settingsParts"; +import { TakeResultBody } from "./TakeOutcomeBanner"; +import { OUTCOME_VIEW, takeNumber, type OutcomeShape } from "./takeOutcomeText"; + +/** The pending takes and the two commands, as the page hands them to the day's summary. */ +export interface PendingTakeControls { + /** Every take waiting, from the recording snapshot. */ + takes: readonly PendingTake[]; + /** What became of the take that last ended or was last resolved, from the same snapshot. */ + lastResult: EpisodeResultSummary | null; + /** Why neither command can be sent now; null when they can. */ + blockedReason: string | null; + /** Sends Recover for a take and resolves with the backend's reply. */ + recover: (take: PendingTake) => Promise; + /** Sends Discard for a take and resolves with the backend's reply. The card asks the operator first. */ + discard: (take: PendingTake) => Promise; +} + +export interface PendingTakesCardProps { + /** The takes and commands; null while the recording backend has not reported, and nothing is drawn then. */ + pending: PendingTakeControls | null; + /** Told after a take was recovered or discarded, so the day's counts are read again. */ + onResolved: () => void; + /** Told when the question before a discard opens and closes, so the dialog under it leaves Escape to it. */ + onQuestionChange: (open: boolean) => void; +} + +/** The mark and word a row carries, from what the backend sent about it. A row the page could not read is marked + * unknown; one nothing may be done with from the page says so rather than "pending". */ +function markOf(take: PendingTake): { shape: OutcomeShape; word: string } { + if (take.unreadable !== null) return { shape: "unknown", word: "Unknown" }; + if (take.phase === "REJECTED") return { shape: "rejected", word: "Rejected, data kept" }; + if (!take.recoverable && !take.discardable) return { shape: "discarded", word: "Left alone" }; + return { shape: "pending", word: "Pending" }; +} + +/** The facts that tell one pending take from another: its length, task and operator. */ +function factsOf(take: PendingTake): string { + // A take cut off while it was being written has no known length. + return [take.durationMs > 0 && formatElapsed(take.durationMs), take.task, take.operator].filter(Boolean).join(" · "); +} + +/** List the pending takes with Recover and Discard, and what became of the one resolved last. */ +export function PendingTakesCard({ pending, onResolved, onQuestionChange }: PendingTakesCardProps) { + // One command at a time, as the connection allows: the take it is for, and which of the two. + const [busy, setBusy] = useState<{ episodeId: string; action: PendingAction } | null>(null); + const [feedback, setFeedback] = useState<{ episodeId: string; text: string } | null>(null); + const [question, setQuestion] = useState(null); + // The take resolved from this card, so its result is shown here and not one of a take that ended before. + const [resolved, setResolved] = useState(null); + useEffect(() => { + onQuestionChange(question !== null); + }, [question, onQuestionChange]); + // Closing the card with the question open must not leave the dialog under it deaf to Escape. + useEffect(() => () => onQuestionChange(false), [onQuestionChange]); + if (pending === null) return null; + const result = pending.lastResult !== null && pending.lastResult.episodeId === resolved ? pending.lastResult : null; + if (pending.takes.length === 0 && result === null) return null; + + /** Send one of the two commands for a take and show the backend's answer beside it. */ + const run = (take: PendingTake, action: PendingAction) => { + setBusy({ episodeId: take.episodeId, action }); + setFeedback(null); + (action === "recover" ? pending.recover : pending.discard)(take).then( + (reply) => { + setBusy(null); + if (reply.outcome === "rejected") { + setFeedback({ episodeId: take.episodeId, text: reply.reason ?? "The backend refused and gave no reason." }); + return; + } + // "ok" says the step ran; what became of the take arrives with the snapshot and is shown below. + setResolved(take.episodeId); + onResolved(); + }, + (error: unknown) => { + setBusy(null); + setFeedback({ episodeId: take.episodeId, text: errorMessage(error) }); + }, + ); + }; + + return ( + + {pending.takes.length > 0 && ( +
    + {pending.takes.map((take, position) => ( + // A row the page could not read may have no id of its own. +
  • +
    + {markOf(take).word} + {take.episodeId === "" ? "A take the backend listed" : `Take ${takeNumber(take.episodeId)} · ${take.sessionId}`} + {factsOf(take)} + {take.current && Holds Record} +
    + {take.reason !== "" &&

    {take.reason}

    } + run(take, "recover")} + onDiscard={() => setQuestion(take)} + /> +
  • + ))} +
+ )} + {result !== null && ( +
+ + +
+ )} + {/* Outside the dialog under it, whose box would otherwise clip and position the question. */} + {question !== null && + createPortal( + { + setQuestion(null); + run(question, "discard"); + }} + onKeep={() => setQuestion(null)} + />, + document.body, + )} +
+ ); +} diff --git a/examples/egocap/frontend/src/RecordingPanel.pendingTakes.test.tsx b/examples/egocap/frontend/src/RecordingPanel.pendingTakes.test.tsx new file mode 100644 index 0000000000..b2c207b8cd --- /dev/null +++ b/examples/egocap/frontend/src/RecordingPanel.pendingTakes.test.tsx @@ -0,0 +1,272 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * Recover and Discard for a pending take, as the recording panel runs them: through the same state machine as + * every other command, with the question before a discard as a dialog of the page that holds focus and suspends + * the recording shortcuts. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { RecordingPanel, type RecordingPanelProps } from "./RecordingPanel"; +import { RECOVER_RUNS_CHECKS, SESSION, earlierTake, heldSnapshot, pendingTake, recordingSnapshot, takeResult } from "./recordingTestDoubles"; +import type { RecordingActions, RecordingCommandResult } from "./recordingTypes"; +import { RecordingCommandUncertainError } from "./useCaptureSession"; + +afterEach(cleanup); + +const OK: RecordingCommandResult = { outcome: "ok", reason: null }; +const TARGET = { batchId: "b1", episodeId: `${SESSION}/episode_1` }; +/** A take of the open session that can be recovered. */ +const SEALED = pendingTake({ phase: "SEALED", recoverable: true, recoverNote: RECOVER_RUNS_CHECKS, durationMs: 2000 }); + +/** Every action answering "ok" at once. */ +function actions(overrides: Partial = {}): Required { + const ok = () => vi.fn(async () => OK); + return { onSetTask: ok(), onStartEpisode: ok(), onStopEpisode: ok(), onDiscardEpisode: ok(), onNewBatch: ok(), onRecoverPending: ok(), onDiscardPending: ok(), ...overrides } as Required; +} + +/** A command the test settles by hand, to look at the panel while it is on its way. */ +function deferred() { + let settle: (reply: RecordingCommandResult) => void = () => undefined; + let fail: (error: Error) => void = () => undefined; + const send = vi.fn( + () => + new Promise((resolve, reject) => { + settle = resolve; + fail = reject; + }), + ); + return { send, settle: (reply: RecordingCommandResult) => act(async () => settle(reply)), fail: (error: Error) => act(async () => fail(error)) }; +} + +function panel(overrides: Partial = {}) { + const props: RecordingPanelProps = { + recordingSnapshot: heldSnapshot(SEALED), + actions: actions(), + operatorToken: "alex", + setOperatorToken: vi.fn(), + clearOperatorToken: vi.fn(), + controlToken: "", + setControlToken: vi.fn(), + clearControlToken: vi.fn(), + ...overrides, + }; + const view = render(); + return { props, update: (next: Partial) => view.rerender() }; +} + +const button = (name: string | RegExp) => screen.getByRole("button", { name }) as HTMLButtonElement; + +describe("recovering a pending take", () => { + it("sends Recover for that take of the current batch, shows it running, and blocks every other control meanwhile", async () => { + const recover = deferred(); + const onPhaseChange = vi.fn(); + panel({ actions: actions({ onRecoverPending: recover.send }), onPhaseChange }); + fireEvent.click(button("Recover take 1")); + expect(recover.send).toHaveBeenCalledWith(TARGET); + expect(onPhaseChange).toHaveBeenLastCalledWith("recovering"); + expect(button("Recovering…").getAttribute("aria-busy")).toBe("true"); + expect(button(/new batch \(r\)/i).disabled).toBe(true); + expect(button(/edit task \(t\)/i).title).toBe("Another action is still in progress"); + // A second press while it runs sends nothing. + fireEvent.click(button("Recovering…")); + expect(recover.send).toHaveBeenCalledTimes(1); + await recover.settle(OK); + expect(onPhaseChange).toHaveBeenLastCalledWith("idle"); + }); + + it("shows what became of the take from the snapshot that follows, not from the reply's ok", async () => { + const { update } = panel(); + await act(async () => fireEvent.click(button("Recover take 1"))); + // "ok" only says the step ran: here the checks rejected the take. + update({ recordingSnapshot: recordingSnapshot({ rejectedCount: 1, lastResult: takeResult("rejected") }) }); + expect(within(screen.getByRole("region", { name: "Last take" })).getByRole("heading").textContent).toBe("Take 1 rejected, and its media removed0:02"); + expect(screen.queryByRole("button", { name: /Recover take/ })).toBeNull(); + }); + + it("shows the backend's refusal beside the take, where the button was pressed", async () => { + const refused = "This take can be finished once the station is set up as when it was recorded: the same cameras and settings."; + panel({ actions: actions({ onRecoverPending: vi.fn(async (): Promise => ({ outcome: "rejected", reason: refused })) }) }); + await act(async () => fireEvent.click(button("Recover take 1"))); + expect(within(screen.getByRole("group", { name: "Take 1: what can be done" })).getByRole("alert").textContent).toBe(refused); + // Said once: the panel's own feedback line stays empty. + expect(document.querySelector(".recording-feedback")).toBeNull(); + expect(button("Recover take 1").getAttribute("aria-busy")).toBe("false"); + }); + + it("falls back to the panel's feedback line when the take the answer was for is no longer shown", async () => { + const { update } = panel({ actions: actions({ onRecoverPending: vi.fn(async (): Promise => ({ outcome: "rejected", reason: "That take is no longer pending." })) }) }); + await act(async () => fireEvent.click(button("Recover take 1"))); + update({ recordingSnapshot: recordingSnapshot({ lastResult: takeResult("discarded") }) }); + expect(document.querySelector(".recording-feedback")?.textContent).toBe("That take is no longer pending."); + }); + + it("treats a lost reply as an unknown outcome: everything stays blocked until a snapshot says what happened", async () => { + const recover = deferred(); + const onPhaseChange = vi.fn(); + const { update } = panel({ actions: actions({ onRecoverPending: recover.send }), onPhaseChange }); + fireEvent.click(button("Recover take 1")); + await recover.fail(new RecordingCommandUncertainError("connection lost before a reply arrived")); + expect(onPhaseChange).toHaveBeenLastCalledWith("uncertain"); + expect(within(screen.getByRole("group", { name: "Take 1: what can be done" })).getByRole("alert").textContent).toBe("connection lost before a reply arrived"); + expect(button("Recover take 1").disabled).toBe(true); + expect(button("Discard take 1").disabled).toBe(true); + // The next snapshot shows the take was in fact kept. + update({ recordingSnapshot: recordingSnapshot({ savedCount: 1, lastResult: takeResult("kept"), revision: 2 }) }); + expect(onPhaseChange).toHaveBeenLastCalledWith("idle"); + expect(within(screen.getByRole("region", { name: "Last take" })).getByRole("heading").textContent).toBe("Take 1 kept0:02"); + }); + + it("draws no Recover for a take that cannot be recovered, and no Discard for one that may not be discarded", () => { + const { update } = panel({ recordingSnapshot: heldSnapshot() }); + expect(screen.queryByRole("button", { name: "Recover take 1" })).toBeNull(); + expect(button("Discard take 1").disabled).toBe(false); + update({ recordingSnapshot: heldSnapshot(pendingTake({ discardable: false })) }); + expect(screen.queryByRole("button", { name: /take 1/ })).toBeNull(); + }); + + it.each([ + ["an operator name", { operatorToken: null }, "Enter an operator name before using recording controls"], + ["the control token", { controlToken: null }, "Enter the recording control token before using recording controls"], + ])("sends neither command without %s, and says why in words", (_what, missing, reason) => { + const given = actions(); + panel({ actions: given, ...missing }); + const group = screen.getByRole("group", { name: "Take 1: what can be done" }); + expect(within(group).getByText(reason)).toBeTruthy(); + expect(button("Recover take 1").disabled).toBe(true); + expect(button("Discard take 1").disabled).toBe(true); + }); + + it("holds both buttons while the page has no handler for them", () => { + panel({ actions: { onNewBatch: vi.fn(async () => OK) } }); + expect(button("Discard take 1").disabled).toBe(true); + expect(screen.getByText("Recover and Discard are not available yet")).toBeTruthy(); + }); +}); + +describe("discarding a pending take", () => { + it("asks first, naming the take and what is removed, and sends nothing until answered", () => { + const given = actions(); + const onModalChange = vi.fn(); + panel({ actions: given, onModalChange }); + fireEvent.click(button("Discard take 1")); + const question = screen.getByRole("alertdialog", { name: "Discard take 1?" }); + expect(within(question).getByText("This removes the take's recorded video and tracking data from this station. It cannot be undone.")).toBeTruthy(); + expect(Array.from(question.querySelectorAll("dd")).map((fact) => fact.textContent)).toEqual([SESSION, "Pour water.", "alex", "0:02"]); + expect(within(question).getByText(RECOVER_RUNS_CHECKS)).toBeTruthy(); + expect(given.onDiscardPending).not.toHaveBeenCalled(); + expect(onModalChange).toHaveBeenLastCalledWith(true); + // The question is outside the panel, so it stays usable while the page behind it is inert. + expect(document.querySelector(".recording-panel")?.contains(question)).toBe(false); + }); + + it("moves focus to the safe answer, holds it inside the question, and returns it to the button when the take is kept", () => { + const given = actions(); + const onModalChange = vi.fn(); + panel({ actions: given, onModalChange }); + const discard = button("Discard take 1"); + discard.focus(); + fireEvent.click(discard); + const question = screen.getByRole("alertdialog"); + const keep = within(question).getByRole("button", { name: "Keep the take" }); + const confirm = within(question).getByRole("button", { name: "Discard take 1" }); + expect(document.activeElement).toBe(keep); + fireEvent.keyDown(keep, { key: "Tab" }); + expect(document.activeElement).toBe(confirm); + fireEvent.keyDown(confirm, { key: "Tab" }); + expect(document.activeElement).toBe(keep); + // Focus sent to the page behind comes back. + button(/new batch \(r\)/i).focus(); + expect(question.contains(document.activeElement)).toBe(true); + fireEvent.click(keep); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(given.onDiscardPending).not.toHaveBeenCalled(); + expect(onModalChange).toHaveBeenLastCalledWith(false); + expect(document.activeElement).toBe(discard); + }); + + it("keeps the take on Escape and on a click outside the question", () => { + const given = actions(); + panel({ actions: given }); + fireEvent.click(button("Discard take 1")); + fireEvent.keyDown(document.activeElement as Element, { key: "Escape" }); + expect(screen.queryByRole("alertdialog")).toBeNull(); + fireEvent.click(button("Discard take 1")); + fireEvent.click(document.querySelector(".discard-take-backdrop") as Element); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(given.onDiscardPending).not.toHaveBeenCalled(); + }); + + it("suspends the recording shortcuts while the question is open, wherever focus is", () => { + const given = actions(); + panel({ actions: given }); + fireEvent.click(button("Discard take 1")); + // New batch would leave the take behind in an earlier session; the task editor would take the keyboard. + for (const key of ["r", "t", "s", "w", "a"]) fireEvent.keyDown(window, { key }); + expect(given.onNewBatch).not.toHaveBeenCalled(); + expect(screen.queryByLabelText("Task name")).toBeNull(); + fireEvent.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Keep the take" })); + // With the question answered the shortcuts work again. + fireEvent.keyDown(window, { key: "t" }); + expect(screen.getByLabelText("Task name")).toBeTruthy(); + }); + + it("sends Discard for that take once the operator confirms, and shows it running", async () => { + const discard = deferred(); + const onPhaseChange = vi.fn(); + panel({ actions: actions({ onDiscardPending: discard.send }), onPhaseChange }); + fireEvent.click(button("Discard take 1")); + fireEvent.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Discard take 1" })); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(discard.send).toHaveBeenCalledWith(TARGET); + expect(onPhaseChange).toHaveBeenLastCalledWith("discardingPending"); + expect(button("Discarding…").getAttribute("aria-busy")).toBe("true"); + await discard.settle(OK); + expect(onPhaseChange).toHaveBeenLastCalledWith("idle"); + }); + + it("closes the question when another viewer resolves the take meanwhile", () => { + const given = actions(); + const { update } = panel({ actions: given }); + fireEvent.click(button("Discard take 1")); + update({ recordingSnapshot: recordingSnapshot({ savedCount: 1, lastResult: takeResult("kept"), revision: 2 }) }); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(given.onDiscardPending).not.toHaveBeenCalled(); + }); + + it("never uses the browser's own confirm for a pending take", () => { + const confirm = vi.spyOn(window, "confirm").mockReturnValue(true); + panel(); + fireEvent.click(button("Discard take 1")); + fireEvent.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Discard take 1" })); + expect(confirm).not.toHaveBeenCalled(); + confirm.mockRestore(); + }); +}); + +describe("where the last take's outcome is drawn", () => { + it("is the panel itself when the page gives no place for it", () => { + panel({ recordingSnapshot: recordingSnapshot({ lastResult: takeResult("flagged") }) }); + expect(document.querySelector(".recording-panel .take-outcome")).not.toBeNull(); + }); + + it("is the place the page gives, and nowhere while that place is not there yet", () => { + const slot = document.createElement("div"); + document.body.append(slot); + const { update } = panel({ recordingSnapshot: recordingSnapshot({ lastResult: takeResult("flagged") }), outcomeSlot: null }); + expect(document.querySelector(".take-outcome")).toBeNull(); + update({ outcomeSlot: slot }); + expect(slot.querySelector(".take-outcome")).not.toBeNull(); + expect(document.querySelector(".recording-panel .take-outcome")).toBeNull(); + slot.remove(); + }); + + it("counts the takes of earlier sessions and opens their list when asked", () => { + const onReviewEarlier = vi.fn(); + panel({ recordingSnapshot: recordingSnapshot({ pendingTakes: [earlierTake()] }), onReviewEarlier }); + fireEvent.click(button("Review in End of day")); + expect(onReviewEarlier).toHaveBeenCalledTimes(1); + }); +}); diff --git a/examples/egocap/frontend/src/RecordingPanel.taskCatalog.test.tsx b/examples/egocap/frontend/src/RecordingPanel.taskCatalog.test.tsx index c1374e4ffe..97b905170c 100644 --- a/examples/egocap/frontend/src/RecordingPanel.taskCatalog.test.tsx +++ b/examples/egocap/frontend/src/RecordingPanel.taskCatalog.test.tsx @@ -34,7 +34,11 @@ function snapshot(overrides: Partial = {}): RecordingSnapshot defaultOperator: null, autoFillOperatorName: false, savedCount: 0, + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, lastResult: null, + pendingTakes: [], readyToRecord: true, notReadyReason: null, revision: 0, diff --git a/examples/egocap/frontend/src/RecordingPanel.test.tsx b/examples/egocap/frontend/src/RecordingPanel.test.tsx index 6dc880ad50..570fb9e6ff 100644 --- a/examples/egocap/frontend/src/RecordingPanel.test.tsx +++ b/examples/egocap/frontend/src/RecordingPanel.test.tsx @@ -16,6 +16,7 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react" import { RecordingPanel } from "./RecordingPanel"; import { RecordingCommandUncertainError } from "./useCaptureSession"; import type { RecordingSnapshot } from "./recordingTypes"; +import { RECORDER_CANNOT_WRITE, takeResult } from "./recordingTestDoubles"; afterEach(() => { cleanup(); @@ -44,7 +45,11 @@ function activeSnapshot(overrides: Partial = {}): RecordingSn defaultOperator: null, autoFillOperatorName: false, savedCount: 0, + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, lastResult: null, + pendingTakes: [], readyToRecord: true, notReadyReason: null, revision: 0, @@ -70,6 +75,34 @@ describe("RecordingPanel", () => { } }); + it("keeps Stop/Save and Discard for the take being recorded while the backend is not ready for another take", async () => { + const onStopEpisode = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); + const onDiscardEpisode = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); + // The backend can say it is not ready while a take goes on (it could not write to the recordings folder for + // a moment); it does not interrupt the take, so the take must still be stoppable from the page. + const recording = activeSnapshot({ episodePhase: "RECORDING", currentEpisodeId: "ep-1", currentEpisodeElapsedMs: 3000, readyToRecord: false, notReadyReason: RECORDER_CANNOT_WRITE }); + render(); + const stop = screen.getByRole("button", { name: /stop\/save \(w\)/i }) as HTMLButtonElement; + expect(stop.disabled).toBe(false); + expect((screen.getByRole("button", { name: /discard \(a\)/i }) as HTMLButtonElement).disabled).toBe(false); + // Nothing on the panel says the take failed or waits to be recovered. + expect(statusText()).toContain("Recording"); + expect(statusText()).not.toContain("Recovery required"); + expect(screen.queryByRole("region", { name: "Last take" })).toBeNull(); + await act(async () => { + fireEvent.keyDown(window, { key: "w" }); + }); + expect(onStopEpisode).toHaveBeenCalledWith({ batchId: "b1", episodeId: "ep-1" }); + }); + + it("gives the backend's reason on Record once that take is over and the backend is still not ready", () => { + const idle = activeSnapshot({ readyToRecord: false, notReadyReason: RECORDER_CANNOT_WRITE }); + render(); + const record = screen.getByRole("button", { name: /record \(s\)/i }) as HTMLButtonElement; + expect(record.disabled).toBe(true); + expect(record.title).toBe(RECORDER_CANNOT_WRITE); + }); + it("with every action wired but no backend snapshot, Edit task is disabled too and the status line invents no values", () => { const noop = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); render( @@ -153,7 +186,7 @@ describe("RecordingPanel", () => { expect(record.title).toBe("Station 'Bench A': no camera is assigned to the ego (head) role"); }); - it("after an interrupted take, Record points to New batch as the way to clear it", () => { + it("after an interrupted take, Record points to recovering or discarding it, not to New batch", () => { const noop = vi.fn().mockResolvedValue({ outcome: "ok", reason: null }); render( { />, ); expect((screen.getByRole("button", { name: /record \(s\)/i }) as HTMLButtonElement).title).toBe( - "A take was interrupted -- use New batch to clear it", + "A take was interrupted -- recover or discard it first", ); expect((screen.getByRole("button", { name: /new batch \(r\)/i }) as HTMLButtonElement).disabled).toBe(false); expect(document.querySelector(".recording-status")?.textContent ?? "").toContain("Recovery required"); @@ -334,7 +367,7 @@ describe("RecordingPanel", () => { void; /** The control token attached to every outgoing recording command, or * null before one has been entered this tab -- the real credential (see - * app.py's lifespan); without it the backend rejects all five mutating - * actions outright. Kept in sessionStorage for this tab's session only + * app.py's lifespan); without it the backend rejects every mutating + * action outright. Kept in sessionStorage for this tab's session only * (see useCaptureSession.ts), never localStorage. */ controlToken: string | null; setControlToken: (token: string) => void; @@ -73,10 +86,15 @@ export interface RecordingPanelProps { loadTaskCatalog?: LoadTaskCatalog; /** Settings owns keyboard and voice commands while its modal is open. */ interactionBlocked?: boolean; + /** Where the last take's outcome and the pending take's buttons are drawn: an element of the page above the + * cameras. Null while that element is not mounted yet (nothing is drawn); left out, they are drawn in the panel. */ + outcomeSlot?: HTMLElement | null; + /** Told when the question before a discard opens and closes, so the page can make everything behind it inert. */ + onModalChange?: (open: boolean) => void; + /** Opens the day's summary, where every take that waits is listed. */ + onReviewEarlier?: () => void; } -const NO_CONTROL_TOKEN_REASON = "Enter the recording control token before using recording controls"; - const PHASE_LABEL: Record = { idle: "Idle", starting: "Starting…", @@ -86,6 +104,8 @@ const PHASE_LABEL: Record = { editingTask: "Editing task", savingTask: "Saving task…", restarting: "Restarting…", + recovering: "Recovering…", + discardingPending: "Discarding…", uncertain: "Outcome unknown…", }; @@ -109,22 +129,14 @@ const PHASE_BADGE_VARIANT: Record { onPhaseChange?.(ui.phase); }, [ui.phase, onPhaseChange]); + // The pending take the operator asked to discard and has not answered the question about yet. + const [discardQuestion, setDiscardQuestionState] = useState(null); + /** Open the question about `take`, or close it with null. The page is told in the same update, not from an + * effect afterwards: when the question closes, the page behind must already take input again, or focus could + * not go back to the button that asked. */ + const setDiscardQuestion = useCallback( + (take: PendingTake | null) => { + setDiscardQuestionState(take); + onModalChange?.(take !== null); + }, + [onModalChange], + ); + // A panel that goes away with its question open must not leave the page inert. Only on unmount: the latest + // callback is read through a ref, so a new callback from the page is never told "closed" for an open question. + const onModalChangeRef = useRef(onModalChange); + useEffect(() => { + onModalChangeRef.current = onModalChange; + }, [onModalChange]); + useEffect(() => () => onModalChangeRef.current?.(false), []); + // The question is a dialog of this panel's own: it suspends the shortcuts and voice commands at once, without + // waiting for the page to hear of it. + const interactionBlocked = blockedByPage || discardQuestion !== null; + // The pending take the last Recover or Discard was sent for, so the backend's answer is shown beside that take. + const [commandTake, setCommandTake] = useState(null); const [operatorDraft, setOperatorDraft] = useState(operatorToken ?? ""); const [controlDraft, setControlDraft] = useState(controlToken ?? ""); // controlToken can become null from outside a local Clear click too (a @@ -171,24 +210,7 @@ export function RecordingPanel({ // site, is what makes "including keyboard shortcuts" automatic. The // backend enforces this independently and is the real authority; this // is just not sending a command it already knows will be rejected. - const eligibility = - operatorToken === null - ? { - startEpisode: { allowed: false, reason: NO_OPERATOR_REASON }, - stopEpisode: { allowed: false, reason: NO_OPERATOR_REASON }, - discardEpisode: { allowed: false, reason: NO_OPERATOR_REASON }, - taskEdit: { allowed: false, reason: NO_OPERATOR_REASON }, - newBatch: { allowed: false, reason: NO_OPERATOR_REASON }, - } - : controlToken === null - ? { - startEpisode: { allowed: false, reason: NO_CONTROL_TOKEN_REASON }, - stopEpisode: { allowed: false, reason: NO_CONTROL_TOKEN_REASON }, - discardEpisode: { allowed: false, reason: NO_CONTROL_TOKEN_REASON }, - taskEdit: { allowed: false, reason: NO_CONTROL_TOKEN_REASON }, - newBatch: { allowed: false, reason: NO_CONTROL_TOKEN_REASON }, - } - : baseEligibility; + const eligibility = withOperatorGate(baseEligibility, operatorToken, controlToken); const mountedRef = useRef(true); useEffect(() => { mountedRef.current = true; @@ -240,8 +262,9 @@ export function RecordingPanel({ * command only ever has one outstanding instance (eligibility blocks * re-entry), so a resolved promise is always the correlated reply for * this exact call; no post-hoc identity re-check is needed or - * performed. */ - const runCommand = useCallback(async (phase: CommandPhase, run: () => Promise | undefined) => { + * performed. `take` names the pending take a Recover or Discard is for. */ + const runCommand = useCallback(async (phase: CommandPhase, run: () => Promise | undefined, take: string | null = null) => { + setCommandTake(take); dispatch({ type: "COMMAND_STARTED", phase }); let result: RecordingCommandResult | undefined; let error: unknown; @@ -305,6 +328,40 @@ export function RecordingPanel({ void runCommand("restarting", () => actions.onNewBatch?.(target)); }, [eligibility, batchId, actions, runCommand]); + // Recover and Discard of a pending take, of the open session or of an earlier one. "ok" only says the step + // ran: what became of the take arrives in the snapshot and is shown as the last result. + const handleRecoverPending = useCallback( + (take: PendingTake) => { + if (!eligibility.resolvePending.allowed || batchId === null || !take.recoverable) return; + const target: RecordingEpisodeIdentity = { batchId, episodeId: take.episodeId }; + void runCommand("recovering", () => actions.onRecoverPending?.(target), take.episodeId); + }, + [eligibility, batchId, actions, runCommand], + ); + + // Discard removes recorded media for good, so the button only asks; the answer sends the command. + const askDiscardPending = useCallback( + (take: PendingTake) => { + if (eligibility.resolvePending.allowed && take.discardable) setDiscardQuestion(take); + }, + [eligibility, setDiscardQuestion], + ); + + const confirmDiscardPending = useCallback(() => { + const take = discardQuestion; + setDiscardQuestion(null); + if (take === null || !eligibility.resolvePending.allowed || batchId === null) return; + const target: RecordingEpisodeIdentity = { batchId, episodeId: take.episodeId }; + void runCommand("discardingPending", () => actions.onDiscardPending?.(target), take.episodeId); + }, [discardQuestion, setDiscardQuestion, eligibility, batchId, actions, runCommand]); + + // Another viewer can resolve the take while the question is open: there is then nothing left to ask about. + useEffect(() => { + if (discardQuestion !== null && recordingSnapshot?.pendingTakes.some((take) => take.episodeId === discardQuestion.episodeId) !== true) { + setDiscardQuestion(null); + } + }, [discardQuestion, setDiscardQuestion, recordingSnapshot]); + const beginTaskEdit = useCallback(() => { if (!eligibility.taskEdit.allowed) return; dispatch({ @@ -641,16 +698,38 @@ export function RecordingPanel({ // has no RECOVERY_REQUIRED value of its own -- with no command in // flight it reads "idle" even while the backend has a genuinely // interrupted take retained and blocking Record. Without this, the - // panel showed "Idle" with no persistent indication that New batch is - // needed, only a one-shot feedback message from whatever command last - // happened to be rejected. + // panel showed "Idle" with no persistent indication that a take waits. const statusLabel = ui.phase === "idle" && recordingSnapshot?.episodePhase === "RECOVERY_REQUIRED" ? "Recovery required" : PHASE_LABEL[ui.phase]; + // The backend's answer to a refused Recover or Discard belongs beside the take it was for, where the operator + // pressed the button; when that take is no longer shown, it falls back to the panel's own feedback line. + const takeShown = commandTake !== null && recordingSnapshot?.pendingTakes.some((take) => take.episodeId === commandTake) === true; + const outcomeArea = ( + + ); + return (
+ {outcomeSlot === undefined ? outcomeArea : outcomeSlot !== null && createPortal(outcomeArea, outcomeSlot)} + {/* Outside the page's own tree: everything in that tree is inert while the question is open. */} + {discardQuestion !== null && + createPortal( setDiscardQuestion(null)} />, document.body)}

Recording

@@ -852,17 +931,11 @@ export function RecordingPanel({ New batch (r)
- {ui.feedback !== null && ( + {ui.feedback !== null && !takeShown && (

{ui.feedback}

)} - {recordingSnapshot?.lastResult != null && ( -

- Last: {recordingSnapshot.lastResult.disposition} - {recordingSnapshot.lastResult.issues.length > 0 ? ` -- ${recordingSnapshot.lastResult.issues.join("; ")}` : ""} -

- )}
); diff --git a/examples/egocap/frontend/src/RecordingPanel.voice.test.tsx b/examples/egocap/frontend/src/RecordingPanel.voice.test.tsx index 25f8d719a4..995426330b 100644 --- a/examples/egocap/frontend/src/RecordingPanel.voice.test.tsx +++ b/examples/egocap/frontend/src/RecordingPanel.voice.test.tsx @@ -107,7 +107,11 @@ function activeSnapshot(overrides: Partial = {}): RecordingSn defaultOperator: null, autoFillOperatorName: false, savedCount: 0, + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, lastResult: null, + pendingTakes: [], readyToRecord: true, notReadyReason: null, revision: 0, diff --git a/examples/egocap/frontend/src/SettingsPanel.test.tsx b/examples/egocap/frontend/src/SettingsPanel.test.tsx index b6bac07a36..2af1fd23b2 100644 --- a/examples/egocap/frontend/src/SettingsPanel.test.tsx +++ b/examples/egocap/frontend/src/SettingsPanel.test.tsx @@ -544,6 +544,103 @@ describe("Advanced tab", () => { }); }); +describe("Capture checks in the Advanced tab", () => { + /** The card's rows as label and value. */ + const rowsOf = (card: HTMLElement) => Array.from(card.querySelectorAll("dl > div")).map((row) => [row.querySelector("dt")?.textContent, row.querySelector("dd")?.textContent]); + + it("shows the thresholds in force, the file they came from and what the station changed, with nothing to edit", async () => { + renderPanel({ initialTab: "advanced" }); + const card = await screen.findByRole("region", { name: "Capture checks" }); + expect(within(card).getByText(/EGOCAP_QC_CONFIG/)).toBeTruthy(); + expect(rowsOf(card)).toEqual([ + ["Defaults file", "data_check_config.yaml"], + ["SHA-256", ""], + ["Station overrides", "guardrails.gloves_expected = true"], + ["Checks", "On"], + ["A take marked bad is", "quarantined: set aside under _quarantine, not time-aligned"], + ["Camera minimum rate", "0.86 of each camera's rate; below it the take is rejected and its media removed"], + ["Frozen stream", "1 s without change marks the take bad"], + ["Gloves", "judged and required"], + ["Tracking gap", "1 s, warning only"], + ["Take length", "1 to 600 s, warning only"], + ]); + expect(card.querySelector("input, select, textarea, button")).toBeNull(); + }); + + it("leads the card with the backend's notices when the station runs the camera rate rule switched off or loosened", async () => { + const backend = fakeBackend(); + const checks = SETTINGS_FIXTURE.quality_checks!; + const notices = [ + "The camera rate rule is switched off for this station: no take is rejected for a low camera rate.", + "This station sets its own expected camera rate (head_human_camera at 20 Hz): the camera rate rule judges against that rate, not the camera's declared one.", + ]; + backend.loadDeployment = vi.fn(async () => ({ ...SETTINGS_FIXTURE, quality_checks: { ...checks, notices } })); + renderPanel({ initialTab: "advanced" }, backend); + const card = await screen.findByRole("region", { name: "Capture checks" }); + const shown = within(card).getByRole("list", { name: "How this station's checks differ from the built-in ones" }); + // Each is the backend's sentence as sent, written out and marked, not left to a reader of the rows below. + expect(within(shown).getAllByRole("listitem").map((item) => item.textContent)).toEqual(notices); + expect(within(shown).getAllByRole("listitem").every((item) => item.querySelector("svg.outcome-icon") !== null)).toBe(true); + expect(card.firstElementChild?.nextElementSibling?.nextElementSibling).toBe(shown); + }); + + it("shows no notice for a station that runs the checks as built in, nor for a backend that sends none", async () => { + renderPanel({ initialTab: "advanced" }); + const card = await screen.findByRole("region", { name: "Capture checks" }); + expect(within(card).queryByRole("list")).toBeNull(); + cleanup(); + const backend = fakeBackend(); + const { notices: _none, ...older } = SETTINGS_FIXTURE.quality_checks!; + backend.loadDeployment = vi.fn(async () => ({ ...SETTINGS_FIXTURE, quality_checks: older })); + renderPanel({ initialTab: "advanced" }, backend); + expect(within(await screen.findByRole("region", { name: "Capture checks" })).queryByRole("list")).toBeNull(); + }); + + it("says a station with quarantine off flags its bad takes, and names a switched-off check as off", async () => { + const backend = fakeBackend(); + const checks = SETTINGS_FIXTURE.quality_checks!; + backend.loadDeployment = vi.fn(async () => ({ + ...SETTINGS_FIXTURE, + quality_checks: { + ...checks, + station_overrides: { "guardrails.quarantine": false, "guardrails.camera_expected_fps": { head_human_camera: 60 } }, + effective: { ...checks.effective, guardrails: { ...checks.effective?.guardrails, quarantine: false, camera_min_fps_enabled: false, freeze_enabled: false, gloves_expected: false } }, + }, + })); + renderPanel({ initialTab: "advanced" }, backend); + const rows = Object.fromEntries(rowsOf(await screen.findByRole("region", { name: "Capture checks" }))); + expect(rows["A take marked bad is"]).toBe("flagged: kept with its session, not time-aligned"); + expect(rows["Camera minimum rate"]).toBe("Off"); + expect(rows["Frozen stream"]).toBe("Off"); + expect(rows["Gloves"]).toBe("not expected"); + expect(rows["Station overrides"]).toBe('guardrails.quarantine = false, guardrails.camera_expected_fps = {"head_human_camera":60}'); + }); + + it("shows why the thresholds could not be read, and no threshold then", async () => { + const backend = fakeBackend(); + backend.loadDeployment = vi.fn(async () => ({ + ...SETTINGS_FIXTURE, + quality_checks: { error: "quality-check configuration is invalid; see backend logs", defaults_file: null, defaults_sha256: null, station_overrides: {}, effective: null }, + })); + renderPanel({ initialTab: "advanced" }, backend); + expect(rowsOf(await screen.findByRole("region", { name: "Capture checks" }))).toEqual([ + ["Status", "quality-check configuration is invalid; see backend logs"], + ["Defaults file", "—"], + ["SHA-256", "—"], + ["Station overrides", "none"], + ]); + }); + + it("shows no such card for a backend that does not report the checks", async () => { + const backend = fakeBackend(); + const { quality_checks: _none, ...older } = SETTINGS_FIXTURE; + backend.loadDeployment = vi.fn(async () => older); + renderPanel({ initialTab: "advanced" }, backend); + expect(await screen.findByRole("region", { name: "Capture" })).toBeTruthy(); + expect(screen.queryByRole("region", { name: "Capture checks" })).toBeNull(); + }); +}); + describe("Deployment credential", () => { it("waits for a token and reloads deployment settings when one is entered", async () => { const { backend, props, rerender } = renderPanel({ controlToken: null, initialTab: "advanced" }); diff --git a/examples/egocap/frontend/src/SettingsPanel.tsx b/examples/egocap/frontend/src/SettingsPanel.tsx index 06fb08b59c..b21c62364a 100644 --- a/examples/egocap/frontend/src/SettingsPanel.tsx +++ b/examples/egocap/frontend/src/SettingsPanel.tsx @@ -17,6 +17,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { CameraSetupCard } from "./CameraSetupCard"; import { DevicesTab } from "./DevicesTab"; +import { OutcomeIcon } from "./outcomeMarks"; import { Card, LoadState, TokenHint, errorMessage, useAction, useEscapeToClose, useModalFocus, type Loaded } from "./settingsParts"; import { StationsCard } from "./StationsCard"; import { fetchSetup, type SetupStatus } from "./setupApi"; @@ -30,6 +31,7 @@ import { importTaskFile, removeTaskFile, saveOperatorSettings, + type CaptureCheckSettings, type EffectiveSettings, type OperatorSettings, type OperatorSettingsChange, @@ -492,10 +494,67 @@ function DisplayTab({ sidebarWidth, sidebarDefault, onResetSidebar }: { sidebarW // --- Advanced -------------------------------------------------------------------------------------------------- +/** A number of seconds as the checks' limits are written, or a dash when the backend did not send it. */ +function seconds(value: number | undefined): string { + return value === undefined ? "—" : `${value} s`; +} + +/** What a finding does to a take: marks it bad, or only warns. */ +function marksBad(value: boolean | undefined): string { + return value === undefined ? "—" : value ? "marks the take bad" : "warning only"; +} + +/** The capture checks' thresholds in force, the file they started from and what the station changed. Read-only. + * The backend's notices lead the card: they say in sentences when this station runs with the checks or the camera + * rate rule switched off or loosened, which the rows below would only show to someone who knows the built-in values. */ +function CaptureChecksCard({ checks }: { checks: CaptureCheckSettings }) { + const guardrails = checks.effective?.guardrails ?? {}; + const duration = checks.effective?.duration ?? {}; + const overrides = Object.entries(checks.station_overrides).map(([key, value]) => `${key} = ${typeof value === "object" ? JSON.stringify(value) : String(value)}`); + const notices = checks.notices ?? []; + return ( + + {notices.length > 0 && ( +
    + {notices.map((notice) => ( +
  • + + {notice} +
  • + ))} +
+ )} +
+ {checks.error !== null && } + + + 0} /> + {checks.effective !== null && ( + <> + + + + + + + + + )} +
+
+ ); +} + /** Show authenticated deployment details without exposing secrets. */ function AdvancedTab({ deployment }: { deployment: Loaded }) { if (deployment.kind !== "loaded") return ; - const { capture, preview, station, recording, visualization, recordings_browser, task_files, origins } = deployment.value; + const { capture, preview, station, recording, quality_checks: checks, visualization, recordings_browser, task_files, origins } = deployment.value; const viewAddress = visualization.host === null ? null : `${visualization.host}:${orDash(visualization.port)}`; return ( <> @@ -531,6 +590,7 @@ function AdvancedTab({ deployment }: { deployment: Loaded }) + {checks !== undefined && }
diff --git a/examples/egocap/frontend/src/TakeOutcomeBanner.test.tsx b/examples/egocap/frontend/src/TakeOutcomeBanner.test.tsx new file mode 100644 index 0000000000..2fef944181 --- /dev/null +++ b/examples/egocap/frontend/src/TakeOutcomeBanner.test.tsx @@ -0,0 +1,355 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * What the recording screen says about a take that has ended: one headline and mark per outcome, the backend's + * sentences as they arrived, and the pending take's two buttons. A take that was not kept must not read as kept. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { TakeOutcomeArea, type PendingTakeCommands } from "./TakeOutcomeBanner"; +import { + CAMERA_SHORT, + CAMERA_SLOW, + CAMERA_STOPPED, + DROP_WARNINGS, + HEADSET_FROZEN, + INTEGRITY_FAILED, + INTEGRITY_NOTE, + MISPLACED, + MISPLACED_NOTE, + NEEDS_SAME_STATION, + NOT_KNOWN_YET, + ONLY_DISCARD, + RECOVER_RUNS_CHECKS, + SESSION, + WRITE_STALLED_NOTE, + earlierTake, + heldSnapshot, + misplacedTake, + pendingTake, + recordingSnapshot, + rejectedDataTake, + takeResult, +} from "./recordingTestDoubles"; +import type { RecordingSnapshot, ShownOutcome } from "./recordingTypes"; +import { outcomeHeadline, takeNumber } from "./takeOutcomeText"; + +afterEach(cleanup); + +/** Commands that can be sent, recording what the buttons ask for. */ +function commands(overrides: Partial = {}): PendingTakeCommands { + return { blockedReason: null, busy: null, feedback: null, onRecover: vi.fn(), onDiscard: vi.fn(), ...overrides }; +} + +function area(snapshot: RecordingSnapshot | null, given: PendingTakeCommands = commands(), onReviewEarlier?: () => void) { + render(); + return given; +} + +/** The last take's block: its headline, its mark, and every line of text under the headline. */ +function lastTake() { + const block = screen.getByRole("region", { name: "Last take" }); + return { + block, + headline: within(block).getByRole("heading").textContent, + mark: block.className.replace("take-outcome take-outcome--", ""), + lines: Array.from(block.querySelectorAll(".take-outcome-body li, .take-outcome-body p")).map((line) => line.textContent), + }; +} + +describe("the outcome of the last take", () => { + it("shows nothing before the first snapshot, and nothing for a batch with no take yet", () => { + area(null); + area(recordingSnapshot()); + expect(document.querySelector(".take-outcome-area")).toBeNull(); + }); + + it("says a kept take was kept, with its length and nothing more", () => { + area(recordingSnapshot({ savedCount: 1, lastResult: takeResult("kept") })); + expect(lastTake()).toMatchObject({ headline: "Take 1 kept0:02", mark: "kept", lines: [] }); + expect(screen.queryByRole("button")).toBeNull(); + }); + + it("keeps a kept take's warnings a keypress away, in the backend's words", () => { + area(recordingSnapshot({ lastResult: takeResult("kept", { warnings: DROP_WARNINGS }) })); + const warnings = lastTake().block.querySelector("details") as HTMLDetailsElement; + expect(warnings.querySelector("summary")?.textContent).toBe("2 warnings"); + expect(Array.from(warnings.querySelectorAll("li")).map((line) => line.textContent)).toEqual(DROP_WARNINGS); + }); + + it("does not pass off a kept take the checks never looked at as one that passed them", () => { + area(recordingSnapshot({ lastResult: takeResult("kept", { qcDecision: "SKIPPED" }) })); + expect(lastTake()).toMatchObject({ headline: "Take 1 kept0:02", lines: ["The capture checks did not run on this take."] }); + }); + + it("says a flagged take was kept but flagged, why in the backend's sentence, and what that means for it", () => { + area(recordingSnapshot({ flaggedCount: 1, lastResult: takeResult("flagged") })); + expect(lastTake()).toMatchObject({ + headline: "Take 1 kept, but flagged0:02", + mark: "flagged", + lines: [HEADSET_FROZEN, "It stays with its session, marked bad, and is not time-aligned."], + }); + }); + + it("says a quarantined take was set aside, why, and where it is", () => { + area(recordingSnapshot({ quarantinedCount: 1, lastResult: takeResult("quarantined") })); + expect(lastTake()).toMatchObject({ + headline: "Take 1 quarantined0:02", + mark: "quarantined", + lines: [HEADSET_FROZEN, "It is set aside in the quarantine folder, apart from its session, and is not time-aligned.", `Location: _quarantine/${SESSION}/episode_1`], + }); + }); + + it("says a rejected take's media was removed, with the camera, its rate and the limit as the backend gave them", () => { + area(recordingSnapshot({ rejectedCount: 1, lastResult: takeResult("rejected") })); + const last = lastTake(); + expect(last).toMatchObject({ headline: "Take 1 rejected, and its media removed0:02", mark: "rejected" }); + expect(last.lines[0]).toBe(CAMERA_SLOW); + expect(last.block.querySelector("details summary")?.textContent).toBe("2 warnings"); + }); + + it("says a take rejected by the integrity check left its data on disk, and where", () => { + area(recordingSnapshot({ rejectedCount: 1, lastResult: takeResult("rejected_data_kept") })); + expect(lastTake()).toMatchObject({ + headline: "Take 1 rejected, its data left on disk0:02", + mark: "rejected", + lines: [INTEGRITY_FAILED, `Location: ${SESSION}/episode_1.pending`], + }); + }); + + it("says a discarded take was discarded", () => { + area(recordingSnapshot({ lastResult: takeResult("discarded") })); + expect(lastTake()).toMatchObject({ headline: "Take 1 discarded0:00", mark: "discarded", lines: [] }); + }); + + it("shows an outcome it does not recognise as unknown with the backend's own words, and warns against counting it as kept", () => { + area(recordingSnapshot({ lastResult: takeResult("unknown", { reportedAs: "kept (disposition REJECTED)" }) })); + expect(lastTake()).toMatchObject({ + headline: "Take 1: outcome not recognised0:02", + mark: "unknown", + lines: ['The backend reported "kept (disposition REJECTED)", which this page does not know. Do not count this take as kept; see the backend log.'], + }); + }); + + it.each(["flagged", "quarantined", "rejected", "rejected_data_kept", "discarded", "interrupted", "unknown"] as const)("never draws a %s take with the kept take's mark or headline", (outcome: ShownOutcome) => { + const kept = outcomeHeadline(takeResult("kept")); + area(recordingSnapshot({ lastResult: takeResult(outcome) })); + const last = lastTake(); + expect(last.mark).not.toBe("kept"); + expect(last.headline?.startsWith(`${kept}0:`)).toBe(false); + // The mark is drawn, not only coloured. + expect(last.block.querySelector("svg.take-outcome-icon")).not.toBeNull(); + }); + + it("shows a recorder note that is not already a reason, such as an encoder that did not stop, labelled as a note", () => { + const note = "A video encoder did not confirm that it stopped; restart the backend before recording again."; + area(recordingSnapshot({ lastResult: takeResult("kept", { issues: [note] }) })); + expect(within(lastTake().block).getByRole("list", { name: "Recorder notes" }).textContent).toBe(`Recorder note: ${note}`); + }); + + it("shows a kept take as kept when it carries the recorder's note that it could not write for a while", () => { + area(recordingSnapshot({ savedCount: 1, lastResult: takeResult("kept", { issues: [WRITE_STALLED_NOTE] }) })); + const last = lastTake(); + expect(last).toMatchObject({ headline: "Take 1 kept0:02", mark: "kept" }); + expect(within(last.block).getByRole("list", { name: "Recorder notes" }).textContent).toBe(`Recorder note: ${WRITE_STALLED_NOTE}`); + }); + + it("gives an interrupted take's reasons in the order sent when the recorder's own note comes first", () => { + const partWay = "Finishing the take failed part-way; see the backend log."; + area(heldSnapshot(pendingTake(), { lastResult: takeResult("interrupted", { reasons: [WRITE_STALLED_NOTE, partWay], issues: [WRITE_STALLED_NOTE, partWay] }) })); + expect(lastTake().lines.slice(0, 2)).toEqual([WRITE_STALLED_NOTE, partWay]); + }); + + it("shows a camera rejected for too few frames in the backend's sentence, as it shows one rejected for its rate", () => { + area(recordingSnapshot({ rejectedCount: 1, lastResult: takeResult("rejected", { reasons: [CAMERA_SHORT], warnings: [] }) })); + const last = lastTake(); + expect(last).toMatchObject({ headline: "Take 1 rejected, and its media removed0:02", mark: "rejected" }); + expect(last.lines[0]).toBe(CAMERA_SHORT); + }); + + it("does not repeat an interrupted take's reason as a note", () => { + area(heldSnapshot()); + expect(within(lastTake().block).queryByRole("list", { name: "Recorder notes" })).toBeNull(); + }); + + it("numbers a routed take by its slot where its data is, as the day's summary does", () => { + area(recordingSnapshot({ lastResult: takeResult("kept", { episodeId: `${SESSION}/episode_9`, location: "Kitchen/2026-03-09-08-15-00/episode_4" }) })); + expect(lastTake().headline).toBe("Take 4 kept0:02"); + }); + + it("makes way for the next take as soon as it starts", () => { + area(recordingSnapshot({ episodePhase: "RECORDING", currentEpisodeId: "e2", lastResult: takeResult("flagged") })); + expect(document.querySelector(".take-outcome-area")).toBeNull(); + }); + + it("announces the outcome without announcing the buttons beside it", () => { + area(heldSnapshot()); + const announced = lastTake().block.querySelector('[role="status"]') as HTMLElement; + expect(announced.textContent).toContain("Take 1 interrupted"); + expect(announced.querySelector("button")).toBeNull(); + }); +}); + +describe("an interrupted take on the recording screen", () => { + it("says why it was interrupted, that it holds Record, and what Recover would do, with the buttons it is given", () => { + area(heldSnapshot(pendingTake({ phase: "SEALED", recoverable: true, recoverNote: RECOVER_RUNS_CHECKS, durationMs: 2000 }))); + const last = lastTake(); + expect(last).toMatchObject({ headline: "Take 1 interrupted0:01", mark: "pending" }); + expect(last.lines).toEqual([CAMERA_STOPPED, "Record is held until this take is recovered or discarded."]); + const actions = within(last.block).getByRole("group", { name: "Take 1: what can be done" }); + expect(within(actions).getByText(RECOVER_RUNS_CHECKS)).toBeTruthy(); + expect(within(actions).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 1", "Recover take 1"]); + }); + + it("draws only the buttons the backend gives the take: no Recover for one cut off while it was written", () => { + area(heldSnapshot()); + const actions = screen.getByRole("group", { name: "Take 1: what can be done" }); + expect(within(actions).getByText(ONLY_DISCARD)).toBeTruthy(); + // Not a disabled Recover: a button that is not offered is not drawn. + expect(within(actions).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 1"]); + expect(within(actions).getByRole("button").className).toBe("recording-button recording-button--discard"); + }); + + it.each([ + ["no camera has been accepted yet", { recoverableKnown: false, recoverNote: NOT_KNOWN_YET }, NOT_KNOWN_YET], + ["other cameras or settings are accepted now", { recoverNote: NEEDS_SAME_STATION }, NEEDS_SAME_STATION], + ])("says only what the backend says of a complete take that cannot be finished while %s, and does not put Discard forward", (_when, fields, note) => { + area(recordingSnapshot({ lastResult: takeResult("interrupted", { episodeId: earlierTake().episodeId }), pendingTakes: [earlierTake({ phase: "CHECKED", recoverable: false, ...fields })] })); + const actions = screen.getByRole("group", { name: "Take 7: what can be done" }); + // The backend's note, and no sentence of the page's own about whether the take can be recovered. + expect(Array.from(actions.querySelectorAll("p")).map((line) => line.textContent)).toEqual([note]); + // No Recover that looks refused for good, and Discard there but small and plain. + expect(within(actions).queryByRole("button", { name: /Recover/ })).toBeNull(); + expect(within(actions).getByRole("button", { name: "Discard take 7" }).className).toBe("recording-button recording-button--secondary recording-button--small pending-take-discard--aside"); + }); + + it("offers Discard alone, with the backend's note, for the take the integrity check rejected with its data kept", () => { + const rejected = rejectedDataTake(); + area(recordingSnapshot({ rejectedCount: 1, lastResult: takeResult("rejected_data_kept", { episodeId: rejected.episodeId, location: `${rejected.episodeId}.pending` }), pendingTakes: [rejected] })); + const last = lastTake(); + expect(last.headline).toBe("Take 2 rejected, its data left on disk0:02"); + // It holds nothing, so nothing says Record is held. + expect(last.lines).toEqual([INTEGRITY_FAILED, `Location: ${rejected.episodeId}.pending`]); + const actions = within(last.block).getByRole("group", { name: "Take 2: what can be done" }); + expect(within(actions).getByText(INTEGRITY_NOTE)).toBeTruthy(); + expect(within(actions).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 2"]); + }); + + it("offers nothing for a record found in a folder it was not written for, and shows the backend's sentence", () => { + const misplaced = misplacedTake(); + area(recordingSnapshot({ lastResult: takeResult("interrupted", { episodeId: misplaced.episodeId, reasons: [MISPLACED], issues: [MISPLACED] }), pendingTakes: [misplaced] })); + const actions = screen.getByRole("group", { name: "Take 1: what can be done" }); + expect(within(actions).getByText(MISPLACED_NOTE)).toBeTruthy(); + expect(within(actions).queryByRole("button")).toBeNull(); + }); + + it("offers nothing for a take it could not read, and says what it could not read in the backend's own word", () => { + const unread = pendingTake({ phase: null, recoverable: false, discardable: false, unreadable: "phase VERIFIED" }); + area(heldSnapshot(unread, { lastResult: null })); + const held = screen.getByRole("region", { name: "Take holding Record" }); + // All the page knows is that the backend says it holds Record: it does not call it interrupted. + expect(within(held).getByRole("heading").textContent).toBe("Take 1 is holding Record"); + expect(held.className).toBe("take-outcome take-outcome--unknown"); + expect(within(held).getByText("This page could not read this take as the backend sent it (phase VERIFIED), so it offers nothing for it. See the backend log.")).toBeTruthy(); + expect(within(held).queryByRole("button")).toBeNull(); + }); + + it("hands Recover and Discard the take they are for", () => { + const take = pendingTake({ recoverable: true, recoverNote: RECOVER_RUNS_CHECKS }); + const given = area(heldSnapshot(take)); + fireEvent.click(screen.getByRole("button", { name: "Recover take 1" })); + expect(given.onRecover).toHaveBeenCalledWith(take); + fireEvent.click(screen.getByRole("button", { name: "Discard take 1" })); + expect(given.onDiscard).toHaveBeenCalledWith(take); + }); + + it("says in words why the two cannot be sent, not only in a tooltip", () => { + const given = area(heldSnapshot(pendingTake({ recoverable: true })), commands({ blockedReason: "Enter an operator name before using recording controls" })); + expect(screen.getByText("Enter an operator name before using recording controls")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Discard take 1" })); + expect(given.onDiscard).not.toHaveBeenCalled(); + }); + + it("shows which of the two is running, holding both buttons without disabling them", () => { + const given = area(heldSnapshot(), commands({ blockedReason: "Already in progress", busy: { episodeId: `${SESSION}/episode_1`, action: "discard" } })); + const running = screen.getByRole("button", { name: "Discarding…" }); + expect(running.getAttribute("aria-busy")).toBe("true"); + fireEvent.click(running); + expect(given.onDiscard).not.toHaveBeenCalled(); + // The reason it is blocked is the running command itself, so it is not said twice. + expect(screen.queryByText("Already in progress")).toBeNull(); + }); + + it("shows the backend's refusal beside the take it was for", () => { + const refused = "This take was cut off while it was being written and cannot be recovered; discard it."; + area(heldSnapshot(), commands({ feedback: { episodeId: `${SESSION}/episode_1`, text: refused } })); + expect(within(screen.getByRole("group", { name: "Take 1: what can be done" })).getByRole("alert").textContent).toBe(refused); + }); + + it("keeps the open session's take and its buttons on screen when the last result is about another take", () => { + const resolved = takeResult("discarded", { episodeId: earlierTake().episodeId }); + area(heldSnapshot(pendingTake({ phase: "SEALED", recoverable: true, recoverNote: RECOVER_RUNS_CHECKS }), { lastResult: resolved })); + const held = screen.getByRole("region", { name: "Take holding Record" }); + expect(within(held).getByRole("heading").textContent).toBe("Take 1 interrupted"); + expect(within(held).getByText(CAMERA_STOPPED)).toBeTruthy(); + expect(within(held).getByText("Record is held until this take is recovered or discarded.")).toBeTruthy(); + expect(within(held).getAllByRole("button")).toHaveLength(2); + expect(lastTake().headline).toBe("Take 7 discarded0:00"); + }); + + it("offers the two buttons for an earlier session's take that was interrupted again, without saying it holds Record", () => { + const again = earlierTake(); + area(recordingSnapshot({ lastResult: takeResult("interrupted", { episodeId: again.episodeId, reasons: [again.reason], issues: [again.reason] }), pendingTakes: [again] })); + const last = lastTake(); + expect(last.lines).toEqual([again.reason]); + expect(within(last.block).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 7", "Recover take 7"]); + expect(document.querySelector(".take-outcome-earlier")).toBeNull(); + }); +}); + +describe("takes that wait and hold nothing", () => { + it("are counted in one line with a way to the list", () => { + const review = vi.fn(); + area(recordingSnapshot({ pendingTakes: [earlierTake()] }), commands(), review); + expect(document.querySelector(".take-outcome-earlier span")?.textContent).toBe("1 take is waiting for a decision."); + fireEvent.click(screen.getByRole("button", { name: "Review in End of day" })); + expect(review).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("button", { name: /Recover take/ })).toBeNull(); + }); + + it("are counted together, as other takes, beside the take shown with its buttons", () => { + area(heldSnapshot(pendingTake(), { pendingTakes: [pendingTake(), earlierTake(), earlierTake({ episodeId: "session_20260307-090000_aaa111/episode_2", sessionId: "session_20260307-090000_aaa111", index: 2 })] })); + expect(document.querySelector(".take-outcome-earlier span")?.textContent).toBe("2 other takes are waiting for a decision."); + expect(screen.getByRole("button", { name: "Discard take 1" })).toBeTruthy(); + }); + + it("count a rejected take of the open session whose data was kept, once the last result is about a later take", () => { + area(recordingSnapshot({ savedCount: 1, lastResult: takeResult("kept", { episodeId: `${SESSION}/episode_3`, location: `${SESSION}/episode_3` }), pendingTakes: [rejectedDataTake()] })); + expect(lastTake().headline).toBe("Take 3 kept0:02"); + // Not "of an earlier session": it is of this one, and the line does not say why a take waits. + expect(document.querySelector(".take-outcome-earlier span")?.textContent).toBe("1 take is waiting for a decision."); + }); + + it("count a row the page could not read, so the operator is led to it", () => { + area(recordingSnapshot({ pendingTakes: [pendingTake({ episodeId: "", current: false, discardable: false, phase: null, unreadable: "not a take record" })] })); + expect(document.querySelector(".take-outcome-earlier span")?.textContent).toBe("1 take is waiting for a decision."); + }); + + it("have no button when there is nowhere to review them", () => { + area(recordingSnapshot({ pendingTakes: [earlierTake()] })); + expect(screen.queryByRole("button")).toBeNull(); + }); +}); + +describe("a take's number", () => { + it("comes from its id, or from where its data is when that is given", () => { + expect(takeNumber(`${SESSION}/episode_12`)).toBe("12"); + expect(takeNumber(`${SESSION}/episode_12`, `${SESSION}/episode_12.pending`)).toBe("12"); + expect(takeNumber(`${SESSION}/episode_12`, `_quarantine/${SESSION}/episode_12`)).toBe("12"); + expect(takeNumber(`${SESSION}/episode_12`, "Kitchen/2026-03-09-08-15-00/episode_3")).toBe("3"); + // A name of another shape is shown whole rather than guessed at. + expect(takeNumber("e1")).toBe("e1"); + }); +}); diff --git a/examples/egocap/frontend/src/TakeOutcomeBanner.tsx b/examples/egocap/frontend/src/TakeOutcomeBanner.tsx new file mode 100644 index 0000000000..c108abd8c8 --- /dev/null +++ b/examples/egocap/frontend/src/TakeOutcomeBanner.tsx @@ -0,0 +1,183 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * What became of the last take, above the cameras, where the operator is looking when a take ends: its outcome in + * a headline with its own mark, then why, in the backend's sentences. It stays until the next take starts. + * + * A take that waits for the operator carries its buttons here when it is the take the result is about. The + * unresolved take of the open session holds Record, so it is always shown, also when the last result is about + * another take. Every other take that waits holds nothing: those are counted in one line that opens the day's + * summary, which lists them. + */ + +import { formatElapsed } from "./formatElapsed"; +import { OutcomeIcon } from "./outcomeMarks"; +import { PendingTakeActions, type PendingAction } from "./PendingTakeActions"; +import type { EpisodeResultSummary, PendingTake, RecordingSnapshot } from "./recordingTypes"; +import { OUTCOME_VIEW, counted, outcomeEffect, outcomeHeadline, takeNumber } from "./takeOutcomeText"; + +/** The two commands as the place showing a pending take is given them. */ +export interface PendingTakeCommands { + /** Why neither command can be sent now; null when they can. */ + blockedReason: string | null; + /** The take one of the two is running for, and which; null when neither is running. */ + busy: { episodeId: string; action: PendingAction } | null; + /** What the backend last answered to one of the two that it refused, with the take it was for. */ + feedback: { episodeId: string; text: string } | null; + /** Sends Recover for a take. */ + onRecover: (take: PendingTake) => void; + /** Asks to discard a take; the question comes before anything is removed. */ + onDiscard: (take: PendingTake) => void; +} + +/** The two buttons of one take, given the commands of the place showing it. */ +function ActionsFor({ take, commands }: { take: PendingTake; commands: PendingTakeCommands }) { + return ( + commands.onRecover(take)} + onDiscard={() => commands.onDiscard(take)} + /> + ); +} + +/** The sentence under a pending take that holds Record. */ +const HOLDS_RECORD = "Record is held until this take is recovered or discarded."; + +/** The result's own text: headline, the backend's reasons, what follows from the outcome, the recorder's notes, + * where the data is when that is somewhere unusual, and the warnings behind a disclosure. */ +export function TakeResultBody({ result, holdsRecord = false }: { result: EpisodeResultSummary; holdsRecord?: boolean }) { + const effect = outcomeEffect(result); + // The recorder's notes are an interrupted take's reasons already; only a note not yet said is added. A note + // stays with a take after it is recovered, so it is labelled: beside "kept" it must not read as the outcome's reason. + const notes = result.issues.filter((note) => !result.reasons.includes(note)); + // A kept take is where every kept take is. One set aside, or left behind by a failed check, is not. + const showLocation = result.location !== null && (result.outcome === "quarantined" || result.outcome === "rejected_data_kept"); + return ( + // Announced when it changes. The buttons beside it are kept out of the announcement. +
+

+ {outcomeHeadline(result)} + {formatElapsed(result.durationMs)} +

+ {result.reasons.length > 0 && ( +
    + {result.reasons.map((reason, index) => ( +
  • {reason}
  • + ))} +
+ )} + {effect !== null &&

{effect}

} + {holdsRecord &&

{HOLDS_RECORD}

} + {notes.length > 0 && ( +
    + {notes.map((note, index) => ( +
  • Recorder note: {note}
  • + ))} +
+ )} + {showLocation && ( +

+ Location: {result.location} +

+ )} + {result.warnings.length > 0 && ( + // A disclosure, not a tooltip: it opens from the keyboard and on a touch screen. +
+ {counted(result.warnings.length, "warning")} +
    + {result.warnings.map((warning, index) => ( +
  • {warning}
  • + ))} +
+
+ )} +
+ ); +} + +/** The last take's result, with its two buttons when it is still waiting to be recovered or discarded. */ +function ResultBlock({ result, pending, commands }: { result: EpisodeResultSummary; pending: PendingTake | null; commands: PendingTakeCommands }) { + const { shape } = OUTCOME_VIEW[result.outcome]; + return ( +
+ + + {pending !== null && } +
+ ); +} + +/** The open session's unresolved take when the last result is about another take: it still holds Record. */ +function HeldBlock({ take, commands }: { take: PendingTake; commands: PendingTakeCommands }) { + // A row the page could not read is not called interrupted: all it knows is that the backend says it holds Record. + const name = take.episodeId === "" ? "A take" : `Take ${takeNumber(take.episodeId)}`; + const shape = take.unreadable === null ? "pending" : "unknown"; + return ( +
+ +
+

+ {take.unreadable === null ? `${name} ${OUTCOME_VIEW.interrupted.headline}` : `${name} is holding Record`} + {/* A take cut off while it was being written has no known length. */} + {take.durationMs > 0 && {formatElapsed(take.durationMs)}} +

+ {take.reason !== "" && ( +
    +
  • {take.reason}
  • +
+ )} +

{HOLDS_RECORD}

+
+ +
+ ); +} + +export interface TakeOutcomeAreaProps { + /** The backend's recording facts; null before the first arrives, and nothing is drawn then. */ + snapshot: RecordingSnapshot | null; + /** Recover and Discard for a pending take shown here. */ + commands: PendingTakeCommands; + /** Opens the day's summary, which lists every take that waits; absent, their line has no button. */ + onReviewEarlier?: () => void; +} + +/** Everything the recording screen says about takes that have ended: the open session's unresolved take, the last + * result, and how many other takes wait. Nothing while a take is being recorded. */ +export function TakeOutcomeArea({ snapshot, commands, onReviewEarlier }: TakeOutcomeAreaProps) { + if (snapshot === null) return null; + // Once the next take starts, the screen is about that take. + if (snapshot.episodePhase !== "IDLE" && snapshot.episodePhase !== "RECOVERY_REQUIRED") return null; + const last = snapshot.lastResult; + // A row with no id is one the page could not read: it is nobody's result. + const lastPending = last === null ? null : (snapshot.pendingTakes.find((take) => take.episodeId !== "" && take.episodeId === last.episodeId) ?? null); + const held = snapshot.pendingTakes.find((take) => take.current && take !== lastPending) ?? null; + // The rest hold nothing: a rejected take with its data kept, what earlier sessions left, a row that was not read. + const others = snapshot.pendingTakes.filter((take) => take !== lastPending && take !== held).length; + if (last === null && held === null && others === 0) return null; + // "Other" only when a waiting take is shown above, so the count is not read as including that one. + const other = held !== null || lastPending !== null ? "other " : ""; + return ( +
+ {held !== null && } + {last !== null && } + {others > 0 && ( +

+ + {others === 1 ? `1 ${other}take is waiting for a decision.` : `${others} ${other}takes are waiting for a decision.`} + {onReviewEarlier !== undefined && ( + + )} +

+ )} +
+ ); +} diff --git a/examples/egocap/frontend/src/WrapUpDialog.test.tsx b/examples/egocap/frontend/src/WrapUpDialog.test.tsx index bd1d46d263..527d3c8737 100644 --- a/examples/egocap/frontend/src/WrapUpDialog.test.tsx +++ b/examples/egocap/frontend/src/WrapUpDialog.test.tsx @@ -7,6 +7,28 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import type { CorrectionReply, DayReportReply } from "./dayReportApi"; import { DAY_REPORT_FIXTURE, UPTIME_FIXTURE } from "./dayReportTestDoubles"; +import type { PendingTakeControls } from "./PendingTakesCard"; +import { + CAMERA_SLOW, + CAMERA_STOPPED, + DROP_WARNINGS, + GLOVE_FROZEN, + HEADSET_FROZEN, + INTEGRITY_KEPT, + INTEGRITY_NOTE, + MISPLACED, + MISPLACED_NOTE, + NOT_KNOWN_YET, + ONLY_DISCARD, + RECOVER_RUNS_CHECKS, + SESSION, + earlierTake, + misplacedTake, + pendingTake, + rejectedDataTake, + takeResult, +} from "./recordingTestDoubles"; +import type { RecordingCommandResult } from "./recordingTypes"; import { SettingsHttpError } from "./settingsApi"; import { WrapUpDialog, type WrapUpBackend, type WrapUpDialogProps } from "./WrapUpDialog"; @@ -61,32 +83,119 @@ describe("WrapUpDialog", () => { expect(body.querySelector('input[type="date"], input[type="checkbox"]')).toBeNull(); }); - it("shows the day's takes by outcome, with rejected and pending takes counted", async () => { + it("shows the day's takes by outcome, each kind counted on its own with what it means", async () => { renderDialog(); const takes = await region("Takes"); - expect(within(takes).getByText("5 takes, 1h 02m recorded.")).toBeTruthy(); - expect(within(takes).getAllByRole("listitem").map((tile) => tile.textContent)).toEqual([ + expect(within(takes).getByText("6 takes, 1h 02m recorded.")).toBeTruthy(); + const tiles = within(takes).getAllByRole("listitem"); + expect(tiles.map((tile) => tile.textContent)).toEqual([ "2Kept1h 02m", - "1Flagged0m 08s", - "1Rejected0m 03s", - "0Discarded0m 00s", - "1Pending0m 04s", + "1Flagged0m 08skept, marked bad", + "1Quarantined0m 06sset aside", + "1Rejected0m 03snot saved", + "0Discarded0m 00sby the operator", + "1Pending0m 04sneeds a decision", ]); + // Each kind has its own drawn mark, so a tile is not told from its neighbour by colour alone. + expect(tiles.map((tile) => tile.querySelector(".outcome-mark")?.className.replace("outcome-mark outcome-mark--", ""))).toEqual([ + "kept", + "flagged", + "quarantined", + "rejected", + "discarded", + "pending", + ]); + expect(tiles.every((tile) => tile.querySelector("svg.outcome-icon") !== null)).toBe(true); }); - it("lists each session's takes with their real outcome, time, task and issues", async () => { + it("lists each session's takes with their real outcome, time, task and the backend's own sentence of what was wrong", async () => { renderDialog(); const sessions = await region("Sessions"); expect(within(sessions).getByText("08:15 · session_20260309-081500_abc123")).toBeTruthy(); - expect(within(sessions).getByText("Bench A · 2 kept · 1 flagged · 1 rejected · 1 pending")).toBeTruthy(); + expect(within(sessions).getByText("Bench A · 2 kept · 1 flagged · 1 quarantined · 1 rejected · 1 pending")).toBeTruthy(); const rows = within(sessions).getAllByRole("row").slice(1).map((row) => Array.from(row.querySelectorAll("td")).map((cell) => cell.textContent)); expect(rows).toEqual([ ["0", "Kept", "60:00", "Pour water.", "alex", "—"], ["1", "Kept", "2:05", "Pour water.", "alex", "—"], - ["2", "Flagged", "0:08", "Pour water.", "alex", "sustained_freeze:pico_controller/head_pose"], - ["3", "Rejected", "0:03", "Pour water.", "alex", "camera_min_fps:head_human_camera"], - ["4", "Pending", "0:04", "Pour water.", "alex", "—"], + ["2", "Flagged", "0:08", "Pour water.", "alex", HEADSET_FROZEN], + ["3", "Rejected, media removed", "0:03", "Pour water.", "alex", `${CAMERA_SLOW}2 warningsWarning: ${DROP_WARNINGS[0]}Warning: ${DROP_WARNINGS[1]}`], + // An interrupted take's reason is the recorder's note; it is said once, not again as an issue. + ["4", "Pending", "0:04", "Pour water.", "alex", CAMERA_STOPPED], + ["5", "Quarantined", "0:06", "Pour water.", "alex", GLOVE_FROZEN], ]); + // A quarantined take keeps its number in the session, so it does not bring the "Recorded under" column. + expect(within(sessions).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Outcome", "Time", "Task", "Operator", "What was wrong"]); + }); + + it("marks each take's outcome with its own drawn mark as well as its word", async () => { + renderDialog(); + const sessions = await region("Sessions"); + const marks = within(sessions).getAllByRole("row").slice(1).map((row) => row.querySelector("td .outcome-mark")?.className.replace("outcome-mark outcome-mark--", "")); + expect(marks).toEqual(["kept", "kept", "flagged", "rejected", "pending", "quarantined"]); + }); + + it("tells a rejected take whose data was kept from one whose media was removed, and says neither when the backend did not", async () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const rejected = session.episodes[3]; + const kinds = { ...session, episodes: [rejected, { ...rejected, index: 6, episode_id: `${SESSION}/episode_6`, location: `${SESSION}/episode_6`, media_removed: false }, { ...rejected, index: 7, episode_id: `${SESSION}/episode_7`, location: `${SESSION}/episode_7`, media_removed: null }] }; + renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [kinds] } })); + const sessions = await region("Sessions"); + expect(within(sessions).getAllByRole("row").slice(1).map((row) => row.querySelectorAll("td")[1].textContent)).toEqual(["Rejected, media removed", "Rejected, data kept", "Rejected"]); + }); + + it("shows a take whose outcome it does not know as unknown with the backend's word, and counts it apart", async () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const tally = { ...session.by_disposition, kept: { count: 1, seconds: 3_600 }, archived: { count: 1, seconds: 125 } }; + const odd = { ...session, by_disposition: tally, episodes: [session.episodes[0], { ...session.episodes[1], disposition: "archived" }] }; + renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, totals: { episodes: 2, seconds: 3_725, by_disposition: tally }, sessions: [odd] } })); + const tiles = within(await region("Takes")).getAllByRole("listitem"); + expect(tiles[0].textContent).toBe("1Kept1h 00m"); + expect(tiles[tiles.length - 1].textContent).toBe("1Unknown (archived)2m 05snot recognised by this page"); + const sessions = await region("Sessions"); + const cell = within(sessions).getAllByRole("row")[2].querySelectorAll("td")[1]; + expect(cell.textContent).toBe("Unknown (archived)"); + expect(cell.querySelector(".outcome-mark")?.className).toBe("outcome-mark outcome-mark--unknown"); + expect(within(sessions).getByText(/1 kept · .*1 Unknown \(archived\)/)).toBeTruthy(); + }); + + it("shows a report of a backend that counts no quarantined takes, rather than failing on the missing count", async () => { + const { quarantined: _none, ...older } = DAY_REPORT_FIXTURE.report.totals.by_disposition; + renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, totals: { ...DAY_REPORT_FIXTURE.report.totals, by_disposition: older } } })); + const tiles = within(await region("Takes")).getAllByRole("listitem"); + expect(tiles[2].textContent).toBe("0Quarantined0m 00sset aside"); + }); + + it("labels a recorder note on a kept take as a note, so it does not read as what was wrong with it", async () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const note = "Finishing the take failed part-way; see the backend log."; + const recovered = { ...session.episodes[0], issues: [note] }; + renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: [recovered] }] } })); + const sessions = await region("Sessions"); + expect(within(sessions).getAllByRole("row")[1].querySelectorAll("td")[5].textContent).toBe(`Recorder note: ${note}`); + }); + + it("writes out every reason of a take in its row, and puts only its warnings behind a disclosure", async () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const glove = "The right glove did not move for 2.0 s (limit 1 s). Check the glove's battery and connection."; + const flagged = { ...session.episodes[2], reasons: [GLOVE_FROZEN, glove], warnings: [DROP_WARNINGS[0]] }; + renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: [flagged] }] } })); + const sessions = await region("Sessions"); + const cell = within(sessions).getAllByRole("row")[1].querySelectorAll("td")[5]; + expect(Array.from(cell.querySelectorAll(".wrap-up-finding")).map((line) => line.textContent)).toEqual([GLOVE_FROZEN, glove]); + const more = cell.querySelector("details") as HTMLDetailsElement; + expect(more.querySelector("summary")?.textContent).toBe("1 warning"); + expect(Array.from(more.querySelectorAll("li")).map((line) => line.textContent)).toEqual([`Warning: ${DROP_WARNINGS[0]}`]); + }); + + it("shows both sentences of an interrupted take whose one fault the recorder noted twice", async () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const encoder = "A video encoder did not confirm that it stopped; restart the backend before recording again."; + const pending = { ...session.episodes[4], reasons: [CAMERA_STOPPED, encoder], issues: [CAMERA_STOPPED, encoder] }; + renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: [pending] }] } })); + const sessions = await region("Sessions"); + const cell = within(sessions).getAllByRole("row")[1].querySelectorAll("td")[5]; + expect(Array.from(cell.querySelectorAll(".wrap-up-finding")).map((line) => line.textContent)).toEqual([CAMERA_STOPPED, encoder]); + expect(cell.querySelector("details")).toBeNull(); }); it("opens the latest session and leaves the earlier ones collapsed", async () => { @@ -94,7 +203,7 @@ describe("WrapUpDialog", () => { const twoSessions = { ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, session_id: "session_morning" }, session] } }; renderDialog({}, fakeBackend(twoSessions)); const sessions = await region("Sessions"); - expect(Array.from(sessions.querySelectorAll("details")).map((details) => details.open)).toEqual([false, true]); + expect(Array.from(sessions.querySelectorAll("details.wrap-up-session")).map((details) => details.open)).toEqual([false, true]); }); it("says when nothing was recorded today", async () => { @@ -184,7 +293,7 @@ describe("station time in the end-of-day dialog", () => { it("shows zero active and down time, not that there is no take, once the report counts one", async () => { renderDialog({}, fakeBackend({ ...DAY_REPORT_FIXTURE, uptime: { ...UPTIME_FIXTURE, state: "ready", reason: null, active_seconds: 0, down_seconds: 0, blockers: [] } })); const time = await region("Station time"); - expect(screen.getByText("5 takes, 1h 02m recorded.")).toBeTruthy(); + expect(screen.getByText("6 takes, 1h 02m recorded.")).toBeTruthy(); expect(within(time).getByText("Active 0m · Down 0m")).toBeTruthy(); expect(within(time).queryByText("No take yet today.")).toBeNull(); }); @@ -483,7 +592,7 @@ describe("correcting a task", () => { renderDialog(); const form = (await region("Sessions")).querySelector(".wrap-up-correction") as HTMLElement; expect(Array.from(form.querySelectorAll("input, select, textarea")).map((control) => control.getAttribute("aria-label"))).toEqual(["Takes to correct", "Correct task"]); - expect(within(await region("Sessions")).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Outcome", "Time", "Task", "Operator", "Issues"]); + expect(within(await region("Sessions")).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Outcome", "Time", "Task", "Operator", "What was wrong"]); }); it("shows the backend's reason for a refused correction and keeps what was typed", async () => { @@ -527,7 +636,7 @@ describe("correcting a task", () => { // The take number shown is the one inside that group, which is what a correction addresses; both groups // number from zero, so each take also says which group it is in. const table = within(sessions).getAllByRole("table")[0]; - expect(within(table).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Recorded under", "Outcome", "Time", "Task", "Operator", "Issues"]); + expect(within(table).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Recorded under", "Outcome", "Time", "Task", "Operator", "What was wrong"]); expect(within(table).getAllByRole("row").slice(1).map((row) => Array.from(row.querySelectorAll("td")).slice(0, 2).map((cell) => cell.textContent))).toEqual([ ["4", "Kitchen/2026-03-09-08-15-00"], ["0", "Bathroom/2026-03-09-08-40-00"], @@ -541,7 +650,7 @@ describe("correcting a task", () => { // The session whose only take was rejected has nothing to relabel, and its unreadable record is reported. expect(sessions.querySelectorAll(".wrap-up-correction")).toHaveLength(1); expect(within(sessions).getByText("session_nothing_kept")).toBeTruthy(); - expect(within(sessions).getByText("Unreadable take record: episode_9.json: unsupported manifest")).toBeTruthy(); + expect(within(sessions).getByText("Take record not counted: episode_9.json: unsupported manifest")).toBeTruthy(); }); it("says where each take is recorded as soon as one is held outside its session, even in a single group", async () => { @@ -604,7 +713,7 @@ describe("keyboard focus in the end-of-day dialog", () => { const twoSessions = { ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, session_id: "session_morning" }, session] } }; renderDialog({}, fakeBackend(twoSessions)); const sessions = await region("Sessions"); - const [collapsed, open] = Array.from(sessions.querySelectorAll("summary")); + const [collapsed, open] = Array.from(sessions.querySelectorAll(".wrap-up-session > summary")); const notes = notesField(screen.getByRole("region", { name: "Station time" })); notes.focus(); // Save notes is disabled, so the collapsed session's summary is next. @@ -613,9 +722,14 @@ describe("keyboard focus in the end-of-day dialog", () => { // Its takes and its correction form are not on screen: the next stop is the open session. fireEvent.keyDown(collapsed, { key: "Tab" }); expect(document.activeElement).toBe(open); + // Inside the open session the first stop is the disclosure of the rejected take's warnings, then the form. fireEvent.keyDown(open, { key: "Tab" }); + const warnings = within(open.parentElement as HTMLElement).getByText("2 warnings"); + expect(document.activeElement).toBe(warnings); + fireEvent.keyDown(warnings, { key: "Tab" }); expect(document.activeElement).toBe(within(open.parentElement as HTMLElement).getByLabelText("Takes to correct")); fireEvent.keyDown(document.activeElement as Element, { key: "Tab", shiftKey: true }); + fireEvent.keyDown(document.activeElement as Element, { key: "Tab", shiftKey: true }); expect(document.activeElement).toBe(open); fireEvent.keyDown(open, { key: "Tab", shiftKey: true }); expect(document.activeElement).toBe(collapsed); @@ -646,3 +760,243 @@ describe("keyboard focus in the end-of-day dialog", () => { expect(task.readOnly).toBe(false); }); }); + +describe("takes waiting to be recovered or discarded", () => { + const OK: RecordingCommandResult = { outcome: "ok", reason: null }; + + /** The open session's take, cut off while writing, and a sealed take an earlier session left behind. */ + function controls(overrides: Partial = {}): PendingTakeControls { + return { takes: [pendingTake(), earlierTake()], lastResult: null, blockedReason: null, recover: vi.fn(async () => OK), discard: vi.fn(async () => OK), ...overrides }; + } + + /** The dialog with `pending`, and a way to hand it the next snapshot's takes. */ + function renderWith(pending: PendingTakeControls | null, backend = fakeBackend()) { + const props: WrapUpDialogProps = { open: true, onClose: vi.fn(), controlToken: "tok", backend, pending }; + const view = render(); + return { props, backend, update: (next: PendingTakeControls | null) => view.rerender() }; + } + + const rowsOf = (card: HTMLElement) => within(within(card).getByRole("list", { name: "Takes waiting to be recovered or discarded" })).getAllByRole("listitem"); + + it("lists nothing when no take waits", async () => { + renderWith(controls({ takes: [] })); + await region("Takes"); + expect(screen.queryByRole("region", { name: "Takes waiting for a decision" })).toBeNull(); + }); + + it("leads the dialog with each waiting take: why it waits, what Recover would do, and the two buttons", async () => { + renderWith(controls()); + await region("Takes"); + const body = document.querySelector(".settings-content-body") as HTMLElement; + expect(body.children[0].getAttribute("aria-label")).toBe("Takes waiting for a decision"); + const [current, earlier] = rowsOf(await region("Takes waiting for a decision")); + expect(current.querySelector(".pending-take-facts")?.textContent).toBe(`PendingTake 1 · ${SESSION}Pour water. · alexHolds Record`); + expect(within(current).getByText(CAMERA_STOPPED)).toBeTruthy(); + expect(within(current).getByText(ONLY_DISCARD)).toBeTruthy(); + // A take of an earlier session, of another day, is listed too: the report itself lists only today's. + expect(earlier.querySelector(".pending-take-facts")?.textContent).toBe("PendingTake 7 · session_20260308-170200_def4560:12 · Pour water. · alex"); + expect(within(earlier).getByText("Finishing the take failed part-way; see the backend log.")).toBeTruthy(); + expect(within(earlier).getByText(RECOVER_RUNS_CHECKS)).toBeTruthy(); + expect(within(earlier).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 7", "Recover take 7"]); + }); + + it("gives each row the buttons the backend allows for it, described by the backend's note", async () => { + renderWith(controls()); + const [current, earlier] = rowsOf(await region("Takes waiting for a decision")); + // Cut off while it was written: Discard only, and no Recover drawn as if it were refused. + expect(within(current).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 1"]); + const discard = within(current).getByRole("button", { name: "Discard take 1" }) as HTMLButtonElement; + expect(discard.disabled).toBe(false); + expect(document.getElementById(discard.getAttribute("aria-describedby") as string)?.textContent).toBe(ONLY_DISCARD); + expect((within(earlier).getByRole("button", { name: "Recover take 7" }) as HTMLButtonElement).disabled).toBe(false); + }); + + it("lists a take the integrity check rejected with its data kept, as that, with Discard alone", async () => { + renderWith(controls({ takes: [rejectedDataTake()] })); + const [row] = rowsOf(await region("Takes waiting for a decision")); + expect(row.querySelector(".pending-take-facts")?.textContent).toBe(`Rejected, data keptTake 2 · ${SESSION}0:02 · Pour water. · alex`); + expect(row.querySelector(".outcome-mark")?.className).toBe("outcome-mark outcome-mark--rejected"); + expect(within(row).getByText(INTEGRITY_KEPT)).toBeTruthy(); + expect(within(row).getByText(INTEGRITY_NOTE)).toBeTruthy(); + expect(within(row).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 2"]); + }); + + it("says only what the backend says of a take whose recovery is not known yet, and does not put Discard forward", async () => { + renderWith(controls({ takes: [earlierTake({ phase: "CHECKED", recoverable: false, recoverableKnown: false, recoverNote: NOT_KNOWN_YET })] })); + const [row] = rowsOf(await region("Takes waiting for a decision")); + expect(row.querySelector(".pending-take-facts")?.textContent).toContain("Pending"); + expect(Array.from(row.querySelectorAll(".pending-take-actions p")).map((line) => line.textContent)).toEqual([NOT_KNOWN_YET]); + expect(within(row).queryByRole("button", { name: /Recover/ })).toBeNull(); + expect(within(row).getByRole("button", { name: "Discard take 7" }).className).toContain("pending-take-discard--aside"); + }); + + it("shows a record found in a folder it was not written for and leaves it alone: neither command is drawn", async () => { + renderWith(controls({ takes: [misplacedTake()] })); + const [row] = rowsOf(await region("Takes waiting for a decision")); + expect(row.querySelector(".pending-take-facts")?.textContent).toBe(`Left aloneTake 1 · ${SESSION}_copyPour water. · alex`); + expect(within(row).getByText(MISPLACED)).toBeTruthy(); + expect(within(row).getByText(MISPLACED_NOTE)).toBeTruthy(); + expect(within(row).queryByRole("button")).toBeNull(); + }); + + it("marks a row it could not read as unknown with what it could not read, offers nothing for it, and keeps the other rows", async () => { + const unread = pendingTake({ phase: null, recoverable: false, discardable: false, current: false, unreadable: "phase VERIFIED" }); + const nameless = pendingTake({ episodeId: "", sessionId: "", phase: null, recoverable: false, discardable: false, current: false, reason: "", recoverNote: "", task: "", operator: "", unreadable: "not a take record" }); + renderWith(controls({ takes: [unread, nameless, earlierTake()] })); + const [first, second, fine] = rowsOf(await region("Takes waiting for a decision")); + expect(first.querySelector(".outcome-mark")?.textContent).toBe("Unknown"); + expect(first.querySelector(".outcome-mark")?.className).toBe("outcome-mark outcome-mark--unknown"); + expect(within(first).getByText("This page could not read this take as the backend sent it (phase VERIFIED), so it offers nothing for it. See the backend log.")).toBeTruthy(); + expect(within(first).queryByRole("button")).toBeNull(); + expect(second.querySelector(".pending-take-name")?.textContent).toBe("A take the backend listed"); + expect(within(second).getByText(/\(not a take record\)/)).toBeTruthy(); + expect(within(second).queryByRole("button")).toBeNull(); + expect(within(fine).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 7", "Recover take 7"]); + }); + + it("recovers a take, reads the day's report again and shows what became of it in the backend's words", async () => { + const pending = controls(); + const { backend, update } = renderWith(pending); + const [, earlier] = rowsOf(await region("Takes waiting for a decision")); + fireEvent.click(within(earlier).getByRole("button", { name: "Recover take 7" })); + expect(pending.recover).toHaveBeenCalledWith(earlierTake()); + await waitFor(() => expect(backend.load).toHaveBeenCalledTimes(2)); + // The snapshot that follows no longer lists the take and carries what became of it. + const result = takeResult("quarantined", { episodeId: earlierTake().episodeId, location: "_quarantine/session_20260308-170200_def456/episode_7" }); + update(controls({ takes: [pendingTake()], lastResult: result })); + const resolved = await region("Take just resolved"); + expect(within(resolved).getByRole("heading").textContent).toBe("Take 7 quarantined0:02"); + expect(within(resolved).getByText(HEADSET_FROZEN)).toBeTruthy(); + expect(rowsOf(screen.getByRole("region", { name: "Takes waiting for a decision" }))).toHaveLength(1); + }); + + it("does not show the last result as this card's doing when the take was resolved elsewhere", async () => { + renderWith(controls({ takes: [pendingTake()], lastResult: takeResult("kept", { episodeId: `${SESSION}/episode_0` }) })); + await region("Takes waiting for a decision"); + expect(screen.queryByRole("region", { name: "Take just resolved" })).toBeNull(); + }); + + it("shows the backend's reason beside the take when Recover is refused, and reads nothing again", async () => { + const refused = "This take can be finished once the station is set up as when it was recorded: the same cameras and settings."; + const pending = controls({ recover: vi.fn(async (): Promise => ({ outcome: "rejected", reason: refused })) }); + const { backend } = renderWith(pending); + const [, earlier] = rowsOf(await region("Takes waiting for a decision")); + fireEvent.click(within(earlier).getByRole("button", { name: "Recover take 7" })); + expect((await within(earlier).findByRole("alert")).textContent).toBe(refused); + expect(backend.load).toHaveBeenCalledTimes(1); + }); + + it("shows why a command's outcome is unknown when the connection was lost before the reply", async () => { + const pending = controls({ discard: vi.fn(async () => Promise.reject(new Error("connection lost before a reply arrived"))) }); + renderWith(pending); + const [current] = rowsOf(await region("Takes waiting for a decision")); + fireEvent.click(within(current).getByRole("button", { name: "Discard take 1" })); + fireEvent.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Discard take 1" })); + expect((await within(current).findByRole("alert")).textContent).toBe("connection lost before a reply arrived"); + }); + + it("asks before discarding, naming the take and what is removed, and sends nothing when the take is kept", async () => { + const pending = controls(); + renderWith(pending); + const [current] = rowsOf(await region("Takes waiting for a decision")); + const discard = within(current).getByRole("button", { name: "Discard take 1" }); + discard.focus(); + fireEvent.click(discard); + const question = screen.getByRole("alertdialog", { name: "Discard take 1?" }); + expect(question.getAttribute("aria-modal")).toBe("true"); + expect(within(question).getByText("This removes the take's recorded video and tracking data from this station. It cannot be undone.")).toBeTruthy(); + expect(Array.from(question.querySelectorAll("dd")).map((fact) => fact.textContent)).toEqual([SESSION, "Pour water.", "alex", "not known"]); + expect(within(question).getByText(ONLY_DISCARD)).toBeTruthy(); + // The safe answer has focus, so Enter pressed out of habit removes nothing. + const keep = within(question).getByRole("button", { name: "Keep the take" }); + expect(document.activeElement).toBe(keep); + fireEvent.click(keep); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(pending.discard).not.toHaveBeenCalled(); + expect(document.activeElement).toBe(discard); + }); + + it("discards after the answer, and only then", async () => { + const pending = controls(); + const { backend } = renderWith(pending); + const [current] = rowsOf(await region("Takes waiting for a decision")); + fireEvent.click(within(current).getByRole("button", { name: "Discard take 1" })); + expect(pending.discard).not.toHaveBeenCalled(); + fireEvent.click(within(screen.getByRole("alertdialog")).getByRole("button", { name: "Discard take 1" })); + expect(pending.discard).toHaveBeenCalledWith(pendingTake()); + expect(screen.queryByRole("alertdialog")).toBeNull(); + await waitFor(() => expect(backend.load).toHaveBeenCalledTimes(2)); + }); + + it("lets Escape answer the question, keeping the take and leaving the dialog under it open", async () => { + const pending = controls(); + const { props } = renderWith(pending); + const [current] = rowsOf(await region("Takes waiting for a decision")); + fireEvent.click(within(current).getByRole("button", { name: "Discard take 1" })); + fireEvent.keyDown(document.activeElement as Element, { key: "Escape" }); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(pending.discard).not.toHaveBeenCalled(); + expect(props.onClose).not.toHaveBeenCalled(); + // With the question gone, Escape closes the dialog again. + fireEvent.keyDown(document.body, { key: "Escape" }); + expect(props.onClose).toHaveBeenCalledTimes(1); + }); + + it("holds focus inside the question while it is open, whatever the dialog under it would do", async () => { + renderWith(controls()); + const [current] = rowsOf(await region("Takes waiting for a decision")); + fireEvent.click(within(current).getByRole("button", { name: "Discard take 1" })); + const question = screen.getByRole("alertdialog"); + const [keep, discard] = within(question).getAllByRole("button"); + fireEvent.keyDown(keep, { key: "Tab" }); + expect(document.activeElement).toBe(discard); + fireEvent.keyDown(discard, { key: "Tab" }); + expect(document.activeElement).toBe(keep); + fireEvent.keyDown(keep, { key: "Tab", shiftKey: true }); + expect(document.activeElement).toBe(discard); + // Focus sent to a control of the dialog underneath comes back to the question. + (screen.getByRole("button", { name: "Close" }) as HTMLButtonElement).focus(); + expect(question.contains(document.activeElement)).toBe(true); + }); + + it("says why the two commands cannot be sent, and sends neither", async () => { + const pending = controls({ blockedReason: "Enter an operator name before using recording controls" }); + renderWith(pending); + const [current, earlier] = rowsOf(await region("Takes waiting for a decision")); + expect(within(current).getByText("Enter an operator name before using recording controls")).toBeTruthy(); + for (const button of [...within(current).getAllByRole("button"), ...within(earlier).getAllByRole("button")]) { + expect((button as HTMLButtonElement).disabled).toBe(true); + } + }); + + it("holds the other rows while one take is being resolved, and does not send the same command twice", async () => { + let settle: (reply: RecordingCommandResult) => void = () => undefined; + const pending = controls({ recover: vi.fn(() => new Promise((resolve) => (settle = resolve))) }); + renderWith(pending); + const [current, earlier] = rowsOf(await region("Takes waiting for a decision")); + const recover = within(earlier).getByRole("button", { name: "Recover take 7" }); + fireEvent.click(recover); + // Held, not disabled: the button keeps focus while its command runs. + const running = within(earlier).getByRole("button", { name: "Recovering…" }) as HTMLButtonElement; + expect(running.disabled).toBe(false); + expect(running.getAttribute("aria-busy")).toBe("true"); + fireEvent.click(running); + expect(pending.recover).toHaveBeenCalledTimes(1); + expect((within(current).getByRole("button", { name: "Discard take 1" }) as HTMLButtonElement).disabled).toBe(true); + expect(within(current).getByText("Another take is being resolved")).toBeTruthy(); + await act(async () => settle(OK)); + expect((within(current).getByRole("button", { name: "Discard take 1" }) as HTMLButtonElement).disabled).toBe(false); + }); + + it("lists the takes that wait even when the day's report cannot be read", async () => { + renderWith(controls(), fakeBackend(new SettingsHttpError("backend restarting"))); + expect(await screen.findByText("The report is unavailable: backend restarting")).toBeTruthy(); + expect(rowsOf(screen.getByRole("region", { name: "Takes waiting for a decision" }))).toHaveLength(2); + }); + + it("lists no take while the recording backend has not reported", async () => { + renderWith(null); + await region("Takes"); + expect(screen.queryByRole("region", { name: "Takes waiting for a decision" })).toBeNull(); + }); +}); diff --git a/examples/egocap/frontend/src/WrapUpDialog.tsx b/examples/egocap/frontend/src/WrapUpDialog.tsx index f74f227095..3a442426bc 100644 --- a/examples/egocap/frontend/src/WrapUpDialog.tsx +++ b/examples/egocap/frontend/src/WrapUpDialog.tsx @@ -15,28 +15,37 @@ * which station it is now for, and saves again. * * Everything shown comes from the backend's report, which reads the recording service's own manifests: a - * rejected, discarded or interrupted take is listed with its real outcome, never left out. The dialog itself - * decides nothing about a take, and the station's time is the backend's own log, not something set here. + * flagged, quarantined, rejected, discarded or interrupted take is listed with its real outcome and the backend's + * own sentence of why, never left out. The dialog itself decides nothing about a take, and the station's time is + * the backend's own log, not something set here. + * + * Takes waiting to be recovered or discarded lead the dialog, with the two commands. They come from the recording + * snapshot, not from the report, so one of an earlier day is listed too. */ import { useCallback, useEffect, useRef, useState } from "react"; import { - DISPOSITIONS, correctSession, fetchDayReport, + knownDisposition, saveDayReport, + tallyRows, type Correction, type CorrectionReply, type DayReportReply, type ReportEpisode, type ReportSession, type TakeDisposition, + type TallyRow, } from "./dayReportApi"; -import { formatElapsed } from "./RecordingPanel"; +import { formatElapsed } from "./formatElapsed"; +import { OutcomeMark } from "./outcomeMarks"; +import { PendingTakesCard, type PendingTakeControls } from "./PendingTakesCard"; import { sentence } from "./sentence"; import { SettingsHttpError } from "./settingsApi"; import { Card, errorMessage, useAction, useEscapeToClose, useModalFocus, type Loaded } from "./settingsParts"; import { saveStationNotes, type StationUptime, type UptimeBlocker } from "./stationsApi"; import { formatActivity, formatTotal } from "./stationTime"; +import { counted, takeNumber, type OutcomeShape } from "./takeOutcomeText"; /** The calls the dialog makes; the page uses the real ones and tests pass fakes. */ export interface WrapUpBackend { @@ -64,19 +73,36 @@ export const REAL_WRAP_UP_BACKEND: WrapUpBackend = { load: fetchDayReport, save: /** The longest notes the backend accepts, so the field stops where a save would be refused. */ const MAX_NOTES_CHARS = 4000; +/** How one outcome is shown in the tiles and the table. */ +interface DispositionView { + /** The outcome in the operator's word. */ + label: string; + /** The mark drawn beside the word, so the outcome is not told by colour alone. */ + shape: OutcomeShape; + /** What the outcome means for the takes counted under it, under the tile's time; null where the word says it. */ + hint: string | null; +} + /** Each outcome in the operator's words. */ -const DISPOSITION_LABELS: Record = { - kept: "Kept", - flagged: "Flagged", - rejected: "Rejected", - discarded: "Discarded", - pending: "Pending", - recording: "Recording", +const DISPOSITION_VIEW: Record = { + kept: { label: "Kept", shape: "kept", hint: null }, + flagged: { label: "Flagged", shape: "flagged", hint: "kept, marked bad" }, + quarantined: { label: "Quarantined", shape: "quarantined", hint: "set aside" }, + rejected: { label: "Rejected", shape: "rejected", hint: "not saved" }, + discarded: { label: "Discarded", shape: "discarded", hint: "by the operator" }, + pending: { label: "Pending", shape: "pending", hint: "needs a decision" }, + recording: { label: "Recording", shape: "recording", hint: null }, }; -/** A take's episode number where its data is: the trailing number of its location. */ +/** A tally row's word and mark: its own for an outcome this page knows, else the backend's word under the mark + * for an unknown outcome, so its takes are not read as any known kind. */ +function viewOf(row: TallyRow): DispositionView { + return row.known === null ? { label: `Unknown (${row.name})`, shape: "unknown", hint: "not recognised by this page" } : DISPOSITION_VIEW[row.known]; +} + +/** A take's episode number where its data is. */ function episodeNumber(episode: ReportEpisode): string { - return episode.location.slice(episode.location.lastIndexOf("_") + 1); + return takeNumber(episode.episode_id, episode.location); } /** The session or routed group holding a take's data: its location without the episode. */ @@ -104,11 +130,15 @@ export interface WrapUpDialogProps { controlToken: string | null; /** The calls the dialog makes; the real routes unless a test passes fakes. */ backend?: WrapUpBackend; + /** The takes waiting to be recovered or discarded, with the two commands; null or left out, none are listed. */ + pending?: PendingTakeControls | null; } -/** Show the day's takes, the station's time and notes, and the correction and report actions. */ -export function WrapUpDialog({ open, onClose, controlToken, backend = REAL_WRAP_UP_BACKEND }: WrapUpDialogProps) { +/** Show the takes that wait, the day's takes, the station's time and notes, and the correction and report actions. */ +export function WrapUpDialog({ open, onClose, controlToken, backend = REAL_WRAP_UP_BACKEND, pending = null }: WrapUpDialogProps) { const dialogRef = useModalFocus(open); + // Whether the question before a discard is open over this dialog; Escape is then that question's to answer. + const [questionOpen, setQuestionOpen] = useState(false); const [state, setState] = useState>({ kind: "loading" }); // The notes as typed, kept here so that reading the report again never replaces them. Null while the operator // has typed nothing: the field then shows what is saved. @@ -146,7 +176,7 @@ export function WrapUpDialog({ open, onClose, controlToken, backend = REAL_WRAP_ else onClose(); }, [notesDraft, onClose]); // Escape asks to close like the button does; over the question it answers "keep editing", never "discard". - useEscapeToClose(open, confirmingDiscard ? () => setConfirmingDiscard(false) : requestClose); + useEscapeToClose(open && !questionOpen, confirmingDiscard ? () => setConfirmingDiscard(false) : requestClose); useEffect(() => { if (!confirmingDiscard) return; // The question replaces Close in the header: focus goes to its safe answer, and afterwards back to where @@ -236,6 +266,8 @@ export function WrapUpDialog({ open, onClose, controlToken, backend = REAL_WRAP_

Enter the control token in the recording panel to see the day's report.

) : ( <> + {/* From the recording snapshot, so it does not wait for the report and outlasts a failed read of it. */} + {state.kind === "loading" &&

Loading…

} {state.kind === "error" &&

The report is unavailable: {state.message}

} {reply !== null && ( @@ -285,24 +317,72 @@ export function WrapUpDialog({ open, onClose, controlToken, backend = REAL_WRAP_ ); } -/** The day's takes by outcome, each with its recorded time. */ +/** The day's takes by outcome, each counted on its own with its recorded time. */ function Totals({ reply }: { reply: DayReportReply }) { const { totals } = reply.report; + // The take being written is a tile only while there is one. + const rows = tallyRows(totals.by_disposition).filter((row) => row.known !== "recording" || row.count > 0); return (
    - {DISPOSITIONS.filter((name) => name !== "recording" || totals.by_disposition.recording.count > 0).map((name) => ( -
  • - {totals.by_disposition[name].count} - {DISPOSITION_LABELS[name]} - {formatActivity(totals.by_disposition[name].seconds)} -
  • - ))} + {rows.map((row) => { + const view = viewOf(row); + return ( +
  • + {row.count} + + {view.label} + + {formatActivity(row.seconds)} + {view.hint !== null && {view.hint}} +
  • + ); + })}
); } +/** What became of one take: its outcome's mark and word. A rejected take says which kind it is, and a word this + * page does not know is shown as it came, under the mark for an unknown outcome. */ +function OutcomeCell({ episode }: { episode: ReportEpisode }) { + const known = knownDisposition(episode.disposition); + if (known === null) return Unknown ({episode.disposition}); + const view = DISPOSITION_VIEW[known]; + // The media of a camera rejection is gone; the data of an integrity failure is still on disk. + const kind = known === "rejected" && episode.media_removed !== null ? (episode.media_removed ? ", media removed" : ", data kept") : ""; + return {`${view.label}${kind}`}; +} + +/** What was wrong with one take, in the backend's sentences: every reason written out, since one take can fail + * for several cameras or carry two sentences for one fault, and the warnings, which never decide, behind a + * disclosure that opens from the keyboard. */ +function Findings({ episode }: { episode: ReportEpisode }) { + // A recorder note is an interrupted take's reason already; only one not yet said is added, labelled as a note: + // it stays with a take after it is recovered and must not read as why the take ended as it did. + const said = [...episode.reasons, ...episode.issues.filter((note) => !episode.reasons.includes(note)).map((note) => `Recorder note: ${note}`)]; + if (said.length === 0 && episode.warnings.length === 0) return <>—; + return ( + <> + {said.map((line, index) => ( + + {line} + + ))} + {episode.warnings.length > 0 && ( +
+ {counted(episode.warnings.length, "warning")} +
    + {episode.warnings.map((line, index) => ( +
  • Warning: {line}
  • + ))} +
+
+ )} + + ); +} + /** One stretch the station could not record: when, for how long, and why. */ function BlockerLine({ blocker }: { blocker: UptimeBlocker }) { return ( @@ -449,13 +529,17 @@ function SessionDetails({ onCorrected: () => void; onTyped: (sessionId: string, typed: boolean) => void; }) { - const counts = DISPOSITIONS.filter((name) => session.by_disposition[name].count > 0).map((name) => `${session.by_disposition[name].count} ${DISPOSITION_LABELS[name].toLowerCase()}`); + const counts = tallyRows(session.by_disposition) + .filter((row) => row.count > 0) + // The backend's own word for an outcome this page does not know is written as it came. + .map((row) => `${row.count} ${row.known === null ? viewOf(row).label : viewOf(row).label.toLowerCase()}`); // Only a take that was finalized has recorded data whose task can be relabelled. const holders = [...new Set(session.episodes.filter((episode) => episode.disposition === "kept" || episode.disposition === "flagged").map(holderOf))]; const { session_id: sessionId } = session; // A routed take is numbered by its slot in its group and an unfinished one by its place in the session, and // each group numbers from zero: once any take is held outside the session, a number alone does not name a take. - const routed = session.episodes.some((episode) => holderOf(episode) !== sessionId); + // A quarantined take is set apart but keeps its number in the session, so it does not make numbers ambiguous. + const routed = session.episodes.some((episode) => episode.disposition !== "quarantined" && holderOf(episode) !== sessionId); const noteTyped = useCallback((typed: boolean) => onTyped(sessionId, typed), [onTyped, sessionId]); return (
@@ -467,7 +551,7 @@ function SessionDetails({ {session.problems.map((problem) => (

- Unreadable take record: {problem} + Take record not counted: {problem}

))} {session.episodes.length > 0 && ( @@ -485,7 +569,7 @@ function SessionDetails({ Task Operator - Issues + What was wrong @@ -494,12 +578,14 @@ function SessionDetails({ {episodeNumber(episode)} {routed && {holderOf(episode)}} - {DISPOSITION_LABELS[episode.disposition]} + {formatElapsed(episode.duration_seconds * 1000)} {episode.task} {episode.operator} - {episode.issues.length === 0 ? "—" : episode.issues.join("; ")} + + + ))} diff --git a/examples/egocap/frontend/src/dayReportApi.test.ts b/examples/egocap/frontend/src/dayReportApi.test.ts index ba3db397a0..f465bdf236 100644 --- a/examples/egocap/frontend/src/dayReportApi.test.ts +++ b/examples/egocap/frontend/src/dayReportApi.test.ts @@ -4,7 +4,7 @@ /** The end-of-day calls: what each sends, the backend's own reason on a refusal, and a malformed body. */ import { afterEach, describe, expect, it, vi } from "vitest"; -import { correctSession, fetchDayReport, saveDayReport } from "./dayReportApi"; +import { correctSession, fetchDayReport, parseReply, saveDayReport, tallyRows } from "./dayReportApi"; import { DAY_REPORT_FIXTURE } from "./dayReportTestDoubles"; import { SettingsHttpError, SettingsParseError } from "./settingsApi"; @@ -59,4 +59,54 @@ describe("the day report", () => { stubFetch(200, { updated: "episode_0", missing: [] }); await expect(correctSession("tok", { session: "s", episodes: "0", task: "x" })).rejects.toThrow(SettingsParseError); }); + + it("rejects a take that does not say what became of it, where it is or which it is", () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + for (const broken of [{ disposition: null }, { location: undefined }, { episode_id: 4 }]) { + const body = { ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: [{ ...session.episodes[0], ...broken }] }] } }; + expect(() => parseReply(body)).toThrow(SettingsParseError); + } + expect(() => parseReply({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, by_disposition: null }] } })).toThrow(SettingsParseError); + }); + + it("fills in what a backend without the checks' sentences leaves out, and does not guess whether media was removed", () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const { reasons: _r, warnings: _w, media_removed: _m, ...older } = session.episodes[3]; + const parsed = parseReply({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: [older] }] } }); + expect(parsed.report.sessions[0].episodes[0]).toMatchObject({ disposition: "rejected", reasons: [], warnings: [], media_removed: null }); + }); + + it("keeps a disposition it does not know as the backend's own word", () => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + const parsed = parseReply({ ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: [{ ...session.episodes[0], disposition: "archived" }] }] } }); + expect(parsed.report.sessions[0].episodes[0].disposition).toBe("archived"); + }); +}); + +describe("a tally read row by row", () => { + const tally = DAY_REPORT_FIXTURE.report.totals.by_disposition; + + it("lists every known disposition in order, quarantined between flagged and rejected", () => { + expect(tallyRows(tally).map((row) => [row.name, row.count])).toEqual([ + ["kept", 2], + ["flagged", 1], + ["quarantined", 1], + ["rejected", 1], + ["discarded", 0], + ["pending", 1], + ["recording", 0], + ]); + }); + + it("counts none for a disposition the backend left out, or sent in another shape", () => { + const { quarantined: _none, ...older } = tally; + expect(tallyRows(older).find((row) => row.name === "quarantined")).toEqual({ name: "quarantined", known: "quarantined", count: 0, seconds: 0 }); + expect(tallyRows({ ...tally, flagged: { count: "1" } as never }).find((row) => row.name === "flagged")).toMatchObject({ count: 0, seconds: 0 }); + }); + + it("lists a disposition it does not know after the known ones, under the backend's word, and only when it counted a take", () => { + const rows = tallyRows({ ...tally, archived: { count: 2, seconds: 30 }, expired: { count: 0, seconds: 0 } }); + expect(rows[rows.length - 1]).toEqual({ name: "archived", known: null, count: 2, seconds: 30 }); + expect(rows.some((row) => row.name === "expired")).toBe(false); + }); }); diff --git a/examples/egocap/frontend/src/dayReportApi.ts b/examples/egocap/frontend/src/dayReportApi.ts index 0e6545bdf5..14eb5202fb 100644 --- a/examples/egocap/frontend/src/dayReportApi.ts +++ b/examples/egocap/frontend/src/dayReportApi.ts @@ -12,27 +12,83 @@ import { CHANGE_TIMEOUT_MS, withTimeout } from "./requestTimeout"; import { SettingsHttpError, SettingsParseError } from "./settingsApi"; import { parseUptime, type StationUptime } from "./stationsApi"; -/** What became of a take. `recording` is the one being written right now. */ -export type TakeDisposition = "kept" | "flagged" | "rejected" | "discarded" | "pending" | "recording"; +/** What became of a take. A `flagged` take and a `quarantined` one were both marked bad by the capture checks: the + * first stayed with its session, the second was set apart. `recording` is the one being written right now. */ +export type TakeDisposition = "kept" | "flagged" | "quarantined" | "rejected" | "discarded" | "pending" | "recording"; /** The dispositions in the order they are listed. */ -export const DISPOSITIONS: readonly TakeDisposition[] = ["kept", "flagged", "rejected", "discarded", "pending", "recording"]; +export const DISPOSITIONS: readonly TakeDisposition[] = ["kept", "flagged", "quarantined", "rejected", "discarded", "pending", "recording"]; + +/** A take count and its recorded time. */ +export interface TallyEntry { + /** How many takes. */ + count: number; + /** Their recorded time together, in seconds. */ + seconds: number; +} + +/** A count and a duration by disposition, as the backend sends it. Read it through `tallyRows`: a backend of + * another version can leave a disposition out or send one this page does not know. */ +export type Tally = Record; + +/** One disposition's row of a tally, as the page lists it. */ +export interface TallyRow extends TallyEntry { + /** The disposition as the backend named it. */ + name: string; + /** The same as one of the dispositions this page knows, or null: its takes are then listed under the backend's + * own word, never added to another kind. */ + known: TakeDisposition | null; +} + +/** The disposition `name` is, when it is one this page knows. */ +export function knownDisposition(name: string): TakeDisposition | null { + return (DISPOSITIONS as readonly string[]).includes(name) ? (name as TakeDisposition) : null; +} -/** A count and a duration for each disposition; every disposition is present. */ -export type Tally = Record; +/** A tally row by row: every known disposition in listing order, with zeros where the backend sent none, then + * any other disposition it counted takes under. */ +export function tallyRows(tally: Tally): TallyRow[] { + const entry = (name: string): TallyEntry => { + const sent = tally[name] as Partial | undefined; + return { count: typeof sent?.count === "number" ? sent.count : 0, seconds: typeof sent?.seconds === "number" ? sent.seconds : 0 }; + }; + const known = DISPOSITIONS.map((name): TallyRow => ({ name, known: name, ...entry(name) })); + const others = Object.keys(tally) + .filter((name) => knownDisposition(name) === null) + .map((name): TallyRow => ({ name, known: null, ...entry(name) })) + .filter((row) => row.count > 0); + return [...known, ...others]; +} -/** One take as the report lists it. */ +/** One take as the report lists it. Every sentence in it was composed by the backend. */ export interface ReportEpisode { + /** The take's index in its session. */ index: number; + /** `/episode_`: the id a pending take of the recording snapshot carries too. */ episode_id: string; - disposition: TakeDisposition; + /** What became of the take: one of `DISPOSITIONS`, or a word this page does not know, which it shows as it is. */ + disposition: string; + /** Its recorded length, in seconds. */ duration_seconds: number; + /** The task it shows: the corrected one when its task was corrected after recording. */ task: string; + /** The free-text details recorded with the task; "" when none. */ task_details: string; + /** The operator who recorded it. */ operator: string; + /** The recorder's own notes on the take, as fixed sentences. */ issues: string[]; + /** What the capture checks decided, as recorded; null when nothing was decided. */ qc_decision: string | null; - /** Where the take's data is, relative to the recording output: `/episode_`. */ + /** The findings that decided what became of the take, one sentence each; for a pending take, why it waits. */ + reasons: string[]; + /** Findings that never decide, one sentence each. */ + warnings: string[]; + /** Tells the two kinds of rejected take apart: true when its media was removed, false when its data was left on + * disk. Null when the backend did not say. */ + media_removed: boolean | null; + /** Where the take's data is, relative to the recording output: `/episode_`, or + * `_quarantine//episode_` for a quarantined take. */ location: string; } @@ -44,7 +100,8 @@ export interface ReportSession { started_at: string | null; by_disposition: Tally; episodes: ReportEpisode[]; - /** Manifests that could not be read: takes the day cannot account for. */ + /** Take records the day does not count, one backend line each, naming the record's file: one that cannot be + * read, or one found in a session folder it was not written for (a folder copied or renamed by hand). */ problems: string[]; } @@ -97,15 +154,46 @@ async function failureOf(response: Response): Promise { return new SettingsHttpError(detail); } -/** Checks the parts the dialog reads without guarding. */ -function parseReply(value: unknown): DayReportReply { - const record = (typeof value === "object" && value !== null ? value : {}) as Record; - const report = record.report as Partial | undefined; - if (typeof report !== "object" || report === null || !Array.isArray(report.sessions) || typeof report.totals !== "object" || report.totals === null) { +/** A list of sentences as sent, or none when the backend sent no such list. */ +function sentences(value: unknown): string[] { + return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []; +} + +/** Whether `value` is a JSON object. */ +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** One take with the fields a backend of another version can leave out filled in, so the dialog reads them + * without guarding. A take whose disposition is not a word is refused: it could not be shown as anything. */ +function parseEpisode(value: unknown): ReportEpisode { + if (!isRecord(value) || typeof value.disposition !== "string" || typeof value.episode_id !== "string" || typeof value.location !== "string") { + throw new SettingsParseError("day report is malformed"); + } + return { + ...(value as unknown as ReportEpisode), + issues: sentences(value.issues), + reasons: sentences(value.reasons), + warnings: sentences(value.warnings), + media_removed: typeof value.media_removed === "boolean" ? value.media_removed : null, + }; +} + +/** One session with its takes read by `parseEpisode`. */ +function parseSession(value: unknown): ReportSession { + if (!isRecord(value) || !Array.isArray(value.episodes) || !isRecord(value.by_disposition)) throw new SettingsParseError("day report is malformed"); + return { ...(value as unknown as ReportSession), episodes: value.episodes.map(parseEpisode), problems: sentences(value.problems) }; +} + +/** Checks the parts the dialog reads without guarding, and fills in what a backend of another version leaves out. */ +export function parseReply(value: unknown): DayReportReply { + const record = isRecord(value) ? value : {}; + const report = record.report; + if (!isRecord(report) || !Array.isArray(report.sessions) || !isRecord(report.totals) || !isRecord(report.totals.by_disposition)) { throw new SettingsParseError("day report is malformed"); } parseUptime(record.uptime); - return value as DayReportReply; + return { ...(value as DayReportReply), report: { ...(report as unknown as DayReport), sessions: report.sessions.map(parseSession) } }; } /** The headers of a change: the credential and the JSON type. */ diff --git a/examples/egocap/frontend/src/dayReportTestDoubles.ts b/examples/egocap/frontend/src/dayReportTestDoubles.ts index c4920c6f7d..2606bd269c 100644 --- a/examples/egocap/frontend/src/dayReportTestDoubles.ts +++ b/examples/egocap/frontend/src/dayReportTestDoubles.ts @@ -4,10 +4,9 @@ /** A day's report for tests: one session whose takes ended every way a take can, and the station's uptime. */ import type { DayReportReply, ReportEpisode, Tally, TakeDisposition } from "./dayReportApi"; +import { CAMERA_SLOW, CAMERA_STOPPED, DROP_WARNINGS, GLOVE_FROZEN, HEADSET_FROZEN, SESSION } from "./recordingTestDoubles"; import type { StationUptime } from "./stationsApi"; -const SESSION = "session_20260309-081500_abc123"; - /** One take of the fixture session. */ function take(index: number, disposition: TakeDisposition, seconds: number, extra: Partial = {}): ReportEpisode { return { @@ -20,6 +19,9 @@ function take(index: number, disposition: TakeDisposition, seconds: number, extr operator: "alex", issues: [], qc_decision: null, + reasons: [], + warnings: [], + media_removed: false, location: `${SESSION}/episode_${index}`, ...extra, }; @@ -28,6 +30,7 @@ function take(index: number, disposition: TakeDisposition, seconds: number, extr const TALLY: Tally = { kept: { count: 2, seconds: 3_725 }, flagged: { count: 1, seconds: 8 }, + quarantined: { count: 1, seconds: 6 }, rejected: { count: 1, seconds: 3 }, discarded: { count: 0, seconds: 0 }, pending: { count: 1, seconds: 4 }, @@ -56,12 +59,12 @@ export const UPTIME_FIXTURE: StationUptime = { as_of: localTime(14, 10), }; -/** Bench A's day: two kept takes, one flagged, one rejected and one interrupted, and its uptime. */ +/** Bench A's day: two kept takes, one flagged, one quarantined, one rejected and one interrupted, and its uptime. */ export const DAY_REPORT_FIXTURE: DayReportReply = { report: { date: "2026-03-09", station: "Bench A", - totals: { episodes: 5, seconds: 3_740, by_disposition: TALLY }, + totals: { episodes: 6, seconds: 3_746, by_disposition: TALLY }, sessions: [ { session_id: SESSION, @@ -71,9 +74,10 @@ export const DAY_REPORT_FIXTURE: DayReportReply = { episodes: [ take(0, "kept", 3_600), take(1, "kept", 125, { task_details: "Left hand, blue cup." }), - take(2, "flagged", 8, { issues: ["sustained_freeze:pico_controller/head_pose"], qc_decision: "FLAGGED_BAD" }), - take(3, "rejected", 3, { issues: ["camera_min_fps:head_human_camera"], qc_decision: "REJECTED_CAMERA" }), - take(4, "pending", 4), + take(2, "flagged", 8, { qc_decision: "FLAGGED_BAD", reasons: [HEADSET_FROZEN] }), + take(3, "rejected", 3, { qc_decision: "REJECTED_CAMERA", reasons: [CAMERA_SLOW], warnings: DROP_WARNINGS, media_removed: true }), + take(4, "pending", 4, { issues: [CAMERA_STOPPED], reasons: [CAMERA_STOPPED] }), + take(5, "quarantined", 6, { qc_decision: "FLAGGED_BAD", reasons: [GLOVE_FROZEN], location: `_quarantine/${SESSION}/episode_5` }), ], problems: [], }, diff --git a/examples/egocap/frontend/src/formatElapsed.ts b/examples/egocap/frontend/src/formatElapsed.ts new file mode 100644 index 0000000000..89cc37f3cd --- /dev/null +++ b/examples/egocap/frontend/src/formatElapsed.ts @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** Formats a millisecond duration as `m:ss`, for a take's clock and its recorded length. */ +export function formatElapsed(ms: number): string { + const totalSeconds = Math.max(0, Math.floor(ms / 1000)); + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + return `${minutes}:${seconds.toString().padStart(2, "0")}`; +} diff --git a/examples/egocap/frontend/src/outcomeMarks.tsx b/examples/egocap/frontend/src/outcomeMarks.tsx new file mode 100644 index 0000000000..eec2cc21f7 --- /dev/null +++ b/examples/egocap/frontend/src/outcomeMarks.tsx @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * The mark drawn beside each outcome's word: on the recording screen, in the status bar and in the day's summary. + * Every outcome has its own outline (a ticked disc, a warning triangle, a box, a crossed octagon, a struck ring, a + * paused diamond), so a take that was not kept reads as such without its colour. + */ + +import type { ReactNode } from "react"; +import type { OutcomeShape } from "./takeOutcomeText"; + +/** Each mark's drawing in a 16 by 16 box. `outcome-icon-cut` strokes are drawn in the background's colour, over the + * filled outline. */ +const DRAWINGS: Record = { + kept: ( + <> + + + + ), + flagged: ( + <> + + + + ), + quarantined: ( + <> + + + + ), + rejected: ( + <> + + + + ), + discarded: ( + <> + + + + ), + pending: ( + <> + + + + ), + recording: , + unknown: ( + <> + + + + ), +}; + +/** One outcome's mark alone. Decorative: the outcome's word is always written beside it. */ +export function OutcomeIcon({ shape, className = "" }: { shape: OutcomeShape; className?: string }) { + return ( + + ); +} + +/** An outcome's mark with its word, coloured for the outcome. */ +export function OutcomeMark({ shape, children }: { shape: OutcomeShape; children: ReactNode }) { + return ( + + + {children} + + ); +} diff --git a/examples/egocap/frontend/src/recordingActions.ts b/examples/egocap/frontend/src/recordingActions.ts index 9ef269ad42..d312b2b9d0 100644 --- a/examples/egocap/frontend/src/recordingActions.ts +++ b/examples/egocap/frontend/src/recordingActions.ts @@ -24,5 +24,7 @@ export function buildRecordingActions(sendRecordingCommand: SendRecordingCommand onStopEpisode: (target: RecordingEpisodeIdentity) => sendRecordingCommand("stop_episode", episodeTargetPayload(target)), onDiscardEpisode: (target: RecordingEpisodeIdentity) => sendRecordingCommand("discard_episode", episodeTargetPayload(target)), onNewBatch: (target: RecordingBatchIdentity) => sendRecordingCommand("new_batch", batchTargetPayload(target)), + onRecoverPending: (target: RecordingEpisodeIdentity) => sendRecordingCommand("recover_pending", episodeTargetPayload(target)), + onDiscardPending: (target: RecordingEpisodeIdentity) => sendRecordingCommand("discard_pending", episodeTargetPayload(target)), }; } diff --git a/examples/egocap/frontend/src/recordingEligibility.ts b/examples/egocap/frontend/src/recordingEligibility.ts index b07a1e4afa..b24700fa35 100644 --- a/examples/egocap/frontend/src/recordingEligibility.ts +++ b/examples/egocap/frontend/src/recordingEligibility.ts @@ -13,7 +13,7 @@ import type { RecordingPhase } from "./recordingUiReducer"; import { sentence } from "./sentence"; import type { RecordingActions, RecordingSnapshot } from "./recordingTypes"; -export type RecordingActionKind = "startEpisode" | "stopEpisode" | "discardEpisode" | "taskEdit" | "newBatch"; +export type RecordingActionKind = "startEpisode" | "stopEpisode" | "discardEpisode" | "taskEdit" | "newBatch" | "resolvePending"; export interface Eligibility { allowed: boolean; @@ -38,12 +38,20 @@ const BUSY_KIND: Partial> = { discarding: "discardEpisode", savingTask: "taskEdit", restarting: "newBatch", + recovering: "resolvePending", + discardingPending: "resolvePending", }; +/** Why nothing can be sent before an operator name is entered. */ +export const NO_OPERATOR_REASON = "Enter an operator name before using recording controls"; + +/** Why nothing can be sent before the control token is entered. */ +export const NO_CONTROL_TOKEN_REASON = "Enter the recording control token before using recording controls"; + /** Computes every action's current eligibility from the real snapshot, the * actually-supplied handler props, and the recording interaction phase -- * any phase other than idle/recording means one command is already in - * flight and blocks the four take-level actions. New batch is stricter: it + * flight and blocks every other action. New batch is stricter: it * is only available while actually idle (not even while recording). */ export function computeEligibility( snapshot: RecordingSnapshot | null, @@ -68,7 +76,7 @@ export function computeEligibility( if (!connected) return blocked("Recording backend not connected yet"); if (actions.onStartEpisode === undefined) return blocked("Start is not available yet"); // The more specific reason first: while an episode is active, "already active" is the true one. - if (episodePhase === "RECOVERY_REQUIRED") return blocked("A take was interrupted -- use New batch to clear it"); + if (episodePhase === "RECOVERY_REQUIRED") return blocked("A take was interrupted -- recover or discard it first"); if (episodePhase !== "IDLE") return blocked("An episode is already active"); if (snapshot.taskText === null || snapshot.taskText.trim() === "") return blocked("Set a task first"); // The backend's own reason (station setup, a stale source) when it gave one. @@ -87,8 +95,8 @@ export function computeEligibility( if (actions.onDiscardEpisode === undefined) return blocked("Discard is not available yet"); // Only the stable RECORDING state is a safe, well-defined point for an // operator-triggered discard; STARTING/STOPPING/FINALIZING are already - // backend-owned transitions in flight, and RECOVERY_REQUIRED is - // cleared by New batch, not by this control. + // backend-owned transitions in flight, and an interrupted take + // (RECOVERY_REQUIRED) is resolved by resolvePending below, which asks first. if (episodePhase !== "RECORDING") return blocked("No active episode to discard"); if (snapshot.currentEpisodeId === null) return blocked("No active episode to discard"); return eligible(); @@ -102,6 +110,14 @@ export function computeEligibility( if (episodePhase === "RECORDING") return blocked("Cannot edit task while recording"); return eligible(); }), + // Recover and Discard of a pending take, of the open session or of an earlier one. + resolvePending: result("resolvePending", () => { + if (!connected) return blocked("Recording backend not connected yet"); + if (actions.onRecoverPending === undefined || actions.onDiscardPending === undefined) return blocked("Recover and Discard are not available yet"); + // The backend refuses both while a take is being recorded or finished. + if (episodePhase !== "IDLE" && episodePhase !== "RECOVERY_REQUIRED") return blocked("Finish the take being recorded first"); + return eligible(); + }), // Deliberately NOT routed through result()'s busy check -- new batch is // unavailable while actually recording too (a take must be stopped or // discarded first, never implicitly), not just while another command @@ -116,3 +132,17 @@ export function computeEligibility( })(), }; } + +/** `eligibility` as this browser may use it: nothing is sent without an operator name and the control token, + * whatever the snapshot allows. The backend enforces both itself; this only keeps the page from sending a command + * it knows will be refused, for buttons and keyboard shortcuts alike. */ +export function withOperatorGate( + eligibility: Record, + operatorToken: string | null, + controlToken: string | null, +): Record { + const missing = operatorToken === null ? NO_OPERATOR_REASON : controlToken === null ? NO_CONTROL_TOKEN_REASON : null; + if (missing === null) return eligibility; + const kinds = Object.keys(eligibility) as RecordingActionKind[]; + return Object.fromEntries(kinds.map((kind) => [kind, blocked(missing)])) as Record; +} diff --git a/examples/egocap/frontend/src/recordingSnapshotParser.test.ts b/examples/egocap/frontend/src/recordingSnapshotParser.test.ts new file mode 100644 index 0000000000..9188a9cc6f --- /dev/null +++ b/examples/egocap/frontend/src/recordingSnapshotParser.test.ts @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * The recording snapshot as the page reads it: every outcome the backend sends, the pending takes, and above all + * what happens to a report the page does not understand. Nothing but an agreeing "kept" may come out as kept. + */ +import { describe, expect, it } from "vitest"; +import { parseRecordingSnapshot } from "./recordingSnapshotParser"; +import { + CAMERA_SLOW, + CAMERA_STOPPED, + DROP_WARNINGS, + HEADSET_FROZEN, + INTEGRITY_FAILED, + INTEGRITY_KEPT, + INTEGRITY_NOTE, + MISPLACED, + MISPLACED_NOTE, + NOT_KNOWN_YET, + ONLY_DISCARD, + SESSION, + wirePendingTake, + wireResult, + wireSnapshot, +} from "./recordingTestDoubles"; + +/** The parsed result of a snapshot whose last result is `result`. */ +function lastResultOf(result: Record) { + const snapshot = parseRecordingSnapshot(wireSnapshot({ last_result: result })); + if (snapshot === null || snapshot.lastResult === null) throw new Error("the snapshot or its last result did not parse"); + return snapshot.lastResult; +} + +describe("the recording snapshot's take result", () => { + it("reads a kept take with its decision, its warnings and where its data is", () => { + expect(lastResultOf(wireResult({ warnings: DROP_WARNINGS }))).toEqual({ + episodeId: `${SESSION}/episode_1`, + outcome: "kept", + reportedAs: "kept", + qcDecision: "PASSED", + reasons: [], + warnings: DROP_WARNINGS, + location: `${SESSION}/episode_1`, + issues: [], + durationMs: 2000, + }); + }); + + it.each([ + ["flagged", { disposition: "KEPT", qc_decision: "FLAGGED_BAD", reasons: [HEADSET_FROZEN] }], + ["quarantined", { disposition: "QUARANTINED", qc_decision: "FLAGGED_BAD", reasons: [HEADSET_FROZEN], location: `_quarantine/${SESSION}/episode_1` }], + ["rejected", { disposition: "REJECTED", qc_decision: "REJECTED_CAMERA", reasons: [CAMERA_SLOW], media_removed: true, location: null }], + ["rejected_data_kept", { disposition: "REJECTED", qc_decision: "SKIPPED", reasons: [INTEGRITY_FAILED], location: `${SESSION}/episode_1.pending` }], + ["discarded", { disposition: "DISCARDED", qc_decision: null, media_removed: true, location: null, duration_ms: 0 }], + ["interrupted", { disposition: "RECOVERY_REQUIRED", qc_decision: null, reasons: [CAMERA_STOPPED], issues: [CAMERA_STOPPED], location: `${SESSION}/episode_1.pending` }], + ] as const)("reads a %s take as that outcome, with the backend's sentences untouched", (outcome, fields) => { + const result = lastResultOf(wireResult({ outcome, ...fields })); + expect(result.outcome).toBe(outcome); + expect(result.reportedAs).toBe(outcome); + expect(result.reasons).toEqual("reasons" in fields ? fields.reasons : []); + expect(result.location).toBe("location" in fields ? fields.location : `${SESSION}/episode_1`); + }); + + it("reads a kept take the checks did not look at as kept, with the decision that says so", () => { + expect(lastResultOf(wireResult({ qc_decision: "SKIPPED" }))).toMatchObject({ outcome: "kept", qcDecision: "SKIPPED" }); + expect(lastResultOf(wireResult({ qc_decision: null }))).toMatchObject({ outcome: "kept", qcDecision: null }); + }); + + it("shows an outcome word it does not know as unknown with that word, and keeps the rest of the snapshot", () => { + const snapshot = parseRecordingSnapshot(wireSnapshot({ saved_count: 3, last_result: wireResult({ outcome: "archived" }) })); + expect(snapshot?.savedCount).toBe(3); + expect(snapshot?.lastResult).toMatchObject({ outcome: "unknown", reportedAs: "archived" }); + }); + + it("shows a disposition it does not know as unknown, never as the outcome sent with it", () => { + expect(lastResultOf(wireResult({ disposition: "ARCHIVED" }))).toMatchObject({ outcome: "unknown", reportedAs: "kept (disposition ARCHIVED)" }); + }); + + it("shows a result without an outcome word as unknown with its disposition: a disposition alone does not say the take passed", () => { + const { outcome: _none, qc_decision: _noDecision, reasons: _noReasons, warnings: _noWarnings, media_removed: _unsaid, location: _nowhere, ...older } = wireResult(); + expect(lastResultOf(older)).toEqual({ + episodeId: `${SESSION}/episode_1`, + outcome: "unknown", + reportedAs: "KEPT", + qcDecision: null, + reasons: [], + warnings: [], + location: null, + issues: [], + durationMs: 2000, + }); + }); + + it.each([ + ["the recorder rejected it", { disposition: "REJECTED" }, "kept (disposition REJECTED)"], + ["the recorder left it pending", { disposition: "RECOVERY_REQUIRED" }, "kept (disposition RECOVERY_REQUIRED)"], + ["its media was removed", { media_removed: true }, "kept (media removed: true)"], + ["it does not say whether its media was removed", { media_removed: undefined }, "kept (media removed: missing)"], + ["the checks marked it bad", { qc_decision: "FLAGGED_BAD" }, "kept (decision FLAGGED_BAD)"], + ["the checks rejected its camera", { qc_decision: "REJECTED_CAMERA" }, "kept (decision REJECTED_CAMERA)"], + ["a check could not run", { qc_decision: "ERROR" }, "kept (decision ERROR)"], + ["it carries no decision field", { qc_decision: undefined }, "kept (decision missing)"], + ["the disposition is missing", { disposition: undefined }, "kept (disposition missing)"], + ])("never shows a take as kept when %s", (_why, fields, reportedAs) => { + expect(lastResultOf(wireResult(fields))).toMatchObject({ outcome: "unknown", reportedAs }); + }); + + it("shows a known outcome whose own facts disagree with it as unknown", () => { + expect(lastResultOf(wireResult({ outcome: "rejected", disposition: "REJECTED", qc_decision: "REJECTED_CAMERA", media_removed: false }))).toMatchObject({ + outcome: "unknown", + reportedAs: "rejected (media removed: false)", + }); + expect(lastResultOf(wireResult({ outcome: "quarantined", disposition: "KEPT", qc_decision: "FLAGGED_BAD" }))).toMatchObject({ + outcome: "unknown", + reportedAs: "quarantined (disposition KEPT)", + }); + }); + + it("shows a result with nothing readable about its outcome as unknown, saying so", () => { + expect(lastResultOf({ episode_id: "e", issues: [], duration_ms: 0, outcome: 7, disposition: null })).toMatchObject({ outcome: "unknown", reportedAs: "nothing readable" }); + }); + + it("drops reasons or warnings of the wrong shape rather than the snapshot", () => { + expect(lastResultOf(wireResult({ reasons: "slow camera", warnings: [1, 2] }))).toMatchObject({ outcome: "kept", reasons: [], warnings: [] }); + }); + + it.each([ + ["no episode id", { episode_id: undefined }], + ["a duration that is not a count", { duration_ms: -1 }], + ["notes that are not a list of sentences", { issues: "none" }], + ])("refuses the whole snapshot when the result has %s", (_what, fields) => { + expect(parseRecordingSnapshot(wireSnapshot({ last_result: wireResult(fields) }))).toBeNull(); + expect(parseRecordingSnapshot(wireSnapshot({ last_result: "KEPT" }))).toBeNull(); + }); +}); + +describe("the recording snapshot's counts and pending takes", () => { + it("reads the four counts of the batch", () => { + const snapshot = parseRecordingSnapshot(wireSnapshot({ saved_count: 5, flagged_count: 1, quarantined_count: 2, rejected_count: 3 })); + expect(snapshot).toMatchObject({ savedCount: 5, flaggedCount: 1, quarantinedCount: 2, rejectedCount: 3 }); + }); + + it("reads a snapshot without the new fields: no count beyond the saved one, and no pending take", () => { + const { flagged_count: _f, quarantined_count: _q, rejected_count: _r, pending_takes: _p, ...older } = wireSnapshot({ saved_count: 2 }); + expect(parseRecordingSnapshot(older)).toMatchObject({ savedCount: 2, flaggedCount: 0, quarantinedCount: 0, rejectedCount: 0, pendingTakes: [] }); + }); + + it("reads each pending take with why it waits and what Recover would do", () => { + const snapshot = parseRecordingSnapshot(wireSnapshot({ episode_phase: "RECOVERY_REQUIRED", ready_to_record: false, pending_takes: [wirePendingTake()] })); + expect(snapshot?.pendingTakes).toEqual([ + { + episodeId: `${SESSION}/episode_1`, + sessionId: SESSION, + index: 1, + phase: "WRITING", + recoverable: false, + recoverableKnown: true, + discardable: true, + current: true, + reason: CAMERA_STOPPED, + recoverNote: ONLY_DISCARD, + task: "Pour water.", + operator: "alex", + durationMs: 0, + unreadable: null, + }, + ]); + }); + + it("reads a take the integrity check rejected with its data kept: it holds nothing and only Discard is offered", () => { + const rejected = wirePendingTake({ phase: "REJECTED", current: false, reason: INTEGRITY_KEPT, recover_note: INTEGRITY_NOTE, duration_ms: 2000 }); + expect(parseRecordingSnapshot(wireSnapshot({ pending_takes: [rejected] }))?.pendingTakes[0]).toMatchObject({ + phase: "REJECTED", + current: false, + recoverable: false, + discardable: true, + recoverNote: INTEGRITY_NOTE, + unreadable: null, + }); + }); + + it("reads a complete take whose recovery is not known yet as exactly that, not as one that cannot be recovered", () => { + const waiting = wirePendingTake({ phase: "CHECKED", current: false, recoverable_known: false, recover_note: NOT_KNOWN_YET }); + expect(parseRecordingSnapshot(wireSnapshot({ pending_takes: [waiting] }))?.pendingTakes[0]).toMatchObject({ recoverable: false, recoverableKnown: false, discardable: true, unreadable: null }); + }); + + it("reads a record found in a folder it was not written for: neither command is offered", () => { + const misplaced = wirePendingTake({ episode_id: `${SESSION}_copy/episode_1`, session_id: `${SESSION}_copy`, current: false, discardable: false, reason: MISPLACED, recover_note: MISPLACED_NOTE }); + expect(parseRecordingSnapshot(wireSnapshot({ pending_takes: [misplaced] }))?.pendingTakes[0]).toMatchObject({ recoverable: false, discardable: false, reason: MISPLACED, unreadable: null }); + }); + + it.each([ + ["a phase it has never seen", { phase: "VERIFIED" }, "phase VERIFIED"], + ["no phase", { phase: undefined }, "phase missing"], + ["no word on whether its recovery is known", { recoverable_known: undefined }, "recoverable_known missing"], + ["no word on whether it may be discarded", { discardable: undefined }, "discardable missing"], + ["a recoverable that is not yes or no", { recoverable: "yes" }, "recoverable yes"], + ["no note of what Recover would do", { recover_note: null }, "recover_note null"], + ["several things wrong at once", { phase: "VERIFIED", discardable: undefined }, "phase VERIFIED, discardable missing"], + ])("keeps the panel when a waiting take has %s: that one row is marked unreadable and offers nothing", (_what, fields, unreadable) => { + // The row would otherwise offer both commands; next to it is a row that is fine. + const broken = wirePendingTake({ phase: "SEALED", recoverable: true, ...fields }); + const fine = wirePendingTake({ episode_id: `${SESSION}/episode_2`, index: 2, current: false }); + const snapshot = parseRecordingSnapshot(wireSnapshot({ saved_count: 4, last_result: wireResult(), pending_takes: [broken, fine] })); + expect(snapshot).toMatchObject({ savedCount: 4, lastResult: { outcome: "kept" } }); + expect(snapshot?.pendingTakes[0]).toMatchObject({ episodeId: `${SESSION}/episode_1`, recoverable: false, discardable: false, unreadable }); + expect(snapshot?.pendingTakes[1]).toMatchObject({ episodeId: `${SESSION}/episode_2`, discardable: true, unreadable: null }); + }); + + it("keeps a row it could not read at all, so the operator sees that something waits", () => { + const snapshot = parseRecordingSnapshot(wireSnapshot({ pending_takes: ["session_x/episode_0", wirePendingTake({ episode_id: undefined })] })); + expect(snapshot?.pendingTakes.map((take) => [take.episodeId, take.unreadable, take.recoverable, take.discardable])).toEqual([ + ["", "not a take record", false, false], + ["", "episode_id missing", false, false], + ]); + }); + + it("shows one unreadable row for a list of waiting takes that is not a list, and keeps the rest of the snapshot", () => { + const snapshot = parseRecordingSnapshot(wireSnapshot({ saved_count: 2, pending_takes: { count: 1 } })); + expect(snapshot?.savedCount).toBe(2); + expect(snapshot?.pendingTakes).toMatchObject([{ episodeId: "", unreadable: "the list of waiting takes is not a list", discardable: false }]); + }); + + it.each([ + ["a count that is not a number", { flagged_count: "1" }], + ["a negative count", { rejected_count: -1 }], + ])("refuses a snapshot with %s", (_what, fields) => { + expect(parseRecordingSnapshot(wireSnapshot(fields))).toBeNull(); + }); +}); diff --git a/examples/egocap/frontend/src/recordingSnapshotParser.ts b/examples/egocap/frontend/src/recordingSnapshotParser.ts new file mode 100644 index 0000000000..f8dcb63c0c --- /dev/null +++ b/examples/egocap/frontend/src/recordingSnapshotParser.ts @@ -0,0 +1,248 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * Reads the backend's recording snapshot (`backend/egocap_web/recording_command.py`) into the page's typed + * `RecordingSnapshot`. It is the backend's own data, but still untrusted input to this browser: a field of the + * wrong shape must never reach render. + * + * Three rules, one for each way a snapshot can be wrong: + * + * - A snapshot whose structure is broken is refused whole (null), and the page keeps what it had. + * - A take's result whose words this page does not know, or whose words contradict each other, is kept and shown + * as `unknown` with the backend's own word. Dropping the snapshot there would leave the previous take's + * outcome on screen, which can read as "kept" for a take that was not. + * - A waiting take with a value this page does not know, or without a field it expects, costs that one row its + * buttons, never the panel: the row is kept, marked unreadable with what was wrong, and offers nothing. + */ + +import type { EpisodeResultSummary, PendingPhase, PendingTake, RecordingSnapshot, TakeOutcome } from "./recordingTypes"; + +/** Thrown by the field checks below; never escapes `parseRecordingSnapshot`. */ +class InvalidRecordingSnapshot extends Error {} + +/** Raises unless `value` is a string. */ +function requireString(value: unknown): string { + if (typeof value !== "string") throw new InvalidRecordingSnapshot(); + return value; +} + +/** Raises unless `value` is a string or null. */ +function requireNullableString(value: unknown): string | null { + return value === null ? null : requireString(value); +} + +/** Raises unless `value` is one of `allowed`'s members. */ +function requireEnum(value: unknown, allowed: ReadonlySet): T { + if (typeof value !== "string" || !allowed.has(value as T)) throw new InvalidRecordingSnapshot(); + return value as T; +} + +/** Raises unless `value` is a nonnegative safe integer. */ +function requireNonNegativeSafeInt(value: unknown): number { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new InvalidRecordingSnapshot(); + return value; +} + +/** Raises unless `value` is a boolean. */ +function requireBoolean(value: unknown): boolean { + if (typeof value !== "boolean") throw new InvalidRecordingSnapshot(); + return value; +} + +/** Raises unless `value` is a nonnegative safe integer or null. */ +function requireNullableNonNegativeSafeInt(value: unknown): number | null { + if (value === null) return null; + return requireNonNegativeSafeInt(value); +} + +/** Raises unless `value` is an array of strings. */ +function requireStrings(value: unknown): string[] { + if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) throw new InvalidRecordingSnapshot(); + return value; +} + +/** A count a backend that predates it does not send: none, rather than dropping the snapshot. */ +function countOrZero(value: unknown): number { + return value === undefined ? 0 : requireNonNegativeSafeInt(value); +} + +/** The sentences of a list the backend sent, or none when it sent no such list or one of another shape. */ +function sentences(value: unknown): string[] { + return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : []; +} + +const EPISODE_PHASES = new Set([ + "IDLE", + "STARTING", + "RECORDING", + "STOPPING", + "FINALIZING", + "RECOVERY_REQUIRED", +]); + +/** What the backend sends with each outcome word: the recorder's disposition, and whether the take's media is + * gone. A result whose outcome disagrees with either is not one this page understands. */ +const OUTCOME_FACTS: Record = { + kept: { disposition: "KEPT", mediaRemoved: false }, + flagged: { disposition: "KEPT", mediaRemoved: false }, + quarantined: { disposition: "QUARANTINED", mediaRemoved: false }, + rejected: { disposition: "REJECTED", mediaRemoved: true }, + rejected_data_kept: { disposition: "REJECTED", mediaRemoved: false }, + discarded: { disposition: "DISCARDED", mediaRemoved: true }, + interrupted: { disposition: "RECOVERY_REQUIRED", mediaRemoved: false }, +}; + +/** What the capture checks can have decided about a kept take: it passed, or nothing was measured. */ +const KEPT_DECISIONS: ReadonlySet = new Set([null, "PASSED", "SKIPPED"]); + +/** A field's value as it is named in an `unknown` outcome's words. */ +function said(value: unknown): string { + return value === undefined ? "missing" : String(value); +} + +/** Whether `word` is one of the backend's outcome words. */ +function isOutcome(word: unknown): word is TakeOutcome { + return typeof word === "string" && Object.prototype.hasOwnProperty.call(OUTCOME_FACTS, word); +} + +/** What the page shows for the judgement fields of a take's result: the backend's outcome when every field + * agrees with it, else `unknown` with the backend's own words. Never raises: a result that cannot be vouched for + * is shown as such, not dropped. */ +function shownOutcome(r: Record): Pick { + const disposition = typeof r.disposition === "string" ? r.disposition : null; + const qcDecision = typeof r.qc_decision === "string" ? r.qc_decision : null; + const word = typeof r.outcome === "string" ? r.outcome : null; + // No outcome word: a backend that predates it, or a broken report. Its disposition alone does not say whether + // the checks marked the take bad, so it is not turned into an outcome here. + if (word === null) return { outcome: "unknown", reportedAs: disposition ?? "nothing readable", qcDecision }; + if (!isOutcome(word)) return { outcome: "unknown", reportedAs: word, qcDecision }; + const facts = OUTCOME_FACTS[word]; + const contradictions = [ + r.disposition !== facts.disposition && `disposition ${said(r.disposition)}`, + r.media_removed !== facts.mediaRemoved && `media removed: ${said(r.media_removed)}`, + // Only the claim of success is held to the checks' decision: a take they marked bad or rejected is not kept. + word === "kept" && !KEPT_DECISIONS.has(r.qc_decision) && `decision ${said(r.qc_decision)}`, + ].filter((found): found is string => typeof found === "string"); + if (contradictions.length > 0) return { outcome: "unknown", reportedAs: `${word} (${contradictions.join(", ")})`, qcDecision }; + return { outcome: word, reportedAs: word, qcDecision }; +} + +/** Raises unless `value` is null or an episode result with its structural fields in place; see the module + * comment for how its judgement fields are read. */ +function parseEpisodeResult(value: unknown): EpisodeResultSummary | null { + if (value === null) return null; + if (typeof value !== "object") throw new InvalidRecordingSnapshot(); + const r = value as Record; + return { + episodeId: requireString(r.episode_id), + ...shownOutcome(r), + reasons: sentences(r.reasons), + warnings: sentences(r.warnings), + location: typeof r.location === "string" ? r.location : null, + issues: requireStrings(r.issues), + // Frozen at the moment the take ended, so its length stays on screen after the live clock stops. + durationMs: requireNonNegativeSafeInt(r.duration_ms), + }; +} + +const PENDING_PHASES: ReadonlySet = new Set(["WRITING", "SEALED", "CHECKED", "REJECTED"]); + +/** A row for something in the list of waiting takes that is not a take record at all. */ +function unreadableTake(what: string): PendingTake { + return { + episodeId: "", + sessionId: "", + index: 0, + phase: null, + recoverable: false, + recoverableKnown: true, + discardable: false, + current: false, + reason: "", + recoverNote: "", + task: "", + operator: "", + durationMs: 0, + unreadable: what, + }; +} + +/** One waiting take. Never raises: see the module comment for what happens to a row that cannot be read whole. */ +function parsePendingTake(value: unknown): PendingTake { + if (typeof value !== "object" || value === null || Array.isArray(value)) return unreadableTake("not a take record"); + const r = value as Record; + // What was not as expected, each named with the backend's own word for it. + const unread: string[] = []; + /** The field's value when it is of the expected kind, else `fallback`, noting what was found. */ + const read = (key: string, expected: (found: unknown) => found is T, fallback: T): T => { + const found = r[key]; + if (expected(found)) return found; + unread.push(`${key} ${said(found)}`); + return fallback; + }; + const isText = (found: unknown): found is string => typeof found === "string"; + const isFlag = (found: unknown): found is boolean => typeof found === "boolean"; + const isCount = (found: unknown): found is number => typeof found === "number" && Number.isSafeInteger(found) && found >= 0; + const isPhase = (found: unknown): found is PendingPhase => typeof found === "string" && PENDING_PHASES.has(found); + const take = { + episodeId: read("episode_id", isText, ""), + sessionId: read("session_id", isText, ""), + index: read("index", isCount, 0), + phase: read("phase", isPhase, null), + recoverable: read("recoverable", isFlag, false), + recoverableKnown: read("recoverable_known", isFlag, true), + discardable: read("discardable", isFlag, false), + current: read("current", isFlag, false), + reason: read("reason", isText, ""), + recoverNote: read("recover_note", isText, ""), + task: read("task", isText, ""), + operator: read("operator", isText, ""), + durationMs: read("duration_ms", isCount, 0), + }; + if (unread.length === 0) return { ...take, unreadable: null }; + // Nothing is offered for a row the page cannot vouch for, least of all a discard, which cannot be undone. + return { ...take, recoverable: false, discardable: false, unreadable: unread.join(", ") }; +} + +/** The waiting takes: none for a backend that predates the list, and one unreadable row for a list of another + * shape, so the operator sees that something waits which this page cannot show. */ +function parsePendingTakes(value: unknown): PendingTake[] { + if (value === undefined) return []; + if (!Array.isArray(value)) return [unreadableTake("the list of waiting takes is not a list")]; + return value.map(parsePendingTake); +} + +/** Converts the backend's snake_case recording snapshot into a `RecordingSnapshot`, or null when its structure + * is broken. */ +export function parseRecordingSnapshot(raw: unknown): RecordingSnapshot | null { + if (typeof raw !== "object" || raw === null) return null; + const r = raw as Record; + try { + return { + batchId: requireString(r.batch_id), + episodePhase: requireEnum(r.episode_phase, EPISODE_PHASES), + currentEpisodeId: requireNullableString(r.current_episode_id), + currentEpisodeElapsedMs: requireNullableNonNegativeSafeInt(r.current_episode_elapsed_ms), + taskText: requireNullableString(r.task_text), + // Absent from a backend that predates task details: treat as none rather than dropping the snapshot. + taskDetails: r.task_details === undefined ? "" : requireString(r.task_details), + defaultOperator: requireNullableString(r.default_operator), + autoFillOperatorName: requireBoolean(r.auto_fill_operator_name), + savedCount: requireNonNegativeSafeInt(r.saved_count), + flaggedCount: countOrZero(r.flagged_count), + quarantinedCount: countOrZero(r.quarantined_count), + rejectedCount: countOrZero(r.rejected_count), + lastResult: parseEpisodeResult(r.last_result), + pendingTakes: parsePendingTakes(r.pending_takes), + readyToRecord: requireBoolean(r.ready_to_record), + // Absent from a backend that predates the reason: treat as none rather than dropping the snapshot. + notReadyReason: r.not_ready_reason === undefined ? null : requireNullableString(r.not_ready_reason), + revision: requireNonNegativeSafeInt(r.revision), + }; + } catch (err) { + if (err instanceof InvalidRecordingSnapshot) return null; + throw err; + } +} diff --git a/examples/egocap/frontend/src/recordingTestDoubles.ts b/examples/egocap/frontend/src/recordingTestDoubles.ts new file mode 100644 index 0000000000..86dffbc780 --- /dev/null +++ b/examples/egocap/frontend/src/recordingTestDoubles.ts @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** Recording snapshots, take results and pending takes for tests, worded as the backend words them. */ +import type { EpisodeResultSummary, PendingTake, RecordingSnapshot, ShownOutcome } from "./recordingTypes"; + +/** The session every fixture take belongs to. */ +export const SESSION = "session_20260309-081500_abc123"; + +/** A frozen headset stream, as the backend says it: the stream, what was measured against which limit, what to check. */ +export const HEADSET_FROZEN = "The headset did not move for 2.0 s (limit 1 s). Check that the headset and both controllers are on, charged and in view."; + +/** A frozen glove stream. */ +export const GLOVE_FROZEN = "The left glove did not move for 1.8 s (limit 1 s). Check the glove's battery and connection."; + +/** A camera below its minimum rate. */ +export const CAMERA_SLOW = + "Camera head_human_camera averaged 15.5 fps, below the minimum of 25.8 fps (0.86 of 30 fps). Check the camera's cable and the load on this PC, then record the take again."; + +/** A camera that recorded too few frames for the take's length, while its rate over its own frames was not what failed. */ +export const CAMERA_SHORT = + "Camera head_human_camera recorded 31 frames; a take of 3.0 s holds about 90. Check the camera's cable and the load on this PC, then record the take again."; + +/** Why Record is refused while the recorder cannot write to the recordings folder. The backend can also give it + * while a take is being recorded, and does not interrupt that take for it. */ +export const RECORDER_CANNOT_WRITE = + "The recorder has not been able to write to the recordings folder for a few seconds. Check the recordings disk; if this stays, finish any take in progress and restart the backend."; + +/** The recorder's note on a take during which it could not write for a while; a kept take can carry it. */ +export const WRITE_STALLED_NOTE = + "The recorder could not write to the recordings folder for a few seconds during this take. If another PC shares that folder, check there that the take was not treated as left behind."; + +/** A failed storage-integrity check. */ +export const INTEGRITY_FAILED = "The recorded data failed an integrity check: manus_glove: required source has no rows."; + +/** A capture source lost during a take. */ +export const CAMERA_STOPPED = "A capture source stopped while the take was recording: camera 'head_human_camera' is stale or has no sample yet."; + +/** Two warnings of a take with dropped frames. */ +export const DROP_WARNINGS = [ + "Camera head_human_camera dropped 29 frames within 2 s (29 in the whole take).", + "Camera head_human_camera averaged 15.5 fps, 48% below its declared 30 fps.", +]; + +/** What Recover would do to a take cut off while it was being written. */ +export const ONLY_DISCARD = "This take was cut off while it was being written, so it is incomplete. It can only be discarded."; + +/** What Recover would do to a sealed take. */ +export const RECOVER_RUNS_CHECKS = "Recover runs the checks on this take and finishes it."; + +/** What a complete take needs while other cameras or settings are accepted than the ones it was recorded with. */ +export const NEEDS_SAME_STATION = "This take can be finished once the station is set up as when it was recorded: the same cameras and settings."; + +/** What is said of a complete take while no camera has been accepted. */ +export const NOT_KNOWN_YET = "Whether this take can be finished is known once the cameras are connected."; + +/** Why a take the integrity check rejected waits, and what can be done with it. */ +export const INTEGRITY_KEPT = "This take failed its integrity check; its data was kept on disk."; +export const INTEGRITY_NOTE = "This take failed its integrity check and cannot be recovered. Discard removes its data."; + +/** Why a record found in a folder it was not written for is listed, and that nothing is done with it. */ +export const MISPLACED = "This take's record was written for another session: its folder was copied or renamed by hand."; +export const MISPLACED_NOTE = `Nothing is done with this take from this page. On the recordings disk, delete its folder if it is a copy, or give the folder back the name ${SESSION} if it was renamed.`; + +/** The fields of a result that differ by outcome, as the backend sends them. */ +const BY_OUTCOME: Record> = { + kept: { qcDecision: "PASSED" }, + flagged: { qcDecision: "FLAGGED_BAD", reasons: [HEADSET_FROZEN] }, + quarantined: { qcDecision: "FLAGGED_BAD", reasons: [HEADSET_FROZEN], location: `_quarantine/${SESSION}/episode_1` }, + rejected: { qcDecision: "REJECTED_CAMERA", reasons: [CAMERA_SLOW], warnings: DROP_WARNINGS, location: null }, + rejected_data_kept: { qcDecision: "SKIPPED", reasons: [INTEGRITY_FAILED], location: `${SESSION}/episode_1.pending` }, + discarded: { location: null, durationMs: 0 }, + interrupted: { reasons: [CAMERA_STOPPED], issues: [CAMERA_STOPPED], location: `${SESSION}/episode_1.pending`, durationMs: 1000 }, + unknown: { reportedAs: "archived" }, +}; + +/** The result of take 1 of the fixture session, ended as `outcome`. */ +export function takeResult(outcome: ShownOutcome, overrides: Partial = {}): EpisodeResultSummary { + return { + episodeId: `${SESSION}/episode_1`, + outcome, + reportedAs: outcome, + qcDecision: null, + reasons: [], + warnings: [], + location: `${SESSION}/episode_1`, + issues: [], + durationMs: 2000, + ...BY_OUTCOME[outcome], + ...overrides, + }; +} + +/** Take 1 of the fixture session, cut off while it was being written and holding Record. */ +export function pendingTake(overrides: Partial = {}): PendingTake { + return { + episodeId: `${SESSION}/episode_1`, + sessionId: SESSION, + index: 1, + phase: "WRITING", + recoverable: false, + recoverableKnown: true, + discardable: true, + current: true, + reason: CAMERA_STOPPED, + recoverNote: ONLY_DISCARD, + task: "Pour water.", + operator: "alex", + durationMs: 0, + unreadable: null, + ...overrides, + }; +} + +/** The same session's take 2, rejected by the integrity check with its data kept: it holds nothing. */ +export function rejectedDataTake(overrides: Partial = {}): PendingTake { + return pendingTake({ episodeId: `${SESSION}/episode_2`, index: 2, phase: "REJECTED", current: false, reason: INTEGRITY_KEPT, recoverNote: INTEGRITY_NOTE, durationMs: 2000, ...overrides }); +} + +/** A record found in a session folder that was copied by hand: neither command is offered for it. */ +export function misplacedTake(overrides: Partial = {}): PendingTake { + const sessionId = `${SESSION}_copy`; + return pendingTake({ episodeId: `${sessionId}/episode_1`, sessionId, current: false, discardable: false, reason: MISPLACED, recoverNote: MISPLACED_NOTE, ...overrides }); +} + +/** A take an earlier session left behind: sealed, so it can be recovered, and holding nothing. */ +export function earlierTake(overrides: Partial = {}): PendingTake { + const sessionId = "session_20260308-170200_def456"; + return pendingTake({ + episodeId: `${sessionId}/episode_7`, + sessionId, + index: 7, + phase: "SEALED", + recoverable: true, + current: false, + reason: "Finishing the take failed part-way; see the backend log.", + recoverNote: RECOVER_RUNS_CHECKS, + durationMs: 12_000, + ...overrides, + }); +} + +/** An idle batch with a task set and nothing recorded. */ +export function recordingSnapshot(overrides: Partial = {}): RecordingSnapshot { + return { + batchId: "b1", + episodePhase: "IDLE", + currentEpisodeId: null, + currentEpisodeElapsedMs: null, + taskText: "Pour water.", + taskDetails: "", + defaultOperator: null, + autoFillOperatorName: false, + savedCount: 0, + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, + lastResult: null, + pendingTakes: [], + readyToRecord: true, + notReadyReason: null, + revision: 1, + ...overrides, + }; +} + +/** A snapshot holding an interrupted take of the open session: Record is held until it is resolved. */ +export function heldSnapshot(take: PendingTake = pendingTake(), overrides: Partial = {}): RecordingSnapshot { + return recordingSnapshot({ + episodePhase: "RECOVERY_REQUIRED", + readyToRecord: false, + lastResult: takeResult("interrupted", { episodeId: take.episodeId }), + pendingTakes: [take], + ...overrides, + }); +} + +/** The backend's own shape of one take's result (`backend/egocap_web/take_outcome.py`): a kept take. */ +export function wireResult(overrides: Record = {}): Record { + return { + episode_id: `${SESSION}/episode_1`, + disposition: "KEPT", + outcome: "kept", + qc_decision: "PASSED", + reasons: [], + warnings: [], + media_removed: false, + location: `${SESSION}/episode_1`, + issues: [], + duration_ms: 2000, + ...overrides, + }; +} + +/** The backend's own shape of one pending take. */ +export function wirePendingTake(overrides: Record = {}): Record { + return { + episode_id: `${SESSION}/episode_1`, + session_id: SESSION, + index: 1, + phase: "WRITING", + recoverable: false, + recoverable_known: true, + discardable: true, + current: true, + reason: CAMERA_STOPPED, + recover_note: ONLY_DISCARD, + task: "Pour water.", + operator: "alex", + duration_ms: 0, + ...overrides, + }; +} + +/** The backend's own shape of a recording snapshot (`backend/egocap_web/recording_command.py`). */ +export function wireSnapshot(overrides: Record = {}): Record { + return { + batch_id: "b1", + episode_phase: "IDLE", + current_episode_id: null, + current_episode_elapsed_ms: null, + task_text: "Pour water.", + task_details: "", + default_operator: null, + auto_fill_operator_name: false, + saved_count: 0, + flagged_count: 0, + quarantined_count: 0, + rejected_count: 0, + last_result: null, + pending_takes: [], + ready_to_record: true, + not_ready_reason: null, + revision: 1, + ...overrides, + }; +} diff --git a/examples/egocap/frontend/src/recordingTypes.ts b/examples/egocap/frontend/src/recordingTypes.ts index 6b477be909..1fd8cce8ae 100644 --- a/examples/egocap/frontend/src/recordingTypes.ts +++ b/examples/egocap/frontend/src/recordingTypes.ts @@ -29,8 +29,15 @@ export type RecordingEpisodePhase = | "FINALIZING" | "RECOVERY_REQUIRED"; -/** The real disposition of a finished episode, once a backend reports one. */ -export type EpisodeDisposition = "KEPT" | "REJECTED" | "DISCARDED"; +/** What became of a take, in the backend's own outcome words (`backend/egocap_web/take_outcome.py`): + * `flagged` and `quarantined` were both marked bad by the capture checks, the first left with its session and the + * second set apart; `rejected` lost its media, `rejected_data_kept` did not; `interrupted` waits to be recovered + * or discarded. */ +export type TakeOutcome = "kept" | "flagged" | "quarantined" | "rejected" | "rejected_data_kept" | "discarded" | "interrupted"; + +/** A take's outcome as the page shows it: one the backend named, or `unknown` when its report is not one this + * page can vouch for. Nothing but a report that says `kept` and agrees with itself is ever shown as kept. */ +export type ShownOutcome = TakeOutcome | "unknown"; /** Identifies one backend recording batch -- distinct from the preview * page's own capture session ID, which is a different resource entirely. */ @@ -45,10 +52,25 @@ export interface RecordingEpisodeIdentity { episodeId: string; } -/** The outcome of the most recently finished episode, for result presentation. */ +/** What became of the take that last ended, or of the pending take that was last recovered or discarded. Every + * sentence in it was composed by the backend and is shown as it arrived. */ export interface EpisodeResultSummary { + /** `/episode_`: the same id a pending take of `pendingTakes` carries. */ episodeId: string; - disposition: EpisodeDisposition; + /** What to show. */ + outcome: ShownOutcome; + /** The backend's own words for the outcome, shown as they came when `outcome` is `unknown`. */ + reportedAs: string; + /** What the capture checks decided, as sent (`PASSED`, `SKIPPED`, ...); null when nothing was decided. */ + qcDecision: string | null; + /** The findings that decided the outcome, one sentence each: which stream, what was measured against which + * limit, what to check. Empty for a kept or discarded take. */ + reasons: readonly string[]; + /** Findings that never decide, one sentence each. */ + warnings: readonly string[]; + /** Where the take's data is, relative to the recording output; null once its media is gone. Never a full path. */ + location: string | null; + /** The recorder's own notes on the take, as fixed sentences; usually none. */ issues: readonly string[]; /** This episode's final duration (ms), frozen at the moment it ended -- * so a just-finished take's duration stays visible/accounted for @@ -58,6 +80,49 @@ export interface EpisodeResultSummary { durationMs: number; } +/** How far a waiting take got, in the backend's words: cut off while it was being written; written but not judged; + * judged but not finished; rejected by the integrity check with its data kept on disk. */ +export type PendingPhase = "WRITING" | "SEALED" | "CHECKED" | "REJECTED"; + +/** A take that waits for the operator: the unresolved one of the session open for recording, which holds Record; + * one the integrity check rejected whose data is still on disk; or what an earlier session of this station left + * behind, which can also be a record found in a folder it was not written for. Only the first holds Record. */ +export interface PendingTake { + /** `/episode_`: the id both commands take. For a record found in a folder it was not written + * for, that folder's name. "" for a row this page could not read at all. */ + episodeId: string; + /** The session the take was recorded in. */ + sessionId: string; + /** The take's index in its session. */ + index: number; + /** How far it got; null for a row this page could not read. */ + phase: PendingPhase | null; + /** Whether Recover is offered. It can change with no command, once the cameras the take was recorded with are + * accepted again. */ + recoverable: boolean; + /** False while no camera has been accepted: the take's settings cannot be compared with anything yet, so + * `recoverable`, false then, is not a finding and nothing is said either way beyond the backend's note. */ + recoverableKnown: boolean; + /** Whether Discard is offered. False for a record nothing may act on from the page. */ + discardable: boolean; + /** True for the take of the open session, which holds Record until it is resolved. */ + current: boolean; + /** Why the take waits, in one backend sentence. */ + reason: string; + /** What Recover would do, or why it is not offered, in the backend's words. For a take the camera check + * rejected, Recover removes its media, so this is shown beside the buttons. */ + recoverNote: string; + /** The task the take was recorded for. */ + task: string; + /** The operator who recorded it. */ + operator: string; + /** Its recorded length; 0 for a take cut off while it was being written, whose length is not known. */ + durationMs: number; + /** What this page could not read of the row, in the backend's own words; null for a row it read whole. A row + * it could not read is shown as such, and neither command is offered for it. */ + unreadable: string | null; +} + /** Longest task details the backend accepts (it rejects anything longer). */ export const MAX_TASK_DETAILS_CHARS = 1000; @@ -99,8 +164,20 @@ export interface RecordingSnapshot { * all -- off by default (station YAML's auto_fill_operator_name). Even when true, * this never means auto-commit: the operator still has to press "Set operator". */ autoFillOperatorName: boolean; + /** Good takes of this batch: those the checks kept. A take marked bad or rejected is counted below instead. */ savedCount: number; + /** Takes of this batch the checks marked bad and left with their session. */ + flaggedCount: number; + /** Takes of this batch the checks marked bad and set apart in quarantine. */ + quarantinedCount: number; + /** Takes of this batch that were rejected, with their media removed or their data kept. */ + rejectedCount: number; + /** What became of the take that last ended or was last resolved; null in a batch with none yet. */ lastResult: EpisodeResultSummary | null; + /** Every take that waits for the operator: first the open session's unresolved one, then its takes the + * integrity check rejected with their data kept, then what earlier sessions of this station left behind, which + * can be many and of any day. */ + pendingTakes: readonly PendingTake[]; /** Whether the backend would currently ADMIT a start_episode command * (no episode already active and a task is set) -- not a real observed * device/capture-source readiness signal. */ @@ -119,7 +196,14 @@ export interface RecordingSnapshot { * _PAYLOAD_VALIDATORS exactly. Kept narrow rather than a bare string so a typo is a compile * error. No `open_session`/`close_session` here -- this component never * opens or closes anything, it only rotates to a fresh batch. */ -export type RecordingActionName = "set_task" | "start_episode" | "stop_episode" | "discard_episode" | "new_batch"; +export type RecordingActionName = + | "set_task" + | "start_episode" + | "stop_episode" + | "discard_episode" + | "new_batch" + | "recover_pending" + | "discard_pending"; /** The real, awaited result of one recording command: the backend's own * handler accepted it ("ok") or rejected it with a real, specific reason @@ -146,4 +230,9 @@ export interface RecordingActions { onStopEpisode?: (target: RecordingEpisodeIdentity) => Promise; onDiscardEpisode?: (target: RecordingEpisodeIdentity) => Promise; onNewBatch?: (target: RecordingBatchIdentity) => Promise; + /** Finishes a pending take: runs its checks if they did not run, then keeps, quarantines, rejects or closes it + * as they decide. "ok" means the step ran; what became of the take is the next snapshot's `lastResult`. */ + onRecoverPending?: (target: RecordingEpisodeIdentity) => Promise; + /** Removes a pending take's unfinished data for good. Callers ask the operator first. */ + onDiscardPending?: (target: RecordingEpisodeIdentity) => Promise; } diff --git a/examples/egocap/frontend/src/recordingUiReducer.ts b/examples/egocap/frontend/src/recordingUiReducer.ts index 5bf1640b3b..b28ba392fa 100644 --- a/examples/egocap/frontend/src/recordingUiReducer.ts +++ b/examples/egocap/frontend/src/recordingUiReducer.ts @@ -5,7 +5,7 @@ /** * The recording interaction state machine: idle -> starting -> recording -> * stopping -> idle (plus discarding/editingTask/savingTask/restarting/ - * uncertain). This is the one place that turns a user action, a command's + * recovering/discardingPending/uncertain). This is the one place that turns a user action, a command's * real success/rejection/unknown outcome, and an observed backend snapshot * into "what phase are we presenting right now" -- it owns no copy of * backend facts (batch id, task text, saved count, elapsed basis, results @@ -24,6 +24,9 @@ export type RecordingPhase = | "editingTask" | "savingTask" | "restarting" + // Resolving a pending take: finishing it, or removing its unfinished data. + | "recovering" + | "discardingPending" // A command's real outcome is genuinely unknown (timeout/disconnect, // not a resolved reply) -- the backend may have actually applied it. // Every action stays blocked until an actual observed snapshot @@ -31,7 +34,7 @@ export type RecordingPhase = | "uncertain"; /** The phases entered only while awaiting one command's own real reply. */ -export type CommandPhase = "starting" | "stopping" | "discarding" | "savingTask" | "restarting"; +export type CommandPhase = "starting" | "stopping" | "discarding" | "savingTask" | "restarting" | "recovering" | "discardingPending"; /** The stable phase (idle/recording) considered "not busy" -- every other * phase blocks starting a different take-level command. */ @@ -45,6 +48,9 @@ const SUCCESS_TARGET: Record = { discarding: "idle", savingTask: "idle", restarting: "idle", + // Whatever became of the pending take, no take is being recorded afterwards. + recovering: "idle", + discardingPending: "idle", }; export interface RecordingUiState { diff --git a/examples/egocap/frontend/src/recordingWire.ts b/examples/egocap/frontend/src/recordingWire.ts index ce329e374e..d6804d5507 100644 --- a/examples/egocap/frontend/src/recordingWire.ts +++ b/examples/egocap/frontend/src/recordingWire.ts @@ -22,7 +22,9 @@ export function batchTargetPayload(target: RecordingBatchIdentity): Record { return { batch_id: target.batchId, episode_id: target.episodeId }; } diff --git a/examples/egocap/frontend/src/settingsApi.ts b/examples/egocap/frontend/src/settingsApi.ts index ba977222fa..88dc52ede9 100644 --- a/examples/egocap/frontend/src/settingsApi.ts +++ b/examples/egocap/frontend/src/settingsApi.ts @@ -16,6 +16,58 @@ export interface CameraSelectionSetting { type: string; } +/** The thresholds takes are judged by after they stop, as far as the page shows them. The backend sends the + * whole documented defaults file's shape; a value it leaves out is shown as a dash. */ +export interface CaptureCheckThresholds { + /** The checks that reject a take or mark it bad. */ + guardrails?: { + /** False: no capture check runs and every take is kept unjudged. */ + enabled?: boolean; + /** True: a take marked bad is set aside in the quarantine folder; false: it stays with its session, flagged. */ + quarantine?: boolean; + /** Whether a camera below its minimum rate rejects the take and removes its media. */ + camera_min_fps_enabled?: boolean; + /** The minimum, as a fraction of each camera's expected rate. */ + camera_min_fps_ratio?: number; + /** Whether a pose stream that stops changing marks the take bad. */ + freeze_enabled?: boolean; + /** How long a pose stream may go unchanged, in seconds. */ + freeze_seconds?: number; + /** Whether the glove streams are judged and required. */ + gloves_expected?: boolean; + /** How long a tracking source may send no data, in seconds. */ + tracking_gap_seconds?: number; + /** Whether such a gap marks the take bad, or only warns. */ + tracking_gap_marks_bad?: boolean; + }; + /** The limits on a take's length. */ + duration?: { + /** The shortest and longest take, in seconds. */ + default?: { min_duration_s?: number; max_duration_s?: number }; + /** Whether a take outside them is marked bad, or only warned about. */ + marks_bad?: boolean; + }; +} + +/** `quality_checks` of `GET /api/settings`: the capture checks' thresholds and where they came from. Read-only: + * they are deployment policy, set in a file, never from the page. */ +export interface CaptureCheckSettings { + /** Why the thresholds could not be read; recording is then held and the other fields are empty. */ + error: string | null; + /** The defaults file's base name; never a path. */ + defaults_file: string | null; + /** That file's SHA-256, so two stations can be told to run the same thresholds. */ + defaults_sha256: string | null; + /** What the station file's `data_check` section changed, by dotted key. */ + station_overrides: Record; + /** One backend sentence for each way this station does not run the checks or the camera rate rule as built in + * (switched off, relaxed, judged against a rate the station set); empty when it does. Nothing else on the page + * says that a station stopped rejecting takes for a low camera rate. Absent from a backend that predates them. */ + notices?: string[]; + /** The thresholds in force. */ + effective: CaptureCheckThresholds | null; +} + export interface EffectiveSettings { capture: { server_url: string; @@ -36,6 +88,8 @@ export interface EffectiveSettings { data_dir: string | null; }; recording: { output_root: string }; + /** Absent from a backend that predates the capture checks' file; the page then shows no such card. */ + quality_checks?: CaptureCheckSettings; visualization: { error: string | null; enabled: boolean; diff --git a/examples/egocap/frontend/src/settingsParts.test.tsx b/examples/egocap/frontend/src/settingsParts.test.tsx index 1d6afd3ac2..97d581265d 100644 --- a/examples/egocap/frontend/src/settingsParts.test.tsx +++ b/examples/egocap/frontend/src/settingsParts.test.tsx @@ -2,7 +2,9 @@ // // SPDX-License-Identifier: Apache-2.0 -/** Modal focus across disclosures: a summary can take focus, and what a collapsed one hides cannot. */ +/** Modal focus across disclosures: a summary can take focus, and what a collapsed one hides cannot. And a dialog + * opened over another: only the one on top holds focus. */ +import { useState } from "react"; import { afterEach, describe, expect, it } from "vitest"; import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { useModalFocus } from "./settingsParts"; @@ -58,3 +60,80 @@ describe("useModalFocus", () => { expect([tab(), tab(), tab(), tab()]).toEqual(["First", "Collapsed", "Open", "First"]); }); }); + +/** A question asked over another dialog. */ +function Question({ onAnswer }: { onAnswer: () => void }) { + const dialogRef = useModalFocus(true); + return ( +
+ + +
+ ); +} + +/** A dialog whose row asks a question over it; answering can remove the row that asked. */ +function Under({ rowGoesAway }: { rowGoesAway: boolean }) { + const dialogRef = useModalFocus(true); + const [asking, setAsking] = useState(false); + const [row, setRow] = useState(true); + return ( + <> +
+ + {row && ( + + )} +
+ {asking && ( + { + setAsking(false); + if (rowGoesAway) setRow(false); + }} + /> + )} + + ); +} + +describe("a dialog opened over another", () => { + it("holds focus by itself: Tab cycles its own controls and the dialog under it does not pull focus back", () => { + render(); + const ask = screen.getByRole("button", { name: "Ask" }); + ask.focus(); + fireEvent.click(ask); + const question = screen.getByRole("alertdialog"); + expect(document.activeElement).toBe(question); + expect([tab(), tab(), tab(), tab(true)]).toEqual(["No", "Yes", "No", "Yes"]); + // Focus sent under the question comes back to it, not to the dialog underneath. + screen.getByRole("button", { name: "Other" }).focus(); + expect(document.activeElement).toBe(question); + }); + + it("gives focus back to the control that opened it, and the dialog under it holds focus again", () => { + render(); + const ask = screen.getByRole("button", { name: "Ask" }); + ask.focus(); + fireEvent.click(ask); + fireEvent.click(screen.getByRole("button", { name: "No" })); + expect(document.activeElement).toBe(ask); + expect([tab(), tab()]).toEqual(["Other", "Ask"]); + }); + + it("gives focus to the dialog under it when the control that opened it is gone", () => { + render(); + const ask = screen.getByRole("button", { name: "Ask" }); + ask.focus(); + fireEvent.click(ask); + fireEvent.click(screen.getByRole("button", { name: "Yes" })); + expect(document.activeElement).toBe(screen.getByRole("dialog", { name: "Under" })); + expect(tab()).toBe("Other"); + }); +}); diff --git a/examples/egocap/frontend/src/settingsParts.tsx b/examples/egocap/frontend/src/settingsParts.tsx index 6ef0114765..bc66d1c899 100644 --- a/examples/egocap/frontend/src/settingsParts.tsx +++ b/examples/egocap/frontend/src/settingsParts.tsx @@ -66,6 +66,10 @@ function hiddenByClosedDetails(element: HTMLElement): boolean { return false; } +/** The dialogs that own focus now, the one opened last at the end. Only that one contains focus and cycles Tab, + * so a question asked over a dialog is not fought for focus by the dialog under it. */ +const openDialogs: HTMLElement[] = []; + /** Own keyboard focus for the dialog lifetime and return it to the invoking control. */ export function useModalFocus(open: boolean) { const dialogRef = useRef(null); @@ -73,17 +77,20 @@ export function useModalFocus(open: boolean) { if (!open || !dialogRef.current) return; const dialog = dialogRef.current; const previous = document.activeElement; + openDialogs.push(dialog); + /** Whether no dialog was opened over this one. */ + const onTop = () => openDialogs[openDialogs.length - 1] === dialog; /** Recompute controls because loading, tab changes, saves and disclosures can change their availability. */ const controls = () => Array.from(dialog.querySelectorAll( 'button, input, select, textarea, summary, a[href], [tabindex]', )).filter((element) => element.tabIndex >= 0 && !element.matches(":disabled") && !element.closest("[hidden], [inert]") && !hiddenByClosedDetails(element)); /** Programmatic focus and pointer interaction must also respect the modal boundary. */ const containFocus = (event: FocusEvent) => { - if (!dialog.contains(event.target as Node)) dialog.focus(); + if (onTop() && !dialog.contains(event.target as Node)) dialog.focus(); }; /** Cycle only the current dialog controls, including wraparound in either direction. */ const onTab = (event: KeyboardEvent) => { - if (event.key !== "Tab" || event.altKey || event.ctrlKey || event.metaKey) return; + if (event.key !== "Tab" || event.altKey || event.ctrlKey || event.metaKey || !onTop()) return; const available = controls(); const current = available.indexOf(document.activeElement as HTMLElement); const next = event.shiftKey @@ -99,7 +106,11 @@ export function useModalFocus(open: boolean) { // Release containment before restoring focus; rerenders must not recapture the invoking control. document.removeEventListener("focusin", containFocus); document.removeEventListener("keydown", onTab); + openDialogs.splice(openDialogs.indexOf(dialog), 1); + // The invoking control can be gone by now (a row whose take was discarded): focus then goes to the dialog + // this one was opened over, which would otherwise be left without it. if (previous instanceof HTMLElement && previous.isConnected) previous.focus(); + else openDialogs[openDialogs.length - 1]?.focus(); }; }, [open]); return dialogRef; diff --git a/examples/egocap/frontend/src/settingsTestDoubles.ts b/examples/egocap/frontend/src/settingsTestDoubles.ts index 0280851fa9..8c77c0938a 100644 --- a/examples/egocap/frontend/src/settingsTestDoubles.ts +++ b/examples/egocap/frontend/src/settingsTestDoubles.ts @@ -90,6 +90,27 @@ export const SETTINGS_FIXTURE: EffectiveSettings = { data_dir: null, }, recording: { output_root: "/var/egocap/recordings" }, + quality_checks: { + error: null, + defaults_file: "data_check_config.yaml", + defaults_sha256: "", + station_overrides: { "guardrails.gloves_expected": true }, + notices: [], + effective: { + guardrails: { + enabled: true, + quarantine: true, + camera_min_fps_enabled: true, + camera_min_fps_ratio: 0.86, + freeze_enabled: true, + freeze_seconds: 1, + gloves_expected: true, + tracking_gap_seconds: 1, + tracking_gap_marks_bad: false, + }, + duration: { default: { min_duration_s: 1, max_duration_s: 600 }, marks_bad: false }, + }, + }, visualization: { error: null, enabled: true, diff --git a/examples/egocap/frontend/src/styles.css b/examples/egocap/frontend/src/styles.css index b343ef2764..341196b156 100644 --- a/examples/egocap/frontend/src/styles.css +++ b/examples/egocap/frontend/src/styles.css @@ -12,6 +12,8 @@ --positive: #4ade80; --warning: #fbbf24; --critical: #f87171; + /* A take set aside in quarantine: its own colour, apart from flagged (warning) and rejected (critical). */ + --quarantine: #a78bfa; --radius-card: 10px; --radius-card-lg: 14px; --radius-chip: 6px; @@ -831,24 +833,29 @@ button.step:hover { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; - color: var(--text-secondary); } -.wrap-up-tile-time { +.wrap-up-tile-time, +.wrap-up-tile-hint { font-size: 12px; color: var(--text-secondary); } -/* One colour per outcome, shared by the tiles and the table. */ +/* The tile's edge takes the colour of its outcome's mark (see .outcome-mark below). */ .wrap-up-tile--kept { border-left-color: var(--positive); } .wrap-up-tile--flagged, -.wrap-up-tile--pending { +.wrap-up-tile--pending, +.wrap-up-tile--unknown { border-left-color: var(--warning); } +.wrap-up-tile--quarantined { + border-left-color: var(--quarantine); +} + .wrap-up-tile--rejected { border-left-color: var(--critical); } @@ -857,31 +864,421 @@ button.step:hover { border-left-color: var(--accent); } -.wrap-up-outcome { +/* Each reason of a take on a line of its own. */ +.wrap-up-finding { + display: block; +} + +.wrap-up-finding + .wrap-up-finding { + margin-top: 2px; +} + +/* A take's warnings, behind its reasons. */ +.wrap-up-findings { + margin-top: 2px; + font-size: 12px; + color: var(--text-secondary); +} + +.wrap-up-findings > summary { + cursor: pointer; +} + +.wrap-up-findings ul { + margin: var(--space-1) 0 0; + padding-left: var(--space-4); +} + +/* What this station's checks do differently from the built-in ones: written out above the thresholds, in the + warning colour with its mark, because nothing else on the page says so. */ +.capture-check-notices { + list-style: none; + margin: 0 0 var(--space-3); + padding: var(--space-2) var(--space-3); + display: flex; + flex-direction: column; + gap: var(--space-2); + border: 1px solid var(--warning); + border-radius: var(--radius-chip); + font-size: 13px; +} + +.capture-check-notices li { + display: flex; + align-items: flex-start; + gap: var(--space-2); +} + +.capture-check-notices .outcome-icon { + margin-top: 3px; + color: var(--warning); +} + +/* --- Outcome marks: each outcome has its own outline and colour, wherever a take's outcome is named --------- */ + +.outcome-icon { + flex: none; + width: 1.05em; + height: 1.05em; +} + +/* Drawn over a filled outline, in the colour behind it. */ +.outcome-icon-cut { + fill: none; + stroke: var(--canvas); + stroke-width: 1.7; + stroke-linecap: round; + stroke-linejoin: round; +} + +.outcome-icon-line { + fill: none; + stroke: currentColor; + stroke-width: 1.6; + stroke-linecap: round; +} + +.outcome-mark { + display: inline-flex; + align-items: center; + gap: 6px; font-weight: 600; } -.wrap-up-outcome--kept { +.outcome-mark--kept { color: var(--positive); } -.wrap-up-outcome--flagged, -.wrap-up-outcome--pending { +.outcome-mark--flagged, +.outcome-mark--pending, +.outcome-mark--unknown { color: var(--warning); } -.wrap-up-outcome--rejected { +.outcome-mark--quarantined { + color: var(--quarantine); +} + +.outcome-mark--rejected { color: var(--critical); } -.wrap-up-outcome--discarded { +.outcome-mark--discarded { color: var(--text-secondary); } -.wrap-up-outcome--recording { +.outcome-mark--recording { color: var(--accent); } +/* --- What became of the last take, above the cameras --------------------------------------------------------- */ + +.take-outcome-area { + display: flex; + flex-direction: column; + gap: var(--space-2); +} + +.take-outcome { + --outcome: var(--text-secondary); + display: flex; + align-items: flex-start; + gap: var(--space-4); + padding: var(--space-3) var(--space-4); + background: color-mix(in srgb, var(--outcome) 9%, var(--surface)); + border: 1px solid color-mix(in srgb, var(--outcome) 45%, var(--border)); + border-left: 6px solid var(--outcome); + border-radius: var(--radius-card); +} + +.take-outcome--kept { + --outcome: var(--positive); +} + +.take-outcome--flagged, +.take-outcome--pending, +.take-outcome--unknown { + --outcome: var(--warning); +} + +.take-outcome--quarantined { + --outcome: var(--quarantine); +} + +.take-outcome--rejected { + --outcome: var(--critical); +} + +.take-outcome-icon { + width: 40px; + height: 40px; + margin-top: 2px; + color: var(--outcome); +} + +.take-outcome-body { + flex: 1 1 0; + min-width: 0; +} + +.take-outcome-headline { + margin: 0; + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: var(--space-3); + font-size: 22px; + font-weight: 700; + line-height: 1.25; +} + +.take-outcome-length { + font-size: 14px; + font-weight: 500; + color: var(--text-secondary); +} + +/* The backend's sentences: large enough to read standing at the station. */ +.take-outcome-reasons, +.take-outcome-notes { + margin: var(--space-1) 0 0; + padding: 0; + list-style: none; + font-size: 15px; +} + +.take-outcome-notes { + color: var(--text-secondary); +} + +.take-outcome-effect, +.take-outcome-where { + margin: var(--space-1) 0 0; + font-size: 13px; + color: var(--text-secondary); +} + +.take-outcome-where code { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + overflow-wrap: anywhere; +} + +.take-outcome-warnings { + margin-top: var(--space-1); + font-size: 13px; + color: var(--text-secondary); +} + +.take-outcome-warnings > summary { + cursor: pointer; +} + +.take-outcome-warnings ul { + margin: var(--space-1) 0 0; + padding-left: var(--space-4); +} + +/* Takes of earlier sessions hold nothing, so they get one quiet line. */ +.take-outcome-earlier { + margin: 0; + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-2) var(--space-3); + padding: var(--space-1) var(--space-4); + border: 1px solid var(--border); + border-radius: var(--radius-chip); + font-size: 13px; + color: var(--warning); +} + +.take-outcome-earlier > span { + color: var(--text-main); +} + +/* --- Recover and Discard for a pending take ------------------------------------------------------------------ */ + +.pending-take-actions { + flex: 0 1 420px; + display: flex; + flex-direction: column; + gap: var(--space-2); + min-width: 260px; +} + +.pending-take-note, +.pending-take-blocked, +.pending-take-feedback, +.pending-take-unreadable { + margin: 0; + font-size: 13px; +} + +.pending-take-unreadable { + color: var(--warning); +} + +/* Discard for a complete take that only cannot be finished right now: there, but not put forward. */ +.pending-take-buttons .pending-take-discard--aside { + flex: 0 0 auto; + min-height: 32px; + font-size: 12px; +} + +.pending-take-blocked { + color: var(--text-secondary); +} + +.pending-take-feedback { + color: var(--warning); +} + +.pending-take-buttons { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.pending-take-buttons .recording-button { + flex: 1 1 150px; + min-height: 44px; + font-size: 15px; +} + +/* A running command holds its button without disabling it, so focus stays where it was. */ +.pending-take-buttons .recording-button[aria-disabled="true"] { + cursor: progress; + opacity: 0.7; +} + +/* Recover is the answer that loses nothing, so it is the filled one. Scoped to the pair of buttons, so it outranks + the plain recording button it is drawn as. */ +.pending-take-buttons .recording-button--recover:enabled { + background: var(--accent); + border-color: var(--accent); + color: #06111f; +} + +.pending-take-buttons .recording-button--recover:enabled:hover { + filter: brightness(1.08); +} + +/* The rows of takes waiting, at the top of the day's summary. */ +.pending-takes { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: var(--space-2); +} + +.pending-take { + padding: var(--space-3); + border: 1px solid var(--border); + border-left: 3px solid var(--warning); + border-radius: var(--radius-chip); +} + +.pending-take-facts { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: var(--space-2) var(--space-3); + font-size: 13px; +} + +.pending-take-facts .settings-note { + margin: 0; +} + +.pending-take-name { + font-weight: 600; + overflow-wrap: anywhere; +} + +.pending-take-holds { + padding: 0 var(--space-2); + border: 1px solid var(--warning); + border-radius: var(--radius-chip); + font-size: 11px; + font-weight: 600; + color: var(--warning); +} + +.pending-take-reason { + margin: var(--space-1) 0 var(--space-2); + font-size: 14px; +} + +.pending-take .pending-take-actions { + flex: none; +} + +/* In a row of the list the two buttons keep their own width instead of filling the dialog. */ +.pending-take .pending-take-buttons .recording-button { + flex: 0 0 auto; + min-width: 190px; + min-height: 40px; +} + +.pending-takes + .take-outcome { + margin-top: var(--space-3); +} + +/* --- The question before a pending take is discarded --------------------------------------------------------- */ + +/* Above the Settings and End of day dialogs: the question can be asked over either. */ +.discard-take-backdrop { + z-index: 42; +} + +.discard-take-dialog { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: min(520px, 92vw); + max-height: 92vh; + overflow-y: auto; + padding: var(--space-5) var(--space-6); + background: var(--surface); + border: 1px solid var(--critical); + border-radius: var(--radius-card-lg); + box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55); + z-index: 43; +} + +.discard-take-dialog h2 { + margin: 0 0 var(--space-2); + font-size: 20px; +} + +.discard-take-dialog p { + margin: 0 0 var(--space-3); +} + +.discard-take-facts dd { + overflow-wrap: anywhere; +} + +.discard-take-note { + font-size: 13px; + color: var(--text-secondary); +} + +.discard-take-buttons { + display: flex; + justify-content: flex-end; + gap: var(--space-3); + margin-top: var(--space-4); +} + +.discard-take-buttons button { + height: 40px; + font-size: 14px; +} + .wrap-up-time { margin: 0; font-size: 15px; @@ -942,15 +1339,26 @@ button.step:hover { margin-top: var(--space-2); } -/* Mostly text, unlike the tracking tables this style comes from: read left to right, numbers still right-aligned. */ -.wrap-up-table th, -.wrap-up-table td { +/* Mostly text, unlike the tracking tables this style comes from: read left to right, numbers still right-aligned. + Named by both classes, so these outrank the tracking tables' right-aligned cells, which are defined further down. */ +.data-table.wrap-up-table thead th, +.data-table.wrap-up-table td { text-align: left; + vertical-align: top; +} + +.data-table.wrap-up-table td { overflow-wrap: anywhere; } -.wrap-up-table th.num-cell, -.wrap-up-table td.num-cell { +/* A heading and an outcome are a word or two: broken in the middle they stop being readable. */ +.data-table.wrap-up-table thead th, +.wrap-up-table .outcome-mark { + white-space: nowrap; +} + +.data-table.wrap-up-table thead th.num-cell, +.data-table.wrap-up-table td.num-cell { text-align: right; } @@ -1812,8 +2220,7 @@ below for the narrow/stacked layout). */ gap: var(--space-2); } -.recording-feedback, -.recording-last-result { +.recording-feedback { margin: 0; font-size: 13px; color: var(--text-secondary); @@ -2258,6 +2665,18 @@ below for the narrow/stacked layout). */ line-height: 1; } +/* Takes of the batch that were not kept, each kind under its own mark. */ +.op-marked { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 1px; + font-size: 13px; + white-space: nowrap; +} + .op-last { min-width: 140px; } @@ -2265,19 +2684,6 @@ below for the narrow/stacked layout). */ .op-last-value { display: block; font-size: 14px; - font-weight: 600; -} - -.op-last--kept .op-last-value { - color: var(--positive); -} - -.op-last--rejected .op-last-value { - color: var(--critical); -} - -.op-last--discarded .op-last-value { - color: var(--text-secondary); } .op-health { @@ -2351,6 +2757,41 @@ below for the narrow/stacked layout). */ color: var(--text-secondary); } +/* --- Last take's outcome ------------------------------------------------- */ + +/* Filled by the recording panel; while it holds nothing it takes no room and no gap. */ +.op-outcome:empty { + display: none; +} + +/* A take can fail for several cameras at once, each with its own sentence. The cameras keep most of the column: + past a third of the window's height the outcome scrolls inside itself. */ +.op-outcome { + max-height: 34vh; + overflow-y: auto; +} + +/* In a window too short for the outcome, the cameras and the controls together, the column scrolls: the cameras + are never squeezed out of sight to make room. */ +.op-main { + overflow-y: auto; +} + +.op-main > .op-stage { + min-height: 120px; +} + +/* A narrow main column: the two buttons go under the sentences instead of squeezing them. */ +@container op-main (max-width: 900px) { + .take-outcome { + flex-wrap: wrap; + } + + .take-outcome .pending-take-actions { + flex: 1 1 100%; + } +} + /* --- Camera stage -------------------------------------------------------- */ .op-stage { @@ -2508,7 +2949,6 @@ below for the narrow/stacked layout). */ /* The bar above already shows the state, timer, task, count and last result; the dock keeps only controls. */ .op-dock .recording-panel-header, .op-dock .recording-status, -.op-dock .recording-last-result, .op-dock .recording-actions-divider { display: none; } diff --git a/examples/egocap/frontend/src/takeOutcomeText.ts b/examples/egocap/frontend/src/takeOutcomeText.ts new file mode 100644 index 0000000000..baa2ba7107 --- /dev/null +++ b/examples/egocap/frontend/src/takeOutcomeText.ts @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * The page's own words for what became of a take: the outcome's name, the headline over it and the one sentence + * of what follows from it. Why a take ended as it did is never worded here: those sentences are composed by the + * backend (`backend/egocap_web/take_outcome.py`) and shown as they arrive, so the page after a take, the list of + * pending takes and the day's summary cannot disagree. + */ + +import type { EpisodeResultSummary, ShownOutcome } from "./recordingTypes"; + +/** The mark drawn beside an outcome's word. Each has its own outline, so an outcome is never told by colour alone. */ +export type OutcomeShape = "kept" | "flagged" | "quarantined" | "rejected" | "discarded" | "pending" | "recording" | "unknown"; + +/** How one outcome is named and marked. */ +export interface OutcomeView { + /** The outcome in a word or two, where there is no room for a sentence. */ + word: string; + /** The mark drawn beside the word. */ + shape: OutcomeShape; + /** What follows "Take N" in the headline over the take's result. */ + headline: string; +} + +/** Each outcome's name, mark and headline. */ +export const OUTCOME_VIEW: Record = { + kept: { word: "Kept", shape: "kept", headline: "kept" }, + flagged: { word: "Flagged", shape: "flagged", headline: "kept, but flagged" }, + quarantined: { word: "Quarantined", shape: "quarantined", headline: "quarantined" }, + rejected: { word: "Rejected", shape: "rejected", headline: "rejected, and its media removed" }, + rejected_data_kept: { word: "Rejected", shape: "rejected", headline: "rejected, its data left on disk" }, + discarded: { word: "Discarded", shape: "discarded", headline: "discarded" }, + interrupted: { word: "Interrupted", shape: "pending", headline: "interrupted" }, + unknown: { word: "Unknown", shape: "unknown", headline: "outcome not recognised" }, +}; + +/** The episode number at the end of a take's id or of where its data is; a pending take's folder ends `.pending`. */ +const EPISODE_NUMBER = /(?:^|\/)episode_(\d+)(?:\.pending)?$/; + +/** The number a take goes by: the one of where its data is, as the day's summary numbers it (a routed take by + * its slot in its group), else the one of its id. A name of another shape is shown whole. */ +export function takeNumber(episodeId: string, location: string | null = null): string { + const found = (location === null ? null : EPISODE_NUMBER.exec(location)) ?? EPISODE_NUMBER.exec(episodeId); + return found === null ? episodeId : found[1]; +} + +/** The headline over a take's result, such as "Take 3 kept, but flagged". */ +export function outcomeHeadline(result: EpisodeResultSummary): string { + const take = `Take ${takeNumber(result.episodeId, result.location)}`; + // An unrecognised outcome is set off from the take's name, so it cannot be read as one of the known endings. + return result.outcome === "unknown" ? `${take}: ${OUTCOME_VIEW.unknown.headline}` : `${take} ${OUTCOME_VIEW[result.outcome].headline}`; +} + +/** What follows from a take's outcome, in one sentence; null where the headline and the backend's reasons say it all. */ +export function outcomeEffect(result: EpisodeResultSummary): string | null { + switch (result.outcome) { + case "kept": + // Kept without a verdict is still kept, but it must not pass for a take the checks looked at. + return result.qcDecision === "PASSED" ? null : "The capture checks did not run on this take."; + case "flagged": + return "It stays with its session, marked bad, and is not time-aligned."; + case "quarantined": + return "It is set aside in the quarantine folder, apart from its session, and is not time-aligned."; + case "unknown": + return `The backend reported "${result.reportedAs}", which this page does not know. Do not count this take as kept; see the backend log.`; + default: + return null; + } +} + +/** A count with its noun, as in "2 warnings". */ +export function counted(count: number, noun: string): string { + return `${count} ${noun}${count === 1 ? "" : "s"}`; +} diff --git a/examples/egocap/frontend/src/useCaptureSession.hook.test.ts b/examples/egocap/frontend/src/useCaptureSession.hook.test.ts index 614f765f49..9fcc9d3c8c 100644 --- a/examples/egocap/frontend/src/useCaptureSession.hook.test.ts +++ b/examples/egocap/frontend/src/useCaptureSession.hook.test.ts @@ -14,6 +14,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, renderHook } from "@testing-library/react"; import { useCaptureSession, RecordingCommandUncertainError } from "./useCaptureSession"; import { PREVIEW_VERSION, SNAPSHOT_TYPE, BINARY_HEADER_SIZE, BINARY_KIND_TRACKING } from "./captureProtocol"; +import { buildRecordingActions } from "./recordingActions"; +import { SESSION, wireResult, wireSnapshot } from "./recordingTestDoubles"; class FakeWebSocket { static instances: FakeWebSocket[] = []; @@ -672,7 +674,12 @@ describe("useCaptureSession (effect integration)", () => { defaultOperator: null, autoFillOperatorName: false, savedCount: 0, + // This wire body predates the counts of takes that were not kept and the pending takes, so none. + flaggedCount: 0, + quarantinedCount: 0, + rejectedCount: 0, lastResult: null, + pendingTakes: [], readyToRecord: false, notReadyReason: null, // this wire body predates the reason, so none revision: 0, @@ -686,6 +693,80 @@ describe("useCaptureSession (effect integration)", () => { expect(result.current.phase).toBe("connected"); }); + it("sends Recover and Discard for a pending take like any command, and reads what became of the take from the reply", async () => { + const { result } = renderHook(() => useCaptureSession()); + const ws1 = FakeWebSocket.instances[0]; + act(() => ws1.open()); + act(() => ws1.emitText(runningSnapshotBody(1))); + act(() => result.current.setControlToken("test-control-token")); + const actions = buildRecordingActions(result.current.sendRecordingCommand); + const target = { batchId: "b1", episodeId: `${SESSION}/episode_1` }; + + for (const [send, action, outcome] of [ + [actions.onRecoverPending, "recover_pending", wireResult()], + [actions.onDiscardPending, "discard_pending", wireResult({ disposition: "DISCARDED", outcome: "discarded", qc_decision: null, media_removed: true, location: null })], + ] as const) { + let settled: unknown; + await act(async () => { + const pending = send?.(target); + const sent = JSON.parse(ws1.sent[ws1.sent.length - 1]) as { request_id: string; action: string; payload: unknown }; + expect(sent.action).toBe(action); + expect(sent.payload).toEqual({ batch_id: "b1", episode_id: `${SESSION}/episode_1` }); + ws1.emitText(JSON.stringify({ type: "recording_reply", request_id: sent.request_id, outcome: "ok", reason: null, snapshot: wireSnapshot({ last_result: outcome }) })); + settled = await pending; + }); + expect(settled).toEqual({ outcome: "ok", reason: null }); + expect(result.current.recordingSnapshot?.lastResult?.outcome).toBe(outcome.outcome); + } + }); + + it("gives Recover as long as Stop to settle, since it checks and finishes a take as Stop does", async () => { + const { result } = renderHook(() => useCaptureSession()); + const ws1 = FakeWebSocket.instances[0]; + act(() => ws1.open()); + act(() => ws1.emitText(runningSnapshotBody(1))); + act(() => result.current.setControlToken("test-control-token")); + let outcome: unknown = "pending"; + act(() => { + result.current.sendRecordingCommand("recover_pending", { batch_id: "b1", episode_id: "e1" }).catch((err: unknown) => { + outcome = err; + }); + }); + // Heartbeats keep the socket itself alive; only the command's own budget may end the wait. + for (let second = 1; second <= 119; second++) { + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000); + }); + act(() => ws1.emitText(runningSnapshotBody(1 + second))); + } + expect(outcome).toBe("pending"); + await act(async () => { + await vi.advanceTimersByTimeAsync(1_500); + }); + expect(outcome).toBeInstanceOf(RecordingCommandUncertainError); + }); + + it("treats a reply whose snapshot it cannot read as an unknown outcome, never as the answer it claims", async () => { + const { result } = renderHook(() => useCaptureSession()); + const ws1 = FakeWebSocket.instances[0]; + act(() => ws1.open()); + act(() => ws1.emitText(runningSnapshotBody(1))); + act(() => result.current.setControlToken("test-control-token")); + let failure: unknown; + await act(async () => { + const pending = result.current.sendRecordingCommand("stop_episode", { batch_id: "b1", episode_id: "e1" }); + const sent = JSON.parse(ws1.sent[0]) as { request_id: string }; + // "ok" with a snapshot of the wrong shape: the page cannot tell what became of the take. + ws1.emitText(JSON.stringify({ type: "recording_reply", request_id: sent.request_id, outcome: "ok", reason: null, snapshot: wireSnapshot({ last_result: "KEPT" }) })); + await pending.catch((err: unknown) => { + failure = err; + }); + }); + expect(failure).toBeInstanceOf(RecordingCommandUncertainError); + expect((failure as Error).message).toBe("the backend's reply could not be read"); + expect(result.current.recordingSnapshot).toBeNull(); + }); + it("a Stop is given far longer than 5 s to settle before its outcome is called unknown", async () => { const { result } = renderHook(() => useCaptureSession()); const ws1 = FakeWebSocket.instances[0]; diff --git a/examples/egocap/frontend/src/useCaptureSession.ts b/examples/egocap/frontend/src/useCaptureSession.ts index 7c66ec0b6a..793391632b 100644 --- a/examples/egocap/frontend/src/useCaptureSession.ts +++ b/examples/egocap/frontend/src/useCaptureSession.ts @@ -30,13 +30,8 @@ import { type TrackingStreamDescriptor, } from "./captureProtocol"; import { decodeTracking, type DecodedTracking } from "./trackingDecoder"; -import type { - EpisodeDisposition, - EpisodeResultSummary, - RecordingActionName, - RecordingCommandResult, - RecordingSnapshot, -} from "./recordingTypes"; +import { parseRecordingSnapshot } from "./recordingSnapshotParser"; +import type { RecordingActionName, RecordingCommandResult, RecordingSnapshot } from "./recordingTypes"; /** How long a command may wait for its reply before its outcome is treated as unknown. Stop retires the ingress * (up to ~32 s when a conversion is stuck), then seals, checks and finalizes the take, so it waits far longer than @@ -51,6 +46,10 @@ const RECORDING_COMMAND_TIMEOUT_MS: Record = { stop_episode: 120_000, discard_episode: 45_000, new_batch: 45_000, + // Recover checks and finalizes a take as Stop does; Discard of a pending take removes its data as Discard does. + // For a take of an earlier session each also opens and closes that session. + recover_pending: 120_000, + discard_pending: 45_000, }; /** sessionStorage key for the entered control token -- scoped to this @@ -109,15 +108,6 @@ function removeStoredTokenBackendInstanceId(): void { } } const KNOWN_OUTCOMES = new Set(["ok", "rejected"]); -const EPISODE_PHASES = new Set([ - "IDLE", - "STARTING", - "RECORDING", - "STOPPING", - "FINALIZING", - "RECOVERY_REQUIRED", -]); -const DISPOSITIONS = new Set(["KEPT", "REJECTED", "DISCARDED"]); /** Rejects a `sendRecordingCommand` promise specifically for a timeout or * lost connection -- a command actually sent whose real outcome is @@ -134,93 +124,6 @@ interface PendingReply { timer: ReturnType; } -/** Thrown internally by parseRecordingSnapshot's field checks; never escapes it. */ -class _InvalidRecordingSnapshot extends Error {} - -/** Raises unless `value` is a string. */ -function requireString(value: unknown): string { - if (typeof value !== "string") throw new _InvalidRecordingSnapshot(); - return value; -} - -/** Raises unless `value` is a string or null. */ -function requireNullableString(value: unknown): string | null { - return value === null ? null : requireString(value); -} - -/** Raises unless `value` is one of `allowed`'s members. */ -function requireEnum(value: unknown, allowed: ReadonlySet): T { - if (typeof value !== "string" || !allowed.has(value as T)) throw new _InvalidRecordingSnapshot(); - return value as T; -} - -/** Raises unless `value` is a nonnegative safe integer. */ -function requireNonNegativeSafeInt(value: unknown): number { - if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new _InvalidRecordingSnapshot(); - return value; -} - -/** Raises unless `value` is a boolean. */ -function requireBoolean(value: unknown): boolean { - if (typeof value !== "boolean") throw new _InvalidRecordingSnapshot(); - return value; -} - -/** Raises unless `value` is a nonnegative safe integer or null. */ -function requireNullableNonNegativeSafeInt(value: unknown): number | null { - if (value === null) return null; - return requireNonNegativeSafeInt(value); -} - -/** Raises unless `value` is null or a well-shaped episode result object. */ -function parseEpisodeResult(value: unknown): EpisodeResultSummary | null { - if (value === null) return null; - if (typeof value !== "object") throw new _InvalidRecordingSnapshot(); - const r = value as Record; - const issues = r.issues; - if (!Array.isArray(issues) || !issues.every((issue) => typeof issue === "string")) throw new _InvalidRecordingSnapshot(); - return { - episodeId: requireString(r.episode_id), - disposition: requireEnum(r.disposition, DISPOSITIONS), - issues, - // Frozen at the moment this episode ended -- the one piece of - // finished-episode timing data the UI actually renders, carried on - // the existing result fact rather than a second parallel record. - durationMs: requireNonNegativeSafeInt(r.duration_ms), - }; -} - -/** Converts the backend's snake_case recording snapshot object into the - * frontend's typed RecordingSnapshot, or null if any field is missing or - * wrong-shaped -- this is real backend-produced data, but still untrusted - * input to this browser process; a malformed field must never reach render. */ -function parseRecordingSnapshot(raw: unknown): RecordingSnapshot | null { - if (typeof raw !== "object" || raw === null) return null; - const r = raw as Record; - try { - return { - batchId: requireString(r.batch_id), - episodePhase: requireEnum(r.episode_phase, EPISODE_PHASES), - currentEpisodeId: requireNullableString(r.current_episode_id), - currentEpisodeElapsedMs: requireNullableNonNegativeSafeInt(r.current_episode_elapsed_ms), - taskText: requireNullableString(r.task_text), - // Absent from a backend that predates task details: treat as none rather than dropping the snapshot. - taskDetails: r.task_details === undefined ? "" : requireString(r.task_details), - defaultOperator: requireNullableString(r.default_operator), - autoFillOperatorName: requireBoolean(r.auto_fill_operator_name), - savedCount: requireNonNegativeSafeInt(r.saved_count), - lastResult: parseEpisodeResult(r.last_result), - readyToRecord: requireBoolean(r.ready_to_record), - // Absent from a backend that predates the reason: treat as none rather than dropping the snapshot. - notReadyReason: r.not_ready_reason === undefined ? null : requireNullableString(r.not_ready_reason), - revision: requireNonNegativeSafeInt(r.revision), - }; - } catch (err) { - if (err instanceof _InvalidRecordingSnapshot) return null; - throw err; - } -} - /** True for a parsed message that is a recording-command reply -- checked * before ever attempting to parse the payload as a preview snapshot, so a * reply can never be misrouted into the snapshot path (or vice versa), and @@ -384,7 +287,7 @@ export interface CaptureSessionState { * automatically, rejects immediately (without sending anything) if not * currently connected OR if no control token has been entered yet. Sends * the current `operatorToken` and `controlToken` with every call; the - * backend rejects any of the five mutating actions without both. */ + * backend rejects every mutating action without both. */ sendRecordingCommand: (action: RecordingActionName, payload: Record) => Promise; /** The operator name attached to every outgoing recording command, or * null before one has ever been entered -- persisted in localStorage @@ -732,12 +635,13 @@ export function useCaptureSession(): CaptureSessionState { const recording = parseRecordingSnapshot(parsed.snapshot); if (recording !== null) installRecordingSnapshot(recording); if (pendingRequestRef.current?.requestId === parsed.request_id) { - settlePendingRequest({ - result: { - outcome: parsed.outcome as RecordingCommandResult["outcome"], - reason: parsed.reason, - }, - }); + // "ok" says only that the step ran; what became of the take is in the snapshot. A reply whose + // snapshot cannot be read is therefore not an answer: the outcome is unknown until one arrives. + settlePendingRequest( + recording === null + ? { error: new RecordingCommandUncertainError("the backend's reply could not be read") } + : { result: { outcome: parsed.outcome as RecordingCommandResult["outcome"], reason: parsed.reason } }, + ); } return; } diff --git a/examples/egocap/pyproject.toml b/examples/egocap/pyproject.toml index 3c756711fc..abfb2fc878 100644 --- a/examples/egocap/pyproject.toml +++ b/examples/egocap/pyproject.toml @@ -128,15 +128,16 @@ include = [ # the explicit `include` allowlist above is what actually keeps the wheel # limited to these real packages. -# No [tool.setuptools.package-data] section: recording/egocap/*.json and -# *.yaml (egocap_stations.example.json, stations/ego_stations.example.yaml, -# config/data_recording/*.yaml, config/data_check/data_check_config.yaml) -# are checkout-local example/reference station configs, not resources any -# installed-package code loads via a relative/importlib.resources path -- -# confirmed by grepping recording/egocap for their filenames outside tests. -# They are deliberately NOT part of the shipped wheel; verified by -# `uv build && unzip -l` showing none of them present. A real deployed -# station supplies its own config, it does not ship with this package. +[tool.setuptools.package-data] +# The one data file installed-package code loads: the documented capture-QC +# defaults, read beside the module by egocap/recording/capture_qc_policy.py. +# The other recording/egocap/*.json and *.yaml files +# (egocap_stations.example.json, stations/ego_stations.example.yaml, +# config/data_recording/*.yaml) are checkout-local example station configs +# that no installed code loads, and stay out of the wheel: a deployed +# station supplies its own. `uv build --wheel && unzip -l` shows which +# files ship. +egocap = ["config/data_check/data_check_config.yaml"] [tool.uv.workspace] # Marks this pyproject.toml as its own workspace root, so `uv sync`/`uv lock` run from inside this diff --git a/examples/egocap/recording/README.md b/examples/egocap/recording/README.md index f5a46a8251..c708615a0f 100644 --- a/examples/egocap/recording/README.md +++ b/examples/egocap/recording/README.md @@ -112,7 +112,14 @@ latency it was recorded under, is refused. The session's calibration files, the routing (`assign_output`/`finalize_episode_dir` route each finalized episode to `///`, falling back to `_unmatched/` when the task description matches no known studio), and the durable `write_json_atomic`/`write_yaml_atomic` primitives the -rest of the package's atomic writes build on. +rest of the package's atomic writes build on. It also owns `SessionLock`, the exclusive hold on a +session directory. For as long as a session is held its lock file is rewritten about once a second, +so a reader the lock itself does not reach (another machine on a shared recordings folder) can tell +an open session from an abandoned one by looking twice, without clocks that agree. The holder +watches its own marker: `silence()` says how long it has not been written once that reaches the +reader's 2.5 s, and a marker write that fails is tried again every second. A write that fails with no +file named by the system is given the name of the file being written (`naming_the_file`), which is +what lets a failure be placed on the recordings disk or not. `video_writer_backends.py` and `constants.py` are the local RGB video writer backends (OpenCV/FFmpeg/NVENC) and shared recording-layout constants. @@ -121,6 +128,17 @@ rest of the package's atomic writes build on. failure to `/errors.jsonl` — a tail-able, greppable record independent of the Zarr store. +`capture_qc.py` judges a finished take from its recorded timestamps and values. Its camera rate rule +asks two things of each camera with the same ratio: the rate over the camera's own frames, once they +span ten frame intervals, and the number of frames against what a take of that length holds less +three intervals, in a take of thirteen intervals or more (`frames_needed`). A take too short for both +is not judged. +`capture_qc_policy.py` reads the thresholds it judges by: the documented defaults in +`egocap/config/data_check/data_check_config.yaml`, with a station's own changes applied over them. Each +key is validated by name, type and range, and an unknown one is refused. See +[`recording_service/README.md`](recording_service/README.md) for every check and what it decides, and +the example's [`README.md`](../README.md#capture-checks) for what an operator sees. + ## Calibration — `egocap/calibration/` Camera intrinsics under OpenCV's radial-tangential (`pinhole`) or `fisheye` lens model, the head @@ -140,8 +158,9 @@ module does, the limits it applies and how an operator uses the tools are in `compute_totals`/`save_daily_log` produce the operator-facing daily activity JSON (`__activity.json`). - `day_report.py`'s `build_day_report()` lists a day's takes by session from the recording service's episode - manifests, each with its disposition (kept, flagged, rejected, discarded, pending, recording) and duration, and totals - them, optionally for a set of station names. It is what the backend's end-of-day report serves. Read-only. + manifests, each with its disposition (kept, flagged, quarantined, rejected, discarded, pending, recording), duration, + the findings that decided it and its warnings, and totals them, optionally for a set of station names. It is what + the backend's end-of-day report serves, which words the findings through its `describe` hook. Read-only. - `count_daily_trajectories.py`'s `count_trajectories()`/`compute_station_data_breakdown()` walk `///episode_*`, grouping by session and attributing each episode to the day it was actually recorded (not the session folder's own date, which can predate a @@ -186,8 +205,11 @@ What the recording service writes into each routed group: │ │ # likewise left_wrist_... and right_wrist_camera_lens_intrinsics.json │ ├── episode_0/, episode_1/, ... │ └── ... -└── _unmatched/ # descriptions matching no known studio - └── ... +├── _unmatched/ # descriptions matching no known studio +│ └── ... +└── _quarantine/ # takes the capture checks marked bad, on a station with quarantine on + └── / + └── episode_/ # is the take's index in its session, which itself never moves ``` Calibration files appear only when present at `EGOCAP_CALIBRATION_DIR` (which always has a diff --git a/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py b/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py index 298708d679..08d0493511 100644 --- a/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py +++ b/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py @@ -14,6 +14,11 @@ episode's ``zarr.json`` carries ``episode_duration`` (seconds) and ``task_description`` (the instruction string used for that episode). +A folder stamped ``quarantine: true`` holds only takes the capture checks +marked bad, and each of them says ``quarantined: true`` itself. Every such +take is counted as excluded whatever the folder's list of discarded indices +says: that list is rewritten after a take arrives, so it can lag behind. + Library functions only — called by the backend's EOD Report handler. No CLI entry point; nothing in the web backend needs a command-line wrapper. """ @@ -48,6 +53,16 @@ def _read_zarr_json(path: Path) -> dict: return payload.get("attributes") or {} +def _is_excluded(ep_idx: int, ep_attrs: dict, session_attrs: dict) -> bool: + """Whether an episode is counted as excluded rather than valid. + + The session folder lists it as discarded, or it is a quarantined take: one that says so itself, or any + episode of a folder stamped as quarantine. + """ + listed = ep_idx in set(session_attrs.get("discarded_episode_indices") or []) + return listed or session_attrs.get("quarantine") is True or ep_attrs.get("quarantined") is True + + def _episode_index(episode_dir: Path) -> int | None: """Return the integer suffix of an ``episode_N`` folder (or ``None``).""" name = episode_dir.name @@ -170,7 +185,6 @@ def compute_station_data_breakdown( continue session_attrs = _read_zarr_json(session_dir / "zarr.json") - discarded = set(session_attrs.get("discarded_episode_indices") or []) for episode_dir in sorted(session_dir.iterdir()): if not episode_dir.is_dir(): @@ -186,7 +200,7 @@ def compute_station_data_breakdown( continue duration = float(ep_attrs.get("episode_duration") or 0.0) breakdown["total_seconds"] += duration - if ep_idx in discarded: + if _is_excluded(ep_idx, ep_attrs, session_attrs): breakdown["excluded_seconds"] += duration else: breakdown["valid_seconds"] += duration @@ -230,7 +244,6 @@ def count_trajectories( continue session_attrs = _read_zarr_json(session_dir / "zarr.json") - discarded = set(session_attrs.get("discarded_episode_indices") or []) # Only accumulate once we see an episode actually recorded # on date_str; a session's timestamp folder name prefixing @@ -263,7 +276,7 @@ def count_trajectories( if track_language and description: stats["descriptions"].add(description) - if ep_idx in discarded: + if _is_excluded(ep_idx, ep_attrs, session_attrs): stats["excluded"] += 1 stats["excluded_seconds"] += duration else: diff --git a/examples/egocap/recording/egocap/analytics/day_report.py b/examples/egocap/recording/egocap/analytics/day_report.py index a018727fa5..352c1ce11d 100644 --- a/examples/egocap/recording/egocap/analytics/day_report.py +++ b/examples/egocap/recording/egocap/analytics/day_report.py @@ -15,30 +15,40 @@ import datetime import re -from collections.abc import Collection +from collections.abc import Callable, Collection, Mapping from pathlib import Path from typing import Any from egocap.analytics.count_daily_trajectories import _read_session_station_name, _read_zarr_json -from egocap.recording.capture_qc import QcDecision +from egocap.recording.capture_qc import QcDecision, deciding_results +from egocap.recording.dataset_check import report_from_dict from egocap.recording.episode_layout import ( + FINALIZATION_QUARANTINE, MANIFEST_DIR, EpisodeManifest, final_dir, manifest_path, + quarantine_destination, scan_manifests, ) #: What became of a take, in the order the page lists them. ``recording`` is the take being written right now. -KEPT, FLAGGED, REJECTED, DISCARDED, PENDING, RECORDING = ( +#: A flagged take and a quarantined one were both marked bad by the capture checks; the first stayed with its +#: session, the second was set apart, and each is counted on its own. +KEPT, FLAGGED, QUARANTINED, REJECTED, DISCARDED, PENDING, RECORDING = ( "kept", "flagged", + "quarantined", "rejected", "discarded", "pending", "recording", ) -DISPOSITIONS = (KEPT, FLAGGED, REJECTED, DISCARDED, PENDING, RECORDING) +DISPOSITIONS = (KEPT, FLAGGED, QUARANTINED, REJECTED, DISCARDED, PENDING, RECORDING) + +#: Extra fields for a take's record, computed from its manifest: how an application words why the take ended as +#: it did. What it returns replaces the record's own fields of the same name. +Describe = Callable[[EpisodeManifest], Mapping[str, Any]] _SESSION_STARTED = re.compile(r"^session_(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})_") @@ -46,13 +56,13 @@ def episode_disposition(manifest: EpisodeManifest, active_episode_id: str | None = None) -> str: """What became of one take, from its manifest alone. - A finalized take is kept, or flagged when capture quality marked its data bad. A take still in an earlier - storage phase is the one being recorded when its id is ``active_episode_id``, and otherwise an interrupted - take waiting to be recovered or discarded. + A finalized take is kept, or flagged when capture quality marked its data bad; a quarantined one was marked + bad and set apart. A take still in an earlier storage phase is the one being recorded when its id is + ``active_episode_id``, and otherwise an interrupted take waiting to be recovered or discarded. """ if manifest.storage_phase == "FINALIZED": return FLAGGED if manifest.qc_decision == QcDecision.FLAGGED_BAD.value else KEPT - if manifest.storage_phase in ("REJECTED", "DISCARDED"): + if manifest.storage_phase in ("QUARANTINED", "REJECTED", "DISCARDED"): return manifest.storage_phase.lower() return RECORDING if manifest.episode_id == active_episode_id else PENDING @@ -76,7 +86,10 @@ def _recorded_date(attributes: dict[str, Any], session_path: Path, manifest: Epi def _location(manifest: EpisodeManifest) -> str: - """Where a take's data is, relative to the recording output: its routed slot, else inside its session.""" + """Where a take's data is, relative to the recording output: the quarantine folder, its routed slot, or + inside its session.""" + if manifest.finalization == FINALIZATION_QUARANTINE: + return quarantine_destination(manifest) if manifest.assignment is not None: return f"{manifest.assignment.get('group')}/episode_{manifest.assignment.get('slot')}" return f"{manifest.session_id}/{manifest.final_path}" @@ -102,10 +115,29 @@ def _add(tally: dict[str, dict[str, float]], disposition: str, seconds: float) - tally[disposition]["seconds"] += seconds -def _episode_record(manifest: EpisodeManifest, disposition: str, attributes: dict[str, Any]) -> dict[str, Any]: +def take_reasons(manifest: EpisodeManifest) -> tuple[list[str], list[str]]: + """Why a take ended as it did, and what it was warned about, as (reasons, warnings) from its stored reports. + + The reasons are the findings that decided: the integrity check's when it failed, else those of the capture + checks behind the decision. A take that was not judged, or that passed, has none. + """ + quality, capture = manifest.quality, manifest.capture_quality + if quality and quality.get("outcome") != "PASSED": + return list(quality.get("issues", [])), [] + if not capture or not manifest.qc_decision: + return [], [] + report = report_from_dict(capture) + decided = deciding_results(report, QcDecision(manifest.qc_decision)) + return [issue for result in decided for issue in result.issues], list(report.warnings) + + +def _episode_record( + manifest: EpisodeManifest, disposition: str, attributes: dict[str, Any], describe: Describe | None +) -> dict[str, Any]: """One take as the report lists it. The task is the finalized episode's own when it has one: a task corrected after recording is written there, while the manifest keeps what the take was started with.""" corrected = attributes.get("task_description") + reasons, warnings = take_reasons(manifest) return { "index": manifest.episode_index, "episode_id": manifest.episode_id, @@ -116,12 +148,15 @@ def _episode_record(manifest: EpisodeManifest, disposition: str, attributes: dic "operator": manifest.operator, "issues": list(manifest.issues), "qc_decision": manifest.qc_decision, + "reasons": reasons, + "warnings": warnings, "location": _location(manifest), + **(describe(manifest) if describe is not None else {}), } def _session_record( - session_path: Path, date: str, active_episode_id: str | None + session_path: Path, date: str, active_episode_id: str | None, describe: Describe | None ) -> tuple[dict[str, Any], dict[str, dict[str, float]]] | None: """One session's takes of ``date`` and their tally, or None when it has none and nothing unreadable.""" manifests, problems = scan_manifests(session_path) @@ -132,7 +167,7 @@ def _session_record( attributes = _final_attributes(session_path, manifest) recorded = _recorded_date(attributes, session_path, manifest) disposition = episode_disposition(manifest, active_episode_id) - record = _episode_record(manifest, disposition, attributes) + record = _episode_record(manifest, disposition, attributes, describe) except OSError: # The manifest vanished between the scan and here (a discard finishing); the next read is correct. continue @@ -161,13 +196,25 @@ def _session_record( return record, tally +def _is_session(entry: Path) -> bool: + """Whether an entry of the recording output is a recording-service session. + + An entry this user may not look into (a file system's own folder, another account's) is not one: it must + not cost the day its report. + """ + try: + return not entry.name.startswith(".") and (entry / MANIFEST_DIR).is_dir() + except OSError: + return False + + def _session_dirs(root: Path) -> list[Path]: """Every recording-service session directly under the recording output, oldest name first.""" try: entries = sorted(root.iterdir()) except OSError: return [] - return [entry for entry in entries if not entry.name.startswith(".") and (entry / MANIFEST_DIR).is_dir()] + return [entry for entry in entries if _is_session(entry)] def _cannot_hold(session_path: Path, date: str) -> bool: @@ -182,13 +229,19 @@ def _cannot_hold(session_path: Path, date: str) -> bool: def build_day_report( - root: Path, date: str, *, stations: Collection[str] | None = None, active_episode_id: str | None = None + root: Path, + date: str, + *, + stations: Collection[str] | None = None, + active_episode_id: str | None = None, + describe: Describe | None = None, ) -> dict[str, Any]: """Every take recorded on ``date`` (``YYYY-MM-DD``), by session, with totals per disposition. ``stations`` limits the report to sessions recorded under one of those station names (a station renamed during the day has more than one); None reports every station. ``active_episode_id`` names the take being - recorded now, if any, so it is not mistaken for an interrupted one. + recorded now, if any, so it is not mistaken for an interrupted one. ``describe`` adds an application's own + fields to each take's record (see :data:`Describe`). """ totals = _empty_tally() sessions = [] @@ -196,9 +249,13 @@ def build_day_report( # Before its station name is read: that already opens the session's files. if _cannot_hold(session_path, date): continue - if stations is not None and _read_session_station_name(session_path) not in stations: + try: + if stations is not None and _read_session_station_name(session_path) not in stations: + continue + found = _session_record(session_path, date, active_episode_id, describe) + except OSError: + # A session whose files cannot be read is passed over, like an entry that is not a session at all. continue - found = _session_record(session_path, date, active_episode_id) if found is None: continue record, tally = found diff --git a/examples/egocap/recording/egocap/config/data_check/data_check_config.yaml b/examples/egocap/recording/egocap/config/data_check/data_check_config.yaml index 145cf1862e..dded231424 100644 --- a/examples/egocap/recording/egocap/config/data_check/data_check_config.yaml +++ b/examples/egocap/recording/egocap/config/data_check/data_check_config.yaml @@ -2,128 +2,56 @@ # # SPDX-License-Identifier: Apache-2.0 -# Ego Capture UI per-episode data-quality thresholds. +# Ego Capture capture-QC thresholds: the documented defaults. # -# Reference data documenting the threshold values capture_qc.py's own defaults are based on; -# this file is not read by any code. Each section maps to a check; an episode is marked bad if -# any enabled check reports an issue. Tune these to your station's tolerances. +# The backend reads this file once at start (EGOCAP_QC_CONFIG names another one for a site), then applies the +# `data_check` section of the station file over it; that section has the same shape and may hold any subset of +# these keys. Every key is optional: one left out keeps the value shown here. An unknown key, a wrong type or a +# value out of range blocks new recordings until it is fixed. +# +# A take is judged once, after it is stopped, from its recorded timestamps and values. Which cameras and pose +# streams each check reads is not configured here: it follows from what the session records. + +guardrails: + enabled: true # false: no capture check runs and every take records SKIPPED + quarantine: true # a take marked bad is finalized under _quarantine/, apart from its session + + # Cameras. A failed gate rejects the take and removes its media. The ratio below is asked twice: of the + # camera's rate over its own frames (when they span ten frame intervals of the expected rate), and of how + # many frames it recorded against how many a take of that length holds, less three intervals (in a take of + # thirteen intervals or more). A take too short for both is not judged. Switching the rule off or lowering + # the ratio keeps takes whose camera lost frames; the settings view says when a station does. + camera_min_fps_enabled: true + camera_min_fps_ratio: 0.86 # of each camera's expected rate (51.6 Hz at 60 Hz) + camera_frame_parity_enabled: false # compares frame counts across cameras; a camera that runs a little under + camera_frame_parity_max_diff: 50 # its nominal rate fails this on every long take, so it stays off + + # Tracking. A failed gate keeps the take and marks it bad. + freeze_enabled: true + freeze_seconds: 1.0 # a pose stream unchanged for this long, judged per stream + freeze_eps: 1.0e-6 # largest per-element change that still counts as unchanged + gloves_expected: false # true where gloves are recorded: their streams are judged and required + tracking_gap_seconds: 1.0 # a tracking source with no row for this long + tracking_gap_marks_bad: false # false: a tracking gap is a warning only + + # Warnings and stored measurements. They never decide. + max_dropped_frames: 6 # per camera, within any drop_window_s + drop_window_s: 2.0 + flat_seconds: 2.0 # a pose stream nearly still for this long + flat_motion_eps: 1.0e-3 + zero_pose_eps: 1.0e-4 # a pose block whose largest absolute value is below this is zeroed + dead_stream_enabled: true # a pose stream unchanged for the whole take + dead_std_eps: 1.0e-6 # mean per-element deviation over time below this: it never varied + dead_frac_identical: 0.95 # or this fraction of rows equal to the first -# --- Timestamp / frame-rate health (per device: cameras, pico, manus) --- timestamp: - enabled: true - # Fail if a device's average FPS deviates from its configured record_fps by - # more than this percentage. Generous so brief startup transients don't fail. - fps_deviation_pct: 10.0 - # Fail if any consecutive frame gap exceeds this many expected frame periods. - max_missing_frames: 3.0 - # Sustained-drop window: fail if any 1s window holds < 60% of expected frames - # (catches a stream that stalls mid-episode, not just a single dropped frame). - frame_drop_window_s: 1.0 - frame_drop_min_fps_ratio: 0.6 - # Fail if devices' time ranges overlap less than this (one source truncated). - coverage_threshold: 0.90 + fps_deviation_pct: 10.0 # warning: a camera's average this far above or below its expected rate -# --- Episode length bounds (seconds) --- duration: default: min_duration_s: 1.0 max_duration_s: 600.0 + marks_bad: false # false: a take outside the limits is a warning only -# --- Camera resolution must match each source's params.camera_resolution --- resolution: - enabled: true - -# --- Guardrails: post-recording capture QC --- -# All capture QC (frame drops / freezes / disconnects) runs here, post-recording, -# where the whole episode is visible. Nothing is gated live during capture: -# frames can arrive late and would cause false positives. A frozen glove/hand is -# also how a dying battery surfaces — a frozen episode is marked bad and the -# operator is prompted to check the glove battery/connection. -# -# Three gates are fatal; every other check is ADVISORY (logged to errors.jsonl and -# written to episode metadata as frame_drops / quality_warnings, never failing -# the episode): -# * a FROZEN stream (the freeze_* block below) marks the take bad: it is kept -# in place, flagged and listed as discarded; -# * a dead avatar hand (avatar_hand_liveness_*) marks the take bad the same way; -# * a camera below its minimum FPS (camera_min_fps_*) REJECTS the take: it is -# not saved at all. -guardrails: - enabled: true - # "Quarantined" in this file means marked bad, not moved: a frozen episode is - # still finalized into its normal studio folder, flagged (freeze_check_passed - # = false) and listed in the dataset's discarded_episode_indices. Nothing is - # uploaded or routed elsewhere; downstream tooling skips the discarded list. - - # --- Sustained freeze: the ONLY fatal (mark-bad) condition --- - # Per stream (each wrist/hand/headset judged independently): the longest - # continuous window where the per-frame max-abs pose delta stays <= freeze_eps. - # The episode is frozen (marked bad) if ANY stream stays frozen for at least - # freeze_seconds — catching any mid-episode dropout of that duration, not just - # streams dead for the whole take. - freeze_enabled: true - freeze_eps: 1.0e-6 - freeze_seconds: 1.0 - - # --- Advisory only (logged + stored, never fatal) --- - # Dropped-frame counts are recorded to metadata (window max + lifetime total) - # so we can mine the real distribution and pick thresholds later. - max_dropped_frames: 6 - drop_window_s: 2.0 - # A sustained no-motion window of at least this many seconds is flagged as a - # "flat" advisory (a glove/controller that dropped its last pose). - flat_seconds: 2.0 - # Per-frame max-abs pose delta at or below this counts as "no motion". - flat_motion_eps: 0.001 - # Pico poses whose max-abs value is under this are treated as all-zero/no-signal. - zero_pose_eps: 0.0001 - # --- Dead-stream ("dead-hand") detection — advisory, per stream --- - # Each pose stream is checked INDEPENDENTLY for being frozen the whole episode, - # so a single dead controller/glove is surfaced as a warning. - dead_stream_enabled: true - # Mean per-element std-over-time below this => the stream never varied. - dead_std_eps: 1.0e-6 - # OR this fraction of frames byte-identical to frame 0 => pinned/frozen. - dead_frac_identical: 0.95 - - # --- Avatar per-hand liveness: FATAL (dead / disconnected glove) --- - # A never-connected or mid-session-dropped avatar (Sharpa exo) glove leaves a - # whole hand pinned at its default (identity keypoints / zero joints) with 0 - # live states while the other hand keeps moving. This gate fails the episode - # (-> marked bad) when a hand is absent, has fewer than avatar_min_states rows, - # or is frozen for the entire episode. Only avatar-glove stations expose the - # *_hand_keypoints fields, so this is inert for pico/manus/wuji configs. - avatar_hand_liveness_enabled: true - avatar_min_states: 2 - - # --- Camera frame-count parity: DISABLED (superseded by camera_min_fps) --- - # Parity compared absolute frame counts between the ego and wrist cameras, so - # the ego OAK's known ~57-58 Hz ceiling at 60 Hz (a device-side limit, - # upstream of the host) failed every take longer than ~20 s even though - # timestamp-based alignment handles the skew without cumulative drift. - # Replaced by the per-camera minimum-fps gate below. - camera_frame_parity_enabled: false - camera_frame_parity_max_diff: 50 - - # --- Camera minimum FPS: FATAL / REJECT (per camera) --- - # Each parity camera (ego + left/right wrist) must average at least - # camera_min_fps_ratio x its configured record_fps over the episode - # (0.86 x 60 = 51.6 Hz). Below that a camera genuinely dropped out or - # stalled; the recorder REJECTS the take (it is not saved at all, unlike a - # frozen take, which is saved and flagged) and the operator re-records the slot. - camera_min_fps_enabled: true - camera_min_fps_ratio: 0.86 - -# --- Pico full-body tracking, when recorded, must be valid --- -pico_body_joints: - enabled: true - device: pico_controller - field: body_joints_pose - valid_field: body_joints_valid - # Keep false for controller-only sessions. Set true for sessions where - # whole-body trackers are required. - required: false - require_valid_field: true - max_invalid_frames: 0 - max_identity_frames: 0 - identity_atol: 1.0e-6 + enabled: true # warning: a camera file encoded at another size than declared diff --git a/examples/egocap/recording/egocap/recording/capture_measure.py b/examples/egocap/recording/egocap/recording/capture_measure.py index cfbf39befb..7488de673a 100644 --- a/examples/egocap/recording/egocap/recording/capture_measure.py +++ b/examples/egocap/recording/egocap/recording/capture_measure.py @@ -2,23 +2,32 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Pure numeric measurements used by the capture-quality checks. +"""Measurements used by the capture-quality checks. -Each function reads arrays and returns numbers (or a problem description); none opens files or decides what a -result means. The decisions live in :mod:`capture_qc`. +Each function reads arrays and returns numbers (or a problem description); none decides what a result means, and +only :func:`video_frame_size` opens a file. The decisions live in :mod:`capture_qc`. """ from __future__ import annotations +from pathlib import Path + +import cv2 import numpy as np __all__ = [ + "INTERVAL_TOLERANCE", "average_fps", + "covers_intervals", + "longest_gap_seconds", "longest_still_seconds", "pico_body_problem", + "rate_measurable", "stream_liveness", "total_frame_drops", + "video_frame_size", "windowed_frame_drops", + "zeroed_pose_rows", ] @@ -29,6 +38,29 @@ def average_fps(timestamps: np.ndarray) -> float: return float((len(timestamps) - 1) / (timestamps[-1] - timestamps[0])) +#: How far short of a number of frame intervals a span may fall and still count as that many: a hundredth of an +#: interval. It is far above the rounding of the stamps (a span of exactly ten intervals computes as 9.999... +#: at some rates and 10.000... at others) and far below the time between two frames, so the same span is on the +#: same side of an edge at every camera rate. +INTERVAL_TOLERANCE = 0.01 + + +def covers_intervals(span_seconds: float, rate_hz: float, intervals: float) -> bool: + """Whether a span of time holds ``intervals`` frame intervals at ``rate_hz``, within the stated tolerance.""" + return span_seconds * rate_hz >= intervals - INTERVAL_TOLERANCE + + +def rate_measurable(timestamps: np.ndarray, expected_fps: float, min_intervals: int) -> bool: + """Whether an average rate over ``timestamps`` means anything: two frames or more, spanning + ``min_intervals`` frame intervals at ``expected_fps``. + + Over a shorter span one frame more or less moves the average by more than any limit worth setting. + """ + if len(timestamps) < 2: + return False + return covers_intervals(float(timestamps[-1] - timestamps[0]), expected_fps, min_intervals) + + def longest_still_seconds(timestamps: np.ndarray, signature: np.ndarray, eps: float) -> float: """Longest window over which consecutive-frame max-abs change stays at or below ``eps``.""" n = min(len(timestamps), len(signature)) @@ -49,6 +81,47 @@ def longest_still_seconds(timestamps: np.ndarray, signature: np.ndarray, eps: fl return float(longest) +def longest_gap_seconds(timestamps: np.ndarray) -> float: + """Longest time between two consecutive rows; 0 with fewer than two rows. + + A source that omits a row while its device is not tracked leaves a hole here that no comparison of + consecutive values can see. + """ + if len(timestamps) < 2: + return 0.0 + return float(np.max(np.diff(np.asarray(timestamps, dtype=np.float64)))) + + +def zeroed_pose_rows(values: np.ndarray, eps: float) -> int: + """How many rows hold a zeroed pose: a 4x4 block whose largest absolute value is below ``eps``. + + A homogeneous transform always has a 1 in its last row, so an all-zero block is never a measured pose. A row + of any other shape is judged whole. + """ + rows = values.shape[0] if values.ndim >= 1 else 0 + if rows == 0: + return 0 + # One block per 4x4 transform, or the whole row when the field is not made of transforms. + blocks = values.reshape(rows, -1, 16) if values.shape[-2:] == (4, 4) else values.reshape(rows, 1, -1) + zeroed = np.max(np.abs(blocks.astype(np.float64)), axis=2) < eps + return int(np.any(zeroed, axis=1).sum()) + + +def video_frame_size(path: Path) -> tuple[int, int]: + """The (width, height) a video file's frames are encoded at, read from its header. + + Raises ``ValueError`` without the path in its text when the file is missing or cannot be opened: the message + is stored with the take. + """ + capture = cv2.VideoCapture(str(path)) + try: + if not capture.isOpened(): + raise ValueError("the video file is missing or cannot be opened") + return int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) + finally: + capture.release() + + def stream_liveness(arr: np.ndarray, std_eps: float, frac_identical: float) -> dict: """Whether one stream is frozen for the whole episode (the native dead-hand measurement). diff --git a/examples/egocap/recording/egocap/recording/capture_qc.py b/examples/egocap/recording/egocap/recording/capture_qc.py index 100b86f7c6..dc37a7bb56 100644 --- a/examples/egocap/recording/egocap/recording/capture_qc.py +++ b/examples/egocap/recording/egocap/recording/capture_qc.py @@ -11,7 +11,13 @@ Gates that reject the take (a camera problem): -* ``camera_min_fps``: each camera must average at least ``camera_min_fps_ratio`` of its expected record rate. +* ``camera_min_fps``: two questions about each camera, both asking the same share (``camera_min_fps_ratio``) of + its expected record rate. Its average rate over its own frames, when they span ``MIN_RATE_INTERVALS`` frame + intervals. And, in a take that lasted, how many frames it recorded against how many a take of that length + holds: :func:`frames_needed` has the formula and its reason. A camera that covered a fraction of the take + fails, however good its rate while it ran; a short gap at either end of a take costs the frames it is worth + and no more. A take too short for either question is not judged: the advisory ``camera_rate_measurable`` says + so, and the take's length is the duration check's to judge. * ``camera_frame_parity`` (opt-in): the listed cameras' frame counts may differ by at most a configured amount. Gates that keep the data but flag the episode bad (a tracking problem): @@ -23,7 +29,16 @@ * ``pico_body_joints``: Pico full-body tracking must have the expected shape, finite values, and no more than the allowed invalid or all-identity frames. -Advisory (typed results and warnings only, never deciding): ``flat_motion``, ``dead_stream`` and ``frame_drops``. +* ``tracking_gap`` (when ``tracking_gap_marks_bad``): a tracking source with no row for at least + ``tracking_gap_seconds``, or with fewer than two rows. A source that omits rows while its device is untracked + shows a dropout this way; the freeze check cannot see it. +* ``duration`` (when ``duration_marks_bad``): the take's length outside ``duration_limits_s``. + +Advisory (typed results and warnings only, never deciding): ``flat_motion``, ``dead_stream``, ``zero_pose``, +``frame_drops``, ``camera_rate_measurable``, ``camera_fps_deviation`` and ``resolution``, plus +``tracking_gap_warning`` and +``duration_warning``, which are the two checks above when they do not mark the take bad. :func:`decide` tells a +gate from an advisory by the result name alone, so the stored report says which one each was. Nothing here imports capture, acquisition or device code. """ @@ -35,48 +50,114 @@ from dataclasses import asdict, dataclass, replace from enum import Enum from pathlib import Path +from typing import Any import numpy as np import zarr from .capture_measure import ( + INTERVAL_TOLERANCE, average_fps, + covers_intervals, + longest_gap_seconds, longest_still_seconds, pico_body_problem, + rate_measurable, stream_liveness, total_frame_drops, + video_frame_size, windowed_frame_drops, + zeroed_pose_rows, ) from .dataset_check import CheckResult, Outcome, QualityReport, report_to_dict -from .episode_layout import FINALIZATION_KEEP, FINALIZATION_REMOVE, FINALIZATION_RETAIN +from .episode_layout import ( + FINALIZATION_KEEP, + FINALIZATION_QUARANTINE, + FINALIZATION_REMOVE, + FINALIZATION_RETAIN, +) from .episode_store import FieldSpec, NumericSourceSpec, VideoSourceSpec __all__ = [ "ALGORITHM_VERSION", "CaptureQcConfig", "PicoBodyConfig", + "PolicySource", "QcDecision", + "advisory_results", "check_capture_quality", "decide", + "deciding_results", "finalization_for", + "frames_needed", "policy_to_dict", "quality_attributes", ] #: Bump when a check's measurement or decision rule changes, so a stored decision names the rules that made it. -ALGORITHM_VERSION = 2 +ALGORITHM_VERSION = 4 CAMERA_MIN_FPS = "camera_min_fps" CAMERA_FRAME_PARITY = "camera_frame_parity" SUSTAINED_FREEZE = "sustained_freeze" AVATAR_HAND_LIVENESS = "avatar_hand_liveness" PICO_BODY_JOINTS = "pico_body_joints" +TRACKING_GAP = "tracking_gap" +DURATION = "duration" FLAT_MOTION = "flat_motion" DEAD_STREAM = "dead_stream" +ZERO_POSE = "zero_pose" FRAME_DROPS = "frame_drops" +CAMERA_FPS_DEVIATION = "camera_fps_deviation" +CAMERA_RATE_MEASURABLE = "camera_rate_measurable" +RESOLUTION = "resolution" +#: The names the two switchable checks report under while they only warn, so :func:`decide` leaves them out. +TRACKING_GAP_WARNING = "tracking_gap_warning" +DURATION_WARNING = "duration_warning" #: Result-name prefixes that decide the outcome, by what a failure means. CAMERA_GATES = (CAMERA_MIN_FPS, CAMERA_FRAME_PARITY) -TRACKING_GATES = (SUSTAINED_FREEZE, AVATAR_HAND_LIVENESS, PICO_BODY_JOINTS) +TRACKING_GATES = (SUSTAINED_FREEZE, AVATAR_HAND_LIVENESS, PICO_BODY_JOINTS, TRACKING_GAP) +#: Every gate whose failure keeps the take and marks it bad: the tracking gates and the take's length. +BAD_GATES = (*TRACKING_GATES, DURATION) + +#: The shortest camera span, in frame intervals at the expected rate, over which an average rate is judged. Over +#: ten intervals one dropped frame costs a tenth of the average, which the default minimum of 0.86 allows; over +#: seven or fewer it alone would reject the take. The edge is exact to ``capture_measure.INTERVAL_TOLERANCE``. +MIN_RATE_INTERVALS = 10 +#: The frame intervals of a take that a healthy camera may not cover: its first frame comes up to one interval +#: after the take's first sample, its last up to one before the take's last, and a frame can be a little late. +#: :func:`frames_needed` takes them off the take's length before it asks for the camera's share. +CAMERA_PHASE_INTERVALS = 3 + + +def frames_needed(take_seconds: float, expected_fps: float, ratio: float) -> tuple[float, float] | None: + """How many frames a take of this length holds at a camera's expected rate, and how many of them the camera + must have recorded: ``(full, needed)``. None for a take too short to ask. + + The whole of the coverage question is here:: + + full = expected_fps x take_seconds + needed = ratio x (full - CAMERA_PHASE_INTERVALS) + + and a camera has covered the take when it recorded ``needed`` frames or more, to within + ``capture_measure.INTERVAL_TOLERANCE`` of a frame. + + ``take_seconds`` is the longest span of any one source of the take, so ``full`` is one frame per interval + for as long as anything was recorded. A healthy camera does not cover all of that (see + ``CAMERA_PHASE_INTERVALS``), so those intervals come off first. ``ratio`` is the share the rate rule asks + (``camera_min_fps_ratio``): a camera may lose to the ends of a take what it may lose inside it, and no more. + Counting frames instead of asking where they lie has no edge to fall off: one frame fewer is one frame + fewer, whether the camera started late, stopped early or ran for a third of the take. + + The question is asked of a take of ``MIN_RATE_INTERVALS + CAMERA_PHASE_INTERVALS`` intervals or more. Below + that the intervals taken off are too large a part of the take for a count to tell a healthy camera from a + starved one. + """ + if not covers_intervals(take_seconds, expected_fps, MIN_RATE_INTERVALS + CAMERA_PHASE_INTERVALS): + return None + full = expected_fps * take_seconds + return full, ratio * (full - CAMERA_PHASE_INTERVALS) + #: The native Avatar glove streams per hand; a hand is alive if any one of them is not frozen. AVATAR_HAND_STREAMS = { @@ -107,11 +188,24 @@ class PicoBodyConfig: identity_atol: float = 1e-6 +@dataclass(frozen=True) +class PolicySource: + """Where a policy's values came from, kept with each take so it names the documented file behind them. + + The defaults file by base name and SHA-256 (never a path), and the station's overrides by dotted key. It is a + record, not a rule: it changes no decision. + """ + + defaults_file: str = "" + defaults_sha256: str = "" + station_overrides: tuple[tuple[str, Any], ...] = () + + @dataclass(frozen=True) class CaptureQcConfig: """Thresholds and the streams each check reads. - The defaults document the values in ``data_check_config.yaml``: a camera must + The defaults are the built-in values that ``data_check_config.yaml`` documents: a camera must average at least 0.86 of its record rate (51.6 Hz at 60 Hz, the value tuned for the ego OAK), a pose may be still for at most 1.0 s (``1e-6`` tolerance), and 2.0 s at ``1e-3`` is a flat-motion advisory. A failed camera gate deletes the take, so a different ratio is a deliberate choice, not a default. @@ -119,34 +213,61 @@ class CaptureQcConfig: # (video source, expected record rate in Hz); None means the source's own configured fps (see ``resolved``) camera_expected_fps: tuple[tuple[str, float | None], ...] = () + # False leaves the cameras' rates measured by the advisories only: no take is rejected for its rate. + camera_min_fps_enabled: bool = True camera_min_fps_ratio: float = 0.86 # Cameras whose frame counts must agree (opt-in; at least two). Off by default for the same reason it is off in # the native configuration: a camera with a hardware ceiling (the ego OAK, about 57-58 Hz against 60) fails # every take longer than about 20 s, and this gate rejects (removes) the take. camera_parity: tuple[str, ...] = () camera_parity_max_diff: int = 50 - pose_streams: tuple[tuple[str, str], ...] = () # (numeric source, float field) checked for freezing + # (numeric source, float field) read by the freeze gate and by the flat-motion, dead-stream and zero-pose + # advisories + pose_streams: tuple[tuple[str, str], ...] = () + # False leaves the pose streams to the advisories only: no take is marked bad for a frozen stream. + freeze_enabled: bool = True freeze_seconds: float = 1.0 freeze_eps: float = 1e-6 + # Numeric sources whose longest time without a row is measured; a warning unless tracking_gap_marks_bad. + tracking_gap_sources: tuple[str, ...] = () + tracking_gap_seconds: float = 1.0 + tracking_gap_marks_bad: bool = False flat_seconds: float = 2.0 flat_eps: float = 1e-3 + zero_pose_eps: float = 1e-4 # advisory: a pose block whose largest absolute value is below this is zeroed avatar_hand_sources: tuple[str, ...] = () # numeric sources that record an Avatar glove's hand streams avatar_min_states: int = 2 + dead_stream_enabled: bool = True # advisory, per pose stream dead_std_eps: float = 1e-6 dead_frac_identical: float = 0.95 pico_body: PicoBodyConfig | None = None max_dropped_frames: int = 6 # advisory: per camera in camera_expected_fps, within any drop_window_s drop_window_s: float = 2.0 + # Advisory: a camera whose average rate is this far, in percent, above or below its expected rate. It is what + # catches a rate declared too low, which the one-sided minimum cannot. + fps_deviation_pct: float = 10.0 + # (shortest, longest) take in seconds, or None for no check; a warning unless duration_marks_bad. + duration_limits_s: tuple[float, float] | None = None + duration_marks_bad: bool = False + # Advisory: (video source, (width, height) its encoded file must have); None means the source's own size. + camera_expected_size: tuple[tuple[str, tuple[int, int] | None], ...] = () + source: PolicySource = PolicySource() def resolved(self, video: tuple[VideoSourceSpec, ...]) -> CaptureQcConfig: - """This policy with every default camera rate replaced by that source's own configured fps. + """This policy with every default camera rate and size replaced by that source's own configured value. An unknown camera keeps its ``None`` so :meth:`problems` reports it. The service resolves once, so the - policy stored with a take (and the configuration digest) always holds concrete rates. + policy stored with a take (and the configuration digest) always holds concrete values. """ - own = {v.name: v.fps for v in video} - rates = tuple((name, own.get(name) if fps is None else fps) for name, fps in self.camera_expected_fps) - return replace(self, camera_expected_fps=rates) + own = {v.name: v for v in video} + rates = tuple( + (name, own[name].fps if fps is None and name in own else fps) for name, fps in self.camera_expected_fps + ) + sizes = tuple( + (name, (own[name].width, own[name].height) if size is None and name in own else size) + for name, size in self.camera_expected_size + ) + return replace(self, camera_expected_fps=rates, camera_expected_size=sizes) def problems(self, numeric: tuple[NumericSourceSpec, ...], video: tuple[VideoSourceSpec, ...]) -> list[str]: """Everything wrong with this configuration against the recorded sources (empty when usable).""" @@ -157,8 +278,11 @@ def problems(self, numeric: tuple[NumericSourceSpec, ...], video: tuple[VideoSou or self.pose_streams or self.avatar_hand_sources or self.pico_body + or self.tracking_gap_sources + or self.camera_expected_size + or self.duration_limits_s ): - problems.append("capture QC names no camera, parity, pose stream, Avatar hand or Pico body check") + problems.append("capture QC names no check to run") video_names = {v.name for v in video} fields = {s.name: {f.name: f for f in s.fields} for s in numeric} for name, fps in self.camera_expected_fps: @@ -166,6 +290,18 @@ def problems(self, numeric: tuple[NumericSourceSpec, ...], video: tuple[VideoSou problems.append(f"camera_expected_fps names unknown video source {name!r}") if fps is not None and not 0 < fps < math.inf: problems.append(f"camera_expected_fps for {name!r} must be a finite number > 0") + for name, size in self.camera_expected_size: + if name not in video_names: + problems.append(f"camera_expected_size names unknown video source {name!r}") + if size is not None and not all(isinstance(side, int) and side > 0 for side in size): + problems.append(f"camera_expected_size for {name!r} must be a positive width and height") + for source in self.tracking_gap_sources: + if source not in fields: + problems.append(f"tracking_gap_sources names unknown numeric source {source!r}") + if self.duration_limits_s is not None: + shortest, longest = self.duration_limits_s + if not 0 <= shortest < longest < math.inf: + problems.append("duration_limits_s must be a finite (shortest, longest) with shortest < longest") if self.camera_parity: unknown = sorted(set(self.camera_parity) - video_names) if len(self.camera_parity) < 2 or len(set(self.camera_parity)) != len(self.camera_parity) or unknown: @@ -190,7 +326,17 @@ def problems(self, numeric: tuple[NumericSourceSpec, ...], video: tuple[VideoSou problems.append("camera_min_fps_ratio must be > 0 and <= 1") if not 0 < self.dead_frac_identical <= 1: problems.append("dead_frac_identical must be > 0 and <= 1") - for label in ("freeze_seconds", "freeze_eps", "flat_seconds", "flat_eps", "dead_std_eps", "drop_window_s"): + for label in ( + "freeze_seconds", + "freeze_eps", + "flat_seconds", + "flat_eps", + "dead_std_eps", + "drop_window_s", + "tracking_gap_seconds", + "zero_pose_eps", + "fps_deviation_pct", + ): if not 0 < getattr(self, label) < math.inf: problems.append(f"{label} must be a finite number > 0") if not isinstance(self.avatar_min_states, int) or self.avatar_min_states < 1: @@ -222,7 +368,12 @@ def _pico_problems(self, fields: dict[str, dict[str, FieldSpec]]) -> list[str]: def policy_to_dict(config: CaptureQcConfig) -> dict: """The concrete, serializable policy (thresholds, mappings and algorithm version) stored with each take.""" - return {"algorithm_version": ALGORITHM_VERSION, **asdict(config)} + policy = {"algorithm_version": ALGORITHM_VERSION, **asdict(config)} + # Overrides read better by key than as pairs; a camera-rate override is itself a name -> rate mapping. + policy["source"]["station_overrides"] = { + key: dict(value) if isinstance(value, tuple) else value for key, value in config.source.station_overrides + } + return policy def _measure(name: str, measure: Callable[[], tuple[list[str], str, dict]]) -> CheckResult: @@ -250,9 +401,15 @@ def check_capture_quality(pending_dir: Path, config: CaptureQcConfig) -> Quality root = zarr.open_group(str(pending_dir), mode="r") except Exception as exc: # noqa: BLE001 - every item is then unmeasured, so every gate is an ERROR names = [ - *[f"{CAMERA_MIN_FPS}:{name}" for name, _ in config.camera_expected_fps], + *[ + f"{CAMERA_MIN_FPS}:{name}" + for name, _ in config.camera_expected_fps + if config.camera_min_fps_enabled + ], *([CAMERA_FRAME_PARITY] if config.camera_parity else []), - *[f"{SUSTAINED_FREEZE}:{s}/{f}" for s, f in config.pose_streams], + *[f"{SUSTAINED_FREEZE}:{s}/{f}" for s, f in config.pose_streams if config.freeze_enabled], + *[f"{TRACKING_GAP}:{s}" for s in config.tracking_gap_sources if config.tracking_gap_marks_bad], + *([DURATION] if config.duration_limits_s and config.duration_marks_bad else []), *[ f"{AVATAR_HAND_LIVENESS}:{s}/{side}" for s in config.avatar_hand_sources @@ -269,13 +426,53 @@ def times(source: str) -> np.ndarray: return root[source]["capture_time"][:] def camera_min_fps(name: str, expected: float | None): + """The two questions of the camera rate rule; a take too short for both is not judged.""" if expected is None: raise ValueError("the expected rate is unresolved; resolve the policy with CaptureQcConfig.resolved()") - fps, minimum = average_fps(times(name)), config.camera_min_fps_ratio * expected + stamps, ratio = times(name), config.camera_min_fps_ratio + minimum = ratio * expected + issues, evidence = [], [] + measured: dict[str, Any] = {"minimum_fps": minimum, "expected_fps": expected} + # The rate while the camera ran, over its own frames. + if rate_measurable(stamps, expected, MIN_RATE_INTERVALS): + fps = average_fps(stamps) + measured["fps"] = fps + evidence.append(f"{fps:.2f} fps average (minimum {minimum:.2f})") + if fps < minimum: + issues.append(f"{name}: {fps:.2f} fps average is below {ratio} x {expected} = {minimum:.2f}") + # How much of the take it recorded at all: the rate above says nothing of a camera that ran for a part. + take = take_seconds() + asked = frames_needed(take, expected, ratio) + if asked is not None: + (full, needed), frames = asked, len(stamps) + measured.update( + frames=frames, span_s=camera_span(stamps), take_s=take, take_frames=full, needed_frames=needed + ) + evidence.append(f"{frames} of {full:.1f} frames in a {take:.2f}s take (needs {needed:.1f})") + if frames < needed - INTERVAL_TOLERANCE: + issues.append( + f"{name}: {frames} frame(s) recorded of the {full:.1f} a {take:.2f}s take holds at " + f"{expected} fps (needs {needed:.1f})" + ) + return issues, "; ".join(evidence) or "too short to measure a rate", measured + + def rate_span(name: str, expected: float | None): + """Whether the camera rate rule could judge this take at all: only a take too short for a rate fails.""" + if expected is None: + raise ValueError("the expected rate is unresolved; resolve the policy with CaptureQcConfig.resolved()") + stamps = times(name) + span = camera_span(stamps) + needed = MIN_RATE_INTERVALS / expected issue = ( - f"{name}: {fps:.2f} fps average is below {config.camera_min_fps_ratio} x {expected} = {minimum:.2f}" + f"{name}: {len(stamps)} frame(s) over {span:.2f}s is too short to measure a rate " + f"(it takes {MIN_RATE_INTERVALS} frame intervals, {needed:.2f}s)" + ) + measured = {"frames": len(stamps), "span_s": span, "needed_s": needed} + judged = ( + rate_measurable(stamps, expected, MIN_RATE_INTERVALS) + or frames_needed(take_seconds(), expected, config.camera_min_fps_ratio) is not None ) - return ([issue] if fps < minimum else []), f"{fps:.2f} fps average (minimum {minimum:.2f})", {"fps": fps} + return ([] if judged else [issue]), f"{len(stamps)} frames over {span:.2f}s", measured def camera_frame_parity(): counts = {name: len(times(name)) for name in config.camera_parity} @@ -294,9 +491,92 @@ def still(source: str, field: str, seconds: float, eps: float): return ( ([issue] if longest >= seconds else []), f"longest still window {longest:.2f}s (limit {seconds}s)", - {"longest_still_s": longest}, + {"longest_still_s": longest, "limit_s": seconds}, + ) + + def tracking_gap(source: str): + """The longest time one tracking source went without a row; too few rows to measure is a finding too.""" + stamps = times(source) + rows, gap, limit = len(stamps), longest_gap_seconds(stamps), config.tracking_gap_seconds + issues = [] + if rows < 2: + # Nothing to measure a gap between: the source recorded next to nothing for the whole take. + issues.append(f"{source}: only {rows} row(s) recorded") + elif gap >= limit: + issues.append(f"{source}: no row for {gap:.2f}s (limit {limit}s)") + measured = {"longest_gap_s": gap, "limit_s": limit, "rows": rows} + return issues, f"longest gap {gap:.2f}s over {rows} rows (limit {limit}s)", measured + + def take_seconds() -> float: + """How long the take lasted: the longest span of any one of its sources. + + Timestamps of different sources are never subtracted from each other. + """ + stamps = [group["capture_time"][:] for _, group in root.groups()] + return max((float(t[-1] - t[0]) for t in stamps if len(t)), default=0.0) + + def camera_span(stamps: np.ndarray) -> float: + """From a camera's first frame to its last, in seconds; nothing for fewer than two frames.""" + return float(stamps[-1] - stamps[0]) if len(stamps) else 0.0 + + def duration(): + """The take's length against the configured limits.""" + shortest, longest = config.duration_limits_s + seconds = take_seconds() + issue = f"the take lasted {seconds:.2f}s, outside {shortest}s to {longest}s" + measured = {"duration_s": seconds, "min_s": shortest, "max_s": longest} + return ([] if shortest <= seconds <= longest else [issue]), f"{seconds:.2f}s", measured + + def zero_pose(source: str, field: str): + """Rows of one pose stream that hold a zeroed pose, written for a joint that could not be tracked.""" + values = root[source][field][:] + zeroed = zeroed_pose_rows(values, config.zero_pose_eps) + issue = ( + f"{source}/{field}: {zeroed} of {len(values)} rows hold a zeroed pose (below {config.zero_pose_eps})" + ) + return ([issue] if zeroed else []), f"{zeroed} zeroed rows", {"zero_rows": zeroed, "rows": len(values)} + + def fps_deviation(name: str, expected: float | None): + """One camera's average rate against its expected rate, in either direction.""" + if expected is None: + raise ValueError("the expected rate is unresolved; resolve the policy with CaptureQcConfig.resolved()") + stamps = times(name) + if not rate_measurable(stamps, expected, MIN_RATE_INTERVALS): + # No rate, so no deviation: the minimum-rate gate or ``camera_rate_measurable`` says which case it is. + return [], "too short to measure a rate", {"expected_fps": expected} + fps = average_fps(stamps) + percent = abs(fps - expected) / expected * 100.0 + side = "below" if fps < expected else "above" + issue = ( + f"{name}: {fps:.2f} fps average is {percent:.1f}% {side} the expected {expected} " + f"(limit {config.fps_deviation_pct}%)" + ) + measured = { + "fps": fps, + "expected_fps": expected, + "deviation_pct": percent, + "limit_pct": config.fps_deviation_pct, + } + return ( + ([issue] if percent > config.fps_deviation_pct else []), + f"{fps:.2f} fps average, {percent:.1f}% from {expected}", + measured, ) + def resolution(name: str, expected: tuple[int, int] | None): + """The frame size one camera's file was encoded at against the size declared for it.""" + if expected is None: + raise ValueError("the expected size is unresolved; resolve the policy with CaptureQcConfig.resolved()") + width, height = video_frame_size(pending_dir / f"{name}.mp4") + issue = f"{name}: encoded frames are {width}x{height}, declared {expected[0]}x{expected[1]}" + measured = { + "width": width, + "height": height, + "expected_width": expected[0], + "expected_height": expected[1], + } + return ([] if (width, height) == tuple(expected) else [issue]), f"{width}x{height}", measured + def avatar_hand(source: str, side: str): group, streams = root[source], [s for s in AVATAR_HAND_STREAMS[side] if s in root[source]] rows, live = 0, False @@ -351,18 +631,33 @@ def drops(name: str, expected: float): measured, ) - results = [ - _measure(f"{CAMERA_MIN_FPS}:{n}", lambda n=n, e=e: camera_min_fps(n, e)) - for n, e in config.camera_expected_fps - ] + # Gates first (they decide), then advisories. A switchable check lands in one list or the other under the name + # that says which, so the stored report alone tells a gate from a warning. + results, advisories = [], [] + if config.camera_min_fps_enabled: + results += [ + _measure(f"{CAMERA_MIN_FPS}:{n}", lambda n=n, e=e: camera_min_fps(n, e)) + for n, e in config.camera_expected_fps + ] if config.camera_parity: results.append(_measure(CAMERA_FRAME_PARITY, camera_frame_parity)) - results += [ - _measure( - f"{SUSTAINED_FREEZE}:{s}/{f}", lambda s=s, f=f: still(s, f, config.freeze_seconds, config.freeze_eps) - ) - for s, f in config.pose_streams - ] + if config.freeze_enabled: + results += [ + _measure( + f"{SUSTAINED_FREEZE}:{s}/{f}", + lambda s=s, f=f: still(s, f, config.freeze_seconds, config.freeze_eps), + ) + for s, f in config.pose_streams + ] + gap_name, gap_list = ( + (TRACKING_GAP, results) if config.tracking_gap_marks_bad else (TRACKING_GAP_WARNING, advisories) + ) + gap_list += [_measure(f"{gap_name}:{s}", lambda s=s: tracking_gap(s)) for s in config.tracking_gap_sources] + if config.duration_limits_s is not None: + if config.duration_marks_bad: + results.append(_measure(DURATION, duration)) + else: + advisories.append(_measure(DURATION_WARNING, duration)) results += [ _measure(f"{AVATAR_HAND_LIVENESS}:{s}/{side}", lambda s=s, side=side: avatar_hand(s, side)) for s in config.avatar_hand_sources @@ -370,16 +665,31 @@ def drops(name: str, expected: float): ] if config.pico_body: results.append(_measure(f"{PICO_BODY_JOINTS}:{config.pico_body.source}", pico_body)) - advisories = [ + advisories += [ _measure(f"{FLAT_MOTION}:{s}/{f}", lambda s=s, f=f: still(s, f, config.flat_seconds, config.flat_eps)) for s, f in config.pose_streams ] + if config.dead_stream_enabled: + advisories += [ + _measure(f"{DEAD_STREAM}:{s}/{f}", lambda s=s, f=f: dead_stream(s, f)) for s, f in config.pose_streams + ] advisories += [ - _measure(f"{DEAD_STREAM}:{s}/{f}", lambda s=s, f=f: dead_stream(s, f)) for s, f in config.pose_streams + _measure(f"{ZERO_POSE}:{s}/{f}", lambda s=s, f=f: zero_pose(s, f)) for s, f in config.pose_streams ] advisories += [ _measure(f"{FRAME_DROPS}:{n}", lambda n=n, e=e: drops(n, e)) for n, e in config.camera_expected_fps ] + advisories += [ + _measure(f"{CAMERA_RATE_MEASURABLE}:{n}", lambda n=n, e=e: rate_span(n, e)) + for n, e in config.camera_expected_fps + ] + advisories += [ + _measure(f"{CAMERA_FPS_DEVIATION}:{n}", lambda n=n, e=e: fps_deviation(n, e)) + for n, e in config.camera_expected_fps + ] + advisories += [ + _measure(f"{RESOLUTION}:{n}", lambda n=n, e=e: resolution(n, e)) for n, e in config.camera_expected_size + ] warnings = tuple(i for r in advisories if r.outcome is not Outcome.PASSED for i in r.issues) failed = [r for r in results if r.outcome is Outcome.FAILED] overall = ( @@ -409,7 +719,7 @@ def decide(report: QualityReport | None) -> QcDecision: kind = r.name.split(":", 1)[0] if kind in CAMERA_GATES: outcomes["camera"].add(r.outcome) - elif kind in TRACKING_GATES: + elif kind in BAD_GATES: outcomes["tracking"].add(r.outcome) camera, tracking = outcomes["camera"], outcomes["tracking"] if Outcome.FAILED in camera: @@ -421,11 +731,48 @@ def decide(report: QualityReport | None) -> QcDecision: return QcDecision.PASSED -def finalization_for(integrity: Outcome, decision: QcDecision) -> str: - """What finalization does with a checked take: failed integrity retains it, a camera rejection removes it.""" +def deciding_results(report: QualityReport | None, decision: QcDecision) -> tuple[CheckResult, ...]: + """The results that made ``decision``, so a caller can say why a take ended as it did. + + The failed camera gates of a rejection, the failed gates that mark a take bad of a flagged one, and the gates + that could not run of an ERROR. A passed or skipped take has none: warnings never decide. + """ + if report is None: + return () + wanted = { + QcDecision.REJECTED_CAMERA: (CAMERA_GATES, Outcome.FAILED), + QcDecision.FLAGGED_BAD: (BAD_GATES, Outcome.FAILED), + QcDecision.ERROR: ((*CAMERA_GATES, *BAD_GATES), Outcome.ERROR), + }.get(decision) + if wanted is None: + return () + gates, outcome = wanted + return tuple(r for r in report.check_results if r.name.split(":", 1)[0] in gates and r.outcome is outcome) + + +def advisory_results(report: QualityReport | None) -> tuple[CheckResult, ...]: + """The advisory results that did not pass: the warnings of a report, with their measurements.""" + if report is None: + return () + gates = (*CAMERA_GATES, *BAD_GATES) + return tuple( + r for r in report.check_results if r.name.split(":", 1)[0] not in gates and r.outcome is not Outcome.PASSED + ) + + +def finalization_for(integrity: Outcome, decision: QcDecision, quarantine: bool = False) -> str: + """What finalization does with a checked take. + + Failed integrity retains it, a camera rejection removes it, and a take marked bad is quarantined where the + station sets bad takes apart (``quarantine``); every other take is kept, a bad one flagged. + """ if integrity is not Outcome.PASSED: return FINALIZATION_RETAIN - return FINALIZATION_REMOVE if decision is QcDecision.REJECTED_CAMERA else FINALIZATION_KEEP + if decision is QcDecision.REJECTED_CAMERA: + return FINALIZATION_REMOVE + if decision is QcDecision.FLAGGED_BAD and quarantine: + return FINALIZATION_QUARANTINE + return FINALIZATION_KEEP def quality_attributes(decision: QcDecision, report: QualityReport | None, policy: dict | None) -> dict: diff --git a/examples/egocap/recording/egocap/recording/capture_qc_policy.py b/examples/egocap/recording/egocap/recording/capture_qc_policy.py new file mode 100644 index 0000000000..f5acfe451d --- /dev/null +++ b/examples/egocap/recording/egocap/recording/capture_qc_policy.py @@ -0,0 +1,345 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The capture-QC policy a station records with: the documented defaults file plus a station's overrides. + +Resolution order: the built-in values (the defaults of :class:`CaptureQcPolicy`), then the defaults file +(``config/data_check/data_check_config.yaml``, or another file a site names), then the ``data_check`` section of +the station file. Every key is optional; an unknown key, a wrong type or a value out of range is a +:class:`CaptureQcPolicyError` naming the key, never a silent fallback. + +The policy holds thresholds and switches only. Which streams each check reads is derived from what a session +records, by :func:`capture_config_for`. +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any + +import yaml + +from .capture_qc import CaptureQcConfig, PolicySource + +__all__ = [ + "SHIPPED_POLICY_FILE", + "CaptureQcPolicy", + "CaptureQcPolicyError", + "capture_config_for", + "effective_mapping", + "load_policy", + "resolve_policy", + "validate_section", +] + +#: The documented defaults shipped with the package (package data, so an installed copy has it too). +SHIPPED_POLICY_FILE = Path(__file__).resolve().parents[1] / "config" / "data_check" / "data_check_config.yaml" + +#: The one authority for every number the checks and this policy share. +_BUILT_IN = CaptureQcConfig() + + +class CaptureQcPolicyError(ValueError): + """A defaults file or station section that cannot be used; the message names the offending key.""" + + +@dataclass(frozen=True) +class CaptureQcPolicy: + """Every switch and threshold of capture QC, resolved for one station. The defaults are the built-in values.""" + + enabled: bool = True + #: A take the checks mark bad is finalized in the quarantine folder instead of its session. + quarantine: bool = True + camera_min_fps_enabled: bool = True + camera_min_fps_ratio: float = _BUILT_IN.camera_min_fps_ratio + camera_frame_parity_enabled: bool = False + camera_frame_parity_max_diff: int = _BUILT_IN.camera_parity_max_diff + freeze_enabled: bool = True + freeze_seconds: float = _BUILT_IN.freeze_seconds + freeze_eps: float = _BUILT_IN.freeze_eps + #: Gloves are recorded at this station: their streams are judged and the glove source must hold rows. + gloves_expected: bool = False + tracking_gap_seconds: float = _BUILT_IN.tracking_gap_seconds + tracking_gap_marks_bad: bool = False + max_dropped_frames: int = _BUILT_IN.max_dropped_frames + drop_window_s: float = _BUILT_IN.drop_window_s + flat_seconds: float = _BUILT_IN.flat_seconds + flat_motion_eps: float = _BUILT_IN.flat_eps + zero_pose_eps: float = _BUILT_IN.zero_pose_eps + dead_stream_enabled: bool = True + dead_std_eps: float = _BUILT_IN.dead_std_eps + dead_frac_identical: float = _BUILT_IN.dead_frac_identical + fps_deviation_pct: float = _BUILT_IN.fps_deviation_pct + min_duration_s: float = 1.0 + max_duration_s: float = 600.0 + duration_marks_bad: bool = False + resolution_enabled: bool = True + #: Station section only: (camera, rate in Hz) replacing that camera's declared rate. + camera_expected_fps: tuple[tuple[str, float], ...] = () + #: Where the values came from: the defaults file and the station's overrides. Not a threshold. + source: PolicySource = PolicySource() + + +def _is_number(value: Any) -> bool: + """A real number; a bool is not one, although Python counts it as an int.""" + return isinstance(value, int | float) and not isinstance(value, bool) + + +def _boolean(value: Any) -> bool: + """A YAML boolean, never a number or string standing in for one.""" + if not isinstance(value, bool): + raise ValueError("must be true or false") + return value + + +def _positive(value: Any) -> float: + """A finite number above zero.""" + if not _is_number(value) or not 0 < value < math.inf: + raise ValueError("must be a finite number > 0") + return float(value) + + +def _non_negative(value: Any) -> float: + """A finite number at or above zero.""" + if not _is_number(value) or not 0 <= value < math.inf: + raise ValueError("must be a finite number >= 0") + return float(value) + + +def _ratio(value: Any) -> float: + """A fraction above zero and at most one.""" + if not _is_number(value) or not 0 < value <= 1: + raise ValueError("must be a number > 0 and <= 1") + return float(value) + + +def _count(value: Any) -> int: + """A whole number at or above zero.""" + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + raise ValueError("must be an integer >= 0") + return value + + +def _camera_rates(value: Any) -> tuple[tuple[str, float], ...]: + """A mapping of camera name to its expected rate in Hz.""" + if not isinstance(value, Mapping) or not all(isinstance(name, str) and name for name in value): + raise ValueError("must map camera names to rates in Hz") + rates = [] + for name, rate in value.items(): + if not _is_number(rate) or not 0 < rate < math.inf: + raise ValueError(f"rate for {name!r} must be a finite number > 0") + rates.append((name, float(rate))) + return tuple(rates) + + +#: Every key of the defaults file, by dotted path: the policy field it sets and the rule its value must meet. +_FILE_KEYS: dict[str, tuple[str, Callable[[Any], Any]]] = { + "guardrails.enabled": ("enabled", _boolean), + "guardrails.quarantine": ("quarantine", _boolean), + "guardrails.camera_min_fps_enabled": ("camera_min_fps_enabled", _boolean), + "guardrails.camera_min_fps_ratio": ("camera_min_fps_ratio", _ratio), + "guardrails.camera_frame_parity_enabled": ("camera_frame_parity_enabled", _boolean), + "guardrails.camera_frame_parity_max_diff": ("camera_frame_parity_max_diff", _count), + "guardrails.freeze_enabled": ("freeze_enabled", _boolean), + "guardrails.freeze_seconds": ("freeze_seconds", _positive), + "guardrails.freeze_eps": ("freeze_eps", _positive), + "guardrails.gloves_expected": ("gloves_expected", _boolean), + "guardrails.tracking_gap_seconds": ("tracking_gap_seconds", _positive), + "guardrails.tracking_gap_marks_bad": ("tracking_gap_marks_bad", _boolean), + "guardrails.max_dropped_frames": ("max_dropped_frames", _count), + "guardrails.drop_window_s": ("drop_window_s", _positive), + "guardrails.flat_seconds": ("flat_seconds", _positive), + "guardrails.flat_motion_eps": ("flat_motion_eps", _positive), + "guardrails.zero_pose_eps": ("zero_pose_eps", _positive), + "guardrails.dead_stream_enabled": ("dead_stream_enabled", _boolean), + "guardrails.dead_std_eps": ("dead_std_eps", _positive), + "guardrails.dead_frac_identical": ("dead_frac_identical", _ratio), + "timestamp.fps_deviation_pct": ("fps_deviation_pct", _positive), + "duration.default.min_duration_s": ("min_duration_s", _non_negative), + "duration.default.max_duration_s": ("max_duration_s", _positive), + "duration.marks_bad": ("duration_marks_bad", _boolean), + "resolution.enabled": ("resolution_enabled", _boolean), +} +#: Keys a station section may add: they describe that station's cameras, so the shared defaults cannot hold them. +_STATION_KEYS: dict[str, tuple[str, Callable[[Any], Any]]] = { + "guardrails.camera_expected_fps": ("camera_expected_fps", _camera_rates), +} +#: Dotted paths that are sections (mappings), not values. +_SECTIONS = frozenset( + key.rsplit(".", depth)[0] for key in (*_FILE_KEYS, *_STATION_KEYS) for depth in range(1, key.count(".") + 1) +) + + +def _flatten(section: Any, prefix: str = "") -> dict[str, Any]: + """A nested section as dotted key -> value, descending only into the known sections.""" + if not isinstance(section, Mapping): + raise CaptureQcPolicyError(f"{prefix.rstrip('.') or 'the data-check configuration'} must be a mapping") + flat: dict[str, Any] = {} + for name, value in section.items(): + key = f"{prefix}{name}" + if key in _SECTIONS: + # An empty section is written as a bare key, which YAML reads as null. + flat.update(_flatten({} if value is None else value, f"{key}.")) + else: + flat[key] = value + return flat + + +def validate_section(section: Any, *, station: bool) -> dict[str, Any]: + """The values of a defaults mapping, or of a station's ``data_check`` section, by dotted key. + + Raises :class:`CaptureQcPolicyError` naming the first key that is unknown, of the wrong type or out of range. + """ + known = {**_FILE_KEYS, **(_STATION_KEYS if station else {})} + values: dict[str, Any] = {} + for key, raw in _flatten(section).items(): + # A key nobody reads is refused, not ignored: a misspelt threshold would otherwise silently keep its + # default while the file says something else. + if key not in known: + if key in _STATION_KEYS: + raise CaptureQcPolicyError(f"{key} is allowed only in a station's data_check section") + raise CaptureQcPolicyError(f"unknown key {key!r}") + # Each rule returns the value in the type its field holds, or says what the value must be. + try: + values[key] = known[key][1](raw) + except ValueError as exc: + raise CaptureQcPolicyError(f"{key} {exc}, got {raw!r}") from None + return values + + +def _apply(policy: CaptureQcPolicy, values: Mapping[str, Any]) -> CaptureQcPolicy: + """``policy`` with the validated dotted-key ``values`` set on their fields.""" + known = {**_FILE_KEYS, **_STATION_KEYS} + return replace(policy, **{known[key][0]: value for key, value in values.items()}) + + +def resolve_policy( + defaults: Any = None, station: Any = None, *, defaults_file: str = "", defaults_sha256: str = "" +) -> CaptureQcPolicy: + """The policy from a parsed defaults mapping and a parsed station section, either of which may be absent. + + ``defaults_file`` and ``defaults_sha256`` name the file the defaults were read from, for the record kept with + each take; a base name only, never a path. + """ + # Each layer is validated on its own, so an error names the key in the file that holds it. + file_values = validate_section(defaults, station=False) if defaults is not None else {} + station_values = validate_section(station, station=True) if station is not None else {} + # Built-in values, then the defaults file, then the station's section. + policy = _apply(_apply(CaptureQcPolicy(), file_values), station_values) + # Checked on the merged result: either file may move one bound past the other. + if policy.min_duration_s >= policy.max_duration_s: + raise CaptureQcPolicyError( + f"duration.default.max_duration_s must be above min_duration_s, got {policy.max_duration_s!r} " + f"with a minimum of {policy.min_duration_s!r}" + ) + # What the station changed is kept by key, in a stable order, as part of the record stored with each take. + overrides = tuple(sorted(station_values.items())) + return replace(policy, source=PolicySource(defaults_file, defaults_sha256, overrides)) + + +def _plain(value: Any) -> Any: + """A validated value in the form it is reported in: camera rates as a name -> rate mapping.""" + return dict(value) if isinstance(value, tuple) else value + + +class _NoDuplicateKeys(yaml.SafeLoader): + """A safe loader that refuses a repeated key instead of keeping the last one.""" + + +def _mapping_without_duplicates(loader: yaml.SafeLoader, node: yaml.MappingNode) -> dict: + """Build one mapping, raising on a key that appears twice: the earlier value would be dropped unseen.""" + mapping: dict = {} + for key_node, value_node in node.value: + key = loader.construct_object(key_node, deep=True) + if key in mapping: + raise CaptureQcPolicyError(f"duplicate key {key!r}") + mapping[key] = loader.construct_object(value_node, deep=True) + return mapping + + +_NoDuplicateKeys.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping_without_duplicates) + + +def load_policy(defaults_path: Path | None = None, station: Any = None) -> CaptureQcPolicy: + """Read the defaults file (the shipped one when none is named) and merge a station's section over it. + + Raises :class:`CaptureQcPolicyError` when the file cannot be read or parsed, or a key is refused. + """ + path = SHIPPED_POLICY_FILE if defaults_path is None else Path(defaults_path) + try: + raw = path.read_bytes() + # An empty file is a valid one that sets nothing. + defaults = yaml.load(raw.decode("utf-8"), Loader=_NoDuplicateKeys) or {} # noqa: S506 - a SafeLoader + except (OSError, UnicodeDecodeError, yaml.YAMLError, TypeError) as exc: + # A TypeError is an unhashable mapping key, which the duplicate check trips over. + raise CaptureQcPolicyError(f"data-check file {path.name} cannot be read: {exc}") from exc + return resolve_policy( + defaults, station, defaults_file=path.name, defaults_sha256=hashlib.sha256(raw).hexdigest() + ) + + +def effective_mapping(policy: CaptureQcPolicy) -> dict[str, Any]: + """The policy in the shape of the defaults file, so a reader can compare the two key by key.""" + nested: dict[str, Any] = {} + for key, (field_name, _rule) in {**_FILE_KEYS, **_STATION_KEYS}.items(): + # Rebuild the file's nesting from the dotted key, creating each section on first use. + *sections, name = key.split(".") + target = nested + for section in sections: + target = target.setdefault(section, {}) + target[name] = _plain(getattr(policy, field_name)) + return nested + + +def capture_config_for( + policy: CaptureQcPolicy, + cameras: Sequence[str], + tracking_streams: Sequence[tuple[str, str]], + glove_streams: Sequence[tuple[str, str]] = (), +) -> CaptureQcConfig | None: + """The checks one session runs: the policy's thresholds over the cameras and pose streams it records. + + ``tracking_streams`` are always judged; ``glove_streams`` only where the station expects gloves, because a + station without them records no glove row. None when the policy switches capture QC off. + """ + if not policy.enabled: + return None + overrides = dict(policy.camera_expected_fps) + # A rate for a camera this session does not record is passed on, so the service refuses it by name at open + # instead of the override silently applying to nothing. + rates = [(name, overrides.get(name)) for name in cameras] + rates += [(name, fps) for name, fps in overrides.items() if name not in cameras] + streams = tuple(tracking_streams) + (tuple(glove_streams) if policy.gloves_expected else ()) + return CaptureQcConfig( + camera_expected_fps=tuple(rates), + camera_min_fps_enabled=policy.camera_min_fps_enabled, + camera_min_fps_ratio=policy.camera_min_fps_ratio, + # Parity compares cameras with each other, so it needs two. + camera_parity=tuple(cameras) if policy.camera_frame_parity_enabled and len(cameras) >= 2 else (), + camera_parity_max_diff=policy.camera_frame_parity_max_diff, + pose_streams=streams, + freeze_enabled=policy.freeze_enabled, + freeze_seconds=policy.freeze_seconds, + freeze_eps=policy.freeze_eps, + tracking_gap_sources=tuple(dict.fromkeys(source for source, _ in streams)), + tracking_gap_seconds=policy.tracking_gap_seconds, + tracking_gap_marks_bad=policy.tracking_gap_marks_bad, + flat_seconds=policy.flat_seconds, + flat_eps=policy.flat_motion_eps, + zero_pose_eps=policy.zero_pose_eps, + dead_stream_enabled=policy.dead_stream_enabled, + dead_std_eps=policy.dead_std_eps, + dead_frac_identical=policy.dead_frac_identical, + max_dropped_frames=policy.max_dropped_frames, + drop_window_s=policy.drop_window_s, + fps_deviation_pct=policy.fps_deviation_pct, + duration_limits_s=(policy.min_duration_s, policy.max_duration_s), + duration_marks_bad=policy.duration_marks_bad, + camera_expected_size=tuple((name, None) for name in cameras) if policy.resolution_enabled else (), + source=policy.source, + ) diff --git a/examples/egocap/recording/egocap/recording/episode_layout.py b/examples/egocap/recording/egocap/recording/episode_layout.py index 693f4a53e4..1468cb9ff9 100644 --- a/examples/egocap/recording/egocap/recording/episode_layout.py +++ b/examples/egocap/recording/egocap/recording/episode_layout.py @@ -6,7 +6,9 @@ A session directory holds ``episode_.pending`` while an episode is being written and, without routing, ``episode_`` once finalized; with routing a finalized episode lives at ``//episode_`` -under the output root instead. The ``.recording/`` sidecar directory holds one ``episode_.json`` manifest per +under the output root instead. A take the capture checks marked bad, on a station that quarantines, is finalized +at ``_quarantine//episode_`` under the output root: the session itself never moves, only where that +one take is published. The ``.recording/`` sidecar directory holds one ``episode_.json`` manifest per episode (and, with routing, ``routes.json``). The manifest lives outside the episode so it stays reachable across the pending-to-final rename; it records what is needed to resume or safely discard an interrupted episode after a crash. @@ -20,10 +22,15 @@ import fcntl import json +import logging import os import re import shutil import tempfile +import threading +import time +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any @@ -35,22 +42,30 @@ from .constants import PENDING_SUFFIX +logger = logging.getLogger("isaaccapture.egocap.episode_layout") + MANIFEST_DIR = ".recording" -MANIFEST_SCHEMA_VERSION = 4 +MANIFEST_SCHEMA_VERSION = 5 #: Older records are decoded onto the current fields when read and rewritten at the current version only when #: next saved; nothing is migrated at startup. -READABLE_SCHEMA_VERSIONS = (1, 2, 3, 4) +READABLE_SCHEMA_VERSIONS = (1, 2, 3, 4, 5) _EPISODE_NAME = re.compile(r"^episode_(\d+)(\.pending)?$") #: What finalization does with a checked take, recorded durably so recovery never re-derives it from policy: -#: KEEP publishes its output, REMOVE deletes this take's own data (a resolved rejection), RETAIN leaves its data -#: in place for explicit resolution. +#: KEEP publishes its output, QUARANTINE publishes it in the quarantine folder instead (kept, but marked bad), +#: REMOVE deletes this take's own data (a resolved rejection), RETAIN leaves its data in place for explicit +#: resolution. FINALIZATION_KEEP = "KEEP" +FINALIZATION_QUARANTINE = "QUARANTINE" FINALIZATION_REMOVE = "REMOVE" FINALIZATION_RETAIN = "RETAIN" -#: Storage phases a manifest can record, in the order an episode passes through them. -PHASES = ("WRITING", "SEALED", "CHECKED", "FINALIZED", "REJECTED", "DISCARDED") +#: Storage phases a manifest can record. An episode passes WRITING, SEALED and CHECKED and ends in one of the rest. +PHASES = ("WRITING", "SEALED", "CHECKED", "FINALIZED", "QUARANTINED", "REJECTED", "DISCARDED") + +#: The folder under the output root that holds quarantined takes, one folder per session. No studio folder can +#: take this name: a studio name loses its leading underscores when it is made into a directory name. +QUARANTINE_DIR = "_quarantine" @dataclass @@ -88,6 +103,13 @@ class EpisodeManifest: duration_seconds: float = 0.0 # Optional free-text context the operator attached to the task; "" on manifests written before it existed. task_details: str = "" + # True for a take started as exempt from the capture checks (a calibration recording): it is finalized + # unjudged. Frozen at the start, so a recovery after a restart treats the take the same way. + capture_checks_exempt: bool = False + # True once a discard of this take was asked for, recorded before anything is deleted. Its data may be partly + # or wholly gone from then on, so the take is never finished as kept, and its emptied directory is still its + # own: a discard interrupted at any point can be repeated. + discard_requested: bool = False schema_version: int = MANIFEST_SCHEMA_VERSION @@ -140,38 +162,60 @@ def manifest_path(session_path: Path, index: int) -> Path: return session_path / MANIFEST_DIR / f"episode_{index}.json" +@contextmanager +def naming_the_file(path: Path) -> Iterator[None]: + """Give a failed write the name of the file it was writing, when the system left the name out. + + The system names a file it cannot open, rename or remove. It names none when writing to an open file or + syncing it fails, which is how a disk that fills up usually shows. The code that was writing knows which + file that was; with the name on the error, whoever reports it can tell which disk it is about. An error + that already names a file keeps that name, and one that carries no error number of the system is left as + it is: it did not come from a write, and a name would replace the text it was raised with. + """ + try: + yield + except OSError as exc: + if exc.filename is None and exc.errno is not None: + exc.filename = str(path) + raise + + def write_json_atomic(path: Path, data: Any) -> None: """Durably write JSON: temp file in the same directory, flush, fsync, atomic replace, directory fsync.""" directory = path.parent - directory.mkdir(exist_ok=True) - fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=path.stem + ".", suffix=".tmp") - try: - with os.fdopen(fd, "w") as handle: - json.dump(data, handle, indent=2, sort_keys=True) - handle.flush() - os.fsync(handle.fileno()) - os.replace(tmp_name, path) - except BaseException: - Path(tmp_name).unlink(missing_ok=True) - raise - fsync_dir(directory) + # Everything below writes this one file, through a temporary one beside it. + with naming_the_file(path): + directory.mkdir(exist_ok=True) + fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=path.stem + ".", suffix=".tmp") + try: + with os.fdopen(fd, "w") as handle: + json.dump(data, handle, indent=2, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp_name, path) + except BaseException: + Path(tmp_name).unlink(missing_ok=True) + raise + fsync_dir(directory) def write_yaml_atomic(path: Path, data: Any) -> None: """Durably write YAML: temp file in the same directory, flush, fsync, atomic replace, directory fsync.""" directory = path.parent - directory.mkdir(exist_ok=True) - fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=path.stem + ".", suffix=".tmp") - try: - with os.fdopen(fd, "w") as handle: - yaml.safe_dump(data, handle, default_flow_style=False, sort_keys=False) - handle.flush() - os.fsync(handle.fileno()) - os.replace(tmp_name, path) - except BaseException: - Path(tmp_name).unlink(missing_ok=True) - raise - fsync_dir(directory) + # Everything below writes this one file, through a temporary one beside it. + with naming_the_file(path): + directory.mkdir(exist_ok=True) + fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=path.stem + ".", suffix=".tmp") + try: + with os.fdopen(fd, "w") as handle: + yaml.safe_dump(data, handle, default_flow_style=False, sort_keys=False) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp_name, path) + except BaseException: + Path(tmp_name).unlink(missing_ok=True) + raise + fsync_dir(directory) def write_manifest(session_path: Path, manifest: EpisodeManifest) -> None: @@ -190,7 +234,15 @@ def write_manifest(session_path: Path, manifest: EpisodeManifest) -> None: SESSION_CONFIG_FILE = "config.yaml" -_FINALIZATIONS = (FINALIZATION_KEEP, FINALIZATION_REMOVE, FINALIZATION_RETAIN) +_FINALIZATIONS = (FINALIZATION_KEEP, FINALIZATION_QUARANTINE, FINALIZATION_REMOVE, FINALIZATION_RETAIN) + + +class ManifestError(ValueError): + """A record that was read and is not a usable take record. + + Its text is written in this module and names no file or directory, so it can be shown to an operator with + the file's name in front. Anything else a read can raise carries the parser's or the interpreter's own text. + """ def _decode_older(data: dict[str, Any]) -> dict[str, Any]: @@ -206,7 +258,7 @@ def _decode_older(data: dict[str, Any]) -> dict[str, Any]: try: outcome = data["quality"]["outcome"] except (KeyError, TypeError) as exc: - raise ValueError(f"schema {version!r} record is missing or damaged: {exc!r}") from exc + raise ManifestError(f"schema {version!r} record's check results are missing or damaged") from exc if outcome != "PASSED": data["finalization"] = FINALIZATION_RETAIN elif data.get("qc_decision") == "REJECTED_CAMERA": # the one legacy value this decode knows about @@ -217,37 +269,98 @@ def _decode_older(data: dict[str, Any]) -> dict[str, Any]: def read_manifest(path: Path) -> EpisodeManifest: - """Load a manifest; unsupported schema versions raise so they are retained and reported, never guessed.""" + """Load a manifest; unsupported schema versions raise so they are retained and reported, never guessed. + + What it raises about the record's content names no file or directory, so a caller can put the file's name + in front and show the text to an operator. + """ data = json.loads(path.read_text()) version = data.get("schema_version") if version not in READABLE_SCHEMA_VERSIONS: - raise ValueError(f"{path}: unsupported manifest schema_version {version!r}") + raise ManifestError(f"unsupported manifest schema_version {version!r}") manifest = EpisodeManifest(**{**_decode_older(data), "schema_version": MANIFEST_SCHEMA_VERSION}) # Paths are not caller data: they must be exactly the canonical names for the episode index. if not isinstance(manifest.episode_index, int) or manifest.episode_index < 0: - raise ValueError(f"{path}: invalid episode_index {manifest.episode_index!r}") + raise ManifestError(f"invalid episode_index {manifest.episode_index!r}") if manifest.storage_phase not in PHASES: - raise ValueError(f"{path}: unsupported storage_phase {manifest.storage_phase!r}") + raise ManifestError(f"unsupported storage_phase {manifest.storage_phase!r}") checked_without_intent = bool(manifest.quality) and manifest.finalization is None if manifest.finalization not in (None, *_FINALIZATIONS) or checked_without_intent: - raise ValueError(f"{path}: invalid finalization {manifest.finalization!r} for a checked take") + raise ManifestError(f"invalid finalization {manifest.finalization!r} for a checked take") expected = episode_dir_names(manifest.episode_index) if (manifest.pending_path, manifest.final_path) != expected: - raise ValueError(f"{path}: non-canonical episode paths {manifest.pending_path!r}, {manifest.final_path!r}") + raise ManifestError(f"non-canonical episode paths {manifest.pending_path!r}, {manifest.final_path!r}") return manifest -def scan_manifests(session_path: Path) -> tuple[list[EpisodeManifest], list[str]]: - """Return every readable manifest in a session plus a diagnostic for each unreadable one.""" - manifests, problems = [], [] +#: The diagnostic for a record written for another session than the directory that holds it. +MISPLACED_RECORD = "written for another session; this session directory was copied or renamed" +#: The diagnostics for a file that is not a record at all, and for one that cannot be opened. Neither carries +#: what the parser, the interpreter or the system said: that text is not written for an operator. +NOT_A_RECORD = "not a take record" +RECORD_UNREADABLE = "the file cannot be read" + + +@dataclass(frozen=True) +class SessionScan: + """What one session directory's records say. + + ``manifests`` are the records of this session. ``misplaced`` are readable records written for another + session, which is what a copied or renamed session directory holds: their paths name data this directory + cannot vouch for, so nothing may act on them. ``problems`` is one diagnostic per record that is unreadable + or misplaced, naming the file and never a directory. + """ + + manifests: tuple[EpisodeManifest, ...] + misplaced: tuple[EpisodeManifest, ...] + problems: tuple[str, ...] + + +def scan_session(session_path: Path) -> SessionScan: + """Read every record of a session directory, sorting out the ones nothing may act on.""" + manifests, misplaced, problems = [], [], [] directory = session_path / MANIFEST_DIR if directory.is_dir(): for path in sorted(directory.glob("episode_*.json")): try: - manifests.append(read_manifest(path)) - except (ValueError, TypeError, json.JSONDecodeError) as exc: + manifest = read_manifest(path) + except ManifestError as exc: problems.append(f"{path.name}: {exc}") - return manifests, problems + except OSError: + problems.append(f"{path.name}: {RECORD_UNREADABLE}") + except Exception: # noqa: BLE001 - damaged JSON, a list for an object, a field nobody declared + problems.append(f"{path.name}: {NOT_A_RECORD}") + else: + if manifest.session_id == session_path.name: + manifests.append(manifest) + else: + misplaced.append(manifest) + problems.append(f"{path.name}: {MISPLACED_RECORD}") + return SessionScan(tuple(manifests), tuple(misplaced), tuple(problems)) + + +def scan_manifests(session_path: Path) -> tuple[list[EpisodeManifest], list[str]]: + """Return every manifest of a session plus a diagnostic for each record that is unreadable or misplaced.""" + scan = scan_session(session_path) + return list(scan.manifests), list(scan.problems) + + +def frozen_station(session_path: Path) -> tuple[bool, str | None]: + """Whether a session's ``config.yaml`` could be read, and the station name frozen in it (None for none). + + The two are told apart on purpose. A session has its sidecar before its ``config.yaml``, and a file can be + unreadable for a moment: "could not be read" must never be taken for "names no station", and still less for + "names another station". + """ + try: + frozen = yaml.safe_load((session_path / SESSION_CONFIG_FILE).read_text()) + except (OSError, yaml.YAMLError): + return False, None + try: + name = frozen["meta"]["egocap_station_name"] + except (KeyError, TypeError): + return True, None + return True, name if isinstance(name, str) and name else None #: Root-group attribute that stamps an episode directory with the episode that owns it. @@ -326,8 +439,92 @@ def _owned_route_final(session_path: Path, manifest: EpisodeManifest) -> Path: return final +def quarantine_group(session_id: str) -> str: + """The output-root-relative folder that holds one session's quarantined takes.""" + return f"{QUARANTINE_DIR}/{session_id}" + + +def quarantine_destination(manifest: EpisodeManifest) -> str: + """The output-root-relative path of a quarantined take: ``_quarantine//episode_``.""" + return f"{quarantine_group(manifest.session_id)}/{manifest.final_path}" + + +def _device(path: Path) -> int: + """The file system a path is on, as the device number the system reports for it.""" + return os.stat(path).st_dev + + +def quarantine_location_problem(output_root: Path, session_id: str | None = None) -> str | None: + """Why no take could be renamed into the quarantine folder under ``output_root``, or None when one could. + + A take is quarantined by one rename out of its session, so the quarantine folder (and, when ``session_id`` + is given, that session's folder in it) must be a plain directory on the file system of the recordings: a + link could lead outside the recording output, and a rename cannot cross file systems. A folder that does not + exist yet is no problem, since it is created inside the output. The answer names no directory, so it can be + shown as it is. + """ + folders = [output_root / QUARANTINE_DIR] + if session_id is not None: + folders.append(folders[0] / session_id) + for folder in folders: + if folder.is_symlink(): + return "is a link" + if not folder.exists(): + return None + if not folder.is_dir(): + return "is not a directory" + if _device(folder) != _device(output_root): + return "is on another file system" + return None + + +def _quarantine_stamp(group_dir: Path) -> str | None: + """The ownership stamp of a session's quarantine folder, or None when it has none that can be read.""" + try: + return json.loads((group_dir / "zarr.json").read_text()).get("attributes", {}).get(ROUTE_ATTR) + except (OSError, json.JSONDecodeError): + return None + + +def _owned_quarantine_final(session_path: Path, manifest: EpisodeManifest) -> Path: + """Resolve a quarantined take's final location, refusing anything but ``_quarantine//episode_``. + + The path is built from the session directory's own name and the canonical episode name, never from other + manifest data. No component may be a symlink or escape the output root, and an existing session folder must + carry this session's ownership stamp, so a damaged or hostile manifest can never redirect a rename or delete. + A session folder that is empty and has no stamp counts as absent: it holds nothing to protect, and the claim + replaces it with the stamped folder. + """ + canonical = episode_dir_names(manifest.episode_index)[1] + if manifest.final_path != canonical: + raise ValueError(f"manifest path {manifest.final_path!r} is not the canonical {canonical!r}") + # The folder is named after the session the manifest sits in; a manifest claiming another session is refused. + if manifest.session_id != session_path.name: + raise ValueError(f"manifest session {manifest.session_id!r} is not the session {session_path.name!r}") + output_root = session_path.parent.resolve() + root_dir = output_root / QUARANTINE_DIR + group_dir = root_dir / manifest.session_id + final = group_dir / canonical + for path in (root_dir, group_dir): + if path.is_symlink() or (path.exists() and path.resolve().parent != path.parent.resolve()): + raise ValueError(f"{path} is a symlink or escapes the output root") + if final.is_symlink(): + raise ValueError(f"{final} is a symlink") + stamp = _quarantine_stamp(group_dir) + if group_dir.is_dir() and stamp != route_id(manifest.session_id, quarantine_group(manifest.session_id)): + if stamp is not None or any(group_dir.iterdir()): + raise PermissionError(f"{group_dir} is not the quarantine folder of session {manifest.session_id!r}") + return final + + def final_dir(session_path: Path, manifest: EpisodeManifest) -> Path: - """The validated final directory of an episode: routed when a slot was assigned, else the session's own.""" + """The validated final directory of an episode. + + The quarantine folder when that is the take's recorded intent, its routed slot when one was assigned, else + the session's own directory. + """ + if manifest.finalization == FINALIZATION_QUARANTINE: + return _owned_quarantine_final(session_path, manifest) if manifest.assignment is not None: return _owned_route_final(session_path, manifest) return _owned_path(session_path, manifest.final_path, episode_dir_names(manifest.episode_index)[1]) @@ -354,6 +551,9 @@ def finalize_episode_dir(session_path: Path, manifest: EpisodeManifest) -> Path: return final if final.exists(): raise FileExistsError(f"both {pending} and {final} exist; refusing to overwrite") + if manifest.finalization == FINALIZATION_QUARANTINE and _quarantine_stamp(final.parent) is None: + # An unstamped folder was only tolerated as absent: a take renamed into it could never be found again. + raise PermissionError(f"{final.parent} has not been claimed as the quarantine folder of this session") os.rename(pending, final) fsync_dir(session_path) if final.parent != session_path: @@ -361,15 +561,33 @@ def finalize_episode_dir(session_path: Path, manifest: EpisodeManifest) -> Path: return final +def _require_owned_pending(pending: Path, manifest: EpisodeManifest) -> None: + """Raise unless the existing ``pending`` directory is this episode's own. + + It must carry this episode's identity. An unstamped directory is accepted only before the stamp exists + (WRITING), or when it is empty and the manifest durably says this take's data is being removed (a rejection + by the camera check, or a discard that was asked for): what an interrupted removal leaves after it deletes + the stamp last. No other take may treat an emptied directory as its own. + """ + identity = read_identity(pending) + if identity == manifest.episode_id: + return + removal_decided = manifest.discard_requested or ( + manifest.storage_phase == "CHECKED" and manifest.finalization == FINALIZATION_REMOVE + ) + cleanup_residue = removal_decided and not any(pending.iterdir()) + if identity is not None or not (manifest.storage_phase == "WRITING" or cleanup_residue): + raise PermissionError(f"{pending} is not owned by episode {manifest.episode_id!r}") + + def locate_episode(session_path: Path, manifest: EpisodeManifest) -> str: """Return ``"pending"`` or ``"final"`` for the directory that holds this episode, validated before any use. The pending name must be a canonical direct child of the session and the final name the canonical session child - or, when routed, the exact assigned ``//episode_`` (no traversal, absolute path or - symlink), the - directory found must carry this episode's identity (an unstamped pending directory is accepted only while - the manifest is still WRITING, before the stamp could exist, or when it is the empty residue of an interrupted - removal of a camera-rejected take, whose stamp is deleted last), and pending and final may not both exist. + or, when routed, the exact assigned ``//episode_`` or, when quarantined, the exact + ``_quarantine//episode_`` (no traversal, absolute path or symlink), the + directory found must carry this episode's identity (see :func:`_require_owned_pending` for the two cases in + which an unstamped pending directory is accepted), and pending and final may not both exist. Recovery and metadata writes go through this check, so nothing is touched when ownership is unclear. """ pending_name, _ = episode_dir_names(manifest.episode_index) @@ -378,18 +596,7 @@ def locate_episode(session_path: Path, manifest: EpisodeManifest) -> str: if pending.exists(): if final.exists(): raise FileExistsError(f"both {pending} and {final} exist; refusing to choose") - identity = read_identity(pending) - # An unstamped directory is accepted only before the stamp exists (WRITING), or when it is empty and the - # manifest durably says this take's data is being removed: what an interrupted removal leaves after it - # deletes the stamp last. No other take may treat an emptied directory as its own. - cleanup_residue = ( - manifest.storage_phase == "CHECKED" - and manifest.finalization == FINALIZATION_REMOVE - and not any(pending.iterdir()) - ) - unstamped_ok = manifest.storage_phase == "WRITING" or cleanup_residue - if identity != manifest.episode_id and not (identity is None and unstamped_ok): - raise PermissionError(f"{pending} is not owned by episode {manifest.episode_id!r}") + _require_owned_pending(pending, manifest) return "pending" if final.exists(): if read_identity(final) != manifest.episode_id: @@ -398,47 +605,204 @@ def locate_episode(session_path: Path, manifest: EpisodeManifest) -> str: raise FileNotFoundError(f"neither {pending} nor {final} exists") -def remove_owned_episode(session_path: Path, manifest: EpisodeManifest) -> None: - """Delete only this episode's pending directory; refuses to touch a finalized episode.""" +class AlreadyPublished(PermissionError): + """The episode is in its final place, so a discard has nothing it may delete: the take is saved.""" + + +def discardable_pending(session_path: Path, manifest: EpisodeManifest) -> Path | None: + """The pending directory a discard of this episode would delete, or None when it has none left. + + Raises when the episode may not be discarded: it is finalized or quarantined, or the directory under its + pending name is not its own. Nothing is changed, so a caller can ask before it records that a discard began. + + A pending directory that is this episode's own is its unfinished data wherever the take was going to be + published, so the final location is not looked at: a destination that cannot be used (a quarantine folder + that is a link, a slot something else holds) never keeps a take from being discarded. With no pending + directory there is nothing to delete, and the final location is looked at only to refuse a take that is + already published there. + """ pending_name, _ = episode_dir_names(manifest.episode_index) pending = _owned_path(session_path, manifest.pending_path, pending_name) - final = final_dir(session_path, manifest) - if manifest.storage_phase == "FINALIZED" or (final.exists() and manifest.storage_phase != "DISCARDED"): - raise PermissionError(f"{final} is finalized output and is never deleted by discard") - if pending.exists(): - locate_episode(session_path, manifest) # raises unless this episode owns the directory - # Everything else goes first and the ownership stamp last: if this is interrupted, what is left still - # proves it is this episode's, so the removal can be retried instead of stranding unowned data. - marker = pending / "zarr.json" - for child in pending.iterdir(): - if child == marker: - continue - shutil.rmtree(child) if child.is_dir() and not child.is_symlink() else child.unlink() - marker.unlink(missing_ok=True) - pending.rmdir() - fsync_dir(session_path) + if manifest.storage_phase in ("FINALIZED", "QUARANTINED"): + raise AlreadyPublished(f"{manifest.episode_id!r} is finalized output and is never deleted by discard") + if not pending.exists(): + final = final_dir(session_path, manifest) + if final.exists() and manifest.storage_phase != "DISCARDED": + raise AlreadyPublished(f"{final} is finalized output and is never deleted by discard") + return None + _require_owned_pending(pending, manifest) + return pending + + +def remove_owned_episode(session_path: Path, manifest: EpisodeManifest) -> None: + """Delete only this episode's pending directory; refuses to touch a finalized or quarantined episode. + + What may be deleted is decided by :func:`discardable_pending`, and nothing else is. + """ + pending = discardable_pending(session_path, manifest) + if pending is None: + return + # Everything else goes first and the ownership stamp last: if this is interrupted, what is left still + # proves it is this episode's, so the removal can be retried instead of stranding unowned data. + marker = pending / "zarr.json" + for child in pending.iterdir(): + if child == marker: + continue + shutil.rmtree(child) if child.is_dir() and not child.is_symlink() else child.unlink() + marker.unlink(missing_ok=True) + pending.rmdir() + fsync_dir(session_path) #: Manifest phases whose pending data still needs a decision (recover or discard). UNRESOLVED_PHASES = ("WRITING", "SEALED", "CHECKED") +#: The lock file a recorder holds for as long as it has a session open. +SESSION_LOCK_FILE = "session.lock" +#: How long an owner waits before its one second attempt at a lock it found held. A probe (see +#: :func:`session_lock_is_free`) holds the lock for an instant, an owner for the session's lifetime. +_PROBE_GRACE_SECONDS = 0.005 +#: How often the holder of a session rewrites its beat in the lock file, for as long as it holds the session. +BEAT_SECONDS = 1.0 +#: How far apart a reader's two looks at a beat must be to tell a session that is open from one that is not: +#: long enough to span two beats, one late beat, and a file system that keeps times to the second. +BEAT_WATCH_SECONDS = 2.5 + + +def session_beat(session_path: Path) -> tuple[bytes, int] | None: + """What a session's lock file holds right now and when it was last written; None when it has none. + + For a reader that must leave alone a session some recorder has open, where the lock itself may not reach + (another machine on a shared disk). The value means nothing by itself and is compared with no clock: a + reader looks twice, :data:`BEAT_WATCH_SECONDS` apart or more, and a session whose value changed in between + is open. The file is opened anew for each look, so a file server's cached attributes are not trusted. + """ + try: + with open(session_path / MANIFEST_DIR / SESSION_LOCK_FILE, "rb") as handle: + return handle.read(64), os.fstat(handle.fileno()).st_mtime_ns + except FileNotFoundError: + return None + + +def session_lock_is_free(session_path: Path) -> bool: + """Whether no recorder has the session open, asked without waiting and without keeping the lock. + + For a reader that must leave alone the sessions another recorder is writing. A session nobody ever opened + has no lock file, and nobody holds it. Nothing is created. + """ + try: + handle = open(session_path / MANIFEST_DIR / SESSION_LOCK_FILE) # noqa: SIM115 - closed below + except FileNotFoundError: + return True + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return False + else: + fcntl.flock(handle, fcntl.LOCK_UN) + return True + finally: + handle.close() + + class SessionLock: - """Exclusive ownership of one session directory, held until explicitly released.""" + """Exclusive ownership of one session directory, held until explicitly released. + + Two signals say the session is taken. The lock tells another recorder on the same machine at once. The beat + tells a reader anywhere the directory can be seen: for as long as the session is held (recording, sealed, + being checked, idle between takes) the lock file is rewritten every :data:`BEAT_SECONDS` by a thread of its + own, which keeps going while the recorder's event loop or storage thread is busy and ends with the process. + + A beat that fails, for whatever reason, is tried again a beat later. A beat that stops is not seen by the + reader it was meant for, so the holder watches its own: :meth:`silence` says how long the beat has been + missing once that is long enough to mislead a reader, and :attr:`stalls` counts the times it was. + """ def __init__(self, session_path: Path) -> None: """Take a non-blocking exclusive lock; raises BlockingIOError if another owner holds the session.""" directory = session_path / MANIFEST_DIR directory.mkdir(parents=True, exist_ok=True) - self._handle = open(directory / "session.lock", "w") # noqa: SIM115 - held for the session's lifetime + # Opened without truncating: an opener that is then refused must not wipe the owner's beat. + descriptor = os.open(directory / SESSION_LOCK_FILE, os.O_RDWR | os.O_CREAT, 0o644) + self._handle = os.fdopen(descriptor, "r+") # held for the session's lifetime try: - fcntl.flock(self._handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + fcntl.flock(self._handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + # A probe of the lock looks like an owner for an instant; a real owner is still there after it. + time.sleep(_PROBE_GRACE_SECONDS) + fcntl.flock(self._handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except BaseException: self._handle.close() raise + # A value no other holder writes, so a new holder is a change even at the same count. + self._token = os.urandom(4).hex() + self._beats = 0 + self._guard = threading.Lock() + self._released = threading.Event() + # When the last beat was written, by this process's own clock, and how often one came too late. + self._last_beat = time.monotonic() + self._stalls = 0 + self._failing = False + self.beat() # at once: a session is never held without a beat + threading.Thread(target=self._keep_beating, name="session-beat", daemon=True).start() + + def beat(self) -> None: + """Rewrite the lock file with a value it never held before; nothing once the lock is released.""" + with self._guard: + if self._handle.closed: + return + self._beats += 1 + self._handle.seek(0) + self._handle.write(f"{self._token} {self._beats}\n") + self._handle.truncate() + self._handle.flush() + # A write may wait in a file server's cache; setting the time is sent to it at once. + os.utime(self._handle.fileno()) + now = time.monotonic() + # A reader that looked twice since the beat before this one saw nothing change. + if now - self._last_beat >= BEAT_WATCH_SECONDS: + self._stalls += 1 + self._last_beat = now + + def silence(self) -> float | None: + """How long this holder's beat has been missing, once that is long enough to mislead a reader. + + Seconds since the last beat was written when they reach :data:`BEAT_WATCH_SECONDS`: a reader where the + lock does not reach may by now have taken the session for one nobody has open. None while the beat is + kept. Measured on this process's own clock; it reads no file and waits for no lock, so it answers also + while a beat is stuck in a write. + """ + silent = time.monotonic() - self._last_beat + return silent if silent >= BEAT_WATCH_SECONDS else None + + @property + def stalls(self) -> int: + """How many beats so far were written a reader's watch time or more after the one before them.""" + return self._stalls + + def _keep_beating(self) -> None: + """Beat until the lock is released. + + Whatever stops one beat must not stop the next: the lock is still held, and a session without a beat + looks closed to a reader the lock does not reach. A failure is logged when it begins, not at every + beat, and again only after a beat got through in between. + """ + while not self._released.wait(BEAT_SECONDS): + try: + self.beat() + except Exception: # noqa: BLE001 - nothing a beat can raise may end the thread that beats + if not self._failing: + self._failing = True + logger.exception("the session's beat could not be written; it is tried again at every beat") + else: + self._failing = False def release(self) -> None: - """Release the lock; safe to call twice.""" - if not self._handle.closed: - fcntl.flock(self._handle, fcntl.LOCK_UN) - self._handle.close() + """Release the lock and stop the beat; safe to call twice.""" + self._released.set() + with self._guard: + if not self._handle.closed: + fcntl.flock(self._handle, fcntl.LOCK_UN) + self._handle.close() diff --git a/examples/egocap/recording/egocap/recording/episode_store.py b/examples/egocap/recording/egocap/recording/episode_store.py index cd6c57ef7a..cc31557e6b 100644 --- a/examples/egocap/recording/egocap/recording/episode_store.py +++ b/examples/egocap/recording/egocap/recording/episode_store.py @@ -27,7 +27,7 @@ import zarr from zarr.codecs import ZstdCodec -from .episode_layout import fsync_tree +from .episode_layout import fsync_tree, naming_the_file from .video_writer_backends import create_video_writer, resolve_video_encoder_options #: Per-source timestamp arrays every group carries (seconds, float64). @@ -111,9 +111,10 @@ def validate_source_specs(numeric: tuple[NumericSourceSpec, ...], video: tuple[V class _SourceArrays: """Buffered, append-only Zarr arrays for one source group.""" - def __init__(self, group: zarr.Group, fields: tuple[FieldSpec, ...]) -> None: - """Create one empty, row-appendable Zarr array per field inside ``group``.""" + def __init__(self, group: zarr.Group, fields: tuple[FieldSpec, ...], directory: Path) -> None: + """Create one empty, row-appendable Zarr array per field inside ``group``, which is ``directory``.""" self.rows = 0 + self._directory = directory self._buffers: dict[str, list[np.ndarray]] = {} self._arrays: dict[str, zarr.Array] = {} for field in fields: @@ -152,7 +153,9 @@ def flush(self) -> None: """Append buffered rows to disk.""" for name, buffered in self._buffers.items(): if buffered: - self._arrays[name].append(np.stack(buffered), axis=0) + # The rows go into files of this source's own directory and nowhere else. + with naming_the_file(self._directory / name): + self._arrays[name].append(np.stack(buffered), axis=0) buffered.clear() @@ -188,10 +191,14 @@ def __init__( self._release_failures: dict[str, str] | None = None timestamps = (*(FieldSpec(n, "float64") for n in TIMESTAMP_FIELDS), FieldSpec(SEQUENCE_FIELD, "int64")) for spec in numeric: - self._numeric[spec.name] = _SourceArrays(self._root.create_group(spec.name), timestamps + spec.fields) + self._numeric[spec.name] = _SourceArrays( + self._root.create_group(spec.name), timestamps + spec.fields, self.pending_dir / spec.name + ) for vspec in video: extra = (FieldSpec("intrinsics", "float64", (3, 3)),) if vspec.intrinsics else () - self._video[vspec.name] = _SourceArrays(self._root.create_group(vspec.name), timestamps + extra) + self._video[vspec.name] = _SourceArrays( + self._root.create_group(vspec.name), timestamps + extra, self.pending_dir / vspec.name + ) def start_encoders(self) -> None: """Start one real encoder per camera, in order. @@ -319,7 +326,8 @@ def seal(self) -> dict[str, int]: if failures: raise RuntimeError("video encoding failed: " + "; ".join(f"{n}: {e}" for n, e in failures.items())) # Payload durability must precede publishing a SEALED manifest. - fsync_tree(self.pending_dir) + with naming_the_file(self.pending_dir): + fsync_tree(self.pending_dir) self._sealed = True return self.counts() diff --git a/examples/egocap/recording/egocap/recording/route.py b/examples/egocap/recording/egocap/recording/route.py index 034c809db6..6badac11df 100644 --- a/examples/egocap/recording/egocap/recording/route.py +++ b/examples/egocap/recording/egocap/recording/route.py @@ -12,6 +12,10 @@ per-episode lengths, and the bad-episode record), which are always recomputed from the finalized episodes themselves, never incremented, so a retry or a crash cannot double count. +A take the capture checks marked bad, on a station that quarantines, is published to the session's quarantine +folder ``/_quarantine//`` instead. That folder is claimed and stamped like a group and +carries the same totals, in which every one of its episodes is listed as discarded with its reasons. + The session's routes live in ``/.recording/routes.json`` next to the manifests. A take's own destination is the ``assignment`` frozen in its manifest, which is what a recovery uses; ``routes.json`` only records which group the session has claimed for each (studio, task, day). Everything stays under the output root, on one @@ -23,9 +27,11 @@ from __future__ import annotations import datetime +import errno import json import os import re +import shutil from collections.abc import Iterable from dataclasses import dataclass from pathlib import Path @@ -33,11 +39,29 @@ from egocap.studio.studio_lookup import _normalize_desc, lookup_studio from egocap.studio.studio_path_names import canonicalize_studio_dir_name, sanitize_studio_dir_name -from .episode_layout import MANIFEST_DIR, ROUTE_ATTR, fsync_dir, route_id, write_json_atomic - -__all__ = ["RoutingConfig", "assign_output", "refresh_group_totals", "resolve_studio"] +from .episode_layout import ( + MANIFEST_DIR, + QUARANTINE_DIR, + ROUTE_ATTR, + fsync_dir, + quarantine_group, + route_id, + write_json_atomic, +) + +__all__ = [ + "RoutingConfig", + "assign_output", + "claim_quarantine_group", + "discard_quarantine_claim", + "refresh_group_totals", + "resolve_studio", +] ROUTES_FILE = "routes.json" +#: Where a session builds its quarantine folder before renaming it into place: inside its own sidecar directory, +#: which only the holder of the session's lock writes to. +QUARANTINE_CLAIM = "quarantine_claim" _FINAL_EPISODE = re.compile(r"^episode_(\d+)$") @@ -213,6 +237,67 @@ def assign_output( return group, _next_output_index(output_root / group, (index for g, index in reserved if g == group)) +def claim_quarantine_group(session_path: Path, session_id: str) -> Path: + """Create the session's quarantine folder once, already stamped as this session's own, and return it. + + The folder is built with its stamp inside the session's sidecar directory and renamed into place, so it + never exists without the stamp: whatever interrupts the claim leaves either no folder or the finished one, + and the claim can simply be repeated. Repeating it after it succeeded changes nothing. An empty folder with + no stamp is replaced by the stamped one; a folder that holds anything without this session's stamp is + refused, never adopted. + """ + output_root = session_path.parent + root_dir, group = output_root / QUARANTINE_DIR, quarantine_group(session_id) + group_dir = output_root / group + # Validated before the first filesystem mutation, like a routed group. + _refuse_symlink(root_dir, group_dir) + root_dir.mkdir(exist_ok=True) + fsync_dir(output_root) # the quarantine root's own entry + stamp_file = group_dir / "zarr.json" + attributes = { + ROUTE_ATTR: route_id(session_id, group), + "quarantine": True, + "discarded_episode_indices": [], + "discarded_reasons": {}, + } + if not stamp_file.exists(): + staging = session_path / MANIFEST_DIR / QUARANTINE_CLAIM + # Whatever is here is a claim that was interrupted: only this session's lock holder ever builds one. + shutil.rmtree(staging, ignore_errors=True) + os.mkdir(staging) + stamp = {"attributes": attributes, "zarr_format": 3, "node_type": "group"} + write_json_atomic(staging / "zarr.json", stamp) + try: + # One atomic step. It replaces an empty directory and fails on one that holds anything. + os.rename(staging, group_dir) + except OSError as exc: + shutil.rmtree(staging, ignore_errors=True) + if exc.errno in (errno.ENOTEMPTY, errno.EEXIST): + raise PermissionError( + f"{group_dir} exists but is not the quarantine folder of session {session_id!r}" + ) from exc + raise + # The new entry must outlive a crash before a take is renamed into it. + fsync_dir(root_dir) + if _load_json(stamp_file).get("attributes", {}).get(ROUTE_ATTR) != route_id(session_id, group): + raise PermissionError(f"{group_dir} exists but is not the quarantine folder of session {session_id!r}") + return group_dir + + +def discard_quarantine_claim(session_path: Path) -> None: + """Remove what an interrupted claim of the session's quarantine folder left in its sidecar, if anything. + + A claim that is repeated clears it itself. This is for a take that is discarded instead of recovered: the + claim is then never repeated, and the half-built folder would stay in the sidecar for good. Only a directory + of that name is removed: a link or a file put there by hand is left alone, and so is whatever a link names. + """ + staging = session_path / MANIFEST_DIR / QUARANTINE_CLAIM + # A claim only ever builds a plain directory, so anything else under the name is not a claim's leftover. + if staging.is_dir() and not staging.is_symlink(): + shutil.rmtree(staging, ignore_errors=True) + fsync_dir(staging.parent) + + def refresh_group_totals(group_dir: Path) -> dict: """Recompute the group's dataset-level attributes from its finalized episodes and persist them. diff --git a/examples/egocap/recording/egocap/stations/ego_stations.example.yaml b/examples/egocap/recording/egocap/stations/ego_stations.example.yaml index b45019245a..2d680fb9e1 100644 --- a/examples/egocap/recording/egocap/stations/ego_stations.example.yaml +++ b/examples/egocap/recording/egocap/stations/ego_stations.example.yaml @@ -8,8 +8,9 @@ # meta.task_description, recording.data_dir, recording.video_encoder and recording.video_encoder_options (the # writer every camera is recorded with; they share names with keys of the recorder CLI's data_recording/config.yaml # but are consumed here), and each video_sources entry's name/type (as the -# cameras requested from CaptureServer) and the alignment section. numeric_sources and the rest of each -# video_sources entry (frame_type, latency, params) are reference data for other tooling, not consumed here -- +# cameras requested from CaptureServer), the alignment section and the data_check section. numeric_sources and +# the rest of each video_sources entry (frame_type, latency, params) are reference data for other tooling, not +# consumed here -- # CaptureServer owns actually opening the selected cameras/devices. Each video_sources name MUST # match one of the names the running CaptureServer instance actually knows about (its own # --camera list, mock or real) -- an unknown name rejects the whole capture session, not just @@ -55,6 +56,18 @@ stations: # poll time when recorded, and a source not listed is not time-aligned. Measure it on the station and # uncomment; no value is assumed. # tracking_latency_s: {pico_controller: , manus_glove: } + # This station's changes to the capture-QC thresholds: any subset of the keys documented in + # recording/egocap/config/data_check/data_check_config.yaml, in the same shape. A key that is unknown, of the + # wrong type or out of range blocks recording until it is fixed. Uncomment what the station needs. + # This section can switch the camera rate rule off or weaken it (guardrails.enabled or + # camera_min_fps_enabled set to false, a low camera_min_fps_ratio, a low camera_expected_fps): a take whose + # camera lost frames is then kept and counted as saved. The settings view lists it under the quality checks' + # notices; nothing else on the page shows it. + # data_check: + # guardrails: + # gloves_expected: true # gloves are recorded here: judged and required + # quarantine: false # keep a take marked bad with its session, flagged + # camera_expected_fps: {head_human_camera: 60} # a camera's rate, where the declared one is wrong video_sources: - type: oak_camera name: head_human_camera diff --git a/examples/egocap/recording/recording_service/README.md b/examples/egocap/recording/recording_service/README.md index 6936fa3337..60dc20a20c 100644 --- a/examples/egocap/recording/recording_service/README.md +++ b/examples/egocap/recording/recording_service/README.md @@ -23,7 +23,7 @@ service = RecordingService(ServiceConfig(output_root, numeric_sources, video_sou await service.open_session() episode = await service.start_episode("task text", "operator") service.submit_sample(episode.episode_id, sample) # ACCEPTED or FULL; invalid input raises -result = await service.stop_episode(episode.episode_id) # KEPT / REJECTED / RECOVERY_REQUIRED +result = await service.stop_episode(episode.episode_id) # KEPT / QUARANTINED / REJECTED / RECOVERY_REQUIRED await service.close() ``` @@ -51,20 +51,76 @@ QcConfig( pose_streams=( ("pico_controller", "head_pose"), ), # (numeric source, float field) to watch; must be required + tracking_gap_sources=("pico_controller",), # sources whose longest time without a row is measured + duration_limits_s=(1.0, 600.0), # shortest and longest take; None runs no duration check + camera_expected_size=( + ("head_human_camera", None), + ), # camera -> (width, height) of its encoded file; None = the source's own size # defaults: camera_min_fps_ratio=0.86, freeze_seconds=1.0, freeze_eps=1e-6, - # flat_seconds=2.0, flat_eps=1e-3 + # flat_seconds=2.0, flat_eps=1e-3, tracking_gap_seconds=1.0, fps_deviation_pct=10.0 ), ) ``` +An application does not have to write these by hand: `egocap.recording.capture_qc_policy` reads the documented +defaults file (`egocap/config/data_check/data_check_config.yaml`) and a station's overrides into one policy, and +`capture_config_for` turns that policy and the session's cameras and pose streams into this value. + | Check | Decision | |---|---| -| `camera_min_fps:` (gate): average rate `(frames-1)/duration` below `ratio x expected` (fewer than two frames counts as 0 fps) | `REJECTED_CAMERA`: the take is rejected and only its own data is removed | +| `camera_min_fps:` (gate), two questions with the same `ratio`. The camera's average rate `(frames-1)/duration` over its own frames is below `ratio x expected` (asked when its frames span ten frame intervals of its expected rate). Or, in a take of thirteen intervals or more by its longest source, the camera recorded fewer frames than `ratio x (expected x take length - 3)`. A take too short for both is not judged | `REJECTED_CAMERA`: the take is rejected and only its own data is removed | | `camera_frame_parity` (opt-in `camera_parity`): the listed cameras' frame counts differ by more than `camera_parity_max_diff` | `REJECTED_CAMERA` | -| `sustained_freeze:/`: no change above `freeze_eps` for `freeze_seconds` | `FLAGGED_BAD`: the episode is kept, with `bad_episode = True` and the native `freeze_check_passed = False` (with `freeze_check_issues`) in its metadata | +| `sustained_freeze:/`: no change above `freeze_eps` for `freeze_seconds` | `FLAGGED_BAD`: the episode is kept, with `bad_episode = True` and the native `freeze_check_passed = False` (with `freeze_check_issues`) in its metadata; with `ServiceConfig.quarantine` it is finalized in the quarantine folder (below) | | `avatar_hand_liveness:/` (opt-in `avatar_hand_sources`): a hand with fewer than `avatar_min_states` rows, no recorded stream, or only streams frozen for the whole episode (a dead or disconnected glove) | `FLAGGED_BAD` | | `pico_body_joints:` (opt-in `pico_body`): wrong shape, no frames, non-finite values, or more invalid / all-identity frames than allowed | `FLAGGED_BAD` | -| `flat_motion`, `dead_stream` (a pose stream frozen the whole episode, noted as sensor dropout when pinned at identity), `frame_drops:` (more than `max_dropped_frames` in any `drop_window_s`) | advisory: warnings only; `frame_drops` is also saved as the native `frame_drops` metadata | +| `tracking_gap:` (`tracking_gap_sources`, with `tracking_gap_marks_bad`): no row for `tracking_gap_seconds`, or fewer than two rows. A source that omits rows while its device is untracked shows a dropout only here: the freeze check compares consecutive rows and cannot see a hole | `FLAGGED_BAD`. Without `tracking_gap_marks_bad` the same measurement is the advisory `tracking_gap_warning:` | +| `duration` (`duration_limits_s`, with `duration_marks_bad`): the longest single-source time span outside the limits | `FLAGGED_BAD`. Without `duration_marks_bad` it is the advisory `duration_warning` | +| `flat_motion`, `dead_stream` (a pose stream frozen the whole episode, noted as sensor dropout when pinned at identity), `zero_pose:/` (rows holding a 4x4 block below `zero_pose_eps`, with the row count stored), `frame_drops:` (more than `max_dropped_frames` in any `drop_window_s`), `camera_rate_measurable:` (the take was too short for a camera rate, so `camera_min_fps` and `camera_fps_deviation` said nothing), `camera_fps_deviation:` (average rate more than `fps_deviation_pct` above or below the expected rate, which is what catches a rate declared too low), `resolution:` (`camera_expected_size`: the encoded file's frame size differs from the declared one) | advisory: warnings only; `frame_drops` is also saved as the native `frame_drops` metadata | + +`camera_min_fps_enabled`, `freeze_enabled` and `dead_stream_enabled` switch one check off and leave the others on +the same streams running. A switchable check reports under a different name as a gate and as an advisory, so a +stored report says which it was without the policy. + +**What the camera rate rule asks.** Rejecting a take removes its media, so the rule asks two plain things of +each camera, both with the same share (`camera_min_fps_ratio`, 0.86 by default) of its expected rate. + +1. *Its rate while it ran*: `(frames - 1) / (last frame - first frame)` must reach `ratio x expected`. Asked + when the camera's own frames span ten frame intervals of its expected rate (`MIN_RATE_INTERVALS`; 0.33 s at + 30 Hz). Over ten intervals one dropped frame costs a tenth of the average, which 0.86 allows; over seven or + fewer it alone would reject the take. +2. *How much of the take it recorded*: `frames >= ratio x (expected x take length - 3)`. The take's length is + the longest span of any one of its sources, so `expected x take length` is the frames a take of that length + holds. Three intervals come off first (`CAMERA_PHASE_INTERVALS`): a healthy camera's first frame comes up to + one interval after the take's first sample and its last up to one before the take's last, and a frame can be + a little late. Asked of a take of thirteen intervals or more (0.43 s at 30 Hz). The formula and its reason + are in one place, `capture_qc.frames_needed`. + +The first question alone cannot see a camera that ran well for a part of the take: ten intervals of perfect +frames in a take of three seconds are a perfect rate. The second counts, so it has no edge to fall off: a +camera that starts late or stops early loses the frames that costs and no more, and one that covered a +fraction of the take fails. A finding of the second question reads "N frame(s) recorded of the F a T s take +holds at R fps (needs M)", and the result stores `frames`, `take_frames`, `needed_frames`, `take_s` and +`span_s` beside `fps` when the rate was measured. + +A take too short for both questions is not judged: the gate passes with the evidence "too short to measure a +rate" and stores no rate, `camera_rate_measurable` adds a warning that says how many frames arrived in how +long, and the take's length is left to the duration check, which with the default limits warns that it is +under 1 s. Both thresholds, ten and thirteen intervals, are exact to a hundredth of a frame interval +(`capture_measure.INTERVAL_TOLERANCE`), and so is the frame count; that is far above the rounding of the +stamps, so the same take gets the same verdict at every camera rate. + +What a camera that loses nothing must do to be rejected by the second question: miss, at the two ends of the +take together, more than 14 % of the take plus 2.6 frame intervals. At 30 Hz that is a first frame more than +0.23 s after Record in a 1 s take, 0.51 s in a 3 s take, 1.5 s in a 10 s take. No real camera's start has been +measured against this. + +**A station can switch the rate rule off.** Everything above is the policy a station's file resolves to, and +that file can turn the rule off or weaken it: `guardrails.enabled: false`, +`guardrails.camera_min_fps_enabled: false`, a low `guardrails.camera_min_fps_ratio`, or a low +`guardrails.camera_expected_fps` for one camera. A take whose camera delivered half its frames is then kept, +counted as saved and time-aligned, with at most a warning. Only the file on the recording PC can do this; no +command from the page can. The backend's settings view lists it in `quality_checks.notices`; nothing else on the +page shows it. Each device check runs only for the sources you declare, and the declaration is validated against the recorded schema before recording (an Avatar source without hand fields, a Pico body field that is not a float `(24, 4, 4)` @@ -79,8 +135,49 @@ stream is measured separately, so one read error cannot erase another's measured failure. `EpisodeResult.qc_decision` and `capture_quality` carry the decision and per-check results (with the measured values); kept episodes store them as `capture_qc_*` metadata, with `domain_checks` set to `EXECUTED` or `SKIPPED`. `freeze_check_passed` is written only when a freeze check ran (`True` if it passed, `False` if it failed). -`bad_episode` is a local classification only: **quarantine routing is not supported** and a bad episode is finalized -like any other. + +**Where a bad take goes (`ServiceConfig.quarantine`).** Off, a take marked bad is finalized like any other and +carries `bad_episode = True`. On, it is finalized at `/_quarantine//episode_` instead +(`` is its index in its session), with `quarantined = True` in its metadata, and ends +`Disposition.QUARANTINED` with `EpisodeResult.quarantine_path` set and `final_path` empty, so nothing that +consumes published output takes it for one. The session never moves: only where that one take is published +differs, and the manifest records it (`finalization: QUARANTINE`, then phase `QUARANTINED`). + +- The session's quarantine folder is created when its first take is sent there, stamped as that session's own + like a routed group, and given the session's frozen `config.yaml` and preserved calibration files. It is built + with its stamp inside the session's sidecar directory and renamed into place, so it never exists without the + stamp: whatever interrupts the claim leaves no folder or the finished one. An empty folder with no stamp counts + as absent and is replaced; one that holds anything without this session's stamp is never adopted. +- Its totals list every episode in it under `discarded_episode_indices` with its reasons, and they are rewritten + before the take's `QUARANTINED` checkpoint: a recorder stopped in between leaves the take pending, and the + recovery repeats them. A quarantined take is not counted as valid in any state: the folder is stamped + `quarantine: true` and each take in it says `quarantined: true`, and the daily counters exclude on either. +- The quarantine location must be a plain directory on the file system of the recordings, since a take gets + there by one rename. A location that is a link, is a file, or is on another file system refuses a new session + (`ConfigurationError: quarantine location is a link ...`) and every later `start_episode`, not the first bad + take. A session reopened to resolve what it left behind is not refused: `recover_episode` of a take that was + to be quarantined says why it cannot finish, and `discard_pending` still works. +- A quarantined take takes no output slot in a routed group, like a rejected one. +- The path is canonical and validated like a routed one (no symlink, no traversal, the folder must carry this + session's stamp) before any rename. A crash between the rename and the `QUARANTINED` checkpoint is recovered + by identity: the take is found where it was published and its data is not written again. +- Discard never deletes quarantined output, and a durably quarantined take is not pending, so there is nothing + to discard. A take still in its pending directory is another matter: that directory is the take's own + unfinished data wherever it was going, so it can be discarded whatever the quarantine folder looks like + (a link, a file, a slot something else holds). +- The switch is part of the configuration digest only when it is on, and never of the layout digest: a take + still to be judged must be finished under the setting it was recorded with, while a checked take finishes by + its recorded intent whatever the switch says later. +- No studio folder can be named `_quarantine`: a studio name loses its leading underscores when it becomes a + directory name. + +**Exempt takes.** `start_episode(..., exempt_from_capture_checks=True)` starts a take the capture checks never +judge, for a calibration recording that holds still or covers a lens on purpose. Storage integrity is still +checked. The take is kept with the decision `SKIPPED`, and its manifest (`capture_checks_exempt`) and metadata +(`capture_qc_exempt`) say why. The flag is frozen when the take starts, so a recovery treats it the same way. +In every other respect an exempt take is an ordinary saved take: it ends `KEPT`, a caller that counts kept takes +counts it, and the backend hands it to time alignment like any other. A caller that must tell them apart reads +the attribute. The configuration a pending take must match depends on how far it got: a SEALED take is still to be judged, so the whole configuration (including the capture policy and `ALGORITHM_VERSION`) must match; a CHECKED take already carries its @@ -88,10 +185,77 @@ decision and the policy that made it, so only the layout-affecting parts (source calibration) must match, and a new capture policy or algorithm cannot strand it. The decision is made durable (with the exact policy and algorithm version, frozen when the take starts) before any -cleanup, together with one *finalization intent* for the checked take: `KEEP` publishes it, `REMOVE` deletes its own data -(a camera rejection), `RETAIN` leaves its data for explicit resolution (an integrity failure). Recovery follows the +cleanup, together with one *finalization intent* for the checked take: `KEEP` publishes it, `QUARANTINE` publishes it +in the quarantine folder, `REMOVE` deletes its own data (a camera rejection), `RETAIN` leaves its data for explicit +resolution (an integrity failure). Recovery follows the recorded intent and never re-derives it from policy. If removing a camera-rejected take's data fails or is interrupted, the take stays listed for -`recover_episode`, which finishes the removal (the ownership stamp is deleted last so it stays retryable). Changing the +`recover_episode`, which finishes the removal (the ownership stamp is deleted last so it stays retryable). + +**No take ends where neither call resolves it.** `discard_pending` first asks whether the take may be discarded +at all (a take already in its final place is refused, and nothing is recorded), then writes `discard_requested` +into the manifest, and only then deletes; for a take that was to be quarantined it also clears what an +interrupted claim of the quarantine folder left in the sidecar (a plain directory only: a link or a file under +that name is left alone). Whatever interrupts the deletion, the record says the take's data was +being removed: its emptied directory is still its own, `discard_pending` finishes the job, and `recover_episode` +refuses it, because its data may be partly gone. `tests/recording_service/test_no_stuck_take.py` stops the +recorder before every file-changing call of starting, finishing, quarantining, rejecting and discarding a take +and checks that a new recorder resolves it with one of the two calls, in either order. + +**A take rejected for integrity** keeps its data in `episode_.pending`. It is resolved (it blocks nothing), +`retained_rejections()` lists it for the session a recorder has open while that data is on disk, +`recover_episode` refuses it, and `discard_pending` removes the data and records `DISCARDED`; the manifest keeps +the failed integrity report. A read of the whole output (below) does not list it: once its session is closed its +data simply stays at `/episode_.pending`, as it always has. + +**What a note says about the disk.** A recorder note that comes from a failed write names the cause in a word +of its own right after its first words: `write failed [storage: full]: ...`, and likewise `quota`, `read-only` +and `denied` (`ENOSPC`, `EDQUOT`, `EROFS`, `EACCES`/`EPERM`). The word is written only for a failure on a file +under the recording output: the system's error number says what went wrong and the error's own file name says +where, and neither is read from text. A calibration file that cannot be read or an encoder program that cannot +be run is a permission error too, and not the recordings disk; a failure that names no file is nobody's. Only +the failure and what it was raised from are looked at. The system names no file when a write or a sync fails, +which is how a full disk usually shows, so the recorder's own writers (a record, a take's rows, the sync of a +take's directory) put the name of the file they were writing on such an error (`episode_layout.naming_the_file`). +`storage_problem(exc, output_root)` gives the same word for a failure a caller caught itself. A write that +fails during a take is noted beside the reason the take was interrupted for. A discard that is refused before +it begins is noted as `discard refused: ...` (the take is already in its final place, or the directory under +its name is not its own), not as a failed one: repeating it would change nothing. + +**Which sessions are open.** A recorder holds its session's lock, and for as long as it does (recording, sealed, +being checked, idle between takes) it rewrites the lock file about once a second from a thread of its own: the +beat. The lock tells another recorder on the same machine at once. The beat tells a reader wherever the +directory can be seen, also where a lock taken on one machine is not seen on another, and it needs no clocks to +agree: a reader looks at the lock file twice, 2.5 s apart or more by its own clock, and a session whose file +changed in between is open. No time on the disk is ever compared with the reader's clock, so files stamped in +the future change nothing. One beat is a 20-byte write and a time stamp. + +A beat that stops is not seen by the reader it was meant for, so the recorder watches its own. Whatever a beat +raises, it is logged when it begins and tried again a beat later; the thread that beats does not end before +the session is released. `RecordingService.beat_silence()` is the seconds since the last beat was written once +they reach the reader's 2.5 s (a stalled disk, a write that fails, a starved process), else `None`; +`snapshot().issues` says so while it lasts; and a take during which the beat stopped that long carries the +note `session beat stopped during the take` in its record and its result. The recorder goes on recording: it +cannot make the disk take a beat, and the take in hand is safest finished. + +**What earlier sessions left behind.** `pending_under_output_root()` lists, without opening any session, the +unresolved takes in the sessions this station recorded, and records found in a session directory they were not +written for (`PendingEpisode.misplaced`, with `written_for` naming the session the record belongs to: a +directory copied or renamed by hand; listed, never acted on, and such a directory's records are reported as +unreadable when it is opened). A session is this station's when the name frozen in its `config.yaml` is one of +`stations` (every name the station has had; by default the configuration's own `station_label`) or when it +carries no name at all. An entry of the output that cannot be read is passed over and logged once. + +Pass the same `OutputScan` to repeated reads. It is what tells an open session from an abandoned one: a take is +listed from the second read on, once two looks 2.5 s apart or more found its session's lock free and its beat +unchanged. `OutputScan.judge(session)` answers the same for one session before a caller reopens it, and +`note_closed(session)` records that the caller itself just released it. It is also what keeps repeated reads +cheap: a session read with nothing left, and a session whose `config.yaml` was read and names another station, +are not opened again, so a repeated read costs one listing of the output plus the sessions that still hold a +take. Nothing is concluded from a session whose lock was held, whose beat was seen, or whose `config.yaml` +could not be read yet (a new session has its sidecar before its `config.yaml`): it is looked at again. Without +an `OutputScan` the call is a single look that asks each session's lock and nothing else. + +Changing the capture policy or algorithm makes an in-flight take incompatible rather than re-judging it silently. Manifests written before capture QC existed (schema 1) still recover and read as "not run". @@ -148,9 +312,9 @@ ServiceConfig( and format section) cannot run against a session's or routed group's `config.yaml`; that reader needs its source configuration supplied separately, never read from the recorded output. -No `data_check_config.yaml` is written in each group directory, and there is no separate -timestamp-consistency, time-range overlap, duration or resolution advisory check (the integrity -check already verifies each video's frame count). Group totals are recomputed fresh whenever a +No `data_check_config.yaml` is written in each group directory (the policy a take was judged by is stored +with the take, as `capture_qc_policy`), and there is no time-range overlap check across sources: their +timestamps are never subtracted from one another. Group totals are recomputed fresh whenever a take in the group is finalized or recovered, not reconciled against a prior count when a session is reopened. An integrity-rejected take keeps its data and reports its path in its result; it is not listed in the pending list. Samples the caller never submitted, such as ones dropped before @@ -178,9 +342,12 @@ Behavior worth knowing: it out of `.recording/` once the episode's data has been dealt with; - a sealed or checked pending directory whose identity stamp (`recording_episode_id` in its root metadata) is missing or belongs to another episode: recovery and discard both refuse it, so inspect the - directory and remove or re-stamp it by hand. The one exception is an empty directory left by an interrupted - removal of a camera-rejected take (stamp deleted last, durably recorded in the manifest): that is finished by - recovery or discard; + directory and remove or re-stamp it by hand. The exception is an empty directory left by an interrupted + removal whose intent is on record (a camera-rejected take, or a take with `discard_requested`; the stamp is + deleted last): that is finished by recovery or discard for the first and by discard for the second; + - a manifest written for another session than the directory that holds it (a session directory copied or + renamed by hand): it is listed in the snapshot issues like an unreadable one, nothing acts on it, and it + blocks a new take in that directory; - a missing or changed session copy of a required calibration asset: `open_session` refuses the session. Restore the copy from the original file (its hash is recorded in `.recording/calibration_assets.json`). - Manifest checkpoints are published in memory only after they are durably written. If the SEALED checkpoint @@ -191,12 +358,12 @@ Behavior worth knowing: - `close()` during RECORDING discards the active take; a stop that was already accepted is allowed to finish. - The service takes a detached snapshot of its configuration at construction; later changes to the caller's config objects do not affect it. -- Quarantine routing is not supported; requesting it (`ServiceConfig.quarantine`) is a configuration error. | Module | Contents | |---|---| | `models.py` | Configuration, sample, result and error types (all recording-owned frozen dataclasses; arrays and dicts inside them are not deep-frozen). | | `recording_service.py` | The service. | +| `output_scan.py` | Reading what earlier sessions left behind across the whole output, cheaply when repeated. | Storage, quality checking, routing and dataset reading live in `egocap/recording/` (`episode_store.py`, `episode_layout.py`, `dataset_check.py`, `dataset_reader.py`, `capture_qc.py`, `capture_measure.py`, @@ -207,6 +374,9 @@ Storage, quality checking, routing and dataset reading live in `egocap/recording `tests/recording_service/` runs the public API against a real recorded episode (`EGOCAP_REAL_EPISODE=`) with the real backend; without it those tests are -SKIPPED. `recording/tools/replay_episode.py` is the full acceptance run: it replays an +SKIPPED. The quarantine tests, the tests of every path that deletes a take's media, the stop-at-every-step runs +and the tests of what a read of the output lists (`test_quarantine_service.py`, `test_quarantine_location.py`, +`test_removal_scope.py`, `test_no_stuck_take.py`, `test_takes_left_behind.py`, `test_short_take_verdicts.py`) +build their takes in the test and always run. `recording/tools/replay_episode.py` is the full acceptance run: it replays an episode through the service and independently verifies the output against a SHA-256 manifest of the input. These tests are not wired into CI; run them locally. diff --git a/examples/egocap/recording/recording_service/__init__.py b/examples/egocap/recording/recording_service/__init__.py index 9520cfe044..bb3a480293 100644 --- a/examples/egocap/recording/recording_service/__init__.py +++ b/examples/egocap/recording/recording_service/__init__.py @@ -41,7 +41,8 @@ VideoSample, VideoSourceSpec, ) -from .recording_service import RecordingService +from .output_scan import OutputScan +from .recording_service import RecordingService, storage_problem __all__ = [ "CalibrationAsset", @@ -56,6 +57,7 @@ "NumericSample", "NumericSourceSpec", "Outcome", + "OutputScan", "PendingEpisode", "PixelFormat", "QcConfig", @@ -75,4 +77,5 @@ "ValidationError", "VideoSample", "VideoSourceSpec", + "storage_problem", ] diff --git a/examples/egocap/recording/recording_service/models.py b/examples/egocap/recording/recording_service/models.py index 34871c6093..b664c47b06 100644 --- a/examples/egocap/recording/recording_service/models.py +++ b/examples/egocap/recording/recording_service/models.py @@ -97,6 +97,8 @@ class Disposition(Enum): """What ultimately happened to an episode's data.""" KEPT = "KEPT" + # Kept, but finalized in the quarantine folder because the capture checks marked it bad. + QUARANTINED = "QUARANTINED" REJECTED = "REJECTED" DISCARDED = "DISCARDED" RECOVERY_REQUIRED = "RECOVERY_REQUIRED" @@ -146,6 +148,8 @@ class ServiceConfig: # at the submission rate, FULL repeats and a size-based or per-source budget would be needed before live use. queue_capacity: int = 512 close_deadline_seconds: float = 30.0 + # True finalizes a take the capture checks marked bad at /_quarantine//episode_ + # instead of with the session's kept takes; False keeps it in place, flagged. quarantine: bool = False calibration_assets: tuple[CalibrationAsset, ...] = () latency: dict[str, float] | None = None @@ -251,11 +255,19 @@ class EpisodeResult: # The kept output's slot in its routed group (None when not routed or not kept); ``episode_index`` stays the # attempt identity and never changes, so a rejected attempt leaves no gap in the output numbering. output_index: int | None = None + # Where a quarantined take was finalized. Separate from ``final_path`` so that no consumer of published + # output takes a quarantined take for one. + quarantine_path: Path | None = None @dataclass(frozen=True) class PendingEpisode: - """An unresolved episode found on disk.""" + """An episode on disk that waits for someone: unresolved, or rejected with its data kept. + + ``storage_phase`` is WRITING, SEALED or CHECKED for an unresolved episode, which must be recovered or + discarded before the session records again. It is REJECTED for an episode the integrity check rejected + whose data is still on disk: that one blocks nothing, cannot be recovered, and can be discarded. + """ session_id: str episode_id: str @@ -264,6 +276,21 @@ class PendingEpisode: storage_phase: str recoverable: bool issues: tuple[str, ...] = () + # What the take was recorded as, for a caller that lists pending takes to an operator. + task: str = "" + operator: str = "" + duration_seconds: float = 0.0 + # The notes the recorder kept in the take's manifest (``issues`` holds only why it is pending now), and the + # finalization intent recorded with its checks, which is what a recovery would finish; None before the checks. + recorded_issues: tuple[str, ...] = () + finalization: str | None = None + # True once a discard of the episode was started: its data may be partly gone, so it can only be discarded. + discard_requested: bool = False + # True for a record found in a session directory it was not written for (a copied or renamed directory). + # It is listed so it can be seen; ``session_id`` and ``episode_id`` then name the directory it was found in, + # ``written_for`` is the session the record names, and no command acts on it. + misplaced: bool = False + written_for: str = "" @dataclass(frozen=True) diff --git a/examples/egocap/recording/recording_service/output_scan.py b/examples/egocap/recording/recording_service/output_scan.py new file mode 100644 index 0000000000..4d309c5411 --- /dev/null +++ b/examples/egocap/recording/recording_service/output_scan.py @@ -0,0 +1,232 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Which takes the sessions under a recording output left for someone to resolve. + +A caller that shows an operator what earlier sessions left behind reads the whole output, and reads it again from +time to time. :class:`OutputScan` keeps what it learned between reads, so a repeated read costs one listing of the +output plus the few sessions that can still change, however many sessions and takes the output holds. + +A session some recorder has open is never listed and never remembered. Two things say so. Its lock, where the +lock reaches. And its beat, which reaches wherever the directory can be seen: the recorder rewrites the lock +file about once a second, so a session whose lock file changed between two looks of this reader's own, far enough +apart, is open. No clock of this machine is compared with any time on the disk. + +Read-only: nothing here opens a session for writing, takes its lock for longer than a probe, or creates a file. +""" + +from __future__ import annotations + +import logging +import os +import stat +import threading +import time +from collections.abc import Callable, Collection +from dataclasses import dataclass +from pathlib import Path + +from egocap.recording.episode_layout import ( + BEAT_WATCH_SECONDS, + MANIFEST_DIR, + UNRESOLVED_PHASES, + EpisodeManifest, + frozen_station, + scan_session, + session_beat, + session_lock_is_free, +) + +__all__ = ["LeftBehind", "OutputScan"] + +logger = logging.getLogger("isaaccapture.egocap.output_scan") + + +@dataclass(frozen=True) +class LeftBehind: + """One take a session left for someone to resolve, with the directory its record was found in. + + ``misplaced`` is True for a record written for another session than that directory (the directory was + copied or renamed): it is listed so the operator sees it, and nothing may act on it. + """ + + session_path: Path + manifest: EpisodeManifest + misplaced: bool = False + + +@dataclass +class _Watch: + """The last beat seen in a session's lock file and when this reader first saw that value.""" + + beat: tuple[bytes, int] | None + since: float + + +class OutputScan: + """Reads what the sessions of one station left behind under a recording output, remembering between reads. + + A session is settled, and not opened again, when it was read with nothing left to resolve or when its + ``config.yaml`` was read and names a station that is not this reader's. A session that still holds a take is + read again every time, and so is one that appeared since the last read, one that was replaced by another + directory of the same name, and one whose ``config.yaml`` could not be read yet. + + A session is listed only once two looks of this reader, :data:`BEAT_WATCH_SECONDS` apart or more, found its + lock free and its beat unchanged; so a take first appears one look after its session is first seen. A + session whose lock is held or whose beat changed is neither listed nor settled. + """ + + def __init__(self, watch_seconds: float = BEAT_WATCH_SECONDS, clock: Callable[[], float] = time.monotonic): + """Start with nothing remembered: the first read looks at every session and lists none. + + ``watch_seconds`` is how far apart two looks at a beat must be; with zero one look is enough, which + asks the lock alone and is for a reader that looks once. ``clock`` is this reader's own monotonic clock, + used only to measure the time between its looks. + """ + self._watch_seconds = watch_seconds + self._clock = clock + self._key: tuple[Path, frozenset[str]] | None = None + # Settled sessions by name, with the directory's own number so a directory that replaces another of the + # same name is read as the new one it is. + self._settled: dict[str, int] = {} + self._watches: dict[str, _Watch] = {} + self._reported: set[str] = set() + self._first_looks = 0 + # The scan runs in a worker thread while its owner asks about one session from the event loop. + self._guard = threading.Lock() + + def read( + self, + output_root: Path, + stations: Collection[str] | str | None, + *, + skip_session: str | None = None, + ) -> list[LeftBehind]: + """Every take left for someone to resolve by the sessions this station recorded under ``output_root``. + + ``stations`` holds every name the station has had (one name may be given by itself). A session is this + station's when the name frozen in it is one of them, and also when it carries no name at all: a session + recorded before the station was named is nobody else's. ``skip_session`` leaves out a session the caller + has open itself. An entry that cannot be read is passed over and logged once. Blocking: call it off the + event loop. + """ + names = frozenset((stations,) if isinstance(stations, str) else (stations or ())) + with self._guard: + if self._key != (output_root, names): + # What was settled for one output or set of names says nothing about another. + self._key, self._settled, self._watches, self._reported = (output_root, names), {}, {}, set() + self._first_looks = 0 + try: + with os.scandir(output_root) as listing: + entries = sorted(((entry.name, entry.inode()) for entry in listing)) + except OSError: # no output yet, so nothing was left behind + return [] + found: list[LeftBehind] = [] + for name, inode in entries: + # Hidden entries are never sessions; the caller's own session is its own to report. + if name.startswith(".") or name == skip_session or self._settled.get(name) == inode: + continue + try: + left, settle = self._read_session(output_root / name, names) + except OSError as exc: + if name not in self._reported: + self._reported.add(name) + logger.warning( + "an entry of the recording output cannot be read and is passed over: %s (%s)", + name, + type(exc).__name__, + ) + continue + found += left + if settle: + self._settled[name] = inode + self._watches.pop(name, None) + present = {name for name, _inode in entries} + # A name that is gone could be used again for something else. + self._settled = {name: inode for name, inode in self._settled.items() if name in present} + self._watches = {name: watch for name, watch in self._watches.items() if name in present} + return found + + def first_looks(self) -> int: + """How many sessions the last read saw for the first time and so could not judge yet. + + A caller that wants their takes listed soon reads again once the watch time has passed. + """ + return self._first_looks + + @property + def watch_seconds(self) -> float: + """How far apart two looks at a session's beat must be.""" + return self._watch_seconds + + def judge(self, session_path: Path) -> tuple[bool | None, float]: + """Whether a session may be acted on now, from this reader's looks at its beat. + + ``(True, 0)``: two looks far enough apart saw the same beat, the last of them just now: no recorder has + it open. ``(False, 0)``: its beat changed since the last look, so one has. ``(None, seconds)``: not + known yet; look again after that long. Blocking for one small file read. + """ + with self._guard: + quiet, wait = self._look(session_path) + return (None, wait) if wait > 0 else (quiet, 0.0) + + def note_closed(self, session_path: Path) -> None: + """Record that the caller itself held this session until now and has released it. + + Its own beat is the one that just stopped, and nobody else can have had the session while it did: the + session counts as watched and quiet from this moment, with no second look to wait for. + """ + with self._guard: + self._watches[session_path.name] = _Watch(session_beat(session_path), float("-inf")) + + def _look(self, session_path: Path) -> tuple[bool, float]: + """One look at a session's beat: (whether it is known to be quiet, seconds until a look can tell).""" + now, beat = self._clock(), session_beat(session_path) + watch = self._watches.get(session_path.name) + if watch is None or watch.beat != beat: + # A first look, or a beat: either way the watch starts over from this value. + first = watch is None + self._watches[session_path.name] = _Watch(beat, now) + if first and self._watch_seconds <= 0: + return True, 0.0 + return False, (self._watch_seconds if first else 0.0) + remaining = self._watch_seconds - (now - watch.since) + return remaining <= 0, max(remaining, 0.0) + + def _read_session(self, session_path: Path, names: frozenset[str]) -> tuple[list[LeftBehind], bool]: + """What one entry of the output left behind, and whether it can be settled for good.""" + try: + sidecar = os.stat(session_path / MANIFEST_DIR) + except (FileNotFoundError, NotADirectoryError): + # Not a session: a studio folder, the quarantine folder, a stray file. Not remembered, since a session + # being created right now looks the same for an instant. + return [], False + if not stat.S_ISDIR(sidecar.st_mode): + return [], False + # Whether a recorder has it open comes before anything is concluded from its files. + if not session_lock_is_free(session_path): + self._watches[session_path.name] = _Watch(session_beat(session_path), self._clock()) + return [], False + first = session_path.name not in self._watches + quiet, _wait = self._look(session_path) + if not quiet: + self._first_looks += first + return [], False + read, station = frozen_station(session_path) + if read and station is not None and station not in names: + # Another station's session is that station's to resolve, and its name never changes. + return [], True + scan = scan_session(session_path) + found = [ + LeftBehind(session_path, manifest) + for manifest in scan.manifests + if manifest.storage_phase in UNRESOLVED_PHASES + ] + found += [ + LeftBehind(session_path, manifest, misplaced=True) + for manifest in scan.misplaced + if manifest.storage_phase in UNRESOLVED_PHASES + ] + # A session whose configuration could not be read is looked at again: it may still be written. + return found, read and not found diff --git a/examples/egocap/recording/recording_service/recording_service.py b/examples/egocap/recording/recording_service/recording_service.py index 2a362fc20e..d5e5a68748 100644 --- a/examples/egocap/recording/recording_service/recording_service.py +++ b/examples/egocap/recording/recording_service/recording_service.py @@ -24,6 +24,7 @@ import asyncio import copy import datetime +import errno import hashlib import json import logging @@ -33,7 +34,7 @@ import time import uuid from collections import deque -from collections.abc import Awaitable, Callable, Coroutine +from collections.abc import Awaitable, Callable, Collection, Coroutine from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, replace from pathlib import Path @@ -56,21 +57,28 @@ from egocap.recording.episode_layout import ( CALIBRATION_RECORD, FINALIZATION_KEEP, + FINALIZATION_QUARANTINE, FINALIZATION_REMOVE, FINALIZATION_RETAIN, IDENTITY_ATTR, MANIFEST_DIR, + MISPLACED_RECORD, SESSION_CONFIG_FILE, UNRESOLVED_PHASES, + AlreadyPublished, EpisodeManifest, SessionLock, destination_path, + discardable_pending, episode_dir_names, finalize_episode_dir, fsync_dir, locate_episode, manifest_path, next_episode_index, + quarantine_destination, + quarantine_group, + quarantine_location_problem, remove_owned_episode, scan_manifests, write_episode_attributes, @@ -79,7 +87,13 @@ write_yaml_atomic, ) from egocap.recording.episode_store import EpisodeStore, validate_source_specs -from egocap.recording.route import assign_output, refresh_group_totals, resolve_studio +from egocap.recording.route import ( + assign_output, + claim_quarantine_group, + discard_quarantine_claim, + refresh_group_totals, + resolve_studio, +) from .models import ( CloseResult, @@ -101,6 +115,7 @@ ValidationError, VideoSample, ) +from .output_scan import OutputScan logger = logging.getLogger(__name__) @@ -139,9 +154,66 @@ def _copy_file_atomic(source: Path, dest: Path) -> None: fsync_dir(directory) +#: What the system's error number says about the recordings disk, in a word of this module's own. +_STORAGE_PROBLEMS = { + errno.ENOSPC: "full", + errno.EDQUOT: "quota", + errno.EROFS: "read-only", + errno.EACCES: "denied", + errno.EPERM: "denied", +} + + +#: The recorder's note on a take during which its session's beat stopped for a reader's watch time or longer. +BEAT_STOPPED_NOTE = "session beat stopped during the take" + + +def _is_under(name: Any, root: str) -> bool: + """Whether a file name carried by an error lies in ``root``, links resolved on both; False for no name.""" + if not isinstance(name, (str, bytes, os.PathLike)): + return False + path = os.path.realpath(os.fsdecode(name)) + return path == root or path.startswith(root + os.sep) + + +def storage_problem(exc: BaseException | None, output_root: Path | str) -> str | None: + """Why the recordings disk refused a write, when that is what ``exc`` is: full, quota, read-only or denied. + + Only for a failure whose own file name lies under ``output_root``. The system's error number says what went + wrong and the name says where: a place that is full or forbidden elsewhere (a calibration file, an encoder + program, a temporary directory) is not the recordings disk, and neither is a failure that names no file. + The failure and what it was raised from are looked at; an error that merely was being handled when another + was raised is not. Decided from the number and the name, never from text, so that a caller can tell an + operator the one fact that needs acting on. None for any other failure. + """ + root = os.path.realpath(os.fspath(output_root)) + seen: set[int] = set() + while exc is not None and id(exc) not in seen: + seen.add(id(exc)) + if isinstance(exc, OSError) and exc.errno in _STORAGE_PROBLEMS: + if any(_is_under(name, root) for name in (exc.filename, exc.filename2)): + return _STORAGE_PROBLEMS[exc.errno] + exc = exc.__cause__ + return None + + +def _retained_rejection(session_path: Path, manifest: EpisodeManifest) -> bool: + """Whether a take was rejected by the integrity check and its data is still on disk. + + Such a take is finished as far as recording goes, and it blocks nothing, but its data stays until someone + removes it. + """ + kept = manifest.storage_phase == "REJECTED" and manifest.finalization == FINALIZATION_RETAIN + return kept and (session_path / manifest.pending_path).is_dir() + + def _layout_digest(config: ServiceConfig) -> str: - """The configuration digest without the capture-QC policy: what the data layout alone depends on.""" - return _digest(replace(config, qc=replace(config.qc, capture=None))) + """The configuration digest without the capture-QC policy: what the data layout alone depends on. + + The quarantine switch is left out with it: a checked take already recorded where it goes, so it finishes by + that intent whatever the switch says later. + """ + return _digest(replace(config, qc=replace(config.qc, capture=None), quarantine=False)) def _digest(config: ServiceConfig) -> str: @@ -151,8 +223,13 @@ def _digest(config: ServiceConfig) -> str: del qc["capture"] # absent, not null, so a take recorded before capture QC existed keeps its digest else: qc["capture_algorithm_version"] = ALGORITHM_VERSION # a changed algorithm is a changed configuration + # Where the thresholds were read from is a record, not a rule: a defaults file edited without changing a + # value must not make a take still to be judged look like one recorded under another policy. + del qc["capture"]["source"] canonical = { **({"routing": True} if config.routing is not None else {}), # routed or not; each take freezes its studio + # Present only when on, so a take recorded before the switch existed keeps its digest. + **({"quarantine": True} if config.quarantine else {}), # A frame type says how a source's fields are resampled, not how its data is laid out, so it is left out: # setting or changing one never makes a take recorded earlier look like a different configuration. "numeric": [{k: v for k, v in asdict(s).items() if k != "frame_type"} for s in config.numeric_sources], @@ -191,6 +268,9 @@ def __init__(self, manifest: EpisodeManifest, sources: list[str], store: Episode # held in memory only and written to the kept episode's attributes. self.capture_session: dict[str, Any] | None = None self.released = store is None + # How often the session's beat had stalled when this take began, and whether a stall was noted on it. + self.beat_stalls = 0 + self.beat_noted = False # Work ownership: ``operating`` while a lifecycle operation owns the take, # ``in_flight`` while a storage call is running even if its waiter went away. self.operating = False @@ -256,6 +336,9 @@ def __init__(self, config: ServiceConfig) -> None: self._lock: SessionLock | None = None self._take: _Take | None = None self._pending: dict[str, PendingEpisode] = {} + # Episodes the integrity check rejected whose data is still on disk: resolved, so they block nothing, and + # listed so that their data can be removed with discard_pending. + self._rejected_kept: dict[str, PendingEpisode] = {} self._retained: dict[str, _Take] = {} self._last_result: EpisodeResult | None = None self._issues: list[str] = [] @@ -280,9 +363,17 @@ async def open_session(self, session_id: str | None = None) -> SessionInfo: """ return await self._run(self._open_impl(session_id)) - async def start_episode(self, task: str, operator: str = "", task_details: str = "") -> EpisodeInfo: - """Allocate an episode, open real writers, and return only once samples can be admitted.""" - return await self._run(self._start_impl(task, operator, task_details)) + async def start_episode( + self, task: str, operator: str = "", task_details: str = "", *, exempt_from_capture_checks: bool = False + ) -> EpisodeInfo: + """Allocate an episode, open real writers, and return only once samples can be admitted. + + ``exempt_from_capture_checks`` starts a take the capture checks never judge (a calibration recording, + which holds still or covers a lens on purpose): it is checked for storage integrity only, finalized as + kept with the decision SKIPPED, and its metadata says it was exempt. It is the caller's own decision, + made in its code; an ordinary take never sets it. + """ + return await self._run(self._start_impl(task, operator, task_details, exempt_from_capture_checks)) def submit_sample(self, episode_id: str, sample: NumericSample | VideoSample) -> SubmissionResult: """Validate, copy and enqueue one sample without waiting. @@ -367,24 +458,91 @@ def pending_episodes(self) -> tuple[PendingEpisode, ...]: """Unresolved episodes found on disk (or retained after a failure), in index order.""" return tuple(sorted(self._pending.values(), key=lambda p: p.episode_index)) + def retained_rejections(self) -> tuple[PendingEpisode, ...]: + """Episodes of the open session that the integrity check rejected and whose data is still on disk. + + They are resolved and block nothing; ``discard_pending`` removes one's data. In index order. + """ + return tuple(sorted(self._rejected_kept.values(), key=lambda p: p.episode_index)) + async def recover_episode(self, episode_id: str) -> EpisodeResult: """Resume the safe disk step of a sealed/checked pending episode; ambiguous writes are refused.""" take = self._pending_take(episode_id, "recovering") - if take.manifest.storage_phase == "WRITING": + m = take.manifest + if m.storage_phase == "REJECTED": + raise StateError( + f"episode {episode_id!r} was rejected by the integrity check, so it cannot be recovered; " + "discard_pending removes its data" + ) + if m.storage_phase == "WRITING": raise StateError( f"episode {episode_id!r} is still marked WRITING, so its completeness is unknown and it cannot be " "recovered; discard it with discard_pending and record again" ) - if not self._same_configuration(take.manifest): + if m.discard_requested: + raise StateError( + f"a discard of episode {episode_id!r} was started, so its data may be incomplete and it cannot be " + "recovered; discard it again with discard_pending" + ) + if not self._same_configuration(m): raise StateError(f"episode {episode_id!r} was recorded with a different configuration") + if m.finalization == FINALIZATION_QUARANTINE: + # Said before anything is tried: a rename into a folder that cannot take it would only fail again. + problem = quarantine_location_problem(Path(self._config.output_root), m.session_id) + if problem is not None: + raise StateError( + f"episode {episode_id!r} cannot be set aside: the quarantine location {problem}; " + "the take was left as it is" + ) take.error = None return await self._begin(take, "recover", self._finish_impl(take)) async def discard_pending(self, episode_id: str) -> EpisodeResult: - """Remove one pending episode's unfinished output once nothing is working on it.""" + """Remove one pending episode's unfinished output once nothing is working on it. + + Also removes the kept data of an episode the integrity check rejected (see ``retained_rejections``). + """ take = self._pending_take(episode_id, "discarding") return await self._begin(take, "discard", self._discard_impl(take)) + def pending_under_output_root( + self, + *, + skip_session: str | None = None, + scan: OutputScan | None = None, + stations: Collection[str] | None = None, + ) -> tuple[PendingEpisode, ...]: + """Unresolved episodes in the sessions this station recorded under the output root, as this + configuration would find them on reopening each one, without opening any. + + For a caller that lists what was left behind by earlier sessions (after a restart, say) so an operator + can recover or discard it; resolving one still means opening its session. ``stations`` is every name + the station has had (by default this configuration's own): a session is listed when the name frozen in + it is one of them or when it carries none. A session some recorder has open is left out, by its lock + where that reaches and by its beat everywhere (see :class:`OutputScan`): its takes are that recorder's. + A record found in a session directory it was not written for is listed as ``misplaced``. An entry of + the output that cannot be read is passed over. ``skip_session`` leaves out a session the caller already + has open. + + ``scan`` carries what earlier reads learned, and it is what tells an open session from an abandoned + one: with the same ``scan``, a take is listed from the second read on, once two looks far enough apart + found its session's beat unchanged. Without one this is a single look with no waiting (the watch time + is zero): only the lock is asked, and every session is read. Read-only and blocking: call it off the + event loop. + """ + scan = scan if scan is not None else OutputScan(watch_seconds=0.0) + label = self._config.station_label + names = stations if stations is not None else ((label,) if label else ()) + left = scan.read(Path(self._config.output_root), names, skip_session=skip_session) + return tuple( + self._pending_record( + item.manifest, + item.session_path / item.manifest.pending_path, + found_in=item.session_path if item.misplaced else None, + ) + for item in left + ) + def snapshot(self) -> RecordingSnapshot: """Immutable facts about the session, current episode, counts, last result and pending data.""" take = self._take @@ -395,10 +553,38 @@ def snapshot(self) -> RecordingSnapshot: info = EpisodeInfo(m.session_id, m.episode_id, m.episode_index, self._root(m.pending_path)) counts = self._counts(take) issues = [*self._issues, *([self._fatal_error] if self._fatal_error else [])] + silent = self.beat_silence() + if silent is not None: + issues.append( + f"the session's beat has not been written for {silent:.0f}s: where its lock does not reach, " + "another recorder may take this session for one nobody has open" + ) return RecordingSnapshot( self._session, self._phase, info, counts, self._last_result, self.pending_episodes(), tuple(issues) ) + def beat_silence(self) -> float | None: + """How long the open session's beat has been missing, once that is long enough to mislead a reader. + + The beat is what tells a reader on another machine that this session is open (see ``SessionLock``). The + recorder cannot make a stalled disk take it, but it can know: seconds since the last beat was written, + when a reader may by now have taken the session for closed; None while the beat is kept and with no + session open. A caller that shows an operator the recorder's state shows this. + """ + return self._lock.silence() if self._lock is not None else None + + def _note_beat(self, take: _Take) -> None: + """Note on a take, once, that the session's beat stopped while the take was recorded or finished. + + The take may then have looked abandoned to another machine. The note goes into the take's record with + the next checkpoint and into its result. + """ + if self._lock is None or take.beat_noted: + return + if self._lock.stalls > take.beat_stalls or self._lock.silence() is not None: + take.beat_noted = True + take.manifest.issues = [*take.manifest.issues, BEAT_STOPPED_NOTE] + async def close(self) -> CloseResult: """Stop admitting samples and settle owned work within one deadline; report whether all was released.""" if self._close_task is None: @@ -610,8 +796,6 @@ async def _call(self, take: _Take, fn: Callable[..., Any], *args: Any) -> Any: def _validate_config(self) -> None: """Refuse a configuration that cannot be recorded with, before any effect.""" cfg = self._config - if cfg.quarantine: - raise ConfigurationError("quarantine routing is not supported") names = [s.name for s in cfg.numeric_sources] + [s.name for s in cfg.video_sources] if not names: raise ConfigurationError("at least one source must be configured") @@ -675,6 +859,9 @@ async def _open_impl(self, session_id: str | None) -> SessionInfo: root.mkdir(parents=True, exist_ok=True) is_new = session_id is None if is_new: + # A session about to record is refused here, not at its first bad take. One reopened to resolve what + # it left behind is not: its takes can still be discarded, whatever the quarantine folder looks like. + self._require_quarantine_location(None) for asset in self._config.calibration_assets: if asset.required and not Path(asset.path).is_file(): raise ConfigurationError( @@ -711,8 +898,23 @@ async def _open_impl(self, session_id: str | None) -> SessionInfo: for manifest in manifests: if manifest.storage_phase in UNRESOLVED_PHASES: self._add_pending(manifest) + elif _retained_rejection(path, manifest): + self._rejected_kept[manifest.episode_id] = self._pending_record( + manifest, path / manifest.pending_path + ) return self._session + def _require_quarantine_location(self, session_id: str | None) -> None: + """Refuse to record where a take marked bad could not be set aside, in a sentence that names no path.""" + if not self._config.quarantine: + return + problem = quarantine_location_problem(Path(self._config.output_root), session_id) + if problem is not None: + raise ConfigurationError( + f"quarantine location {problem}: it must be a plain directory on the same file system as the " + "recordings" + ) + def _prepare_session_assets(self, session_path: Path, is_new: bool) -> None: """Preserve caller-supplied assets in a new session; verify the session's own copies on reopen. @@ -869,21 +1071,57 @@ def _same_configuration(self, manifest: EpisodeManifest) -> bool: return manifest.config_digest == _digest(self._config) def _add_pending(self, manifest: EpisodeManifest, issues: tuple[str, ...] = ()) -> None: - """Record an unresolved episode and whether a safe recovery step exists for it.""" + """Record an unresolved episode of the open session and whether a safe recovery step exists for it.""" + self._pending[manifest.episode_id] = self._pending_record( + manifest, self._root(manifest.pending_path), issues + ) + + def _pending_record( + self, + manifest: EpisodeManifest, + pending_path: Path, + issues: tuple[str, ...] = (), + *, + found_in: Path | None = None, + ) -> PendingEpisode: + """An episode that waits for someone, as this configuration sees it: what it is, why it waits and + whether it can be recovered. + + ``found_in`` is given for a record found in a session directory it was not written for. Such a record + is named after the directory it is in, so that it cannot be mistaken for the take it is a copy of, and + it is never recoverable. + """ same_config = self._same_configuration(manifest) - problems = list(issues) - if manifest.storage_phase == "WRITING": + phase, problems = manifest.storage_phase, list(issues) + # One note for why it waits, the most decisive first. + if found_in is not None: + problems.append(MISPLACED_RECORD) + elif manifest.discard_requested: + problems.append("a discard of this take was started and did not finish") + elif phase == "REJECTED": + problems.append("rejected by the integrity check; its data was kept") + elif phase == "WRITING": problems.append("interrupted while writing; completeness cannot be established") elif not same_config: problems.append("recorded with a different configuration") - self._pending[manifest.episode_id] = PendingEpisode( - manifest.session_id, - manifest.episode_id, + recoverable = phase in ("SEALED", "CHECKED") and same_config + session_id = manifest.session_id if found_in is None else found_in.name + return PendingEpisode( + session_id, + manifest.episode_id if found_in is None else f"{session_id}/{manifest.final_path}", manifest.episode_index, - self._root(manifest.pending_path), - manifest.storage_phase, - manifest.storage_phase in ("SEALED", "CHECKED") and same_config, + pending_path, + phase, + recoverable and not manifest.discard_requested and found_in is None, tuple(problems), + manifest.task, + manifest.operator, + manifest.duration_seconds, + tuple(manifest.issues), + manifest.finalization, + manifest.discard_requested, + found_in is not None, + manifest.session_id if found_in is not None else "", ) def _root(self, relative: str) -> Path: @@ -898,7 +1136,7 @@ def _source_declarations(self) -> list[dict[str, Any]]: {"kind": "video", **asdict(s)} for s in cfg.video_sources ] - async def _start_impl(self, task: str, operator: str, task_details: str) -> EpisodeInfo: + async def _start_impl(self, task: str, operator: str, task_details: str, exempt: bool = False) -> EpisodeInfo: """Checkpoint a WRITING manifest, then open the real store; enter RECORDING only on success.""" if self._session is None or self._closing: raise StateError("no open session") @@ -911,6 +1149,8 @@ async def _start_impl(self, task: str, operator: str, task_details: str) -> Epis session = self._session if not (session.session_path / SESSION_CONFIG_FILE).is_file(): raise StateError("session has no frozen source declarations; start a new session to record") + # Asked again for every take: the folder can be replaced while the session is open. + self._require_quarantine_location(session.session_id) index = next_episode_index(session.session_path) pending_name, final_name = episode_dir_names(index) manifest = EpisodeManifest( @@ -929,8 +1169,10 @@ async def _start_impl(self, task: str, operator: str, task_details: str) -> Epis capture_policy=policy_to_dict(self._config.qc.capture) if self._config.qc.capture else None, # The studio is decided now, so a later change of task cannot reroute a take waiting for QC. studio=resolve_studio(task, self._config.routing) if self._config.routing is not None else None, + capture_checks_exempt=exempt, ) take = _Take(manifest, list(self._source_kinds), None) + take.beat_stalls = self._lock.stalls if self._lock is not None else 0 self._phase = RecordingPhase.STARTING self._take = take self._start_task = asyncio.current_task() @@ -958,7 +1200,7 @@ async def _start_impl(self, task: str, operator: str, task_details: str) -> Epis logger.warning("episode start failed: %s", exc) take.released = take.store is None if manifest_path(session.session_path, index).exists(): - await self._retain(take, f"start failed: {exc}") + await self._retain(take, f"start failed{self._because(exc)}: {exc}") else: self._take = None self._phase = RecordingPhase.IDLE @@ -978,7 +1220,7 @@ async def _worker(self, take: _Take) -> None: await self._call(take, self._write, take, sample) except Exception as exc: # noqa: BLE001 - a write failure retains the take; stop reports it logger.error("episode write failed: %s", exc) - take.error = f"write failed: {exc}" + take.error = f"write failed{self._because(exc)}: {exc}" take.admission_closed = True return continue @@ -1028,6 +1270,8 @@ async def _finish_impl(self, take: _Take) -> EpisodeResult: """Seal, check and finalize (or reject) the take, resuming from whichever phase its manifest records.""" m = take.manifest session_path = self._root("") + # Whatever the beat did while the take was recorded is noted before the first checkpoint below. + self._note_beat(take) try: if m.storage_phase == "WRITING": assert take.store is not None @@ -1054,8 +1298,9 @@ async def _finish_impl(self, take: _Take) -> EpisodeResult: # Not recoverable by design: the files are sealed but the take is still WRITING on disk. return await self._retain( take, - f"the take was written and sealed, but its SEALED manifest could not be saved ({exc}); " - "it cannot be resumed, so discard it with discard_pending and record again", + f"the take was written and sealed{self._because(exc)}, but its SEALED manifest could " + f"not be saved ({exc}); it cannot be resumed, so discard it with discard_pending and " + "record again", ) if self._take is take: self._phase = RecordingPhase.FINALIZING @@ -1082,8 +1327,10 @@ async def _finish_impl(self, take: _Take) -> EpisodeResult: if report.outcome is Outcome.ERROR: return await self._retain(take, "quality check errored: " + "; ".join(report.issues)) capture = None - if report.outcome is Outcome.PASSED and self._config.qc.capture is not None: + judged = self._config.qc.capture is not None and not m.capture_checks_exempt + if report.outcome is Outcome.PASSED and judged: # Capture quality is judged only on integrity-valid data; the checker reports its own errors. + # A take started as exempt is not judged at all, so it records SKIPPED like one with no policy. capture = await self._call( take, check_capture_quality, session_path / m.pending_path, self._config.qc.capture ) @@ -1099,10 +1346,12 @@ async def _finish_impl(self, take: _Take) -> EpisodeResult: quality=report_to_dict(report), capture_quality=report_to_dict(capture) if capture else None, qc_decision=decision.value, - finalization=finalization_for(report.outcome, decision), + finalization=finalization_for(report.outcome, decision, self._config.quarantine), storage_phase="CHECKED", ) if m.storage_phase == "CHECKED": + # And whatever it did while the take was checked, before the checkpoint that finishes the take. + self._note_beat(take) if m.finalization == FINALIZATION_KEEP: if m.studio is not None and m.assignment is None: await self._assign_output(take) @@ -1116,17 +1365,27 @@ async def _finish_impl(self, take: _Take) -> EpisodeResult: self._attributes(m, take.timing, take.capture_session), ) final = await self._call(take, finalize_episode_dir, session_path, m) - await self._checkpoint(take, storage_phase="FINALIZED") + # Before the checkpoint, so that a recovery after an interruption repeats them. if m.assignment is not None: - # Best effort, after the take is durably FINALIZED: the totals are derived from the - # finalized episodes, so a failure here (an unreadable sibling, a damaged group stamp) - # must not strand a take that is already published. The next take finalized in the group - # recomputes them. - try: - await self._call(take, refresh_group_totals, final.parent) - except Exception as exc: # noqa: BLE001 - reported on the kept result, never fatal - logger.error("refreshing totals of %s failed: %s", final.parent, exc) - m.issues.append(f"group totals were not refreshed: {exc}") + await self._refresh_totals(take, final.parent) + await self._checkpoint(take, storage_phase="FINALIZED") + elif m.finalization == FINALIZATION_QUARANTINE: + # The same steps as a kept take, published in the session's quarantine folder instead. After a + # crash between the rename and the QUARANTINED checkpoint the take is already there, so the + # folder is not prepared again and the data is not rewritten: only its identity is verified. + if where == "pending": + await self._call(take, self._prepare_quarantine, session_path, m.session_id) + await self._call( + take, + write_episode_attributes, + session_path / m.pending_path, + self._attributes(m, take.timing, take.capture_session), + ) + final = await self._call(take, finalize_episode_dir, session_path, m) + # The folder's totals are what lists this take as not valid. They are rewritten before the + # checkpoint: interrupted in between, the take is still pending and a recovery repeats them. + await self._refresh_totals(take, final.parent) + await self._checkpoint(take, storage_phase="QUARANTINED") elif m.finalization == FINALIZATION_REMOVE: # Remove only this take's owned data; a failed removal retains the take (visible, recoverable). if where == "pending": @@ -1138,9 +1397,31 @@ async def _finish_impl(self, take: _Take) -> EpisodeResult: raise ValueError(f"unknown finalization {m.finalization!r}") except Exception as exc: # noqa: BLE001 - any storage failure retains the take with its diagnostic logger.error("finishing episode %s failed: %s", m.episode_id, exc) - return await self._retain(take, f"{m.storage_phase.lower()} step failed: {exc}") + return await self._retain(take, f"{m.storage_phase.lower()} step failed{self._because(exc)}: {exc}") return self._conclude(take) + async def _refresh_totals(self, take: _Take, group_dir: Path) -> None: + """Recompute the totals of the group or quarantine folder a take was just renamed into; best effort. + + The take is already in place and the totals are derived from the episodes themselves, so a failure here + (an unreadable sibling, a damaged stamp) must not strand it: the failure is noted on the take and the + next take published there recomputes them. + """ + try: + await self._call(take, refresh_group_totals, group_dir) + except Exception as exc: # noqa: BLE001 - reported on the result, never fatal + logger.error("refreshing totals of %s failed: %s", group_dir, exc) + take.manifest.issues.append(f"group totals were not refreshed: {exc}") + + def _prepare_quarantine(self, session_path: Path, session_id: str) -> None: + """Claim the session's quarantine folder and give it the session's frozen config and calibration files. + + Runs on the take's storage thread, before the take is renamed into the folder. Repeating it changes + nothing, so a recovery after a failure part-way simply runs it again. + """ + claim_quarantine_group(session_path, session_id) + self._seed_group_assets(session_path, quarantine_group(session_id)) + async def _assign_output(self, take: _Take) -> None: """Freeze the kept take's group and slot durably, before anything is published to them.""" m = take.manifest @@ -1210,6 +1491,10 @@ def _attributes( "integrity_check_passed": quality.get("outcome") == "PASSED", "integrity_check_issues": list(quality.get("issues", [])), **quality_attributes(decision, report, m.capture_policy), + # Stated on every episode, so a reader never has to infer it from where the episode was found. + "quarantined": m.finalization == FINALIZATION_QUARANTINE, + # Why an episode recorded under a capture policy still says SKIPPED: it was started as exempt. + "capture_qc_exempt": m.capture_checks_exempt, "config_digest": m.config_digest, "sources": m.sources, } @@ -1245,11 +1530,35 @@ async def _discard_impl(self, take: _Take) -> EpisodeResult: take.released = await self._call(take, take.store.abort) if not take.released: return await self._retain(take, "encoder release unconfirmed; data kept, restart the recorder") + # Asked first, changing nothing: a discard that is going to be refused (the take is already + # published) must not leave a record saying one began, which would then refuse its recovery. + try: + await self._call(take, discardable_pending, session_path, m) + except AlreadyPublished as exc: + # Nothing was tried and nothing can be: the take is saved and only its last record is missing. + logger.warning("discard of episode %s was refused: %s", m.episode_id, exc) + return await self._retain( + take, "discard refused: the take is already in its final place; recover it to finish" + ) + except PermissionError as exc: + logger.error("discard of episode %s was refused: %s", m.episode_id, exc) + return await self._retain( + take, "discard refused: the directory under the take's name is not the take's own" + ) + # The intent is durable before anything is deleted: whatever interrupts the removal, the record says + # that this take's data was being removed, so its emptied directory is still its own and the discard + # can be repeated. + if not m.discard_requested: + await self._checkpoint(take, discard_requested=True) await self._call(take, remove_owned_episode, session_path, m) + if m.finalization == FINALIZATION_QUARANTINE: + # A claim of the quarantine folder that was interrupted for this take is never repeated now. + # Nothing else can be claiming: a take waiting with this intent keeps the session from recording. + await self._call(take, discard_quarantine_claim, session_path) await self._checkpoint(take, storage_phase="DISCARDED") except Exception as exc: # noqa: BLE001 - a failed removal leaves the take recoverable with its diagnostic logger.error("discarding episode %s failed: %s", m.episode_id, exc) - return await self._retain(take, f"discard failed: {exc}") + return await self._retain(take, f"discard failed{self._because(exc)}: {exc}") return self._conclude(take) async def _interrupt_impl(self, take: _Take, reason: str) -> EpisodeResult: @@ -1261,7 +1570,24 @@ async def _interrupt_impl(self, take: _Take, reason: str) -> EpisodeResult: take.wake.set() if take.worker is not None: await asyncio.wait({take.worker}) - return await self._retain(take, reason) + found = take.error + if not found: + return await self._retain(take, reason) + # What the recorder itself found (a write that failed) is kept beside the caller's reason, in the record + # and in the result: it is often the cause of it, and the only note that says what was wrong with the disk. + take.manifest.issues = [*take.manifest.issues, found] + result = await self._retain(take, reason) + return replace(result, issues=(found, *result.issues)) + + def _because(self, exc: BaseException) -> str: + """The storage problem behind a failure as a mark for a recorder note, or nothing. + + The mark goes right after the note's own first words (``write failed [storage: full]: ...``), where a + reader of the note can find it without reading the system's text that follows. It is written only for + a failure on a file under this recorder's output. + """ + problem = storage_problem(exc, self._config.output_root) + return f" [storage: {problem}]" if problem else "" async def _retain(self, take: _Take, message: str) -> EpisodeResult: """Keep the take's data and release its encoders; the episode now needs recovery or discard.""" @@ -1274,25 +1600,38 @@ async def _retain(self, take: _Take, message: str) -> EpisodeResult: message += f"; encoder release failed: {exc}" if not take.released: message += "; encoder release unconfirmed" + self._note_beat(take) m.issues = [*m.issues, message] - if m.storage_phase in UNRESOLVED_PHASES: + if m.storage_phase in (*UNRESOLVED_PHASES, "REJECTED"): try: await self._call(take, write_manifest, self._root(""), m) except Exception as exc: # noqa: BLE001 - the in-memory record still reports the failure message += f"; manifest checkpoint failed: {exc}" - self._add_pending(m, (message,)) + if m.storage_phase == "REJECTED": + # A rejected take whose discard failed is still a rejected take with data on disk: it stays listed + # for another discard and goes on blocking nothing. + self._rejected_kept[m.episode_id] = self._pending_record(m, self._root(m.pending_path), (message,)) + else: + self._add_pending(m, (message,)) self._retained[m.episode_id] = take if self._take is take: self._phase = RecordingPhase.RECOVERY_REQUIRED - return self._result(take, Disposition.RECOVERY_REQUIRED, (message,)) + # Why it is pending now, after what the take's record says the beat did: both are news to the caller. + noted = (BEAT_STOPPED_NOTE,) if take.beat_noted else () + return self._result(take, Disposition.RECOVERY_REQUIRED, (*noted, message)) def _conclude(self, take: _Take) -> EpisodeResult: """The take reached a terminal storage phase: clear pending state and return to idle.""" m = take.manifest self._pending.pop(m.episode_id, None) self._retained.pop(m.episode_id, None) + self._rejected_kept.pop(m.episode_id, None) + if m.storage_phase == "REJECTED" and m.finalization == FINALIZATION_RETAIN: + # Its data stays on disk until someone removes it, so it is listed from now on. + self._rejected_kept[m.episode_id] = self._pending_record(m, self._root(m.pending_path)) disposition = { "FINALIZED": Disposition.KEPT, + "QUARANTINED": Disposition.QUARANTINED, "REJECTED": Disposition.REJECTED, "DISCARDED": Disposition.DISCARDED, }[m.storage_phase] @@ -1312,11 +1651,14 @@ def _result(self, take: _Take, disposition: Disposition, issues: tuple[str, ...] if disposition is Disposition.KEPT: routed = self._root("").parent / destination_path(m.assignment) if m.assignment else None final = routed or self._root(m.final_path) + quarantined = disposition is Disposition.QUARANTINED + quarantine = self._root("").parent / quarantine_destination(m) if quarantined else None # A resolved rejection has removed its data; an integrity rejection keeps its pending directory. removed = disposition is Disposition.DISCARDED or ( disposition is Disposition.REJECTED and m.finalization == FINALIZATION_REMOVE ) - pending = None if disposition is Disposition.KEPT or removed else self._root(m.pending_path) + published = disposition is Disposition.KEPT or quarantined + pending = None if published or removed else self._root(m.pending_path) quality = report_from_dict(m.quality) if m.quality else None return EpisodeResult( m.session_id, @@ -1332,6 +1674,7 @@ def _result(self, take: _Take, disposition: Disposition, issues: tuple[str, ...] QcDecision(m.qc_decision) if m.qc_decision else None, report_from_dict(m.capture_quality) if m.capture_quality else None, m.assignment["slot"] if disposition is Disposition.KEPT and m.assignment else None, + quarantine, ) def _counts(self, take: _Take) -> tuple[SourceCounts, ...]: @@ -1362,7 +1705,7 @@ def _require_accepting(self) -> None: def _pending_take(self, episode_id: str, verb: str) -> _Take: """The take for an unresolved episode, once no work is running on it.""" self._require_accepting() - if episode_id not in self._pending: + if episode_id not in self._pending and episode_id not in self._rejected_kept: raise StateError(f"no pending episode {episode_id!r}") take = self._retained.get(episode_id) if take is not None: @@ -1375,6 +1718,7 @@ def _pending_take(self, episode_id: str, verb: str) -> _Take: if manifest is None: raise StateError(f"episode {episode_id!r} has no readable manifest") take = _Take(manifest, list(self._source_kinds), None) + take.beat_stalls = self._lock.stalls if self._lock is not None else 0 for source, counts in manifest.counts.items(): take.accepted[source] = counts["accepted"] take.written[source] = counts["written"] diff --git a/examples/egocap/tests/backend/qc_takes.py b/examples/egocap/tests/backend/qc_takes.py new file mode 100644 index 0000000000..8fc5835769 --- /dev/null +++ b/examples/egocap/tests/backend/qc_takes.py @@ -0,0 +1,186 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Takes built in the test and recorded through the real coordinator and the real recording service. + +The frames are real wire values: tracking payloads encoded by the capture protocol and JPEG camera images, so a +take goes through the same conversion, ingress, writer and checks as one from a station. The session's +configuration comes from the application's own factory, so the checks that run are the ones a backend would run. +""" + +from __future__ import annotations + +import hashlib +import io +from pathlib import Path +from types import SimpleNamespace + +from PIL import Image + +from capture_server import protocol as capture_protocol +from capture_server.client import CameraImage, CaptureFrame +from egocap.recording.capture_qc_policy import CaptureQcPolicy +from egocap_web import app as app_module +from egocap_web.recording_session import RecordingSessionCoordinator +from tests.backend.test_recording_session import ( + IDENTITY_QUAT, + _controller_values, + _hand_values, + _tracking_descriptor, +) + +CAMERA_NAME = "head_human_camera" +#: A CaptureServer camera as the capture monitor describes it once accepted. +CAMERA = SimpleNamespace(name=CAMERA_NAME, width=64, height=48, fps=30.0) +TRACKING_HZ = 60.0 +#: Takes start here on the capture clock; any value works, since only differences are measured. +START_NS = 50_000_000_000 + +ALWAYS_READY = lambda: (True, None) # noqa: E731 + + +STATION = "Bench A" + + +def config_factory( + output_root: Path, + policy: CaptureQcPolicy | None = CaptureQcPolicy(), + cameras=(CAMERA,), + station: str | None = STATION, +): + """The application's own recording configuration factory over a fixed set of accepted cameras. + + The video is written by OpenCV so that no encoder process is involved. + """ + monitor = SimpleNamespace(camera_descriptors=tuple(cameras), native=SimpleNamespace(started=None)) + return app_module._recording_config_factory( + monitor, station, output_root, video_encoder="opencv_mp4v", qc_policy=policy + ) + + +def make_coordinator( + output_root: Path, + policy: CaptureQcPolicy | None = CaptureQcPolicy(), + *, + cameras=(CAMERA,), + station: str | None = STATION, + watch_seconds: float = 0.0, + **kwargs, +): + """A coordinator over the real recording service, configured as the backend would configure it. + + ``watch_seconds`` is how far apart its two looks at a session's beat must be before it lists that session's + takes. The backend's own value spans the recorder's one-second beat; here it is zero unless a test is about + a session another recorder has open, so that a take left behind is listed by the first read. + """ + return RecordingSessionCoordinator( + config_factory(output_root, policy, cameras, station), + queue_capacity=8192, + readiness_check=kwargs.pop("readiness_check", ALWAYS_READY), + watch_seconds=watch_seconds, + **kwargs, + ) + + +def tracking_frame(at_s: float, *, head_x: float, hand_x: float, finger_spread: float = 1.0) -> CaptureFrame: + """One fully valid tracking frame at ``at_s`` seconds into the take, with the head and controllers placed. + + ``finger_spread`` scales every hand joint's position: the recorded hand pose is relative to the wrist, so only + a change of the joints against each other moves it. + """ + values: dict[str, object] = { + "head.present": 1, + "head.position": (head_x, 0.0, 0.0), + "head.orientation": IDENTITY_QUAT, + "head.is_valid": 1, + "head.is_tracked": 1, + } + for side, offset in (("left", -0.2), ("right", 0.2)): + controller = _controller_values(f"controller_{side}") + controller[f"controller_{side}.aim_position"] = (offset + hand_x, 1.0, 0.0) + values.update(controller) + hand = _hand_values(f"hand_{side}") + hand[f"hand_{side}.joint_positions"] = hand[f"hand_{side}.joint_positions"] * finger_spread + values.update(hand) + at_ns = START_NS + int(round(at_s * 1e9)) + return CaptureFrame( + session_id="capture-1", + description=_tracking_descriptor(), + stream_id=0, + sequence=int(round(at_s * TRACKING_HZ)), + capture_time_ns=at_ns, + receive_time_ns=at_ns, + payload=capture_protocol.encode_tracking_frame(values), + ) + + +def camera_image(at_s: float, index: int, name: str = CAMERA_NAME) -> CameraImage: + """One JPEG camera frame at ``at_s`` seconds into the take.""" + buffer = io.BytesIO() + Image.new("RGB", (CAMERA.width, CAMERA.height), color=(index % 255, 40, 90)).save(buffer, format="JPEG") + at_ns = START_NS + int(round(at_s * 1e9)) + return CameraImage( + session_id="capture-1", + stream_id=1, + sequence=index, + capture_time_ns=at_ns, + receive_time_ns=at_ns, + name=name, + jpeg=buffer.getvalue(), + ) + + +def take_frames( + *, seconds: float = 2.0, camera_hole: float = 0.0, frozen_head: bool = False, frozen_hands: bool = False +): + """Every frame of one take, in capture order: tracking at 60 Hz and the camera at its declared 30 Hz. + + ``camera_hole`` withholds that many seconds of camera frames from the middle of the take (the frames at both + of its edges are delivered, so the camera's own span is still the whole take). ``frozen_head`` holds the head + at one pose while the controllers keep moving; ``frozen_hands`` holds both hand skeletons still. + """ + frames: list[tuple[float, object]] = [] + for i in range(int(seconds * TRACKING_HZ) + 1): + at = i / TRACKING_HZ + spread = 1.0 if frozen_hands else 1.0 + 0.001 * i + head_x = 0.0 if frozen_head else 0.001 * i + frames.append((at, tracking_frame(at, head_x=head_x, hand_x=0.001 * i, finger_spread=spread))) + hole_from = seconds / 2.0 - camera_hole / 2.0 + for i in range(int(seconds * CAMERA.fps) + 1): + at = i / CAMERA.fps + if camera_hole and hole_from < at < hole_from + camera_hole: + continue + frames.append((at, camera_image(at, i))) + return [frame for _at, frame in sorted(frames, key=lambda item: item[0])] + + +def offer(coordinator: RecordingSessionCoordinator, frames) -> None: + """Hand frames to the coordinator the way the capture monitor's callbacks do.""" + for frame in frames: + if isinstance(frame, CameraImage): + coordinator.on_capture_image(frame) + else: + coordinator.on_capture_frame(frame) + + +async def record(coordinator: RecordingSessionCoordinator, frames=None, operator: str = "alex"): + """Record one take to its result. The coordinator must hold a task.""" + episode = await coordinator.start_episode(operator) + offer(coordinator, take_frames() if frames is None else frames) + return await coordinator.stop_episode(episode.episode_id) + + +def tree(root: Path) -> dict[str, str]: + """Every file under ``root`` by relative path with a digest of its bytes; lock files are left out.""" + return { + path.relative_to(root).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(root.rglob("*")) + if path.is_file() and path.name != "session.lock" + } + + +def changed(before: dict[str, str], after: dict[str, str]) -> tuple[set[str], set[str], set[str]]: + """What differs between two :func:`tree` results, as (removed, added, modified) relative paths.""" + removed, added = set(before) - set(after), set(after) - set(before) + return removed, added, {path for path in set(before) & set(after) if before[path] != after[path]} diff --git a/examples/egocap/tests/backend/test_app_livekit_recording.py b/examples/egocap/tests/backend/test_app_livekit_recording.py index e4debb8fd5..76e446e0fe 100644 --- a/examples/egocap/tests/backend/test_app_livekit_recording.py +++ b/examples/egocap/tests/backend/test_app_livekit_recording.py @@ -13,10 +13,11 @@ import pytest from capture_server import protocol as p +from egocap.recording.capture_qc_policy import CaptureQcPolicy, resolve_policy from egocap_web import app as app_module from egocap_web.livekit_receiver import RECEIVER_FRAMES_PER_STREAM from egocap_web.recording_adapter import RecordingIngress -from recording_service import PixelFormat, VideoSample +from recording_service import ConfigurationError, PixelFormat, RecordingService, VideoSample def _stream(stream_id: int, basis, width=6) -> p.LiveKitCameraStream: @@ -306,8 +307,144 @@ def test_config_factory_declares_capture_qc_fps_for_each_recordable_livekit_stre ] +def _camera(name="head"): + return SimpleNamespace(name=name, width=8, height=6, fps=15.0) + + +POSES = (("pico_controller", "head_pose"), ("pico_controller", "left_pose"), ("pico_controller", "right_pose")) +GLOVES = (("manus_glove", "left_hand_pose"), ("manus_glove", "right_hand_pose")) + + @pytest.mark.parametrize("started", [None, SimpleNamespace(streams=[])]) -def test_config_factory_has_no_capture_qc_without_a_recordable_livekit_stream(tmp_path, started): - camera = SimpleNamespace(name="head", width=8, height=6, fps=15.0) - monitor = SimpleNamespace(camera_descriptors=(camera,), native=SimpleNamespace(started=started)) - assert app_module._recording_config_factory(monitor, None, tmp_path)().qc.capture is None +def test_config_factory_judges_a_capture_server_camera_and_the_pose_streams_without_any_livekit_stream( + tmp_path, started +): + monitor = SimpleNamespace(camera_descriptors=(_camera(),), native=SimpleNamespace(started=started)) + config = app_module._recording_config_factory(monitor, None, tmp_path)() + capture = config.qc.capture + assert capture is not None and capture.camera_expected_fps == (("head", None),) + assert capture.camera_expected_size == (("head", None),) + assert capture.pose_streams == POSES and capture.tracking_gap_sources == ("pico_controller",) + assert capture.duration_limits_s == (1.0, 600.0) + assert config.qc.required_sources == ("pico_controller", "head") + + +def test_config_factory_judges_every_camera_of_both_kinds_the_same_way(tmp_path): + stream = _stream(16, p.LiveKitTimestampBasis.SENSOR_CAPTURE_MONOTONIC_US) + monitor = SimpleNamespace( + camera_descriptors=(_camera(),), native=SimpleNamespace(started=_monitor([stream]).native.started) + ) + capture = app_module._recording_config_factory(monitor, None, tmp_path)().qc.capture + assert capture.camera_expected_fps == (("head", None), ("cam16", None)) + assert capture.camera_expected_size == (("head", None), ("cam16", None)) + assert capture.pose_streams == POSES + + +def test_config_factory_with_no_camera_at_all_still_judges_the_pose_streams(tmp_path): + monitor = SimpleNamespace(camera_descriptors=(), native=SimpleNamespace(started=None)) + capture = app_module._recording_config_factory(monitor, None, tmp_path)().qc.capture + assert capture.camera_expected_fps == () and capture.pose_streams == POSES + + +def test_config_factory_quarantines_by_default_and_follows_the_station_switch(tmp_path): + monitor = SimpleNamespace(camera_descriptors=(_camera(),), native=SimpleNamespace(started=None)) + assert app_module._recording_config_factory(monitor, None, tmp_path)().quarantine is True + kept = resolve_policy({}, {"guardrails": {"quarantine": False}}) + assert app_module._recording_config_factory(monitor, None, tmp_path, qc_policy=kept)().quarantine is False + + +def test_config_factory_requires_and_judges_the_gloves_only_where_the_station_expects_them(tmp_path): + monitor = SimpleNamespace(camera_descriptors=(_camera(),), native=SimpleNamespace(started=None)) + expected = resolve_policy({}, {"guardrails": {"gloves_expected": True}}) + config = app_module._recording_config_factory(monitor, None, tmp_path, qc_policy=expected)() + assert config.qc.required_sources == ("pico_controller", "manus_glove", "head") + assert config.qc.capture.pose_streams == POSES + GLOVES + assert config.qc.capture.tracking_gap_sources == ("pico_controller", "manus_glove") + default = app_module._recording_config_factory(monitor, None, tmp_path)() + assert "manus_glove" not in default.qc.required_sources + assert not set(GLOVES) & set(default.qc.capture.pose_streams) + + +def test_config_factory_takes_its_thresholds_and_camera_rates_from_the_policy(tmp_path): + monitor = SimpleNamespace(camera_descriptors=(_camera(),), native=SimpleNamespace(started=None)) + policy = resolve_policy( + {"guardrails": {"freeze_seconds": 3.0}}, + {"guardrails": {"camera_min_fps_ratio": 0.5, "camera_expected_fps": {"head": 30}}}, + defaults_file="site.yaml", + defaults_sha256="digest", + ) + capture = app_module._recording_config_factory(monitor, None, tmp_path, qc_policy=policy)().qc.capture + assert (capture.freeze_seconds, capture.camera_min_fps_ratio) == (3.0, 0.5) + assert capture.camera_expected_fps == (("head", 30.0),) + assert (capture.source.defaults_file, capture.source.defaults_sha256) == ("site.yaml", "digest") + + +def test_config_factory_runs_no_capture_check_when_the_policy_switches_them_off(tmp_path): + monitor = SimpleNamespace(camera_descriptors=(_camera(),), native=SimpleNamespace(started=None)) + off = resolve_policy({"guardrails": {"enabled": False}}) + config = app_module._recording_config_factory(monitor, None, tmp_path, qc_policy=off)() + assert config.qc.capture is None and config.qc.required_sources == ("pico_controller", "head") + + +def test_config_factory_builds_nothing_while_the_policy_could_not_be_read(tmp_path): + monitor = SimpleNamespace(camera_descriptors=(_camera(),), native=SimpleNamespace(started=None)) + factory = app_module._recording_config_factory(monitor, None, tmp_path, qc_policy=None) + with pytest.raises(ConfigurationError, match="quality-check configuration is invalid"): + factory() + + +def test_the_built_configuration_is_one_the_recording_service_accepts(tmp_path): + stream = _stream(16, p.LiveKitTimestampBasis.SENSOR_CAPTURE_MONOTONIC_US, width=8) + monitor = SimpleNamespace( + camera_descriptors=(_camera(),), native=SimpleNamespace(started=_monitor([stream]).native.started) + ) + for policy in (CaptureQcPolicy(), resolve_policy({}, {"guardrails": {"gloves_expected": True}})): + config = app_module._recording_config_factory(monitor, None, tmp_path, qc_policy=policy)() + RecordingService(config)._validate_config() + + +# --- the capture-QC policy at startup ------------------------------------------ + + +def test_the_policy_is_the_shipped_defaults_file_when_nothing_else_is_configured(monkeypatch): + monkeypatch.delenv("EGOCAP_QC_CONFIG", raising=False) + policy, error = app_module._load_qc_policy(None) + assert error is None and policy.source.defaults_file == "data_check_config.yaml" + assert policy.quarantine is True and policy.camera_min_fps_ratio == 0.86 + + +def test_a_site_file_and_the_station_section_are_merged_into_the_policy(monkeypatch, tmp_path): + site = tmp_path / "site_checks.yaml" + site.write_text("guardrails:\n freeze_seconds: 2.0\n camera_min_fps_ratio: 0.9\n") + monkeypatch.setenv("EGOCAP_QC_CONFIG", str(site)) + station = SimpleNamespace(data_check={"guardrails": {"camera_min_fps_ratio": 0.8}}) + policy, error = app_module._load_qc_policy(station) + assert error is None and (policy.freeze_seconds, policy.camera_min_fps_ratio) == (2.0, 0.8) + assert policy.source.defaults_file == "site_checks.yaml" + + +@pytest.mark.parametrize("content", ["guardrails:\n freeze_seconds: -1\n", "guardrails: [unclosed\n", None]) +def test_a_bad_qc_file_yields_no_policy_and_a_public_reason_without_its_path( + monkeypatch, tmp_path, content, caplog +): + site = tmp_path / "site_checks.yaml" + if content is not None: + site.write_text(content) + monkeypatch.setenv("EGOCAP_QC_CONFIG", str(site)) + policy, error = app_module._load_qc_policy(None) + assert policy is None and error == "quality-check configuration is invalid; see backend logs" + assert str(tmp_path) not in error + assert "new recording is blocked" in caplog.text + + +def test_a_bad_qc_configuration_blocks_recording_by_its_public_reason(accepted_tracking): + stream = _stream(16, p.LiveKitTimestampBasis.SENSOR_CAPTURE_MONOTONIC_US) + monitor = _ready_monitor([stream]) + assert app_module._recording_readiness_check(monitor, None, None)() == (True, None) + blocked = app_module._recording_readiness_check(monitor, None, None, app_module.QC_CONFIG_INVALID)() + assert blocked == (False, "quality-check configuration is invalid; see backend logs") + # A bad station file is the earlier step and is reported first. + both = app_module._recording_readiness_check( + monitor, "station is invalid", None, app_module.QC_CONFIG_INVALID + )() + assert both == (False, "station is invalid") diff --git a/examples/egocap/tests/backend/test_auto_align.py b/examples/egocap/tests/backend/test_auto_align.py index b4cfdaff07..f3a47129b5 100644 --- a/examples/egocap/tests/backend/test_auto_align.py +++ b/examples/egocap/tests/backend/test_auto_align.py @@ -17,6 +17,7 @@ from egocap.recording.episode_layout import ( FINALIZATION_KEEP, + FINALIZATION_QUARANTINE, FINALIZATION_RETAIN, EpisodeManifest, episode_dir_names, @@ -25,7 +26,7 @@ from egocap_web import auto_align from egocap_web.auto_align import AutoAligner from egocap_web.session_locks import ALIGNER, CORRECTION, SessionLocks -from recording_service import Disposition, EpisodeResult +from recording_service import Disposition, EpisodeResult, QcDecision from tests.recording.unit.test_align_kept_episode import ( INDEX, build_raw, @@ -57,7 +58,9 @@ """ -def _result(index=3, disposition=Disposition.KEPT, final_path="default", session_id="session_a"): +def _result( + index=3, disposition=Disposition.KEPT, final_path="default", session_id="session_a", qc_decision=None, **more +): if final_path == "default": final_path = Path("/routed/group") / "episode_000007" return EpisodeResult( @@ -70,6 +73,8 @@ def _result(index=3, disposition=Disposition.KEPT, final_path="default", session counts=(), duration_seconds=1.0, quality=None, + qc_decision=qc_decision, + **more, ) @@ -101,6 +106,33 @@ def test_results_that_are_not_a_kept_episode_with_a_path_are_ignored(result): assert aligner._queue.empty() +@pytest.mark.parametrize( + "result", + [ + # Marked bad and kept with its session. + _result(qc_decision=QcDecision.FLAGGED_BAD), + # Marked bad and set apart: not a kept episode, and it has no published path. + _result( + disposition=Disposition.QUARANTINED, + final_path=None, + qc_decision=QcDecision.FLAGGED_BAD, + quarantine_path=Path("/out/_quarantine/session_a/episode_3"), + ), + ], +) +def test_a_take_the_checks_marked_bad_is_never_queued_for_alignment(result): + aligner = AutoAligner(Path("/out"), "head") + aligner.submit(result) + assert aligner._queue.empty() + + +@pytest.mark.parametrize("decision", [QcDecision.PASSED, QcDecision.SKIPPED, None]) +def test_a_kept_take_that_passed_or_was_not_judged_is_queued(decision): + aligner = AutoAligner(Path("/out"), "head") + aligner.submit(_result(qc_decision=decision)) + assert aligner._queue.qsize() == 1 + + def test_kept_results_are_queued_before_any_session_has_reported_its_sources(): aligner = AutoAligner(Path("/out"), "head") aligner.submit(_result()) @@ -209,6 +241,22 @@ def test_scan_finds_only_kept_episodes_without_an_aligned_copy(tmp_path): assert jobs == [auto_align._Job("s1", 0, tmp_path / "s1" / episode_dir_names(0)[1])] +def test_scan_skips_a_flagged_take_and_a_quarantined_one(tmp_path): + _write_session_manifest(tmp_path, "s1", 0, qc_decision="PASSED") + _write_session_manifest(tmp_path, "s1", 1, qc_decision="FLAGGED_BAD") + _write_session_manifest( + tmp_path, + "s1", + 2, + qc_decision="FLAGGED_BAD", + storage_phase="QUARANTINED", + finalization=FINALIZATION_QUARANTINE, + qualified=None, + ) + _write_session_manifest(tmp_path, "s1", 3, qc_decision="SKIPPED") + assert [job.episode_index for job in AutoAligner(tmp_path, "head").scan()] == [0, 3] + + def test_scan_finds_older_sessions_work_even_when_the_newest_session_is_empty(tmp_path): _write_session_manifest(tmp_path, "s1", 0) _write_session_manifest(tmp_path, "s2", 0) diff --git a/examples/egocap/tests/backend/test_calibration_routes.py b/examples/egocap/tests/backend/test_calibration_routes.py index 89c51cf298..7400f4a880 100644 --- a/examples/egocap/tests/backend/test_calibration_routes.py +++ b/examples/egocap/tests/backend/test_calibration_routes.py @@ -53,7 +53,11 @@ from tests.backend.test_calibration_service import ( BOARD, CAMERA_TAKE, + DATA_KEPT, + GLOVE_TAKE, HEAD, + NO_CAMERA_ROWS, + NO_CAMERA_ROWS_SAID, POSITION, SESSION, SOLVE, @@ -113,6 +117,18 @@ async def lifespan(app: FastAPI): return TestClient(small), world +def wait_for_capture(monitor) -> None: + """Wait until the mock capture stack delivers what a take is admitted on: a running session, the camera's + picture and a tracking sample. The camera's first picture can arrive before the first tracking sample.""" + _poll_until_sync( + lambda: ( + monitor.snapshot().running + and monitor.preview.camera("head_human_camera") is not None + and monitor.preview.tracking() is not None + ) + ) + + def call(client: TestClient, method: str, path: str, body, headers=None): arguments = {"headers": headers} if body is None else {"headers": headers, "json": body} return getattr(client, method)(f"{ROOT}{path}", **arguments) @@ -247,13 +263,12 @@ def test_a_take_ended_from_another_page_is_settled_by_the_next_poll_and_the_over client, world = station(tmp_path) with client: client.post(f"{ROOT}/recording", json=CAMERA_TAKE, headers=AUTH) - world.recorder.issues = ("required source 'head_camera' has no data",) + world.recorder.quality = NO_CAMERA_ROWS world.recorder.finish(Disposition.REJECTED) polled = client.get(f"{ROOT}/recording", headers=AUTH).json() assert polled["phase"] == "failed" and polled["take"] is None - assert polled["problem"] == ( - "the take was rejected by the recorder's checks: required source 'head_camera' has no data" - ) + # The tool's lead, then the recording page's own sentence for what the integrity check found. + assert polled["problem"] == f"the integrity check rejected it; {DATA_KEPT}. {NO_CAMERA_ROWS_SAID}" assert world.task() == ("Pour water.", "left hand") assert client.get(ROOT, headers=AUTH).json()["recording"] == polled @@ -685,9 +700,7 @@ def test_the_real_recorder_rejects_a_take_without_tracking_and_the_tool_says_why context = client.app.state.recording_context auth = {"X-Control-Token": context.control_token} monitor = client.app.state.monitor - _poll_until_sync( - lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None - ) + wait_for_capture(monitor) context.coordinator.set_task("Pour water.") client.put("/api/operator-settings", json={"camera_roles": {"ego": "head_human_camera"}}, headers=auth) # A wrist-style intrinsics-only take needs no head pose to solve, and is still not kept without rows. @@ -701,11 +714,128 @@ def test_the_real_recorder_rejects_a_take_without_tracking_and_the_tool_says_why stopped = client.post(f"{ROOT}/recording/stop", json={}, headers=auth).json() assert (stopped["phase"], stopped["take"]) == ("failed", None) - assert stopped["problem"] == ( - f"{NO_TRACKING_RECORDED}; the take was rejected by the recorder's checks: " - "pico_controller: required source has no rows" + said = "The recorded data failed an integrity check: pico_controller: required source has no rows." + assert stopped["problem"] == f"{NO_TRACKING_RECORDED}; {DATA_KEPT}. {said}" + snapshot = context.snapshot() + assert snapshot["task_text"] == "Pour water." + # The recording page is told the same of the take, and lists it with its data still on disk. + result = snapshot["last_result"] + assert (result["outcome"], result["reasons"], result["media_removed"]) == ( + "rejected_data_kept", + [said], + False, ) - assert context.snapshot()["task_text"] == "Pour water." + (row,) = snapshot["pending_takes"] + assert (row["episode_id"], row["phase"], row["task"]) == ( + result["episode_id"], + "REJECTED", + "Calibration: head camera", + ) + assert (row["recoverable"], row["discardable"], row["current"]) == (False, True, False) + pending = tmp_path / "recordings" / result["location"] + assert pending.name.endswith(".pending") and pending.is_dir() + # It holds nothing: the tool records again at once, and the page's Discard removes the data. + assert snapshot["ready_to_record"] is True + discard = parse_recording_command( + { + "request_id": "r1", + "action": "discard_pending", + "payload": {"batch_id": context.batch_id, "episode_id": row["episode_id"]}, + "operator_token": "sam", + "control_token": context.control_token, + } + ) + discarded = client.portal.call(handle_recording_command, discard, context) + assert (discarded["outcome"], discarded["reason"]) == ("ok", None) + assert discarded["snapshot"]["pending_takes"] == [] and not pending.exists() + finally: + server.stop() + + +#: How long each take of the mock's faults lasts: long enough for the camera rule and the freeze rule to judge it. +FAULT_TAKE_SECONDS = 3.5 + + +@pytest.mark.parametrize( + ("faults", "tool_request", "from_the_page"), + [ + # Every camera delivers for a second, then withholds its frames for a second and a half. + ( + {"camera_faults": {"camera_stall"}}, + {**CAMERA_TAKE, "mode": "intrinsic"}, + ("rejected", "REJECTED_CAMERA", True), + ), + # Every tracking pose stops changing, as hands and a headset held still do. + ({"ic_faults": {"sample_freeze"}}, GLOVE_TAKE, ("quarantined", "FLAGGED_BAD", False)), + ], + ids=["a camera that withholds frames", "tracking that does not change"], +) +def test_the_real_application_keeps_a_tools_take_the_capture_checks_reject_or_set_aside_when_record_starts_it( + monkeypatch, unused_tcp_port, tmp_path, faults, tool_request, from_the_page +): + """The real application against the real CaptureServer, whose mock runs with one of its capture faults.""" + from egocap_web import app as app_module + + station_file = tmp_path / "station.yaml" + station_file.write_text("video_sources:\n- type: oak_camera\n name: head_human_camera\n", encoding="utf-8") + calibration = tmp_path / "calibration" + calibration.mkdir() + # The glove tool builds on the head camera's installed calibration. + (calibration / "head_camera_intrinsics.json").write_text(json.dumps(good_record())) + (calibration / "head_camera_extrinsics.json").write_text(json.dumps(POSITION)) + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(station_file)) + monkeypatch.setenv("EGOCAP_CAPTURE_SERVER_URL", f"ws://127.0.0.1:{unused_tcp_port}") + monkeypatch.setenv("EGOCAP_CALIBRATION_DIR", str(calibration)) + monkeypatch.delenv("EGOCAP_OPERATOR_SETTINGS_FILE", raising=False) + output = tmp_path / "recordings" + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: output) + start = capture_server_support.start_capture_server + monkeypatch.setattr(capture_server_support, "start_capture_server", functools.partial(start, **faults)) + server = _ServerThread(unused_tcp_port) + try: + with TestClient(real_app) as client: + context = client.app.state.recording_context + auth = {"X-Control-Token": context.control_token} + wait_for_capture(client.app.state.monitor) + context.coordinator.set_task("Pour water.") + client.put("/api/operator-settings", json={"camera_roles": {"ego": "head_human_camera"}}, headers=auth) + + def manifest(episode_id: str) -> dict: + session, episode = episode_id.split("/") + return json.loads((output / session / ".recording" / f"{episode}.json").read_text()) + + def page(action: str, **payload) -> dict: + command = parse_recording_command( + { + "request_id": "r1", + "action": action, + "payload": {"batch_id": context.batch_id, **payload}, + "operator_token": "sam", + "control_token": context.control_token, + } + ) + return client.portal.call(handle_recording_command, command, context) + + # The tool's take is kept, unjudged, and the tool names it as the take it means from now on. + started = client.post(f"{ROOT}/recording", json=tool_request, headers=auth) + assert started.status_code == 200, started.json() + time.sleep(FAULT_TAKE_SECONDS) + stopped = client.post(f"{ROOT}/recording/stop", json={}, headers=auth).json() + assert (stopped["phase"], stopped["problem"]) == ("saved", None), stopped + kept = context.snapshot()["last_result"] + assert (kept["outcome"], kept["qc_decision"], kept["location"]) == ("kept", "SKIPPED", stopped["take"]) + assert manifest(kept["episode_id"])["capture_checks_exempt"] is True + assert (output / stopped["take"] / "head_human_camera.mp4").is_file() + assert not (output / "_quarantine").exists() + + # The same capture, recorded from the recording page for as long, is judged. + record = page("start_episode") + assert record["outcome"] == "ok", record["reason"] + time.sleep(FAULT_TAKE_SECONDS) + judged = page("stop_episode", episode_id=record["snapshot"]["current_episode_id"]) + result = judged["snapshot"]["last_result"] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == from_the_page + assert manifest(result["episode_id"])["capture_checks_exempt"] is False finally: server.stop() @@ -773,9 +903,7 @@ def test_the_real_application_records_a_calibration_take_and_gives_the_operators auth = {"X-Control-Token": context.control_token} assert client.get(ROOT).status_code == 403 monitor = client.app.state.monitor - _poll_until_sync( - lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None - ) + wait_for_capture(monitor) context.coordinator.set_task("Pour water.", task_details="left hand") take_request = {**CAMERA_TAKE, "mode": "intrinsic"} # The recorder's LiveKit feed is watched, so a camera that arrives that way is guided by the frames @@ -812,7 +940,7 @@ def test_the_real_application_records_a_calibration_take_and_gives_the_operators assert started.json()["phase"] == "recording" and started.json()["camera"] == "head_human_camera" snapshot = context.snapshot() assert snapshot["task_text"] == "Calibration: head camera" and snapshot["episode_phase"] == "RECORDING" - # Frames must flow into the take before it is stopped, or the recorder's checks reject it as empty. + # Frames must flow into the take before it is stopped, or the integrity check rejects it as empty. time.sleep(0.4) polled = client.get(f"{ROOT}/recording", headers=auth).json() assert polled["phase"] == "recording" and polled["guide"]["available"] is True @@ -968,9 +1096,7 @@ def test_the_real_application_refuses_the_lens_of_a_corrected_camera_and_records context = client.app.state.recording_context auth = {"X-Control-Token": context.control_token} monitor = client.app.state.monitor - _poll_until_sync( - lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None - ) + wait_for_capture(monitor) context.coordinator.set_task("Pour water.") client.put("/api/operator-settings", json={"camera_roles": {"ego": "head_human_camera"}}, headers=auth) overview = client.get(ROOT, headers=auth).json() @@ -1102,9 +1228,7 @@ def test_the_real_application_holds_a_take_in_its_own_words_while_a_file_of_the_ context = client.app.state.recording_context auth = {"X-Control-Token": context.control_token} monitor = client.app.state.monitor - _poll_until_sync( - lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None - ) + wait_for_capture(monitor) context.coordinator.set_task("Pour water.") client.put("/api/operator-settings", json={"camera_roles": {"ego": "head_human_camera"}}, headers=auth) # The session could not carry the lens its video passes through: no take, from either page, and @@ -1182,9 +1306,7 @@ def test_the_real_application_holds_every_take_while_the_launchers_report_cannot context = client.app.state.recording_context auth = {"X-Control-Token": context.control_token} monitor = client.app.state.monitor - _poll_until_sync( - lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None - ) + wait_for_capture(monitor) context.coordinator.set_task("Pour water.") client.put("/api/operator-settings", json={"camera_roles": {"ego": "head_human_camera"}}, headers=auth) # Not "not corrected", as if it were known: null, and the note that says why and what to do. diff --git a/examples/egocap/tests/backend/test_calibration_service.py b/examples/egocap/tests/backend/test_calibration_service.py index 2129b03619..55545049ab 100644 --- a/examples/egocap/tests/backend/test_calibration_service.py +++ b/examples/egocap/tests/backend/test_calibration_service.py @@ -12,6 +12,7 @@ import asyncio import base64 import dataclasses +import errno import json import logging import threading @@ -43,6 +44,7 @@ other_camera_problem, reply, sendable, + with_sentences, ) from egocap_web.calibration_frames import NewestFrames from egocap_web.calibration_service import ( @@ -94,8 +96,10 @@ StreamsState, UnreadStreams, ) +from egocap_web.take_outcome import STORAGE_SENTENCES, describe_result from recording_service import ( CalibrationAsset, + CheckResult, ConfigurationError, Disposition, EpisodeInfo, @@ -104,11 +108,14 @@ NumericSourceSpec, Outcome, PixelFormat, + QcDecision, QualityReport, RecordingPhase, ServiceConfig, SourceCounts, + StateError, VideoSample, + storage_problem, ) from tests.backend.test_recording_adapter import default_tracking_values from tests.backend.test_rectification_service import SMALL_CHOICE, launcher_applied @@ -209,10 +216,15 @@ def __init__(self, root: Path): #: What a discard ends as; the recorder keeps a take it could not remove, as an interrupted one. self.discarded_as = Disposition.DISCARDED self.issues: tuple[str, ...] = () - #: Tracking rows the take holds, and what the recorder's checks found in it. + #: Tracking rows the take holds, what the checks found in it and what the capture checks decided. self.tracking_rows = 120 self.quality: QualityReport | None = None self.capture_quality: QualityReport | None = None + self.qc_decision: QcDecision | None = None + #: Why no take would be admitted now, as the readiness check words it; None while one would. + self.not_ready: str | None = None + #: Whether each take was started exempt from the capture checks, in the order they were started. + self.exempt: list[bool] = [] #: Set to make a stop or discard wait, as a take being finalized would. self.hold: asyncio.Event | None = None self.started = 0 @@ -231,8 +243,16 @@ def set_task(self, task_text: str, task_details: str = "") -> None: self.calls.append(("set_task", task_text, task_details)) self.context = SimpleNamespace(task_text=task_text, task_details=task_details) - async def start_episode(self, operator: str) -> EpisodeInfo: + def readiness(self) -> tuple[bool, str | None]: + return self.not_ready is None, self.not_ready + + def recordings_disk_problem(self, exc: BaseException) -> str | None: + # The recording service's own rule for what a failure says about the recordings disk. + return storage_problem(exc, self.root) + + async def start_episode(self, operator: str, *, exempt_from_capture_checks: bool = False) -> EpisodeInfo: self.calls.append(("start", operator, self.context.task_text)) + self.exempt.append(exempt_from_capture_checks) if self.start_error is not None: raise self.start_error self.started += 1 @@ -284,6 +304,7 @@ def finish(self, disposition: Disposition) -> EpisodeResult: duration_seconds=12.0, quality=self.quality, issues=self.issues, + qc_decision=self.qc_decision, capture_quality=self.capture_quality, ) if disposition is Disposition.RECOVERY_REQUIRED: @@ -452,6 +473,11 @@ def page_command(world: World, action: str, **payload): ) +def page_record(result: EpisodeResult) -> dict: + """The recording page's record of a take: what the recording context keeps of the last result.""" + return describe_result(result) + + def kept_take(world: World) -> Path: """Where the real recorder put the take it last kept.""" return world.context.coordinator.snapshot().service.last_result.final_path @@ -532,7 +558,8 @@ async def test_a_cancel_the_recorder_could_not_carry_out_says_the_take_is_still_ # The recorder keeps a take whose data it could not remove, as an interrupted one, and says why. world.recorder.discarded_as = Disposition.RECOVERY_REQUIRED world.recorder.issues = ("discard failed: [Errno 5] Input/output error: '/data/session/episode_1.pending'",) - with caplog.at_level(logging.INFO, logger="isaaccapture.egocap.calibration_service"): + # The recorder's note is logged where a take is described for the page, once for the page and the tool. + with caplog.at_level(logging.INFO, logger="isaaccapture.egocap.take_outcome"): status = await world.service.cancel_recording() assert (status["phase"], status["take"], status["problem"]) == ("failed", None, TAKE_INTERRUPTED) # What the recorder says is true of the tool too: the next take is held, and the reason stays in the log. @@ -541,27 +568,73 @@ async def test_a_cancel_the_recorder_could_not_carry_out_says_the_take_is_still_ assert (await world.service.poll_recording())["problem"] == TAKE_INTERRUPTED +async def test_a_take_the_recorder_is_not_ready_for_is_refused_in_the_readiness_checks_own_sentence(world): + # The reason Record on the recording page is refused with, as the backend's readiness check words it. + world.recorder.not_ready = "camera 'head_camera' is stale or has no sample yet" + await refused(world.service.start_recording(CAMERA_TAKE), 409, world.recorder.not_ready) + # The recorder was not asked for anything: no task text was put in the operator's place. + assert world.recorder.calls == [] and world.context.revision == 0 + await refused(world.service.poll_recording(), 404, "no calibration recording has been started") + world.recorder.not_ready = None + assert (await world.service.start_recording(CAMERA_TAKE))["phase"] == "recording" + + +async def test_a_recorder_that_gives_no_reason_for_not_being_ready_still_refuses_the_take_in_a_sentence(world): + world.recorder.readiness = lambda: (False, None) + await refused(world.service.start_recording(CAMERA_TAKE), 409, "required sources are not ready") + assert world.recorder.calls == [] + + @pytest.mark.parametrize( - ("error", "detail"), + ("error", "detail", "level"), [ - (CoordinatorBusyError("camera 'head_camera' is stale or has no sample yet"), None), + # What the coordinator and the recording service raise is worded for the log, with recorder states, ids + # and directories: the tool answers with the sentence the recording page gives for the same refusal. ( - RuntimeError("[Errno 28] No space left on device: '/data/session'"), - "the take could not be started; see the backend log", + CoordinatorBusyError("stopping already in progress"), + "Another recording command is still running; try again in a moment.", + logging.WARNING, + ), + ( + StateError("unresolved pending episodes: ['session_20260304-081500_abc123/episode_4']"), + "A take is waiting to be recovered or discarded. Resolve it, or start a new batch, before recording.", + logging.WARNING, ), - # The recording service words a refused configuration for a log, with the directory of what is missing. ( ConfigurationError("required calibration asset missing: /data/run/session_rectification.json"), + "A calibration file this station requires is missing or changed; see the backend log.", + logging.WARNING, + ), + ( + CoordinatorBusyError( + "LiveKit video is not ready: [Errno 111] connect call failed ('192.0.2.7', 7880)" + ), + "LiveKit video is not ready; see the backend log.", + logging.WARNING, + ), + # Anything else is a failure: named when the recordings disk caused it, a pointer to the log when not. + ( + RuntimeError("[Errno 28] No space left on device: '/data/session'"), "the take could not be started; see the backend log", + logging.ERROR, ), + ("a full recordings disk", STORAGE_SENTENCES["full"], logging.ERROR), ], ) -async def test_a_refused_start_puts_the_task_back_and_leaves_no_recording(world, caplog, error, detail): +async def test_a_refused_start_puts_the_task_back_and_leaves_no_recording(world, caplog, error, detail, level): + if error == "a full recordings disk": + # A failure on a file under the recording output, as the system reports a disk with no room left. + error = OSError(errno.ENOSPC, "No space left on device", str(world.root / SESSION / "episode_1.pending")) world.recorder.start_error = error - with caplog.at_level(logging.ERROR, logger="isaaccapture.egocap.calibration_service"): + with caplog.at_level(logging.WARNING, logger="isaaccapture.egocap.calibration_service"): said = await refused(world.service.start_recording(CAMERA_TAKE), 409, detail) - # The recorder's own reasons are written for operators; anything else stays in the log. - assert said == (detail or str(error)) and "/data" not in said + # Nothing the recorder raised reaches the page: no directory, no address, no id and no error number. + for raw in ("/data", str(world.root), "192.0.2.7", "Errno", "episode_4", "already in progress"): + assert raw not in said + # It is in the log instead, with a traceback only for what was not a refusal on purpose. + (logged,) = caplog.records + assert logged.levelno == level and str(error) in logged.getMessage() + assert bool(logged.exc_info) is (level == logging.ERROR) assert world.task() == ("Pour water.", "left hand") await refused(world.service.poll_recording(), 404, "no calibration recording has been started") # Nothing is left claimed: the next start goes through. @@ -569,6 +642,17 @@ async def test_a_refused_start_puts_the_task_back_and_leaves_no_recording(world, assert (await world.service.start_recording(CAMERA_TAKE))["phase"] == "recording" +@pytest.mark.parametrize("request_body", [CAMERA_TAKE, GLOVE_TAKE]) +async def test_every_take_either_tool_starts_is_started_exempt_from_the_capture_checks(world, request_body): + world.calibrate_headset() + # Whatever the request claims: the flag is the service's own and no field of a request is read for it. + claims = {"exempt_from_capture_checks": False, "capture_qc_exempt": False, "calibration": False} + await world.service.start_recording({**request_body, **claims}) + await world.service.stop_recording() + await world.service.start_recording(request_body) + assert world.recorder.exempt == [True, True] + + async def test_a_take_kept_from_another_page_is_noticed_by_the_next_poll(world): await world.service.start_recording(CAMERA_TAKE) world.recorder.finish(Disposition.KEPT) @@ -577,28 +661,131 @@ async def test_a_take_kept_from_another_page_is_noticed_by_the_next_poll(world): assert world.task() == ("Pour water.", "left hand") +#: What the integrity check finds in a take with an empty camera, and the page's sentence for it. +NO_CAMERA_ROWS = QualityReport(Outcome.FAILED, ("head_camera: required source has no rows",), (), ()) +NO_CAMERA_ROWS_SAID = "The recorded data failed an integrity check: head_camera: required source has no rows." +DATA_KEPT = "its data stays on disk and can be discarded on the recording page" + + @pytest.mark.parametrize( - ("disposition", "issues", "problem"), + ("disposition", "quality", "issues", "problem"), [ + # Rejected by the integrity check, the only check a calibration take is judged by: its data is kept. + ( + Disposition.REJECTED, + NO_CAMERA_ROWS, + (), + f"the integrity check rejected it; {DATA_KEPT}. {NO_CAMERA_ROWS_SAID}", + ), + (Disposition.REJECTED, None, (), f"the integrity check rejected it; {DATA_KEPT}"), + # A note the recorder wrote for its log is never a reason: it can name a directory. ( Disposition.REJECTED, - ("required source 'head_camera' has no data", "tracking gap of 1.2 s"), - "the take was rejected by the recorder's checks: required source 'head_camera' has no data; " - "tracking gap of 1.2 s", + NO_CAMERA_ROWS, + ("group totals were not refreshed: [Errno 13] Permission denied: '/data/x'",), + f"the integrity check rejected it; {DATA_KEPT}. {NO_CAMERA_ROWS_SAID}", ), - (Disposition.REJECTED, (), "the take was rejected by the recorder's checks"), - (Disposition.DISCARDED, (), "the take was discarded"), - (Disposition.RECOVERY_REQUIRED, ("recording pipeline failed: /data/x",), TAKE_INTERRUPTED), + (Disposition.DISCARDED, None, (), "the take was discarded"), + (Disposition.RECOVERY_REQUIRED, None, ("recording pipeline failed: /data/x",), TAKE_INTERRUPTED), ], ) -async def test_a_take_that_ended_badly_without_the_tool_fails_with_what_the_recorder_says( - world, disposition, issues, problem +async def test_a_take_that_ended_badly_without_the_tool_fails_with_what_the_recording_page_says( + world, disposition, quality, issues, problem ): await world.service.start_recording(CAMERA_TAKE) - world.recorder.issues = issues + world.recorder.quality, world.recorder.issues = quality, issues world.recorder.finish(disposition) status = await world.service.poll_recording() assert (status["phase"], status["take"], status["problem"]) == ("failed", None, problem) + # Word for word what the recording page shows of the same take, after the tool's own lead. + reasons = page_record(world.recorder.last_result)["reasons"] + assert disposition is not Disposition.REJECTED or status["problem"].endswith(" ".join(reasons)) + assert "/data" not in status["problem"] and "Errno" not in status["problem"] + + +#: A camera below its minimum rate, as the capture checks measure and report it. +SLOW_CAMERA = CheckResult( + "camera_min_fps:head_camera", + Outcome.FAILED, + ("head_camera: 11.20 fps average is below 0.86 x 30.0 = 25.80",), + measurements={"fps": 11.2, "minimum_fps": 25.8, "expected_fps": 30.0}, +) +SLOW_CAMERA_SAID = ( + "Camera head_camera averaged 11.2 fps, below the minimum of 25.8 fps (0.86 of 30 fps). " + "Check the camera's cable and the load on this PC, then record the take again." +) +#: A headset that did not move, as the capture checks measure and report it. +FROZEN_HEAD = CheckResult( + "sustained_freeze:pico_controller/head_pose", + Outcome.FAILED, + ("pico_controller/head_pose: no motion for 2.00s (limit 1.0s, eps 1e-06)",), + measurements={"longest_still_s": 2.0, "limit_s": 1.0}, +) +FROZEN_HEAD_SAID = ( + "The headset did not move for 2.0 s (limit 1 s). " + "Check that the headset and both controllers are on, charged and in view." +) + + +@pytest.mark.parametrize( + ("disposition", "decision", "check", "problem"), + [ + ( + Disposition.REJECTED, + QcDecision.REJECTED_CAMERA, + SLOW_CAMERA, + f"the capture checks rejected it and removed its media. {SLOW_CAMERA_SAID}", + ), + ( + Disposition.KEPT, + QcDecision.FLAGGED_BAD, + FROZEN_HEAD, + f"the capture checks marked it bad. {FROZEN_HEAD_SAID}", + ), + ( + Disposition.QUARANTINED, + QcDecision.FLAGGED_BAD, + FROZEN_HEAD, + f"the capture checks marked it bad and set it aside. {FROZEN_HEAD_SAID}", + ), + ], +) +async def test_a_take_the_capture_checks_judged_all_the_same_is_never_taken_for_a_kept_one( + world, disposition, decision, check, problem +): + """A calibration take is started exempt, so the recorder never reports one of these of it. A take that was + judged all the same is told as the recording page tells it, and never offered to a solve.""" + await world.service.start_recording(CAMERA_TAKE) + world.recorder.disposition, world.recorder.qc_decision = disposition, decision + world.recorder.capture_quality = QualityReport(Outcome.FAILED, check.issues, (), (check,)) + status = await world.service.stop_recording() + assert (status["phase"], status["take"], status["problem"]) == ("failed", None, problem) + await refused(world.service.start_solve(SOLVE), 404, "record a calibration take first") + + +def test_a_refusal_is_followed_by_whole_sentences_only_as_many_as_a_dialog_shows(): + assert with_sentences("the take was not kept", []) == "the take was not kept" + assert with_sentences("the take was not kept", ["It was short.", "It was dark."]) == ( + "the take was not kept. It was short. It was dark." + ) + # A sentence that does not fit is left out whole, and so is every one after it, however short. + long, fits = "x" * 200 + ".", "y" * 77 + "." + assert with_sentences("the take was not kept", [fits, long, "No."]) == f"the take was not kept. {fits}" + assert len(with_sentences("the take was not kept", ["z" * 276 + "."])) == 300 + assert with_sentences("the take was not kept", ["z" * 277 + "."]) == "the take was not kept" + # The lead is cut like any refusal text, and nothing follows a lead that fills the dialog. + assert with_sentences("w" * 400, ["No."]) == "w" * 300 + + +async def test_an_outcome_the_tool_does_not_know_is_never_taken_for_a_kept_take(world): + await world.service.start_recording(CAMERA_TAKE) + kept = world.recorder.finish(Disposition.KEPT) + world.recorder.open = False + # The page's record of the take, with a word for its outcome that a later backend might add. + world.context.last_result = {**page_record(kept), "outcome": "archived", "reasons": [7, "It was archived."]} + status = await world.service.poll_recording() + assert (status["phase"], status["take"]) == ("failed", None) + assert status["problem"] == "the take was not kept. It was archived." async def test_a_take_rejected_for_holding_no_tracking_says_so_in_words_for_the_operator(world): @@ -611,24 +798,36 @@ async def test_a_take_rejected_for_holding_no_tracking_says_so_in_words_for_the_ Outcome.FAILED, ("pico_controller: required source has no rows",), (), () ) status = await world.service.stop_recording() + # The tool's own sentence says why, in place of "the integrity check rejected it"; the page's follows whole. assert status["phase"] == "failed" and status["problem"] == ( - f"{NO_TRACKING_RECORDED}; the take was rejected by the recorder's checks: " - "pico_controller: required source has no rows" + f"{NO_TRACKING_RECORDED}; {DATA_KEPT}. " + "The recorded data failed an integrity check: pico_controller: required source has no rows." ) + assert len(status["problem"]) <= 300 -async def test_a_take_rejected_for_its_camera_carries_the_checks_findings_and_no_word_about_tracking(world): +async def test_a_reason_that_would_not_fit_whole_is_left_to_the_recording_page(world): await world.service.start_recording(CAMERA_TAKE) world.recorder.disposition = Disposition.REJECTED - world.recorder.issues = ("the take was removed",) - world.recorder.capture_quality = QualityReport( - Outcome.FAILED, ("head_camera: 11.2 fps is below 0.86 of 30",), (), () - ) + world.recorder.tracking_rows = 0 + found = ("pico_controller: required source has no rows", "manus_glove: required source has no rows") + world.recorder.quality = QualityReport(Outcome.FAILED, found, (), ()) status = await world.service.stop_recording() + # The second sentence has no room in the dialog, and half of it would read as another finding. assert status["problem"] == ( - "the take was rejected by the recorder's checks: the take was removed; " - "head_camera: 11.2 fps is below 0.86 of 30" + f"{NO_TRACKING_RECORDED}; {DATA_KEPT}. " + "The recorded data failed an integrity check: pico_controller: required source has no rows." ) + assert len(page_record(world.recorder.last_result)["reasons"]) == 2 + + +async def test_a_take_rejected_for_its_camera_carries_the_checks_findings_and_no_word_about_tracking(world): + await world.service.start_recording(CAMERA_TAKE) + world.recorder.disposition, world.recorder.qc_decision = Disposition.REJECTED, QcDecision.REJECTED_CAMERA + world.recorder.capture_quality = QualityReport(Outcome.FAILED, SLOW_CAMERA.issues, (), (SLOW_CAMERA,)) + # No poll saw a tracking row, and the recorder's own count says the take holds them. + status = await world.service.stop_recording() + assert status["problem"] == f"the capture checks rejected it and removed its media. {SLOW_CAMERA_SAID}" @pytest.mark.parametrize("tracked", [False, True]) @@ -636,12 +835,11 @@ async def test_with_only_the_pages_record_left_the_polls_say_whether_a_rejected_ if tracked: world.track() await world.service.start_recording(CAMERA_TAKE) - world.recorder.finish(Disposition.REJECTED) + world.context.last_result = page_record(world.recorder.finish(Disposition.REJECTED)) world.recorder.open = False - world.context.last_result = {"episode_id": f"{SESSION}/episode_1", "disposition": "REJECTED", "issues": []} - rejected = "the take was rejected by the recorder's checks" status = await world.service.poll_recording() - assert status["problem"] == (rejected if tracked else f"{NO_TRACKING_RECORDED}; {rejected}") + lead = "the integrity check rejected it" if tracked else NO_TRACKING_RECORDED + assert status["problem"] == f"{lead}; {DATA_KEPT}" async def test_an_interrupted_take_fails_the_recording_and_holds_the_next_one(world): @@ -650,28 +848,31 @@ async def test_an_interrupted_take_fails_the_recording_and_holds_the_next_one(wo # The take is still the recorder's episode; nothing is writing it, and it waits for the operator. assert (await world.service.poll_recording())["problem"] == TAKE_INTERRUPTED await refused(world.service.start_recording(CAMERA_TAKE), 409, INTERRUPTED_TAKE_WAITS) - # Both sentences send the operator to what the recording page offers for an interrupted take: a new batch. - # It has no control that recovers or discards one. + # Both sentences send the operator to what the recording page offers for an interrupted take: its Recover + # and Discard. A new batch would only leave the take waiting as an earlier session's. for sentence in (TAKE_INTERRUPTED, INTERRUPTED_TAKE_WAITS): - assert "new batch on the recording page" in sentence - assert "recover" not in sentence and "discard" not in sentence + assert "recover or discard it on the recording page" in sentence + assert "new batch" not in sentence + # The operator's task text is back, so the take that waits lends its text to nothing. + assert world.task() == ("Pour water.", "left hand") async def test_a_take_whose_session_was_closed_is_settled_from_the_pages_record_of_it(world): await world.service.start_recording(CAMERA_TAKE) - world.recorder.finish(Disposition.KEPT) + world.context.last_result = page_record(world.recorder.finish(Disposition.KEPT)) world.recorder.open = False - world.context.last_result = {"episode_id": f"{SESSION}/episode_1", "disposition": "KEPT", "issues": []} status = await world.service.poll_recording() - # That record keeps no path: a kept take is its pending directory under its final name. + # That record says where the take is, relative to the recording output, as the page names it. assert (status["phase"], status["take"]) == ("saved", f"{SESSION}/episode_1") + kept = world.episode(f"{SESSION}/episode_1") + assert world.service.resolve_take(None, "camera") == kept.resolve() async def test_a_take_nothing_remembers_fails_as_unknown(world): await world.service.start_recording(CAMERA_TAKE) - world.recorder.finish(Disposition.KEPT) + kept = world.recorder.finish(Disposition.KEPT) world.recorder.open = False - world.context.last_result = {"episode_id": "another", "disposition": "KEPT", "issues": []} + world.context.last_result = {**page_record(kept), "episode_id": "another"} status = await world.service.poll_recording() assert (status["phase"], status["problem"]) == ("failed", OUTCOME_UNKNOWN) assert world.task() == ("Pour water.", "left hand") @@ -819,7 +1020,9 @@ def closing(task_text, task_details=""): raise CoordinatorBusyError("recording session is closing") world.recorder.set_task = closing - await refused(world.service.start_recording(CAMERA_TAKE), 409, "recording session is closing") + # The coordinator's own words are for the log; the tool says what the recording page says of the same. + shutting_down = "The recorder is shutting down; no recording command is accepted." + await refused(world.service.start_recording(CAMERA_TAKE), 409, shutting_down) assert world.task() == ("Pour water.", "left hand") and world.context.revision == 0 @@ -857,34 +1060,47 @@ async def test_stopping_a_take_that_already_ended_elsewhere_answers_with_what_be assert ("stopping", f"{SESSION}/episode_1") not in world.recorder.calls -async def test_a_stop_the_recorder_checks_reject_fails_the_recording_with_their_findings(world): +async def test_a_stop_the_integrity_check_rejects_fails_the_recording_with_its_findings(world): await world.service.start_recording(CAMERA_TAKE) - world.recorder.disposition = Disposition.REJECTED - world.recorder.issues = ("required source 'head_camera' has no data",) + world.recorder.disposition, world.recorder.quality = Disposition.REJECTED, NO_CAMERA_ROWS status = await world.service.stop_recording() assert status["phase"] == "failed" and status["take"] is None - assert ( - status["problem"] - == "the take was rejected by the recorder's checks: required source 'head_camera' has no data" - ) + assert status["problem"] == f"the integrity check rejected it; {DATA_KEPT}. {NO_CAMERA_ROWS_SAID}" assert world.task() == ("Pour water.", "left hand") @pytest.mark.parametrize( ("error", "detail"), [ - (CoordinatorBusyError("ingress did not settle yet"), "ingress did not settle yet"), + # The recording page's sentences for the same refusals; what was raised stays in the log. + ( + CoordinatorBusyError("ingress did not settle (conversion work still unresolved)"), + "The take is still being written; try again in a moment.", + ), + ( + StateError("episode 'session_20260304-081500_abc123/episode_1' already has a discard in progress"), + "Another recording command is still running; try again in a moment.", + ), (RuntimeError("/data/session went away"), "the take could not be ended; see the backend log"), ( ConfigurationError("required calibration asset missing: /data/run/session_rectification.json"), - "the take could not be ended; see the backend log", + "A calibration file this station requires is missing or changed; see the backend log.", + ), + ( + ConfigurationError("quarantine location is a link: it must be a plain directory"), + "The quarantine folder in the recording output is a link, so a take marked bad could not be set " + "aside. Make it a plain folder on the recordings disk.", ), + ("a full recordings disk", STORAGE_SENTENCES["full"]), ], ) async def test_a_stop_the_recorder_refuses_leaves_the_take_recording(world, error, detail): await world.service.start_recording(CAMERA_TAKE) + if error == "a full recordings disk": + error = OSError(errno.ENOSPC, "No space left on device", str(world.root / SESSION / "episode_1.pending")) world.recorder.end_error = error - await refused(world.service.stop_recording(), 409, detail) + said = await refused(world.service.stop_recording(), 409, detail) + assert "/data" not in said and str(world.root) not in said and "episode_1" not in said status = await world.service.poll_recording() # Still recording, under the calibration task, and a later stop goes through. assert status["phase"] == "recording" and world.task() == (CALIBRATION_TASK, "") @@ -932,11 +1148,11 @@ async def test_a_stop_finishes_and_restores_the_task_even_when_the_request_that_ async def test_a_start_is_followed_and_tracked_even_when_the_request_that_asked_goes_away(world): release, start = asyncio.Event(), world.recorder.start_episode - async def owned_start(operator): + async def owned_start(operator, **flags): # As the real coordinator starts a take: in a task of its own, which a cancelled caller does not stop. async def work(): await release.wait() - return await start(operator) + return await start(operator, **flags) return await asyncio.shield(asyncio.ensure_future(work())) diff --git a/examples/egocap/tests/backend/test_calibration_take_exemption.py b/examples/egocap/tests/backend/test_calibration_take_exemption.py new file mode 100644 index 0000000000..412a6272b8 --- /dev/null +++ b/examples/egocap/tests/backend/test_calibration_take_exemption.py @@ -0,0 +1,395 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A take a calibration tool records is exempt from the capture checks, and is the recorder's like any other. + +The calibration service runs over the real coordinator and the real recording service, configured by the +application's own factory, so the checks in force are a backend's own. Takes are built in the test (see +qc_takes.py): a camera that delivers too few frames, a tracking stream that does not change. Started by a tool +they are kept and read by that tool; started from the recording page, the same frames are rejected and +quarantined. A tool's take that is interrupted, or that the integrity check rejects, waits on the recording page +and is resolved by its commands, and what the tool says of it is what the page says. +""" + +from __future__ import annotations + +import asyncio +import json +import threading +import time +from pathlib import Path + +import numpy as np +import pytest +import zarr + +import recording_service.recording_service as service_module +from egocap.calibration.take import CalibrationTake +from egocap.recording import episode_layout +from egocap.recording.episode_layout import read_manifest +from egocap_web.calibration_service import ( + DATA_KEPT, + INTERRUPTED_TAKE_WAITS, + NO_TRACKING_RECORDED, + TAKE_INTERRUPTED, +) +from egocap_web.recording_command import RecordingContext, interrupted_take +from egocap_web.recording_session import SESSION_BEAT_STOPPED +from tests.backend.qc_takes import CAMERA_NAME, changed, make_coordinator, offer, take_frames, tree +from tests.backend.test_calibration_service import ( + CAMERA_TAKE, + GLOVE_TAKE, + SOLVE, + Pipeline, + World, + finished, + refused, +) +from tests.backend.test_takes_left_behind_wire import FULL, TOKEN, _full, _lose_capture, _restart, _rows, _send + +#: A take the checks would reject (a stalled camera) and one they would mark bad (nothing tracked moves). +TOO_FEW_FRAMES = dict(camera_hole=1.0) +NOTHING_MOVES = dict(frozen_head=True, frozen_hands=True) +CALIBRATION_TASK = "Calibration: head camera" +TAKE_WAITS = "A take is waiting to be recovered or discarded. Resolve it, or start a new batch, before recording." +QUARANTINE_IS_A_LINK = ( + "The quarantine folder in the recording output is a link, so a take marked bad could not be set aside. " + "Make it a plain folder on the recordings disk." +) + + +def _station(tmp_path: Path) -> World: + """A station whose calibration tools record through the real coordinator, wired as the application wires + them: the head camera is the one the recorder records, and the recording page settles the tools first.""" + coordinator = make_coordinator(tmp_path / "recordings") + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + world = World(tmp_path, context=context) + world.roles["ego"] = CAMERA_NAME + world.offered = frozenset({CAMERA_NAME}) + context.settle_tools = world.service.settle + return world + + +@pytest.fixture +async def station(tmp_path): + made = _station(tmp_path) + yield made + await made.service.aclose() + await made.context.coordinator.close(final=True) + + +async def _calibration_take(world: World, request: dict, frames) -> dict: + """Record one take with a calibration tool, from its start to its stop; the tool's status after the stop.""" + started = await world.service.start_recording(request) + assert started["phase"] == "recording", started + offer(world.context.coordinator, frames) + return await world.service.stop_recording() + + +async def _page_take(world: World, frames) -> dict: + """Record one take from the recording page's commands; the page's record of what became of it.""" + started = await _send(world.context, "start_episode") + assert started["outcome"] == "ok", started["reason"] + offer(world.context.coordinator, frames) + stopped = await _send(world.context, "stop_episode", episode_id=started["snapshot"]["current_episode_id"]) + assert stopped["outcome"] == "ok", stopped["reason"] + return stopped["snapshot"]["last_result"] + + +def _exempt_and_unjudged(world: World, take: str) -> None: + """The take's record and its metadata say it was started exempt, and that no capture check judged it.""" + episode = world.root / take + manifest = read_manifest(episode.parent / ".recording" / f"{episode.name}.json") + assert manifest.capture_checks_exempt is True and manifest.capture_quality is None + assert (manifest.storage_phase, manifest.finalization, manifest.qc_decision) == ( + "FINALIZED", + "KEEP", + "SKIPPED", + ) + attrs = zarr.open_group(str(episode), mode="r").attrs + assert attrs["capture_qc_exempt"] is True and attrs["capture_qc_decision"] == "SKIPPED" + assert attrs["domain_checks"] == "SKIPPED" and attrs["quarantined"] is False + # Nothing of it was set aside or removed. + assert episode.is_dir() and not (world.root / "_quarantine").exists() + + +# --- kept and read by the tool, where the same frames from the recording page are not kept ------------------- + + +async def test_a_calibration_take_whose_camera_delivered_too_few_frames_is_kept_and_solved_from( + station, monkeypatch +): + world = station + saved = await _calibration_take(world, CAMERA_TAKE, take_frames(**TOO_FEW_FRAMES)) + assert (saved["phase"], saved["problem"]) == ("saved", None) + _exempt_and_unjudged(world, saved["take"]) + # The recording page is told the same: kept, and not judged. + snapshot = world.context.snapshot() + result = snapshot["last_result"] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == ("kept", "SKIPPED", False) + assert result["location"] == saved["take"] and result["reasons"] == [] and snapshot["saved_count"] == 1 + assert snapshot["pending_takes"] == [] and snapshot["task_text"] == "pour water" + # The headset tool solves from the take its recording saved: every frame the camera did deliver is there. + episode = (world.root / saved["take"]).resolve() + assert CalibrationTake(episode).frame_count(CAMERA_NAME) == 32 + pipeline = Pipeline(monkeypatch) + started = await world.service.start_solve({**SOLVE, "mode": "intrinsic"}) + assert started["take"] == saved["take"] + assert (await finished(world))["state"] == "done" + assert (pipeline.calls[0]["episode"], pipeline.calls[0]["camera"]) == (episode, CAMERA_NAME) + + +async def test_a_glove_take_in_which_nothing_tracked_moves_is_kept_and_read_by_the_glove_tool(station): + world = station + world.calibrate_headset() + saved = await _calibration_take(world, GLOVE_TAKE, take_frames(**NOTHING_MOVES)) + assert (saved["phase"], saved["problem"], saved["tool"]) == ("saved", None, "glove") + _exempt_and_unjudged(world, saved["take"]) + assert world.context.snapshot()["last_result"]["outcome"] == "kept" + # The glove tool means this take, and reads the poses the hands were held in for every picture of it. + episode = world.service.resolve_take(None, "glove") + assert episode == (world.root / saved["take"]).resolve() + take = CalibrationTake(episode) + times = take.camera_times(CAMERA_NAME) + head, head_tracked = take.head_poses_at(times) + assert len(times) == 61 and head_tracked.all() and np.ptp(head, axis=0).max() == 0.0 + hands, hands_tracked = take.hand_poses_at(times) + assert hands_tracked.all() and all(np.ptp(hands[side], axis=0).max() == 0.0 for side in ("left", "right")) + + +async def test_the_same_takes_started_from_the_recording_page_are_rejected_and_quarantined(station): + world = station + slow = await _page_take(world, take_frames(**TOO_FEW_FRAMES)) + assert (slow["outcome"], slow["qc_decision"], slow["media_removed"]) == ("rejected", "REJECTED_CAMERA", True) + assert slow["location"] is None and slow["reasons"][0].startswith(f"Camera {CAMERA_NAME} averaged 15.5 fps") + still = await _page_take(world, take_frames(**NOTHING_MOVES)) + assert (still["outcome"], still["qc_decision"], still["media_removed"]) == ( + "quarantined", + "FLAGGED_BAD", + False, + ) + session = still["episode_id"].split("/")[0] + assert still["location"] == f"_quarantine/{session}/episode_1" + assert (world.root / still["location"]).is_dir() and not (world.root / session / "episode_1").exists() + snapshot = world.context.snapshot() + assert (snapshot["saved_count"], snapshot["rejected_count"], snapshot["quarantined_count"]) == (0, 1, 1) + + +async def test_the_exemption_is_the_calibration_takes_alone_and_never_reaches_the_take_after_it(station): + world = station + defective = dict(**TOO_FEW_FRAMES, frozen_head=True) + # A page take, a calibration take and a page take again, of the same frames, in one session. + first = await _page_take(world, take_frames(**defective)) + saved = await _calibration_take(world, CAMERA_TAKE, take_frames(**defective)) + after = await _page_take(world, take_frames(**defective)) + assert (first["outcome"], saved["phase"], after["outcome"]) == ("rejected", "saved", "rejected") + _exempt_and_unjudged(world, saved["take"]) + session = world.root / saved["take"].split("/")[0] + flags = [read_manifest(session / ".recording" / f"episode_{n}.json").capture_checks_exempt for n in range(3)] + assert flags == [False, True, False] + + +# --- a take that waits: interrupted, or rejected by the integrity check ---------------------------------------- + + +async def test_an_interrupted_calibration_take_waits_on_the_recording_page_and_is_discarded_there(station): + world, context = station, station.context + await world.service.start_recording(CAMERA_TAKE) + offer(context.coordinator, take_frames()[:90]) + await _lose_capture(context) + # The tool says so, and where it is resolved; the operator's task text is back in the same look. + status = await world.service.poll_recording() + assert (status["phase"], status["take"], status["problem"]) == ("failed", None, TAKE_INTERRUPTED) + snapshot = context.snapshot() + assert (snapshot["task_text"], snapshot["episode_phase"]) == ("pour water", "RECOVERY_REQUIRED") + # The recording page lists it like any interrupted take: it holds Record, and says why it waits. + result = snapshot["last_result"] + assert (result["outcome"], result["reasons"]) == ( + "interrupted", + ["A capture source stopped while the take was recording: capture is not running."], + ) + (row,) = snapshot["pending_takes"] + assert (row["episode_id"], row["task"], row["operator"]) == (result["episode_id"], CALIBRATION_TASK, "alex") + assert (row["current"], row["phase"], row["recoverable"], row["discardable"]) == (True, "WRITING", False, True) + # What the tools ask before a take is what the page's list says: one take of the open session waits. + assert interrupted_take(context.coordinator.snapshot().service) is True + assert [take.current for take in context.coordinator.pending_takes()] == [True] + # The tools and the page's Record are held by the same take, each in its own sentence. + await refused(world.service.start_recording(CAMERA_TAKE), 409, INTERRUPTED_TAKE_WAITS) + await refused(world.service.start_recording(GLOVE_TAKE), 409, INTERRUPTED_TAKE_WAITS) + record = await _send(context, "start_episode") + assert (record["outcome"], record["reason"]) == ("rejected", TAKE_WAITS) + assert context.snapshot()["task_text"] == "pour water" + # The page's Discard removes it, and only it; the tool records again in the same session. + before = tree(world.root) + discarded = await _send(context, "discard_pending", episode_id=row["episode_id"]) + assert (discarded["outcome"], discarded["reason"]) == ("ok", None) + assert discarded["snapshot"]["pending_takes"] == [] and discarded["snapshot"]["episode_phase"] == "IDLE" + assert interrupted_take(context.coordinator.snapshot().service) is False + removed, added, modified = changed(before, tree(world.root)) + session = row["session_id"] + assert removed and all(path.startswith(f"{session}/episode_0.pending/") for path in removed) + assert added == set() and modified == {f"{session}/.recording/episode_0.json"} + saved = await _calibration_take(world, CAMERA_TAKE, take_frames()) + assert (saved["phase"], saved["take"]) == ("saved", f"{session}/episode_1") + + +async def test_a_calibration_take_recovered_on_the_recording_page_is_finished_exempt_as_it_was_started( + station, monkeypatch +): + world, context = station, station.context + # Finishing the take fails once it was written and sealed: it waits complete, and can be recovered. + with monkeypatch.context() as patched: + patched.setattr(service_module, "check_episode", lambda *a, **k: (_ for _ in ()).throw(_full(world.root))) + status = await _calibration_take(world, CAMERA_TAKE, take_frames(**TOO_FEW_FRAMES, frozen_head=True)) + assert (status["phase"], status["problem"]) == ("failed", TAKE_INTERRUPTED) + snapshot = context.snapshot() + assert snapshot["task_text"] == "pour water" + (row,) = snapshot["pending_takes"] + assert (row["current"], row["phase"], row["recoverable"], row["task"]) == ( + True, + "SEALED", + True, + CALIBRATION_TASK, + ) + assert row["reason"] == FULL and row["recover_note"] == "Recover runs the checks on this take and finishes it." + # Recover runs the checks, and the take is the exempt one it was started as: kept, where the same frames + # from the recording page are rejected. + recovered = await _send(context, "recover_pending", episode_id=row["episode_id"]) + result = recovered["snapshot"]["last_result"] + assert (recovered["outcome"], result["outcome"], result["qc_decision"]) == ("ok", "kept", "SKIPPED") + _exempt_and_unjudged(world, result["location"]) + assert recovered["snapshot"]["pending_takes"] == [] + assert (await _calibration_take(world, CAMERA_TAKE, take_frames()))["phase"] == "saved" + + +async def test_an_interrupted_calibration_take_left_behind_by_a_new_batch_or_a_restart_is_still_listed(tmp_path): + world = _station(tmp_path) + context = world.context + await world.service.start_recording(CAMERA_TAKE) + offer(context.coordinator, take_frames()[:90]) + await _lose_capture(context) + assert (await world.service.poll_recording())["problem"] == TAKE_INTERRUPTED + episode_id = context.snapshot()["pending_takes"][0]["episode_id"] + # New batch on the recording page leaves it as an earlier session's take, which holds nothing. + rotated = await _send(context, "new_batch") + assert rotated["outcome"] == "ok" + row = _rows(context.snapshot())[episode_id] + assert (row["current"], row["task"], row["discardable"]) == (False, CALIBRATION_TASK, True) + # No take of an open session waits any more, so nothing holds the tools: the row is all that is left of it. + assert interrupted_take(context.coordinator.snapshot().service) is False + saved = await _calibration_take(world, CAMERA_TAKE, take_frames()) + assert saved["phase"] == "saved" and saved["take"].split("/")[0] != row["session_id"] + await world.service.aclose() + await context.coordinator.close(final=True) + # A backend started over the same recordings lists it too, and its Discard removes it. + restarted = await _restart(world.root) + row = _rows(restarted.snapshot())[episode_id] + assert (row["current"], row["task"], row["phase"]) == (False, CALIBRATION_TASK, "WRITING") + discarded = await _send(restarted, "discard_pending", episode_id=episode_id) + assert (discarded["outcome"], discarded["reason"]) == ("ok", None) + assert discarded["snapshot"]["pending_takes"] == [] + assert discarded["snapshot"]["last_result"]["outcome"] == "discarded" + await restarted.coordinator.close(final=True) + + +async def test_a_calibration_take_without_tracking_is_rejected_with_its_data_kept_and_discarded_from_the_page( + station, +): + world, context = station, station.context + pictures = [frame for frame in take_frames() if hasattr(frame, "jpeg")] + status = await _calibration_take(world, CAMERA_TAKE, pictures) + said = "The recorded data failed an integrity check: pico_controller: required source has no rows." + assert (status["phase"], status["take"]) == ("failed", None) + assert status["problem"] == f"{NO_TRACKING_RECORDED}; {DATA_KEPT}. {said}" + snapshot = context.snapshot() + result = snapshot["last_result"] + assert (result["outcome"], result["qc_decision"], result["reasons"]) == ( + "rejected_data_kept", + "SKIPPED", + [said], + ) + # Its data is where it was recorded, it holds nothing, and the page's Discard is what removes it. + pending = world.root / result["location"] + assert pending.name == "episode_0.pending" and pending.is_dir() + (row,) = snapshot["pending_takes"] + assert (row["phase"], row["current"], row["recoverable"], row["discardable"]) == ( + "REJECTED", + False, + False, + True, + ) + assert snapshot["ready_to_record"] is True and snapshot["rejected_count"] == 1 + assert (await _calibration_take(world, CAMERA_TAKE, take_frames()))["phase"] == "saved" + discarded = await _send(context, "discard_pending", episode_id=row["episode_id"]) + assert (discarded["outcome"], discarded["reason"]) == ("ok", None) + assert discarded["snapshot"]["pending_takes"] == [] and not pending.exists() + + +# --- what the tool is told when the recorder will not start -------------------------------------------------- + + +def _no_recorder_text(detail: str, world: World) -> None: + """A refusal of the tool names no directory, no recorder state and no error of the system.""" + assert str(world.root) not in detail and str(world.root.parent) not in detail + assert "RECOVERY_REQUIRED" not in detail and "Errno" not in detail and "Error" not in detail + + +async def test_a_calibration_take_is_refused_in_the_recorders_sentence_while_its_session_marker_is_not_written( + station, monkeypatch +): + world, context = station, station.context + # A beat every 20 ms, counted as missing after 300 ms without one. + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + monkeypatch.setattr(episode_layout, "BEAT_WATCH_SECONDS", 0.3) + # A kept calibration take leaves its session open, idle. + assert (await _calibration_take(world, CAMERA_TAKE, take_frames()))["phase"] == "saved" + real_beat, broken = episode_layout.SessionLock.beat, threading.Event() + + def beat(lock): + if broken.is_set(): + raise RuntimeError("nothing a beat expects") + real_beat(lock) + + monkeypatch.setattr(episode_layout.SessionLock, "beat", beat) + broken.set() + deadline = time.monotonic() + 5.0 + while context.coordinator.readiness()[0]: + assert time.monotonic() < deadline, "the missing beat was never noticed" + await asyncio.sleep(0.005) + # The sentence Record on the recording page is refused with, and no task text was put in the operator's place. + await refused(world.service.start_recording(CAMERA_TAKE), 409, SESSION_BEAT_STOPPED) + assert context.snapshot()["not_ready_reason"] == SESSION_BEAT_STOPPED + assert context.coordinator.snapshot().context.task_text == "pour water" + broken.clear() + while not context.coordinator.readiness()[0]: + assert time.monotonic() < deadline, "the beat never came back" + await asyncio.sleep(0.005) + assert (await _calibration_take(world, CAMERA_TAKE, take_frames()))["phase"] == "saved" + + +async def test_a_calibration_take_the_recorder_refuses_or_fails_to_start_is_told_as_the_page_tells_record( + station, monkeypatch +): + world, context = station, station.context + # A session cannot open while a take marked bad could not be set aside, whoever asks for the take. + (world.root / "elsewhere").mkdir() + (world.root / "_quarantine").symlink_to(world.root / "elsewhere") + said = await refused(world.service.start_recording(CAMERA_TAKE), 409, QUARANTINE_IS_A_LINK) + _no_recorder_text(said, world) + record = await _send(context, "start_episode") + assert (record["outcome"], record["reason"]) == ("rejected", QUARANTINE_IS_A_LINK) + (world.root / "_quarantine").unlink() + # A recordings disk with no room left is named, as it is when Record is pressed. + with monkeypatch.context() as patched: + patched.setattr(service_module, "write_manifest", lambda *a, **k: (_ for _ in ()).throw(_full(world.root))) + said = await refused(world.service.start_recording(CAMERA_TAKE), 409, FULL) + _no_recorder_text(said, world) + # Each refusal put the operator's task text back, and left nothing started or waiting. + snapshot = context.snapshot() + assert (snapshot["task_text"], snapshot["pending_takes"]) == ("pour water", []) + await refused(world.service.poll_recording(), 404, "no calibration recording has been started") + assert (await _calibration_take(world, CAMERA_TAKE, take_frames()))["phase"] == "saved" + assert str(world.root) not in json.dumps(context.snapshot()) diff --git a/examples/egocap/tests/backend/test_capture_check_exemption.py b/examples/egocap/tests/backend/test_capture_check_exemption.py new file mode 100644 index 0000000000..9242e7c2f6 --- /dev/null +++ b/examples/egocap/tests/backend/test_capture_check_exemption.py @@ -0,0 +1,151 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A calibration take, started by backend code, is exempt from the capture checks; a page command never is. + +Takes are recorded through the real coordinator and the real service from frames built in the test. The +calibration tools are the backend code that starts exempt takes: their routes are asked through the real router, +over the calibration service on the same coordinator. +""" + +from __future__ import annotations + +from contextlib import asynccontextmanager + +import zarr +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from egocap.recording.episode_layout import read_manifest +from egocap_web import calibration_routes +from egocap_web.recording_command import RecordingContext, handle_recording_command, parse_recording_command +from recording_service import Disposition, QcDecision +from tests.backend.qc_takes import CAMERA_NAME, make_coordinator, offer, take_frames +from tests.backend.test_calibration_service import CAMERA_TAKE, GLOVE_TAKE, World + +TOKEN = "" +#: A take the checks would reject (a stalled camera) and mark bad (a frozen headset). +DEFECTIVE = dict(camera_hole=1.0, frozen_head=True) + + +async def test_a_take_started_as_exempt_through_the_coordinator_is_kept_unjudged(tmp_path): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("calibrate the headset") + episode = await coordinator.start_episode("alex", exempt_from_capture_checks=True) + offer(coordinator, take_frames(**DEFECTIVE)) + result = await coordinator.stop_episode(episode.episode_id) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.SKIPPED + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["capture_qc_exempt"] is True and attrs["domain_checks"] == "SKIPPED" + # The next take, started the ordinary way, is judged again. + episode = await coordinator.start_episode("alex") + offer(coordinator, take_frames(**DEFECTIVE)) + assert (await coordinator.stop_episode(episode.episode_id)).disposition is Disposition.REJECTED + await coordinator.close() + + +async def test_the_pages_start_command_can_never_make_a_take_exempt(tmp_path): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + + async def send(action, **payload): + raw = { + "request_id": "r", + "action": action, + "payload": {"batch_id": context.batch_id, **payload}, + "operator_token": "alex", + "control_token": TOKEN, + # Fields a page could add to the envelope: none of them is read. + "exempt_from_capture_checks": True, + "calibration": True, + } + return await handle_recording_command(parse_recording_command(raw), context) + + # Whatever the payload claims, the handler starts the take with no flag at all. + started = await send( + "start_episode", exempt_from_capture_checks=True, calibration=True, capture_qc_exempt=True + ) + assert started["outcome"] == "ok" + offer(coordinator, take_frames(**DEFECTIVE)) + stopped = await send("stop_episode", episode_id=started["snapshot"]["current_episode_id"]) + result = stopped["snapshot"]["last_result"] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == ( + "rejected", + "REJECTED_CAMERA", + True, + ) + await coordinator.close() + + +#: What a page might send to say how a take is to be judged. No route and no command reads any of it. +CLAIMS = ("exempt_from_capture_checks", "capture_checks_exempt", "capture_qc_exempt", "calibration", "exempt") + + +def test_no_field_sent_to_the_calibration_routes_or_with_a_command_decides_which_takes_are_exempt(tmp_path): + """The calibration routes on the real router, and the page's commands, over one real coordinator.""" + root = tmp_path / "recordings" + coordinator = make_coordinator(root) + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + world = World(tmp_path, context=context) + world.roles["ego"] = CAMERA_NAME + world.offered = frozenset({CAMERA_NAME}) + world.calibrate_headset() + context.settle_tools = world.service.settle + + @asynccontextmanager + async def lifespan(app: FastAPI): + yield + await world.service.aclose() + await coordinator.close(final=True) + + application = FastAPI(lifespan=lifespan) + application.include_router(calibration_routes.router) + application.state.calibration, application.state.recording_context = world.service, context + auth = {"X-Control-Token": TOKEN} + + def manifest(take_or_episode_id: str): + session, episode = take_or_episode_id.split("/") + return read_manifest(root / session / ".recording" / f"{episode}.json") + + with TestClient(application) as client: + # A take either tool starts is exempt whatever its request says of the checks, one way or the other. + for request, said in ((CAMERA_TAKE, False), (GLOVE_TAKE, True), (CAMERA_TAKE, "no")): + claims = dict.fromkeys(CLAIMS, said) + started = client.post("/api/calibration/recording", json={**request, **claims}, headers=auth) + assert started.status_code == 200, started.json() + client.portal.call(offer, coordinator, take_frames(**DEFECTIVE)) + stopped = client.post("/api/calibration/recording/stop", json=claims, headers=auth).json() + assert (stopped["phase"], stopped["problem"]) == ("saved", None), stopped + assert manifest(stopped["take"]).capture_checks_exempt is True + assert manifest(stopped["take"]).qc_decision == "SKIPPED" + + # A page command is never exempt, though it carries every field a calibration request does and names + # the calibration tool in its envelope and its payload. + def send(action, **payload): + raw = { + "request_id": "r", + "action": action, + "payload": {"batch_id": context.batch_id, **CAMERA_TAKE, **dict.fromkeys(CLAIMS, True), **payload}, + "operator_token": "alex", + "control_token": TOKEN, + **CAMERA_TAKE, + **dict.fromkeys(CLAIMS, True), + } + return client.portal.call(handle_recording_command, parse_recording_command(raw), context) + + started = send("start_episode") + assert started["outcome"] == "ok", started["reason"] + client.portal.call(offer, coordinator, take_frames(**DEFECTIVE)) + stopped = send("stop_episode", episode_id=started["snapshot"]["current_episode_id"]) + result = stopped["snapshot"]["last_result"] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == ( + "rejected", + "REJECTED_CAMERA", + True, + ) + assert manifest(result["episode_id"]).capture_checks_exempt is False + # A pending take's commands carry the fields too, and they change nothing about a take either. + assert send("recover_pending", episode_id=result["episode_id"])["outcome"] == "rejected" diff --git a/examples/egocap/tests/backend/test_capture_qc_takes.py b/examples/egocap/tests/backend/test_capture_qc_takes.py new file mode 100644 index 0000000000..2c4798dc09 --- /dev/null +++ b/examples/egocap/tests/backend/test_capture_qc_takes.py @@ -0,0 +1,225 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What the capture checks do to a take recorded through the real coordinator and the real service. + +Frames are built in the test (see qc_takes.py) and the session is configured by the application's own factory, +so these are the checks, thresholds and dispositions a station gets: a stalled camera rejects the take and +removes its media, a frozen stream marks it bad, a healthy take is judged rather than skipped, and the +thresholds are the ones in the documented file and the station's section. +""" + +from __future__ import annotations + +import pytest +import zarr + +from egocap.recording.capture_qc_policy import load_policy, resolve_policy +from egocap.recording.episode_layout import read_manifest +from recording_service import Disposition, QcDecision, RecordingPhase +from tests.backend.qc_takes import changed, make_coordinator, record, take_frames, tree + + +async def _kept_first(coordinator): + """Give the session a kept take, so a later removal has other data beside it to leave alone.""" + coordinator.set_task("pour water") + result = await record(coordinator) + assert result.disposition is Disposition.KEPT + return result + + +async def test_a_healthy_take_with_only_a_capture_server_camera_is_judged_and_kept(tmp_path): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + result = await record(coordinator) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.PASSED + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["domain_checks"] == "EXECUTED" and attrs["capture_qc_decision"] == "PASSED" + assert attrs["bad_episode"] is False and attrs["quarantined"] is False + assert attrs["freeze_check_passed"] is True and attrs["capture_qc_warnings"] == [] + ran = {entry["name"]: entry["outcome"] for entry in attrs["capture_qc_results"]} + assert ran == { + "camera_min_fps:head_human_camera": "PASSED", + "sustained_freeze:pico_controller/head_pose": "PASSED", + "sustained_freeze:pico_controller/left_pose": "PASSED", + "sustained_freeze:pico_controller/right_pose": "PASSED", + "tracking_gap_warning:pico_controller": "PASSED", + "duration_warning": "PASSED", + "flat_motion:pico_controller/head_pose": "PASSED", + "flat_motion:pico_controller/left_pose": "PASSED", + "flat_motion:pico_controller/right_pose": "PASSED", + "dead_stream:pico_controller/head_pose": "PASSED", + "dead_stream:pico_controller/left_pose": "PASSED", + "dead_stream:pico_controller/right_pose": "PASSED", + "zero_pose:pico_controller/head_pose": "PASSED", + "zero_pose:pico_controller/left_pose": "PASSED", + "zero_pose:pico_controller/right_pose": "PASSED", + "frame_drops:head_human_camera": "PASSED", + "camera_rate_measurable:head_human_camera": "PASSED", + "camera_fps_deviation:head_human_camera": "PASSED", + "resolution:head_human_camera": "PASSED", + } + await coordinator.close() + + +async def test_the_take_names_the_documented_file_its_thresholds_came_from(tmp_path): + policy = load_policy(station={"guardrails": {"freeze_seconds": 1.5}}) + coordinator = make_coordinator(tmp_path / "out", policy) + coordinator.set_task("pour water") + result = await record(coordinator) + stored = zarr.open_group(str(result.final_path), mode="r").attrs["capture_qc_policy"] + assert stored["algorithm_version"] == 4 and stored["freeze_seconds"] == 1.5 + assert stored["camera_min_fps_ratio"] == 0.86 and stored["camera_expected_fps"] == [ + ["head_human_camera", 30.0] + ] + assert stored["source"] == { + "defaults_file": "data_check_config.yaml", + "defaults_sha256": policy.source.defaults_sha256, + "station_overrides": {"guardrails.freeze_seconds": 1.5}, + } + assert "/" not in stored["source"]["defaults_file"] + await coordinator.close() + + +async def test_a_camera_with_a_one_second_hole_in_a_two_second_take_is_rejected_and_its_media_removed(tmp_path): + root = tmp_path / "out" + coordinator = make_coordinator(root) + kept = await _kept_first(coordinator) + (root / "notes.txt").write_text("operator notes") + before = tree(root) + result = await record(coordinator, take_frames(camera_hole=1.0)) + assert result.disposition is Disposition.REJECTED and result.qc_decision is QcDecision.REJECTED_CAMERA + assert result.final_path is None and result.pending_path is None and result.quarantine_path is None + session = kept.final_path.parent + assert not (session / "episode_1.pending").exists() and not (session / "episode_1").exists() + # Nothing but the rejected take's own manifest is new, and no other file was removed or rewritten. + assert changed(before, tree(root)) == (set(), {f"{session.name}/.recording/episode_1.json"}, set()) + manifest = read_manifest(session / ".recording" / "episode_1.json") + assert (manifest.storage_phase, manifest.finalization) == ("REJECTED", "REMOVE") + # Slow over its own frames, and short of the frames a take of two seconds holds. + assert result.capture_quality.issues == ( + "head_human_camera: 15.50 fps average is below 0.86 x 30.0 = 25.80", + "head_human_camera: 32 frame(s) recorded of the 60.0 a 2.00s take holds at 30.0 fps (needs 49.0)", + ) + # The session records again straight away. + assert coordinator.snapshot().service.phase is RecordingPhase.IDLE + assert (await record(coordinator)).disposition is Disposition.KEPT + await coordinator.close() + + +async def test_the_same_slow_camera_passes_when_the_station_lowers_the_ratio(tmp_path): + station = {"guardrails": {"camera_min_fps_ratio": 0.5}} + coordinator = make_coordinator(tmp_path / "out", load_policy(station=station)) + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(camera_hole=1.0)) + # 15.5 fps is above 0.5 x 30: the threshold came from the station's section, not from the code. + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.PASSED + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["capture_qc_policy"]["camera_min_fps_ratio"] == 0.5 + # The stall is still recorded: as dropped frames and as a rate far from the declared one. + assert any("dropped frames" in warning for warning in attrs["capture_qc_warnings"]) + assert any("below the expected 30.0" in warning for warning in attrs["capture_qc_warnings"]) + await coordinator.close() + + +async def test_a_take_whose_head_pose_never_changes_is_quarantined_by_default(tmp_path): + root = tmp_path / "out" + coordinator = make_coordinator(root) + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(frozen_head=True)) + assert result.disposition is Disposition.QUARANTINED and result.qc_decision is QcDecision.FLAGGED_BAD + assert result.quarantine_path == root / "_quarantine" / result.session_id / "episode_0" + assert result.final_path is None and not (root / result.session_id / "episode_0").exists() + attrs = zarr.open_group(str(result.quarantine_path), mode="r").attrs + assert attrs["capture_qc_decision"] == "FLAGGED_BAD" and attrs["bad_episode"] is True + assert attrs["quarantined"] is True and attrs["freeze_check_passed"] is False + assert attrs["freeze_check_issues"] == [ + "pico_controller/head_pose: no motion for 2.00s (limit 1.0s, eps 1e-06)" + ] + assert coordinator.snapshot().service.phase is RecordingPhase.IDLE + await coordinator.close() + + +async def test_with_the_station_switch_off_the_frozen_take_is_kept_with_its_session_and_flagged(tmp_path): + root = tmp_path / "out" + coordinator = make_coordinator(root, resolve_policy({}, {"guardrails": {"quarantine": False}})) + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(frozen_head=True)) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.FLAGGED_BAD + assert result.final_path == root / result.session_id / "episode_0" and not (root / "_quarantine").exists() + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["capture_qc_decision"] == "FLAGGED_BAD" and attrs["bad_episode"] is True + assert attrs["quarantined"] is False + await coordinator.close() + + +async def test_where_gloves_are_expected_a_frozen_glove_stream_marks_the_take_bad_by_name(tmp_path): + policy = resolve_policy({}, {"guardrails": {"gloves_expected": True, "quarantine": False}}) + coordinator = make_coordinator(tmp_path / "out", policy) + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(frozen_hands=True)) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.FLAGGED_BAD + assert result.capture_quality.issues == ( + "manus_glove/left_hand_pose: no motion for 2.00s (limit 1.0s, eps 1e-06)", + "manus_glove/right_hand_pose: no motion for 2.00s (limit 1.0s, eps 1e-06)", + ) + await coordinator.close() + + +async def test_where_gloves_are_not_expected_still_hands_do_not_mark_the_take_bad(tmp_path): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(frozen_hands=True)) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.PASSED + assert not any("manus_glove" in r.name for r in result.capture_quality.check_results) + await coordinator.close() + + +async def test_a_take_shorter_than_the_minimum_is_kept_with_a_duration_warning(tmp_path): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(seconds=0.5)) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.PASSED + assert "the take lasted 0.50s, outside 1.0s to 600.0s" in result.capture_quality.warnings + await coordinator.close() + + +async def test_a_station_that_expects_gloves_rejects_a_take_with_no_glove_row(tmp_path, monkeypatch): + from egocap_web import recording_adapter + + policy = resolve_policy({}, {"guardrails": {"gloves_expected": True}}) + coordinator = make_coordinator(tmp_path / "out", policy) + coordinator.set_task("pour water") + with_gloves = await record(coordinator) + assert with_gloves.disposition is Disposition.KEPT and with_gloves.qc_decision is QcDecision.PASSED + judged = {r.name for r in with_gloves.capture_quality.check_results} + assert "sustained_freeze:manus_glove/left_hand_pose" in judged and "tracking_gap_warning:manus_glove" in judged + # No hand is tracked: the adapter omits every glove row, and a required source without rows fails integrity. + monkeypatch.setattr(recording_adapter, "build_manus_glove_fields", lambda tracking: None) + without = await record(coordinator) + # Integrity is judged first; nothing of capture quality was measured, which is recorded as skipped. + assert without.disposition is Disposition.REJECTED and without.qc_decision is QcDecision.SKIPPED + assert without.quality.issues == ("manus_glove: required source has no rows",) + # An integrity failure keeps the data where it is for inspection. + assert without.pending_path is not None and without.pending_path.is_dir() + await coordinator.close() + + +async def test_switching_the_checks_off_records_every_take_as_skipped(tmp_path): + coordinator = make_coordinator(tmp_path / "out", resolve_policy({"guardrails": {"enabled": False}})) + coordinator.set_task("pour water") + result = await record(coordinator, take_frames(camera_hole=1.0, frozen_head=True)) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.SKIPPED + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["domain_checks"] == "SKIPPED" and attrs["capture_qc_decision"] == "SKIPPED" + await coordinator.close() + + +async def test_a_session_cannot_open_while_the_policy_could_not_be_read(tmp_path): + coordinator = make_coordinator(tmp_path / "out", None) + coordinator.set_task("pour water") + with pytest.raises(Exception, match="quality-check configuration is invalid"): + await coordinator.start_episode("alex") + assert not (tmp_path / "out").exists() + await coordinator.close() diff --git a/examples/egocap/tests/backend/test_command_refusals.py b/examples/egocap/tests/backend/test_command_refusals.py new file mode 100644 index 0000000000..17a8206ad1 --- /dev/null +++ b/examples/egocap/tests/backend/test_command_refusals.py @@ -0,0 +1,427 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""No reply to a recording command carries what a lower layer raised, a directory, or a recorder state name. + +The coordinator and the recording service word their refusals for the log. Each kind is given here as they +write it, with ids and directories in it, and the sentence the operator reads must hold none of that. +""" + +from __future__ import annotations + +import errno +import logging + +import pytest + +from egocap_web.livekit_recording import own_start_refusal +from egocap_web.recording_command import ( + RECORDER_REFUSALS, + RecordingContext, + _public_refusal, + handle_recording_command, + parse_recording_command, + refusal_sentence, +) +from egocap_web.recording_session import CoordinatorBusyError +from recording_service import ConfigurationError, StateError +from tests.backend.qc_takes import make_coordinator + +TOKEN = "" +WAITING = "A take is waiting to be recovered or discarded. Resolve it, or start a new batch, before recording." +BUSY = "Another recording command is still running; try again in a moment." +SHUTTING_DOWN = "The recorder is shutting down; no recording command is accepted." +NOT_RECORDED = "That take is not the one being recorded." +STILL_WRITING = "The take is still being written; try again in a moment." +EPISODE = "session_20261126-101500_ab12cd/episode_3" + +REFUSALS = [ + (CoordinatorBusyError("recording session is closing"), SHUTTING_DOWN), + (StateError("service is closing or closed; no new lifecycle commands are accepted"), SHUTTING_DOWN), + (CoordinatorBusyError("discarding_pending already in progress"), BUSY), + (CoordinatorBusyError("new_batch already in progress"), BUSY), + (StateError(f"episode {EPISODE!r} already has a stop in progress"), BUSY), + ( + CoordinatorBusyError("recording session failed; use New batch before recording again"), + "The recording session failed; use New batch before recording again.", + ), + ( + CoordinatorBusyError("a recording session (failed) already exists; close it before opening a new one"), + "The recording session did not close; use New batch before recording again.", + ), + ( + CoordinatorBusyError(f"previous session did not fully release: {EPISODE}: work did not settle"), + "The previous session did not close; restart the backend before recording again.", + ), + (CoordinatorBusyError("a previous take's ingress has not yet settled"), STILL_WRITING), + (CoordinatorBusyError("ingress did not settle (conversion work still unresolved)"), STILL_WRITING), + (CoordinatorBusyError("ingress did not settle yet"), STILL_WRITING), + # What the room connection raised is not the backend's own sentence: it stays in the log. + ( + CoordinatorBusyError("LiveKit video is not ready: [Errno 111] Connect call failed ('192.0.2.9', 7880)"), + "LiveKit video is not ready; see the backend log.", + ), + (CoordinatorBusyError("LiveKit video is not ready"), "LiveKit video is not ready; see the backend log."), + ( + CoordinatorBusyError("start was superseded while storage was opening"), + "Capture stopped being ready while the take was starting; try again.", + ), + ( + CoordinatorBusyError("start was superseded before activation"), + "Capture stopped being ready while the take was starting; try again.", + ), + (CoordinatorBusyError("no matching active episode"), NOT_RECORDED), + (StateError(f"no active episode {EPISODE!r}"), NOT_RECORDED), + ( + CoordinatorBusyError("finish or discard the take being recorded first"), + "Finish or discard the take being recorded first.", + ), + (CoordinatorBusyError("an episode is active"), "Stop or discard the take being recorded first."), + (StateError("cannot start an episode while RECOVERY_REQUIRED"), WAITING), + (StateError(f"episode {EPISODE!r} needs recovery; use recover_episode or discard_pending"), WAITING), + (StateError(f"unresolved pending episodes: [{EPISODE!r}]"), WAITING), + ( + StateError("unreadable episode manifests must be resolved first: ['episode_2.json: Expecting value']"), + "This session holds a take record that cannot be read; start a new batch to record.", + ), + ( + StateError("cannot start an episode while FINALIZING"), + "A take is still being started, recorded or finished.", + ), + (StateError("cannot stop while STOPPING"), "That take is not being recorded any more."), + (StateError("cannot discard while FINALIZING"), "That take is not being recorded any more."), + (CoordinatorBusyError("no open recording session"), "No recording session is open."), + (StateError("no open session"), "No recording session is open."), + ( + StateError("session has no frozen source declarations; start a new session to record"), + "This session cannot record; start a new batch.", + ), + ( + StateError("session 'session_20261126-101500_ab12cd' is owned by another recorder"), + "That session is open in another recorder.", + ), + ( + ConfigurationError( + "required calibration asset 'head.json' not found at /srv/station/calibration/head.json" + ), + "A calibration file this station requires is missing or changed; see the backend log.", + ), + ( + ConfigurationError("quality-check configuration is invalid; see backend logs"), + "The quality-check configuration is invalid; see the backend log.", + ), + ( + ConfigurationError( + "quarantine location is a link: it must be a plain directory on the same file system as the recordings" + ), + "The quarantine folder in the recording output is a link, so a take marked bad could not be set aside. " + "Make it a plain folder on the recordings disk.", + ), + ( + ConfigurationError( + "quarantine location is not a directory: it must be a plain directory on the same file system as the " + "recordings" + ), + "The quarantine folder in the recording output is a file, not a folder, so a take marked bad could not be " + "set aside. Make it a plain folder on the recordings disk.", + ), + ( + ConfigurationError( + "quarantine location is on another file system: it must be a plain directory on the same file system " + "as the recordings" + ), + "The quarantine folder in the recording output is on another disk than the recordings, so a take marked " + "bad could not be set aside. Make it a plain folder on the recordings disk.", + ), + # Anything nobody wrote a sentence for gets the fixed one for its kind. + ( + StateError("something new about /srv/recordings/session_x while SEALED"), + "The recorder refused the command; see the backend log.", + ), + ( + CoordinatorBusyError("something else entirely: [Errno 5] /srv/x"), + "The recorder refused the command; see the backend log.", + ), + ( + ConfigurationError("camera resolution (3072000 bytes/decoded frame) cannot fit even one queued frame"), + "The recording configuration is not valid; see the backend log.", + ), + ( + ConfigurationError("capture QC: pose stream source 'manus_glove' must be a required source"), + "The recording configuration is not valid; see the backend log.", + ), +] + +#: Recorder state names and other marks of text that was not written for an operator. +_NOT_FOR_AN_OPERATOR = ( + "RECOVERY_REQUIRED", + "FINALIZING", + "STOPPING", + "SEALED", + "WRITING", + "Errno", + "/srv", + "session_2026", + "episode_", + "discarding_pending", + "new_batch", + "ingress", + "lifecycle", +) + + +@pytest.mark.parametrize(("raised", "sentence"), REFUSALS, ids=[str(raised)[:48] for raised, _ in REFUSALS]) +def test_each_refusal_is_said_in_a_sentence_written_for_the_operator(raised, sentence): + said = _public_refusal(raised) + assert said == sentence + assert not any(mark in said for mark in _NOT_FOR_AN_OPERATOR) + + +async def test_backend_code_that_records_takes_of_its_own_is_refused_in_the_same_sentences(tmp_path): + """The calibration tools start, stop and discard takes through the coordinator, not through a command.""" + root = tmp_path / "out" + coordinator = make_coordinator(root) + otherwise = "the take could not be started; see the backend log" + # A refusal on purpose is the sentence a command is answered with, whichever of the three raised it. + assert {type(raised) for raised, _ in REFUSALS} == set(RECORDER_REFUSALS) + for raised, sentence in REFUSALS: + assert refusal_sentence(coordinator, raised, otherwise) == sentence + # Anything else is a failure: the recordings disk is named when it is the cause, and only then. + full = OSError(errno.ENOSPC, "No space left on device", str(root / "session" / "episode_0.pending")) + assert refusal_sentence(coordinator, full, otherwise) == STORAGE[0][1] + elsewhere = OSError(errno.ENOSPC, "No space left on device", "/srv/elsewhere/file") + assert refusal_sentence(coordinator, elsewhere, otherwise) == otherwise + assert refusal_sentence(coordinator, RuntimeError("/srv/session went away"), otherwise) == otherwise + await coordinator.close() + + +def _command(context: RecordingContext, action: str, **payload): + return parse_recording_command( + { + "request_id": "r", + "action": action, + "payload": {"batch_id": context.batch_id, **payload}, + "operator_token": "alex", + "control_token": TOKEN, + } + ) + + +@pytest.mark.parametrize( + ("action", "payload"), + [ + ("start_episode", {}), + ("stop_episode", {"episode_id": EPISODE}), + ("discard_episode", {"episode_id": EPISODE}), + ("new_batch", {}), + ], +) +@pytest.mark.parametrize(("raised", "sentence"), REFUSALS[:6] + REFUSALS[18:21] + REFUSALS[-4:]) +async def test_a_command_the_coordinator_or_the_service_refuses_is_answered_with_that_sentence_and_logged( + tmp_path, monkeypatch, caplog, action, payload, raised, sentence +): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + + async def refuse(*_args, **_kwargs): + raise raised + + monkeypatch.setattr(coordinator, action, refuse) + with caplog.at_level(logging.WARNING, logger="egocap_web.recording_command"): + reply = await handle_recording_command(_command(context, action, **payload), context) + assert (reply["outcome"], reply["reason"]) == ("rejected", sentence) + # What was raised is in the log for whoever has to find the cause. + assert str(raised) in caplog.text + await coordinator.close() + + +async def test_a_start_while_capture_is_not_ready_is_answered_with_the_readiness_reason_the_page_already_shows( + tmp_path, +): + coordinator = make_coordinator(tmp_path / "out", readiness_check=lambda: (False, "capture is not running")) + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + reply = await handle_recording_command(_command(context, "start_episode"), context) + assert (reply["outcome"], reply["reason"]) == ("rejected", "capture is not running") + assert reply["snapshot"]["not_ready_reason"] == "capture is not running" + assert not (tmp_path / "out").exists() # refused before any storage was opened + await coordinator.close() + + +async def test_a_start_refused_without_a_reason_still_gets_a_sentence(tmp_path): + coordinator = make_coordinator(tmp_path / "out", readiness_check=lambda: (False, None)) + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + reply = await handle_recording_command(_command(context, "start_episode"), context) + assert (reply["outcome"], reply["reason"]) == ("rejected", "required sources are not ready") + await coordinator.close() + + +# --- a LiveKit start that is refused says why, when the backend's own LiveKit code wrote the reason --- + +LIVEKIT_REASONS = [ + "wrist_left: the LiveKit track was lost before recording started", + "wrist_left: the first frame carries no capture time, so it cannot be recorded (the bridge publishes none " + "while time sync is not up)", + "head-cam.2: frames are 1280x720, expected 1920x1080", + "a LiveKit stream sent no frame before the recording could start", + "joining the LiveKit room took longer than 10 s", + "the publisher did not answer clock-sync requests, so its frame times cannot be placed", + "the publisher's clock mapping jumped before the take started", + "the clock mapping is uncertain by 3.21 ms, over the 2.00 ms budget (EGOCAP_LIVEKIT_SYNC_BUDGET_MS)", +] + + +@pytest.mark.parametrize("reason", LIVEKIT_REASONS) +def test_a_livekit_reason_the_backend_wrote_is_passed_on(reason): + assert own_start_refusal(reason) == reason + said = _public_refusal(CoordinatorBusyError(f"LiveKit video is not ready: {reason}")) + assert said == f"LiveKit video is not ready: {reason}." + # Only as far as the backend wrote it: whatever follows is dropped. + longer = _public_refusal(CoordinatorBusyError(f"LiveKit video is not ready: {reason}; and [Errno 5] /srv/x")) + assert longer == said + + +@pytest.mark.parametrize( + "reason", + [ + "[Errno 111] Connect call failed", + "ConnectError: engine: signal failure: ws connect", + "wrist left: the LiveKit track was lost before recording started", + "the LiveKit track was lost before recording started", + "../x: the LiveKit track was lost before recording started", + "Joining the LiveKit room took longer than 10 s", + "", + ], +) +def test_any_other_livekit_reason_stays_in_the_log(reason): + assert own_start_refusal(reason) is None + said = _public_refusal(CoordinatorBusyError(f"LiveKit video is not ready: {reason}")) + assert said == "LiveKit video is not ready; see the backend log." + + +async def test_the_sentences_the_livekit_source_refuses_a_start_with_are_the_ones_passed_on(): + """The start refusals are read off the source itself, so a sentence added there and not here fails.""" + import inspect + + from egocap_web import livekit_recording + + source = inspect.getsource(livekit_recording.LiveKitRecordingSource) + raised = [line for line in source.splitlines() if "raise RuntimeError(" in line and "problem" not in line] + assert len(raised) == 5 # three per stream, the first-frame timeout and the join timeout + assert len(livekit_recording._START_REFUSALS) == len(LIVEKIT_REASONS) == 8 + + +# --- a recordings disk that refuses a write is named, from the error number --------------------------- + +STORAGE = [ + (errno.ENOSPC, "The recordings disk is full. Free space, then record again."), + ( + errno.EDQUOT, + "The disk quota for the recordings is used up. Free space or raise the quota, then record again.", + ), + (errno.EROFS, "The recordings folder is read-only. Make it writable, then record again."), + (errno.EACCES, "The backend may not write to the recordings folder. Fix its permissions, then record again."), + (errno.EPERM, "The backend may not write to the recordings folder. Fix its permissions, then record again."), +] + + +@pytest.mark.parametrize(("number", "sentence"), STORAGE) +@pytest.mark.parametrize("action", ["start_episode", "stop_episode", "discard_episode", "new_batch"]) +async def test_a_command_that_fails_on_the_recordings_disk_says_which_way_it_failed( + tmp_path, monkeypatch, caplog, action, number, sentence +): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + + async def fail(*_args, **_kwargs): + try: + raise OSError(number, "whatever the system says", str(tmp_path / "out" / "session_x")) + except OSError as cause: + raise RuntimeError("the step could not finish") from cause + + monkeypatch.setattr(coordinator, action, fail) + payload = {"episode_id": EPISODE} if action in ("stop_episode", "discard_episode") else {} + with caplog.at_level(logging.ERROR, logger="egocap_web.recording_command"): + reply = await handle_recording_command(_command(context, action, **payload), context) + assert (reply["outcome"], reply["reason"]) == ("rejected", sentence) + assert str(tmp_path) not in str(reply) and "whatever the system says" in caplog.text + await coordinator.close() + + +def _handled_while_another_was_raised(tmp_path): + """An unrelated failure raised while a permission error under the output was being handled.""" + try: + try: + raise PermissionError(errno.EACCES, "Permission denied", str(tmp_path / "out" / "session_x")) + except PermissionError: + raise RuntimeError("the capture source went away") # noqa: B904 - the point: no cause is given + except RuntimeError as unrelated: + return unrelated + + +@pytest.mark.parametrize( + "failure", + [ + lambda tmp_path: PermissionError(errno.EACCES, "Permission denied", str(tmp_path / "calibration" / "a")), + lambda tmp_path: PermissionError(errno.EACCES, "Permission denied", str(tmp_path / "bin" / "ffmpeg")), + lambda tmp_path: OSError(errno.ENOSPC, "No space left on device", str(tmp_path / "scratch" / "x")), + lambda tmp_path: PermissionError(errno.EPERM, "Operation not permitted"), + _handled_while_another_was_raised, + ], + ids=[ + "a calibration file", + "an encoder program", + "a full temporary directory", + "a failure that names no file", + "only the context of another failure", + ], +) +async def test_a_failure_that_is_not_on_a_file_of_the_recording_output_keeps_the_general_sentence( + tmp_path, monkeypatch, failure +): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + raised = failure(tmp_path) + + async def fail(*_args, **_kwargs): + raise raised + + monkeypatch.setattr(coordinator, "start_episode", fail) + reply = await handle_recording_command(_command(context, "start_episode"), context) + assert reply["outcome"] == "rejected" + assert reply["reason"] == "The recording command failed; see the backend log." + await coordinator.close() + + +async def test_with_no_configuration_to_tell_the_output_from_a_failure_keeps_the_general_sentence( + tmp_path, monkeypatch +): + coordinator = make_coordinator(tmp_path / "out") + inside = OSError(errno.ENOSPC, "No space left on device", str(tmp_path / "out" / "session_x")) + assert coordinator.recordings_disk_problem(inside) == "full" + + def cannot_build(): + raise RuntimeError("the capture checks' thresholds cannot be read") + + monkeypatch.setattr(coordinator, "_scan_config_factory", cannot_build) + assert coordinator.recordings_disk_problem(inside) is None + await coordinator.close() + + +async def test_a_failure_that_is_not_the_disk_keeps_the_fixed_sentence(tmp_path, monkeypatch): + coordinator = make_coordinator(tmp_path / "out") + coordinator.set_task("pour water") + context = RecordingContext(coordinator=coordinator, control_token=TOKEN) + + async def fail(*_args, **_kwargs): + raise OSError(errno.EIO, "No space left on device") # the text says full; the number does not + + monkeypatch.setattr(coordinator, "start_episode", fail) + reply = await handle_recording_command(_command(context, "start_episode"), context) + assert reply["reason"] == "The recording command failed; see the backend log." + await coordinator.close() diff --git a/examples/egocap/tests/backend/test_day_report_routes.py b/examples/egocap/tests/backend/test_day_report_routes.py index 879062921d..75a6b41d58 100644 --- a/examples/egocap/tests/backend/test_day_report_routes.py +++ b/examples/egocap/tests/backend/test_day_report_routes.py @@ -104,6 +104,80 @@ def _session( return session +def _capture(*results): + """A stored capture report: (name, outcome, issue, measurements) per check.""" + failed = [issue for _name, outcome, issue, _measured in results if outcome != "PASSED"] + return { + "outcome": "FAILED" if failed else "PASSED", + "issues": failed, + "warnings": [], + "check_results": [ + {"name": name, "outcome": outcome, "issues": [issue], "measurements": measured} + for name, outcome, issue, measured in results + ], + } + + +def test_each_take_of_the_day_carries_the_reason_as_the_operator_reads_it(tmp_path): + passed = {"outcome": "PASSED", "issues": [], "warnings": [], "check_results": []} + frozen = ( + "sustained_freeze:manus_glove/left_hand_pose", + "FAILED", + "manus_glove/left_hand_pose: no motion for 1.80s (limit 1.0s, eps 1e-06)", + {"longest_still_s": 1.8, "limit_s": 1.0}, + ) + slow = ( + "camera_min_fps:head_human_camera", + "FAILED", + "head_human_camera: 15.50 fps average is below 0.86 x 30.0 = 25.80", + {"fps": 15.5, "minimum_fps": 25.8, "expected_fps": 30.0}, + ) + _session( + tmp_path, + takes=( + _manifest( + 0, + "QUARANTINED", + quality=passed, + capture_quality=_capture(frozen), + qc_decision="FLAGGED_BAD", + finalization="QUARANTINE", + ), + _manifest( + 1, + "REJECTED", + quality=passed, + capture_quality=_capture(slow), + qc_decision="REJECTED_CAMERA", + finalization="REMOVE", + ), + _manifest(2, "WRITING", issues=[f"write failed: [Errno 28] No space left on device: '{tmp_path}/x'"]), + ), + ) + client, _recorder = _client(tmp_path) + body = client.get("/api/day-report", headers=AUTH).json() + report = body["report"] + assert report["totals"]["by_disposition"]["quarantined"] == {"count": 1, "seconds": 10.0} + quarantined, rejected, pending = report["sessions"][0]["episodes"] + assert (quarantined["disposition"], quarantined["location"]) == ( + "quarantined", + f"_quarantine/{SESSION}/episode_0", + ) + assert quarantined["reasons"] == [ + "The left glove did not move for 1.8 s (limit 1 s). Check the glove's battery and connection." + ] + assert quarantined["media_removed"] is False + assert (rejected["disposition"], rejected["media_removed"]) == ("rejected", True) + assert rejected["reasons"] == [ + "Camera head_human_camera averaged 15.5 fps, below the minimum of 25.8 fps (0.86 of 30 fps). " + "Check the camera's cable and the load on this PC, then record the take again." + ] + # A recorder note can name a directory; the day's summary sends the sentence for its kind instead. + assert pending["disposition"] == "pending" + assert pending["reasons"] == pending["issues"] == ["Writing the take to disk failed; see the backend log."] + assert str(tmp_path) not in json.dumps(report["sessions"][0]["episodes"]) + + def _day(root: Path) -> Path: return _session( root, @@ -149,6 +223,7 @@ def test_the_report_shows_todays_takes_for_the_station_in_use_with_its_observed_ assert {name: entry["count"] for name, entry in report["totals"]["by_disposition"].items()} == { "kept": 1, "flagged": 1, + "quarantined": 0, "rejected": 1, "discarded": 0, "pending": 1, @@ -561,3 +636,34 @@ def snapshot(): assert client.get("/api/day-report", headers=AUTH).status_code == 200 assert client.post("/api/day-report/save", json={}, headers=AUTH).status_code == 200 assert len(readers) == 3 and not any("asyncio_" in name for name in readers) + + +def test_a_take_record_that_cannot_be_read_is_reported_by_file_name_never_by_directory(tmp_path): + client, _recorder = _client(tmp_path) + session = _session(tmp_path, takes=(_manifest(0, "FINALIZED"),)) + good = json.loads(manifest_path(session, 0).read_text()) + (session / ".recording" / "episode_1.json").write_text(json.dumps({**good, "schema_version": 99})) + (session / ".recording" / "episode_2.json").write_text("{ not json") + body = client.get("/api/day-report", headers=AUTH) + (only,) = body.json()["report"]["sessions"] + assert only["problems"][0] == "episode_1.json: unsupported manifest schema_version 99" + # What is not a record is called that: no text of the JSON parser or the interpreter, no class name. + assert only["problems"][1] == "episode_2.json: not a take record" + assert str(tmp_path) not in body.text + + +def test_a_folder_of_the_output_that_cannot_be_read_does_not_cost_the_day_its_report(tmp_path, monkeypatch): + client, _recorder = _client(tmp_path) + _session(tmp_path, takes=(_manifest(0, "FINALIZED"),)) + (tmp_path / "lost+found").mkdir() + real_is_dir = Path.is_dir + + def is_dir(self): + if "lost+found" in self.parts: + raise PermissionError(13, "Permission denied", str(self)) + return real_is_dir(self) + + monkeypatch.setattr(Path, "is_dir", is_dir) + response = client.get("/api/day-report", headers=AUTH) + assert response.status_code == 200 + assert [s["session_id"] for s in response.json()["report"]["sessions"]] == [SESSION] diff --git a/examples/egocap/tests/backend/test_mock_stack_capture_qc.py b/examples/egocap/tests/backend/test_mock_stack_capture_qc.py new file mode 100644 index 0000000000..540ffa7bf8 --- /dev/null +++ b/examples/egocap/tests/backend/test_mock_stack_capture_qc.py @@ -0,0 +1,118 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Takes through the whole mock stack, judged by the shipped thresholds: the manual run, automated. + +The production CaptureServer runs in its mock mode with one camera, the backend's own capture monitor connects to +it, and the coordinator is configured by the application's factory and readiness check. Each take lasts a few +real seconds. A healthy take is kept, the mock camera's stall fault gets the take rejected and its media removed, +and the mock tracking source's freeze fault gets it quarantined. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import uuid +from pathlib import Path + +import zarr + +from capture_server import protocol as p +from egocap_web import app as app_module +from egocap_web.capture_status import CaptureStatusMonitor +from egocap_web.config import CaptureStatusConfig +from egocap_web.recording_session import RecordingSessionCoordinator +from recording_service import Disposition, QcDecision, RecordingPhase +from tests.support.capture_server import start_capture_server, stop_capture_server + +CAMERA = "head_human_camera" +TAKE_SECONDS = 3.5 + + +@contextlib.asynccontextmanager +async def _mock_stack(port: int, output_root: Path, *, camera_faults=(), ic_faults=()): + """The mock CaptureServer, the backend's monitor on it, and a coordinator ready to record.""" + running = await start_capture_server(port, camera_faults=set(camera_faults), ic_faults=set(ic_faults)) + config = CaptureStatusConfig( + capture_server_url=f"ws://127.0.0.1:{port}", + cameras=(p.CameraSelection(name=CAMERA, type=p.CameraType.OAK_D_COLOR),), + ) + monitor = CaptureStatusMonitor(config, backend_instance_id=str(uuid.uuid4())) + coordinator = RecordingSessionCoordinator( + # OpenCV writes the video, so no encoder process is involved. + app_module._recording_config_factory(monitor, "Bench A", output_root, video_encoder="opencv_mp4v"), + queue_capacity=4096, + queue_bytes=256 * 1024 * 1024, + readiness_check=app_module._recording_readiness_check(monitor, None, config.capture_server_url), + ) + monitor.set_recording(coordinator) + await monitor.start() + try: + for _ in range(500): + if coordinator.readiness()[0]: + break + await asyncio.sleep(0.02) + assert coordinator.readiness() == (True, None) + coordinator.set_task("pour water") + yield coordinator + finally: + await coordinator.close(final=True) + await monitor.stop() + await stop_capture_server(running) + + +async def _take(coordinator: RecordingSessionCoordinator): + episode = await coordinator.start_episode("alex") + await asyncio.sleep(TAKE_SECONDS) + return await coordinator.stop_episode(episode.episode_id) + + +def _measured(result, name: str) -> dict: + return next(r.measurements for r in result.capture_quality.check_results if r.name == name) + + +async def test_a_healthy_take_through_the_mock_stack_is_judged_and_kept(unused_tcp_port, tmp_path): + async with _mock_stack(unused_tcp_port, tmp_path / "out") as coordinator: + result = await _take(coordinator) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.PASSED + rate = _measured(result, f"camera_min_fps:{CAMERA}") + # The adapter takes every frame the camera produces and counts nothing else: the recorded rate is the + # declared one, neither short of it nor inflated by the empty polls between frames. + assert 0.95 * rate["expected_fps"] < rate["fps"] < 1.05 * rate["expected_fps"] + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["capture_qc_decision"] == "PASSED" and attrs["domain_checks"] == "EXECUTED" + + +async def test_the_mock_cameras_stall_fault_gets_the_take_rejected_and_its_media_removed( + unused_tcp_port, tmp_path +): + root = tmp_path / "out" + async with _mock_stack(unused_tcp_port, root, camera_faults={"camera_stall"}) as coordinator: + result = await _take(coordinator) + # Each stall is shorter than the staleness limit, so the take ended normally: it was judged, not + # interrupted, and the session is ready for the next take. + assert coordinator.snapshot().service.phase is RecordingPhase.IDLE + assert result.disposition is Disposition.REJECTED and result.qc_decision is QcDecision.REJECTED_CAMERA + rate = _measured(result, f"camera_min_fps:{CAMERA}") + assert rate["fps"] < 0.6 * rate["expected_fps"] + session = root / result.session_id + assert not (session / "episode_0.pending").exists() and not (session / "episode_0").exists() + assert result.final_path is None and result.pending_path is None + + +async def test_the_mock_tracking_freeze_fault_gets_the_take_quarantined(unused_tcp_port, tmp_path): + root = tmp_path / "out" + async with _mock_stack(unused_tcp_port, root, ic_faults={"sample_freeze"}) as coordinator: + result = await _take(coordinator) + assert result.disposition is Disposition.QUARANTINED and result.qc_decision is QcDecision.FLAGGED_BAD + assert result.quarantine_path == root / "_quarantine" / result.session_id / "episode_0" + frozen = { + r.name for r in result.capture_quality.check_results if r.name.startswith("sustained_freeze") and r.issues + } + assert frozen == { + "sustained_freeze:pico_controller/head_pose", + "sustained_freeze:pico_controller/left_pose", + "sustained_freeze:pico_controller/right_pose", + } diff --git a/examples/egocap/tests/backend/test_qc_wire.py b/examples/egocap/tests/backend/test_qc_wire.py new file mode 100644 index 0000000000..963541ce43 --- /dev/null +++ b/examples/egocap/tests/backend/test_qc_wire.py @@ -0,0 +1,734 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What the page receives about a take and its pending takes, and what its two commands for a pending take do. + +Every take is recorded through the real coordinator and the real recording service from frames built in the test +(see qc_takes.py), and every command goes through the command handler the WebSocket uses. Where a command leads +to recorded media being removed, the whole recording output is compared file by file before and after. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import json + +import pytest + +import recording_service.output_scan as output_scan +import recording_service.recording_service as service_module +from egocap.recording import episode_layout +from egocap.recording.capture_qc_policy import CaptureQcPolicy, resolve_policy +from egocap.recording.episode_layout import read_manifest +from egocap_web import recording_adapter +from egocap_web.recording_command import ( + RecordingCommandError, + RecordingContext, + handle_recording_command, + parse_recording_command, +) +from egocap_web.recording_session import RecordingSessionCoordinator +from recording_service import RecordingPhase +from tests.backend.qc_takes import ( + ALWAYS_READY, + CAMERA, + changed, + config_factory, + make_coordinator, + offer, + take_frames, + tree, +) + +TOKEN = "" +HEAD_FROZEN = ( + "The headset did not move for 2.0 s (limit 1 s). " + "Check that the headset and both controllers are on, charged and in view." +) +CAMERA_SLOW = ( + "Camera head_human_camera averaged 15.5 fps, below the minimum of 25.8 fps (0.86 of 30 fps). " + "Check the camera's cable and the load on this PC, then record the take again." +) +CAMERA_STALE = "camera 'head_human_camera' is stale or has no sample yet" +INTERRUPTED = f"A capture source stopped while the take was recording: {CAMERA_STALE}." + + +def _context(coordinator: RecordingSessionCoordinator) -> RecordingContext: + coordinator.set_task("pour water") + return RecordingContext(coordinator=coordinator, control_token=TOKEN) + + +async def _send(context: RecordingContext, action: str, request_id: str = "r", **payload) -> dict: + """One command through the handler the WebSocket uses; returns the whole reply.""" + command = parse_recording_command( + { + "request_id": request_id, + "action": action, + "payload": {"batch_id": context.batch_id, **payload}, + "operator_token": "alex", + "control_token": TOKEN, + } + ) + return await handle_recording_command(command, context) + + +async def _take(context: RecordingContext, frames=None) -> dict: + """Record one take from Record to Stop through the commands; returns the snapshot after Stop.""" + started = await _send(context, "start_episode") + assert started["outcome"] == "ok", started["reason"] + episode_id = started["snapshot"]["current_episode_id"] + offer(context.coordinator, take_frames() if frames is None else frames) + stopped = await _send(context, "stop_episode", episode_id=episode_id) + assert stopped["outcome"] == "ok", stopped["reason"] + return stopped["snapshot"] + + +async def _interrupt(context: RecordingContext, frames=None) -> dict: + """Start a take and lose a capture source during it; returns the snapshot once the take is retained.""" + started = await _send(context, "start_episode") + assert started["outcome"] == "ok", started["reason"] + offer(context.coordinator, take_frames(seconds=1.0) if frames is None else frames) + context.coordinator.on_capture_lost(CAMERA_STALE) + for _ in range(500): + snapshot = context.coordinator.snapshot() + if snapshot.service.phase is RecordingPhase.RECOVERY_REQUIRED and snapshot.active_operation is None: + break + await asyncio.sleep(0.01) + return context.snapshot() + + +def _session_of(snapshot: dict) -> str: + return snapshot["last_result"]["episode_id"].split("/")[0] + + +# --- the outcome of each take ---------------------------------------------------------------- + + +async def test_a_kept_take_is_sent_with_its_outcome_and_counts_as_saved(tmp_path): + context = _context(make_coordinator(tmp_path / "out")) + snapshot = await _take(context) + session = _session_of(snapshot) + assert snapshot["last_result"] == { + "episode_id": f"{session}/episode_0", + "disposition": "KEPT", + "outcome": "kept", + "qc_decision": "PASSED", + "reasons": [], + "warnings": [], + "media_removed": False, + "location": f"{session}/episode_0", + "issues": [], + "duration_ms": 2000, + } + counts = { + name: snapshot[name] for name in ("saved_count", "flagged_count", "quarantined_count", "rejected_count") + } + assert counts == {"saved_count": 1, "flagged_count": 0, "quarantined_count": 0, "rejected_count": 0} + assert snapshot["pending_takes"] == [] and snapshot["episode_phase"] == "IDLE" + json.dumps(snapshot) + await context.coordinator.close() + + +async def test_a_frozen_take_is_sent_as_quarantined_with_the_stream_the_measure_the_limit_and_what_to_check( + tmp_path, +): + context = _context(make_coordinator(tmp_path / "out")) + snapshot = await _take(context, take_frames(frozen_head=True)) + result, session = snapshot["last_result"], _session_of(snapshot) + assert (result["disposition"], result["outcome"], result["qc_decision"]) == ( + "QUARANTINED", + "quarantined", + "FLAGGED_BAD", + ) + assert result["reasons"] == [HEAD_FROZEN] and result["media_removed"] is False + assert result["location"] == f"_quarantine/{session}/episode_0" + # Its warnings are the same finding seen by the advisories: nearly still, and unchanged for the whole take. + assert result["warnings"] == [ + "The headset barely moved for 2.0 s (limit 2 s).", + "The headset did not change for the whole take.", + ] + assert (snapshot["saved_count"], snapshot["quarantined_count"], snapshot["flagged_count"]) == (0, 1, 0) + # A quarantined take is resolved: nothing is pending and the next take can start. + assert snapshot["pending_takes"] == [] and snapshot["ready_to_record"] is True + await context.coordinator.close() + + +async def test_with_quarantine_off_the_same_take_is_sent_as_flagged_and_stays_in_its_session(tmp_path): + policy = resolve_policy({}, {"guardrails": {"quarantine": False}}) + context = _context(make_coordinator(tmp_path / "out", policy)) + snapshot = await _take(context, take_frames(frozen_head=True)) + result, session = snapshot["last_result"], _session_of(snapshot) + assert (result["disposition"], result["outcome"], result["qc_decision"]) == ("KEPT", "flagged", "FLAGGED_BAD") + assert result["reasons"] == [HEAD_FROZEN] and result["location"] == f"{session}/episode_0" + assert (snapshot["saved_count"], snapshot["flagged_count"], snapshot["quarantined_count"]) == (0, 1, 0) + await context.coordinator.close() + + +async def test_a_camera_rejection_is_sent_with_the_camera_its_rate_and_the_limit_and_its_media_is_gone(tmp_path): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + await _take(context) + before = tree(root) + snapshot = await _take(context, take_frames(camera_hole=1.0)) + result, session = snapshot["last_result"], _session_of(snapshot) + assert (result["disposition"], result["outcome"], result["qc_decision"]) == ( + "REJECTED", + "rejected", + "REJECTED_CAMERA", + ) + assert result["reasons"] == [CAMERA_SLOW] and result["media_removed"] is True and result["location"] is None + assert (snapshot["saved_count"], snapshot["rejected_count"]) == (1, 1) + assert changed(before, tree(root)) == (set(), {f"{session}/.recording/episode_1.json"}, set()) + await context.coordinator.close() + + +async def test_an_integrity_rejection_is_sent_as_rejected_with_its_data_kept(tmp_path, monkeypatch): + policy = resolve_policy({}, {"guardrails": {"gloves_expected": True}}) + context = _context(make_coordinator(tmp_path / "out", policy)) + monkeypatch.setattr(recording_adapter, "build_manus_glove_fields", lambda tracking: None) + snapshot = await _take(context) + result, session = snapshot["last_result"], _session_of(snapshot) + assert (result["disposition"], result["outcome"], result["qc_decision"]) == ( + "REJECTED", + "rejected_data_kept", + "SKIPPED", + ) + assert result["reasons"] == [ + "The recorded data failed an integrity check: manus_glove: required source has no rows." + ] + assert result["media_removed"] is False and result["location"] == f"{session}/episode_0.pending" + assert (tmp_path / "out" / session / "episode_0.pending").is_dir() + assert snapshot["rejected_count"] == 1 and snapshot["saved_count"] == 0 + await context.coordinator.close() + + +async def test_a_discarded_take_is_sent_as_discarded_and_adds_to_no_count(tmp_path): + context = _context(make_coordinator(tmp_path / "out")) + started = await _send(context, "start_episode") + offer(context.coordinator, take_frames(seconds=0.5)) + reply = await _send(context, "discard_episode", episode_id=started["snapshot"]["current_episode_id"]) + result = reply["snapshot"]["last_result"] + assert (result["disposition"], result["outcome"], result["media_removed"]) == ("DISCARDED", "discarded", True) + assert result["reasons"] == [] and result["location"] is None + counts = [ + reply["snapshot"][n] for n in ("saved_count", "flagged_count", "quarantined_count", "rejected_count") + ] + assert counts == [0, 0, 0, 0] + await context.coordinator.close() + + +async def test_a_new_batch_starts_every_count_again(tmp_path): + context = _context(make_coordinator(tmp_path / "out")) + await _take(context) + await _take(context, take_frames(frozen_head=True)) + await _take(context, take_frames(camera_hole=1.0)) + before = context.snapshot() + assert (before["saved_count"], before["quarantined_count"], before["rejected_count"]) == (1, 1, 1) + reply = await _send(context, "new_batch") + snapshot = reply["snapshot"] + assert reply["outcome"] == "ok" and snapshot["last_result"] is None + assert [snapshot[n] for n in ("saved_count", "flagged_count", "quarantined_count", "rejected_count")] == [ + 0 + ] * 4 + await context.coordinator.close() + + +# --- a pending take of the open session ------------------------------------------------------ + + +async def test_an_interrupted_take_is_sent_as_interrupted_and_listed_as_the_one_blocking_record(tmp_path): + context = _context(make_coordinator(tmp_path / "out")) + snapshot = await _interrupt(context) + result, session = snapshot["last_result"], _session_of(snapshot) + assert (result["disposition"], result["outcome"], result["qc_decision"]) == ( + "RECOVERY_REQUIRED", + "interrupted", + None, + ) + assert result["reasons"] == [INTERRUPTED] and result["issues"] == [INTERRUPTED] + assert result["location"] == f"{session}/episode_0.pending" and result["media_removed"] is False + assert snapshot["episode_phase"] == "RECOVERY_REQUIRED" and snapshot["ready_to_record"] is False + (pending,) = snapshot["pending_takes"] + assert pending == { + "episode_id": f"{session}/episode_0", + "session_id": session, + "index": 0, + "phase": "WRITING", + "recoverable": False, + "recoverable_known": True, + "discardable": True, + "current": True, + "reason": INTERRUPTED, + "recover_note": "This take was cut off while it was being written, so it is incomplete. " + "It can only be discarded.", + "task": "pour water", + "operator": "alex", + "duration_ms": 0, + } + assert snapshot["saved_count"] == 0 + json.dumps(snapshot) + await context.coordinator.close() + + +async def test_recover_on_a_take_cut_off_while_writing_is_rejected_with_the_reason_and_changes_nothing(tmp_path): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + snapshot = await _interrupt(context) + before = tree(root) + reply = await _send(context, "recover_pending", episode_id=snapshot["pending_takes"][0]["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "This take was cut off while it was being written and cannot be recovered; discard it.", + ) + assert tree(root) == before and reply["snapshot"]["pending_takes"] == snapshot["pending_takes"] + assert str(root) not in reply["reason"] + await context.coordinator.close() + + +async def test_discarding_the_pending_take_removes_only_it_and_returns_the_session_to_idle(tmp_path): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + kept = await _take(context) + quarantined = await _take(context, take_frames(frozen_head=True)) + (root / "notes.txt").write_text("operator notes") + snapshot = await _interrupt(context) + session = _session_of(kept) + before = tree(root) + pending_files = {path for path in before if path.startswith(f"{session}/episode_2.pending/")} + assert pending_files + reply = await _send(context, "discard_pending", episode_id=snapshot["pending_takes"][0]["episode_id"]) + assert reply["outcome"] == "ok" and reply["reason"] is None + after = reply["snapshot"] + assert (after["last_result"]["outcome"], after["last_result"]["media_removed"]) == ("discarded", True) + assert after["pending_takes"] == [] and after["episode_phase"] == "IDLE" and after["ready_to_record"] is True + # Only the pending take's own files are gone, and only its manifest changed. + assert changed(before, tree(root)) == (pending_files, set(), {f"{session}/.recording/episode_2.json"}) + assert (root / kept["last_result"]["location"]).is_dir() + assert (root / quarantined["last_result"]["location"]).is_dir() + # Record works again in the same session, without a new batch. + assert (await _take(context))["last_result"]["episode_id"] == f"{session}/episode_3" + assert context.snapshot()["saved_count"] == 2 + await context.coordinator.close() + + +def _fail_first_removal(monkeypatch): + """Make the recording service's next removal of a rejected take fail after one directory is gone.""" + real_remove, state = service_module.remove_owned_episode, {"failing": True} + + def remove(session_path, manifest): + if not state["failing"]: + return real_remove(session_path, manifest) + state["failing"] = False + real_rmtree, deleted = episode_layout.shutil.rmtree, [] + + def rmtree(path, *args, **kwargs): + if deleted: + raise OSError("device error") + deleted.append(path) + real_rmtree(path, *args, **kwargs) + + episode_layout.shutil.rmtree = rmtree + try: + return real_remove(session_path, manifest) + finally: + episode_layout.shutil.rmtree = real_rmtree + + monkeypatch.setattr(service_module, "remove_owned_episode", remove) + + +async def test_a_rejection_whose_removal_failed_part_way_is_listed_and_recover_finishes_removing_only_it( + tmp_path, monkeypatch +): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + kept = await _take(context) + session = _session_of(kept) + before_take = tree(root) + _fail_first_removal(monkeypatch) + snapshot = await _take(context, take_frames(camera_hole=1.0)) + assert snapshot["last_result"]["outcome"] == "interrupted" + assert snapshot["last_result"]["reasons"] == ["Finishing the take failed part-way; see the backend log."] + assert snapshot["last_result"]["qc_decision"] == "REJECTED_CAMERA" + (pending,) = snapshot["pending_takes"] + assert (pending["phase"], pending["recoverable"], pending["current"]) == ("CHECKED", True, True) + assert pending["recover_note"] == "The camera check rejected this take. Recover finishes removing its media." + assert snapshot["ready_to_record"] is False and snapshot["rejected_count"] == 0 + reply = await _send(context, "recover_pending", episode_id=pending["episode_id"]) + assert reply["outcome"] == "ok" + after = reply["snapshot"] + assert (after["last_result"]["outcome"], after["last_result"]["media_removed"]) == ("rejected", True) + assert after["last_result"]["reasons"] == [CAMERA_SLOW] + assert after["pending_takes"] == [] and after["ready_to_record"] is True and after["rejected_count"] == 1 + # Against the output before the take started, only the rejected take's manifest is new. + assert changed(before_take, tree(root)) == (set(), {f"{session}/.recording/episode_1.json"}, set()) + await context.coordinator.close() + + +async def test_a_take_whose_checks_could_not_run_is_recovered_judged_and_counted(tmp_path, monkeypatch): + context = _context(make_coordinator(tmp_path / "out")) + real_check = service_module.check_capture_quality + monkeypatch.setattr(service_module, "check_capture_quality", lambda *_: (_ for _ in ()).throw(OSError("busy"))) + snapshot = await _take(context, take_frames(frozen_head=True)) + (pending,) = snapshot["pending_takes"] + assert (pending["phase"], pending["recoverable"]) == ("SEALED", True) + assert pending["recover_note"] == "Recover runs the checks on this take and finishes it." + monkeypatch.setattr(service_module, "check_capture_quality", real_check) + reply = await _send(context, "recover_pending", episode_id=pending["episode_id"]) + after = reply["snapshot"] + assert reply["outcome"] == "ok" and after["last_result"]["outcome"] == "quarantined" + assert after["last_result"]["reasons"] == [HEAD_FROZEN] + assert after["quarantined_count"] == 1 and after["pending_takes"] == [] + await context.coordinator.close() + + +async def test_a_command_for_a_take_that_is_not_pending_is_rejected(tmp_path): + context = _context(make_coordinator(tmp_path / "out")) + kept = await _take(context) + for action in ("recover_pending", "discard_pending"): + reply = await _send(context, action, episode_id=kept["last_result"]["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + reply = await _send(context, action, episode_id="session_none/episode_0") + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + await context.coordinator.close() + + +@pytest.mark.parametrize("action", ["recover_pending", "discard_pending"]) +def test_the_two_commands_need_a_batch_and_an_episode_id(action): + for payload in ({"batch_id": "b"}, {"episode_id": "s/episode_0"}, {"batch_id": "b", "episode_id": ""}): + with pytest.raises(RecordingCommandError): + parse_recording_command({"request_id": "r", "action": action, "payload": payload}) + parsed = parse_recording_command( + {"request_id": "r", "action": action, "payload": {"batch_id": "b", "episode_id": "s/episode_0"}} + ) + assert parsed.action == action + + +@pytest.mark.parametrize("action", ["recover_pending", "discard_pending"]) +async def test_the_two_commands_need_the_control_token_an_operator_and_the_current_batch(tmp_path, action): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + snapshot = await _interrupt(context) + episode_id, before = snapshot["pending_takes"][0]["episode_id"], tree(root) + + async def send(**overrides): + raw = { + "request_id": "r", + "action": action, + "payload": {"batch_id": context.batch_id, "episode_id": episode_id}, + "operator_token": "alex", + "control_token": TOKEN, + } + raw.update(overrides) + return await handle_recording_command(parse_recording_command(raw), context) + + assert (await send(control_token="wrong"))["reason"] == "Enter the current recording control token" + assert (await send(operator_token=None))["reason"] == "Enter an operator name before using recording controls" + stale = await send(payload={"batch_id": "another-batch", "episode_id": episode_id}) + assert (stale["outcome"], stale["reason"]) == ("rejected", "no matching batch") + assert tree(root) == before and len(context.snapshot()["pending_takes"]) == 1 + await context.coordinator.close() + + +# --- pending takes of earlier sessions ------------------------------------------------------- + + +async def _restart(root, policy=CaptureQcPolicy(), **kwargs) -> RecordingContext: + """A new coordinator and context over the same output, as after a backend restart; reads what was left.""" + context = _context(make_coordinator(root, policy, **kwargs)) + await context.coordinator.refresh_pending() + return context + + +async def _leave_like_a_killed_backend(context: RecordingContext) -> str: + """Start a take and leave it as a killed process would: files half-written, its manifest still WRITING with + no note, and the session's lock gone with the process. Returns the episode id.""" + started = await _send(context, "start_episode") + offer(context.coordinator, take_frames(seconds=1.0)) + coordinator = context.coordinator + await coordinator._current_ingress.stop() # what was offered reaches the disk, as it would have by then + service = coordinator._service + take = service._take + take.worker.cancel() + await service._call(take, take.store.abort) + service._lock.release() + return started["snapshot"]["current_episode_id"] + + +async def test_a_take_left_writing_by_a_killed_recorder_is_listed_after_a_restart_and_discarded_from_the_page( + tmp_path, +): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + kept = await _take(first) + episode_id = await _leave_like_a_killed_backend(first) + session = _session_of(kept) + (root / "notes.txt").write_text("operator notes") + + context = await _restart(root) + snapshot = context.snapshot() + (pending,) = snapshot["pending_takes"] + assert pending == { + "episode_id": episode_id, + "session_id": session, + "index": 1, + "phase": "WRITING", + "recoverable": False, + "recoverable_known": True, + "discardable": True, + "current": False, + "reason": "The recorder stopped while this take was being written.", + "recover_note": "This take was cut off while it was being written, so it is incomplete. " + "It can only be discarded.", + "task": "pour water", + "operator": "alex", + "duration_ms": 0, + } + # A take of an earlier session blocks nothing: Record is ready, in a session of its own. + assert snapshot["episode_phase"] == "IDLE" and snapshot["ready_to_record"] is True + assert snapshot["last_result"] is None + + refused = await _send(context, "recover_pending", episode_id=episode_id) + assert (refused["outcome"], refused["reason"]) == ( + "rejected", + "This take was cut off while it was being written and cannot be recovered; discard it.", + ) + before = tree(root) + pending_files = {path for path in before if path.startswith(f"{session}/episode_1.pending/")} + assert pending_files + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert reply["outcome"] == "ok" + after = reply["snapshot"] + assert after["pending_takes"] == [] and after["last_result"]["outcome"] == "discarded" + assert after["last_result"]["episode_id"] == episode_id + assert changed(before, tree(root)) == (pending_files, set(), {f"{session}/.recording/episode_1.json"}) + assert (root / kept["last_result"]["location"]).is_dir() + # It was not recorded in this batch, so it adds to none of its counts. + assert [after[n] for n in ("saved_count", "flagged_count", "quarantined_count", "rejected_count")] == [0] * 4 + assert read_manifest(root / session / ".recording" / "episode_1.json").storage_phase == "DISCARDED" + await context.coordinator.close() + + +async def test_a_sealed_take_of_an_earlier_session_is_recovered_and_judged_after_a_restart(tmp_path, monkeypatch): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + real_check = service_module.check_capture_quality + monkeypatch.setattr(service_module, "check_capture_quality", lambda *_: (_ for _ in ()).throw(OSError("busy"))) + left = await _take(first, take_frames(frozen_head=True)) + episode_id, session = left["pending_takes"][0]["episode_id"], _session_of(left) + await first.coordinator.close() + monkeypatch.setattr(service_module, "check_capture_quality", real_check) + + context = await _restart(root) + (pending,) = context.snapshot()["pending_takes"] + assert (pending["phase"], pending["recoverable"], pending["current"]) == ("SEALED", True, False) + assert pending["reason"] == "Finishing the take failed part-way; see the backend log." + assert pending["recover_note"] == "Recover runs the checks on this take and finishes it." + reply = await _send(context, "recover_pending", episode_id=episode_id) + assert reply["outcome"] == "ok" + after = reply["snapshot"] + assert after["last_result"]["outcome"] == "quarantined" and after["last_result"]["reasons"] == [HEAD_FROZEN] + assert after["last_result"]["location"] == f"_quarantine/{session}/episode_0" + assert (root / "_quarantine" / session / "episode_0").is_dir() and after["pending_takes"] == [] + assert after["quarantined_count"] == 0 and after["episode_phase"] == "IDLE" + assert read_manifest(root / session / ".recording" / "episode_0.json").storage_phase == "QUARANTINED" + await context.coordinator.close() + + +async def test_a_healthy_sealed_take_of_an_earlier_session_is_recovered_as_kept_and_sent_to_the_aligner( + tmp_path, monkeypatch +): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + real_check = service_module.check_capture_quality + monkeypatch.setattr(service_module, "check_capture_quality", lambda *_: (_ for _ in ()).throw(OSError("busy"))) + left = await _take(first) + await first.coordinator.close() + monkeypatch.setattr(service_module, "check_capture_quality", real_check) + context = await _restart(root) + kept = [] + context.coordinator.on_episode_kept = kept.append + reply = await _send(context, "recover_pending", episode_id=left["pending_takes"][0]["episode_id"]) + assert reply["snapshot"]["last_result"]["outcome"] == "kept" and reply["snapshot"]["saved_count"] == 0 + assert [result.episode_id for result in kept] == [left["pending_takes"][0]["episode_id"]] + await context.coordinator.close() + + +async def test_a_session_whose_frozen_declarations_no_longer_match_is_refused_with_its_reason_and_left_untouched( + tmp_path, +): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + left = await _interrupt(first) + episode_id = left["pending_takes"][0]["episode_id"] + await first.coordinator.close() + + recording = config_factory(root) + + def changed_declarations(): + config = recording() + pico, manus = config.numeric_sources + return dataclasses.replace(config, numeric_sources=(dataclasses.replace(pico, frame_type="Other"), manus)) + + coordinator = RecordingSessionCoordinator( + changed_declarations, queue_capacity=8192, readiness_check=ALWAYS_READY, watch_seconds=0.0 + ) + context = _context(coordinator) + await coordinator.refresh_pending() + assert [take["episode_id"] for take in context.snapshot()["pending_takes"]] == [episode_id] + before = tree(root) + for action in ("discard_pending", "recover_pending"): + reply = await _send(context, action, episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "This take's session cannot be reopened under the current settings: its source declarations or " + "calibration files have changed. The take was left on disk.", + ) + assert str(root) not in reply["reason"] + assert tree(root) == before + assert [take["episode_id"] for take in context.snapshot()["pending_takes"]] == [episode_id] + await coordinator.close() + + +async def test_a_new_batch_past_an_interrupted_take_keeps_it_listed_as_an_earlier_sessions(tmp_path): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + interrupted = await _interrupt(context) + episode_id = interrupted["pending_takes"][0]["episode_id"] + reply = await _send(context, "new_batch") + snapshot = reply["snapshot"] + assert reply["outcome"] == "ok" + (pending,) = snapshot["pending_takes"] + assert (pending["episode_id"], pending["current"], pending["recoverable"]) == (episode_id, False, False) + assert pending["reason"] == INTERRUPTED + # The next take opens a session of its own, and the old take is still there to resolve afterwards. + assert snapshot["episode_phase"] == "IDLE" and snapshot["ready_to_record"] is True + kept = await _take(context) + assert kept["last_result"]["outcome"] == "kept" and _session_of(kept) != episode_id.split("/")[0] + assert [take["episode_id"] for take in kept["pending_takes"]] == [episode_id] + # It was written a moment ago by this very backend, which held its session until New batch: no time on the + # disk is compared with the clock, so it is discarded at once. + discarded = await _send(context, "discard_pending", episode_id=episode_id) + assert discarded["outcome"] == "ok" and discarded["snapshot"]["pending_takes"] == [] + assert discarded["snapshot"]["saved_count"] == 1 + await context.coordinator.close() + + +async def test_an_earlier_sessions_take_cannot_be_resolved_while_a_take_is_being_recorded(tmp_path): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + left = await _interrupt(first) + episode_id = left["pending_takes"][0]["episode_id"] + await first.coordinator.close() + context = await _restart(root) + started = await _send(context, "start_episode") + before = tree(root) + for action in ("recover_pending", "discard_pending"): + reply = await _send(context, action, episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "Finish or discard the take being recorded first.", + ) + assert {path for path in before if "episode_0.pending" in path} <= set(tree(root)) + await _send(context, "discard_episode", episode_id=started["snapshot"]["current_episode_id"]) + assert (await _send(context, "discard_pending", episode_id=episode_id))["outcome"] == "ok" + await context.coordinator.close() + + +async def test_whether_an_earlier_take_can_be_recovered_follows_the_cameras_accepted_by_now(tmp_path, monkeypatch): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + monkeypatch.setattr(service_module, "check_capture_quality", lambda *_: (_ for _ in ()).throw(OSError("busy"))) + left = await _take(first) + await first.coordinator.close() + monkeypatch.undo() + + accepted = {"cameras": ()} + coordinator = RecordingSessionCoordinator( + lambda: config_factory(root, cameras=accepted["cameras"])(), + queue_capacity=8192, + readiness_check=ALWAYS_READY, + watch_seconds=0.0, + ) + context = _context(coordinator) + await coordinator.refresh_pending() + (pending,) = context.snapshot()["pending_takes"] + # No camera is accepted yet, so there is nothing to compare the take's settings with: nothing is said + # about whether it can be recovered, and nothing tells the operator to discard it. + assert (pending["recoverable"], pending["recoverable_known"], pending["discardable"]) == (False, False, True) + assert pending["recover_note"] == "Whether this take can be finished is known once the cameras are connected." + revision = context.snapshot()["revision"] + accepted["cameras"] = (CAMERA,) + await coordinator.refresh_pending() + snapshot = context.snapshot() + assert snapshot["pending_takes"][0]["recoverable"] is True and snapshot["revision"] > revision + assert snapshot["pending_takes"][0]["recoverable_known"] is True + assert snapshot["pending_takes"][0]["episode_id"] == left["pending_takes"][0]["episode_id"] + await coordinator.close() + + +async def test_after_its_first_read_the_periodic_read_opens_only_the_sessions_that_still_hold_a_take( + tmp_path, monkeypatch +): + root = tmp_path / "out" + for _ in range(3): # sessions with nothing left to resolve + finished = _context(make_coordinator(root)) + await _take(finished) + await finished.coordinator.close() + first = _context(make_coordinator(root)) + left = await _interrupt(first) + await first.coordinator.close() + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + coordinator = make_coordinator(root) + await coordinator.refresh_pending() + assert len(opened) == 4 and len(coordinator.pending_takes()) == 1 + opened.clear() + for _ in range(3): + await coordinator.refresh_pending() + # Three more reads opened one session each: the one that holds the take, never the three that hold none. + assert opened == [left["pending_takes"][0]["session_id"]] * 3 + assert len(coordinator.pending_takes()) == 1 + await coordinator.close() + + +async def test_the_open_sessions_own_takes_are_not_listed_twice(tmp_path): + context = _context(make_coordinator(tmp_path / "out")) + await _interrupt(context) + await context.coordinator.refresh_pending() + (pending,) = context.snapshot()["pending_takes"] + assert pending["current"] is True + await context.coordinator.close() + + +async def test_a_configuration_that_cannot_be_built_keeps_the_last_list(tmp_path): + root = tmp_path / "out" + first = _context(make_coordinator(root)) + left = await _interrupt(first) + await first.coordinator.close() + failing = {"now": False} + + def factory(): + if failing["now"]: + raise RuntimeError("no configuration yet") + return config_factory(root)() + + coordinator = RecordingSessionCoordinator( + factory, queue_capacity=8192, readiness_check=ALWAYS_READY, watch_seconds=0.0 + ) + await coordinator.refresh_pending() + listed = coordinator.pending_takes() + assert [take.episode.episode_id for take in listed] == [left["pending_takes"][0]["episode_id"]] + failing["now"] = True + await coordinator.refresh_pending() + assert coordinator.pending_takes() == listed + await coordinator.close() + + +async def test_an_output_with_nothing_recorded_lists_nothing(tmp_path): + coordinator = make_coordinator(tmp_path / "never_created") + await coordinator.refresh_pending() + assert coordinator.pending_takes() == () and coordinator.open_session_id() is None + await coordinator.close() diff --git a/examples/egocap/tests/backend/test_readiness_text.py b/examples/egocap/tests/backend/test_readiness_text.py new file mode 100644 index 0000000000..2c5ef2a911 --- /dev/null +++ b/examples/egocap/tests/backend/test_readiness_text.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The sentences the readiness check writes are the only capture reasons that may be passed on.""" + +from __future__ import annotations + +import time +from types import SimpleNamespace + +import pytest + +from egocap_web import app as app_module +from egocap_web import readiness_text +from egocap_web.readiness_text import camera_stale, readiness_sentence + + +@pytest.mark.parametrize( + "sentence", + [ + readiness_text.TRACKING_NOT_ACCEPTED, + readiness_text.CAPTURE_NOT_RUNNING, + readiness_text.TRACKING_STALE, + readiness_text.NO_CAMERA_SELECTED, + readiness_text.TRACKING_UNSUPPORTED, + camera_stale("head_human_camera"), + camera_stale("cam-2.left"), + ], +) +def test_every_sentence_the_backend_writes_is_recognised_with_or_without_what_follows_it(sentence): + assert readiness_sentence(sentence) == sentence + assert readiness_sentence(f"{sentence}; encoder release unconfirmed") == sentence + assert readiness_sentence(f"{sentence}: field 'x' is missing") == sentence + + +@pytest.mark.parametrize( + "text", + [ + "", + "ERROR", + "X_LINK_ERROR device ABC123 disconnected", + "ValueError: invalid literal for int() with base 10: 'abc'", + " capture is not running", + "Capture is not running", + "camera head_human_camera is stale or has no sample yet", + "camera 'head human' is stale or has no sample yet", + "camera '../x' is stale or has no sample yet", + "camera '" + "a" * 65 + "' is stale or has no sample yet", + "camera 'head_human_camera' is stale", + "the camera 'head_human_camera' is stale or has no sample yet", + ], +) +def test_text_that_is_not_one_of_those_sentences_is_not_recognised(text): + assert readiness_sentence(text) is None + + +def _monitor(*, descriptor=object(), running=True, tracking_age=0.0, cameras=(), camera_ages=None): + """A capture monitor as the readiness check reads it, with every fact settable.""" + now = time.monotonic() + camera_ages = camera_ages or {} + preview = SimpleNamespace( + tracking=lambda: None if tracking_age is None else SimpleNamespace(received_monotonic=now - tracking_age), + camera=lambda name: ( + SimpleNamespace(received_monotonic=now - camera_ages[name]) if name in camera_ages else None + ), + ) + return SimpleNamespace( + tracking_descriptor=descriptor, + native=SimpleNamespace(status=SimpleNamespace(running=running), started=None), + preview=preview, + camera_descriptors=tuple(SimpleNamespace(name=name) for name in cameras), + ) + + +def test_the_readiness_check_answers_in_exactly_those_sentences(monkeypatch): + monkeypatch.setattr(app_module, "validate_tracking_descriptor", lambda descriptor: None) + + def reason(**facts): + ready, why = app_module._recording_readiness_check(_monitor(**facts))() + assert not ready + return why + + assert reason(descriptor=None) == "tracking source not yet accepted" + assert reason(running=False) == "capture is not running" + assert reason(tracking_age=None) == "tracking source is stale or has no sample yet" + assert reason(tracking_age=60.0) == "tracking source is stale or has no sample yet" + assert reason() == "no camera selected" + assert reason(cameras=("head_human_camera",)) == "camera 'head_human_camera' is stale or has no sample yet" + stale = reason(cameras=("head_human_camera",), camera_ages={"head_human_camera": 60.0}) + assert stale == "camera 'head_human_camera' is stale or has no sample yet" + for why in (reason(descriptor=None), reason(running=False), reason(tracking_age=None), reason(), stale): + assert readiness_sentence(why) == why + ready = app_module._recording_readiness_check( + _monitor(cameras=("head_human_camera",), camera_ages={"head_human_camera": 0.0}) + )() + assert ready == (True, None) + + +def test_an_unsupported_descriptor_is_recognised_by_its_sentence_and_its_detail_is_not_part_of_it(monkeypatch): + def refuse(descriptor): + raise app_module.RecordingAdapterError("field 'head.position' has shape (4,)") + + monkeypatch.setattr(app_module, "validate_tracking_descriptor", refuse) + ready, why = app_module._recording_readiness_check(_monitor())() + assert (ready, why) == ( + False, + "tracking descriptor unsupported for recording: field 'head.position' has shape (4,)", + ) + assert readiness_sentence(why) == "tracking descriptor unsupported for recording" diff --git a/examples/egocap/tests/backend/test_recording_command.py b/examples/egocap/tests/backend/test_recording_command.py index e26e044032..6ce2c0c571 100644 --- a/examples/egocap/tests/backend/test_recording_command.py +++ b/examples/egocap/tests/backend/test_recording_command.py @@ -504,15 +504,21 @@ def factory() -> ServiceConfig: assert context.revision == before + 1 -async def test_an_unexpected_failure_is_a_rejected_reply_not_a_dead_receiver(tmp_path: Path, monkeypatch): +async def test_an_unexpected_failure_is_a_rejected_reply_not_a_dead_receiver(tmp_path: Path, monkeypatch, caplog): context = await _open_context(tmp_path) async def boom(operator: str = ""): - raise OSError("disk full") + raise OSError(5, "Input/output error", str(tmp_path / "out" / "session" / ".recording")) monkeypatch.setattr(context.coordinator, "start_episode", boom) reply = await handle_recording_command(_command("start_episode", {"batch_id": context.batch_id}), context) - assert reply["outcome"] == "rejected" and "disk full" in reply["reason"] + # The viewer gets a reply with a fixed sentence; what was raised, which names a directory, is in the log. + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "The recording command failed; see the backend log.", + ) + assert str(tmp_path) not in str(reply) + assert "Input/output error" in caplog.text # --- control-token gate ------------------------------------------------------- diff --git a/examples/egocap/tests/backend/test_recording_session.py b/examples/egocap/tests/backend/test_recording_session.py index 489d15138b..e04451ce6f 100644 --- a/examples/egocap/tests/backend/test_recording_session.py +++ b/examples/egocap/tests/backend/test_recording_session.py @@ -931,7 +931,7 @@ def _recovered_result(disposition): ("disposition", "expected_calls"), [(Disposition.KEPT, 1), (Disposition.RECOVERY_REQUIRED, 0), (Disposition.DISCARDED, 0)], ) -async def test_a_recovered_episode_calls_the_kept_hook_only_when_it_was_kept( +async def test_a_recovered_episode_is_always_reported_and_calls_the_kept_hook_only_when_it_was_kept( tmp_path: Path, monkeypatch, disposition, expected_calls ): coordinator = make_coordinator(tmp_path) @@ -946,7 +946,8 @@ async def recover_episode(self, episode_id): coordinator.on_episode_result = results.append monkeypatch.setattr(coordinator, "_require_open", lambda: RecoveringService()) assert await coordinator.recover_episode("s/episode_0") is result - assert kept == [result] * expected_calls and results == [] + # The page learns what became of the take whatever it was; only a kept one goes on to the aligner. + assert kept == [result] * expected_calls and results == [result] async def test_a_recovered_episode_without_a_kept_hook_succeeds(tmp_path: Path, monkeypatch): diff --git a/examples/egocap/tests/backend/test_settings_routes.py b/examples/egocap/tests/backend/test_settings_routes.py index c393ee63f1..147de7d939 100644 --- a/examples/egocap/tests/backend/test_settings_routes.py +++ b/examples/egocap/tests/backend/test_settings_routes.py @@ -9,10 +9,12 @@ from pathlib import Path from types import SimpleNamespace +import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from capture_server import protocol as p +from egocap.recording.capture_qc_policy import load_policy, resolve_policy from egocap_web.app import app as real_app from egocap_web.config import CaptureStatusConfig, VisualizationConfig from egocap_web.settings_routes import EffectiveSettings, router @@ -181,3 +183,113 @@ def test_deployment_snapshot_requires_a_valid_token_before_disclosing_any_values assert response.status_code == 403 assert response.headers["cache-control"] == "no-store" assert response.json() == {"detail": "control token rejected"} + + +def test_the_quality_checks_report_the_thresholds_in_force_and_where_they_came_from(monkeypatch): + _clear_env(monkeypatch) + policy = resolve_policy( + {"guardrails": {"freeze_seconds": 2.0}}, + {"guardrails": {"camera_min_fps_ratio": 0.8, "camera_expected_fps": {"head": 30}}}, + defaults_file="site_checks.yaml", + defaults_sha256="digest-of-the-file", + ) + body = _client(_snapshot(qc_policy=policy)).get("/api/settings").json() + checks = body["quality_checks"] + assert (checks["error"], checks["defaults_file"], checks["defaults_sha256"]) == ( + None, + "site_checks.yaml", + "digest-of-the-file", + ) + assert checks["station_overrides"] == { + "guardrails.camera_expected_fps": {"head": 30.0}, + "guardrails.camera_min_fps_ratio": 0.8, + } + effective = checks["effective"] + assert ( + effective["guardrails"]["camera_min_fps_ratio"] == 0.8 and effective["guardrails"]["freeze_seconds"] == 2.0 + ) + assert effective["guardrails"]["quarantine"] is True + assert effective["guardrails"]["camera_expected_fps"] == {"head": 30.0} + assert effective["duration"] == { + "default": {"min_duration_s": 1.0, "max_duration_s": 600.0}, + "marks_bad": False, + } + assert effective["timestamp"] == {"fps_deviation_pct": 10.0} and effective["resolution"] == {"enabled": True} + + +def test_the_shipped_defaults_file_is_named_by_base_name_and_digest_never_by_its_directory(monkeypatch): + _clear_env(monkeypatch) + checks = _client(_snapshot(qc_policy=load_policy())).get("/api/settings").json()["quality_checks"] + assert checks["defaults_file"] == "data_check_config.yaml" and len(checks["defaults_sha256"]) == 64 + assert checks["station_overrides"] == {} and "/" not in checks["defaults_file"] + + +def test_unreadable_quality_checks_report_the_public_reason_and_no_thresholds(monkeypatch): + _clear_env(monkeypatch) + snapshot = _snapshot(qc_policy=None, qc_error="quality-check configuration is invalid; see backend logs") + assert _client(snapshot).get("/api/settings").json()["quality_checks"] == { + "error": "quality-check configuration is invalid; see backend logs", + "defaults_file": None, + "defaults_sha256": None, + "station_overrides": {}, + "effective": None, + "notices": [], + } + + +@pytest.mark.parametrize( + ("station", "notices"), + [ + ({}, []), + ({"guardrails": {"freeze_seconds": 3.0, "quarantine": False}}, []), + ( + {"guardrails": {"camera_min_fps_enabled": False}}, + ["The camera rate rule is switched off for this station: no take is rejected for a low camera rate."], + ), + ( + {"guardrails": {"camera_min_fps_ratio": 0.01}}, + [ + "The camera rate rule is relaxed for this station: a camera may fall to 0.01 of its expected rate " + "(built in: 0.86)." + ], + ), + ({"guardrails": {"camera_min_fps_ratio": 0.95}}, []), # stricter than built in needs no notice + ( + {"guardrails": {"enabled": False, "camera_min_fps_enabled": False}}, + ["Capture checks are switched off for this station: no take is judged, rejected or marked bad."], + ), + ( + {"guardrails": {"camera_expected_fps": {"head_human_camera": 1.0}}}, + [ + "This station sets its own expected camera rate (head_human_camera at 1 Hz): the camera rate rule " + "judges against that rate, not the camera's declared one." + ], + ), + ( + {"guardrails": {"camera_min_fps_ratio": 0.5, "camera_expected_fps": {"head": 30, "wrist": 15}}}, + [ + "The camera rate rule is relaxed for this station: a camera may fall to 0.5 of its expected rate " + "(built in: 0.86).", + "This station sets its own expected camera rate (head at 30 Hz, wrist at 15 Hz): the camera rate " + "rule judges against that rate, not the camera's declared one.", + ], + ), + ], +) +def test_the_settings_say_when_a_station_does_not_run_the_camera_rate_rule_as_built_in( + monkeypatch, station, notices +): + """Nothing else on the page shows that a station's file stopped rejecting takes for a low camera rate.""" + _clear_env(monkeypatch) + policy = resolve_policy({}, station) + checks = _client(_snapshot(qc_policy=policy)).get("/api/settings").json()["quality_checks"] + assert checks["notices"] == notices + + +def test_a_defaults_file_that_switches_the_rule_off_is_noticed_like_a_stations_own_section(monkeypatch): + _clear_env(monkeypatch) + policy = resolve_policy({"guardrails": {"camera_min_fps_enabled": False}}, {}) + checks = _client(_snapshot(qc_policy=policy)).get("/api/settings").json()["quality_checks"] + assert checks["notices"] == [ + "The camera rate rule is switched off for this station: no take is rejected for a low camera rate." + ] diff --git a/examples/egocap/tests/backend/test_station_config.py b/examples/egocap/tests/backend/test_station_config.py index 60f5f4470d..85951429bd 100644 --- a/examples/egocap/tests/backend/test_station_config.py +++ b/examples/egocap/tests/backend/test_station_config.py @@ -399,3 +399,54 @@ def test_the_accepted_encoder_names_are_exactly_the_writers_kinds(tmp_path): assert resolved.video_encoder == kind with pytest.raises(StationConfigError, match="not supported"): load_station_config(_write(tmp_path, _NAMED + "recording:\n video_encoder: not_a_writer\n")) + + +def test_a_station_without_a_data_check_section_overrides_no_threshold(tmp_path): + assert load_station_config(_write(tmp_path, "meta: {egocap_station_name: Station 01}\n")).data_check is None + assert load_station_config(_write(tmp_path, "data_check:\n")).data_check is None + + +def test_the_data_check_section_is_kept_as_written_once_every_key_is_accepted(tmp_path): + station = load_station_config( + _write( + tmp_path, + """ +stations: + station_01: + data_check: + guardrails: + camera_min_fps_ratio: 0.80 + gloves_expected: true + quarantine: false + camera_expected_fps: {head_human_camera: 60} + duration: + marks_bad: true +""", + ) + ) + assert station.data_check == { + "guardrails": { + "camera_min_fps_ratio": 0.80, + "gloves_expected": True, + "quarantine": False, + "camera_expected_fps": {"head_human_camera": 60}, + }, + "duration": {"marks_bad": True}, + } + + +@pytest.mark.parametrize( + ("section", "named"), + [ + ("{guardrails: {camera_min_fps_rejects: false}}", "unknown key 'guardrails.camera_min_fps_rejects'"), + ("{guardrails: {camera_min_fps_ratio: 1.5}}", "guardrails.camera_min_fps_ratio must be a number > 0"), + ("{guardrails: {quarantine: sometimes}}", "guardrails.quarantine must be true or false"), + ("{guardrails: {camera_expected_fps: {head: 0}}}", "rate for 'head' must be a finite number > 0"), + ("[guardrails]", "must be a mapping"), + ], +) +def test_a_bad_data_check_key_fails_the_station_load_naming_the_station_and_the_key(tmp_path, section, named): + path = _write(tmp_path, f"stations:\n station_07:\n data_check: {section}\n") + with pytest.raises(StationConfigError) as raised: + load_station_config(path) + assert "station 'station_07': data_check: " in str(raised.value) and named in str(raised.value) diff --git a/examples/egocap/tests/backend/test_station_service.py b/examples/egocap/tests/backend/test_station_service.py index 3723308da3..a3e6332f67 100644 --- a/examples/egocap/tests/backend/test_station_service.py +++ b/examples/egocap/tests/backend/test_station_service.py @@ -167,6 +167,24 @@ async def test_renaming_the_station_in_use_carries_its_day_to_the_new_name(tmp_p assert session.events == [] # the label did not change +async def test_a_station_that_is_not_in_use_has_its_rename_recorded_too(tmp_path): + service, session, bench_id, other_id = await _with_two_stations(tmp_path) + other_name = next(s.name for s in service.registry.stations if s.station_id == other_id) + await service.select(bench_id) + session.events.clear() + session.blocked = TAKE_IN_PROGRESS # a take is being recorded on the station in use: this is still allowed + await service.update(other_id, {"name": "Cart Y"}) + # The station in use is untouched: no rotation, no new label. The other station's old name is remembered. + assert service.label() == "Bench A" and session.events == [("renamed", f"{other_name} -> Cart Y")] + session.events.clear() + # With no station in use at all, a rename is recorded as well. + session.blocked = None + await service.select(None) + session.events.clear() + await service.update(bench_id, {"name": "Bench Z"}) + assert session.events == [("renamed", "Bench A -> Bench Z")] + + async def test_a_rename_is_kept_even_when_its_day_cannot_be_carried_over(tmp_path, caplog): service, session, bench_id, _ = await _with_two_stations(tmp_path) await service.select(bench_id) diff --git a/examples/egocap/tests/backend/test_station_uptime.py b/examples/egocap/tests/backend/test_station_uptime.py index f6febb964e..853611bca4 100644 --- a/examples/egocap/tests/backend/test_station_uptime.py +++ b/examples/egocap/tests/backend/test_station_uptime.py @@ -323,8 +323,9 @@ def test_a_renamed_station_keeps_its_day_under_the_new_name(tmp_path): assert (report["active_seconds"], report["notes"]) == (60 + 30 + 40, "typo in the name") assert log.names("Bench A") == frozenset({"Bench A", "Bnech A"}) assert "Bnech A" not in _day_file(tmp_path)["stations"] - log.rename("Never seen", "Whatever") # nothing to carry - assert "Whatever" not in log._payload["stations"] + # A station with no timeline today has no day to carry, and its old name is kept all the same. + log.rename("Never seen", "Whatever") + assert log._payload["stations"]["Whatever"] == {"segments": [], "notes": "", "aliases": ["Never seen"]} def test_a_rename_onto_a_name_used_earlier_today_joins_the_two_histories(tmp_path): @@ -845,3 +846,96 @@ def test_a_take_cut_short_by_a_silence_reaches_the_daily_log(tmp_path): clock.advance(1800) log.observe("Bench A", READY, None) assert _activity(tmp_path, "2026-03-09")["active_station_time_seconds"] == 120.0 + + +def test_every_name_a_station_has_had_is_followed_back_through_the_days(tmp_path): + """A take left under an earlier name is still this station's, however long ago it was renamed.""" + log, clock = _log(tmp_path) + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bnech A") + log.rename("Bnech A", "Bench A") + clock.advance(24 * 3600) # the next day + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bench A") + log.rename("Bench A", "Bench A2") + clock.advance(24 * 3600) # and the day after + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bench A2") + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Cart B") + assert log.names("Bench A2") == frozenset({"Bench A2"}) # today's names alone + assert log.all_names("Bench A2") == frozenset({"Bench A2", "Bench A", "Bnech A"}) + assert log.all_names("Cart B") == frozenset({"Cart B"}) + assert log.all_names("Never seen") == frozenset({"Never seen"}) + # A backend started later reads the same from the day files. + later, _clock = _log(tmp_path, clock) + assert later.all_names("Bench A2") == frozenset({"Bench A2", "Bench A", "Bnech A"}) + # A rename made today is seen without reading the files again. + later.observe("Bench A2", READY, None) + later.rename("Bench A2", "Bench A3") + assert later.all_names("Bench A3") == frozenset({"Bench A3", "Bench A2", "Bench A", "Bnech A"}) + + +def test_the_names_of_earlier_days_are_read_again_when_the_day_changes(tmp_path): + log, clock = _log(tmp_path) + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bench A") + assert log.all_names("Bench A") == frozenset({"Bench A"}) + log.rename("Bench A", "Bench A2") + clock.advance(24 * 3600) + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bench A2") + # Yesterday's rename is in yesterday's file now, and no longer in today's timeline. + assert log.names("Bench A2") == frozenset({"Bench A2"}) + assert log.all_names("Bench A2") == frozenset({"Bench A2", "Bench A"}) + + +def test_a_log_directory_that_cannot_be_listed_gives_the_names_of_today(tmp_path, monkeypatch): + log, clock = _log(tmp_path) + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bench A") + log.rename("Bench A", "Bench A2") + real_glob = type(tmp_path).glob + + def glob(self, pattern): + if pattern == "*_timeline.json": + raise PermissionError(13, "Permission denied") + return real_glob(self, pattern) + + monkeypatch.setattr(type(tmp_path), "glob", glob) + assert log.all_names("Bench A2") == frozenset({"Bench A2", "Bench A"}) + + +def test_a_rename_is_recorded_for_a_station_with_no_timeline_that_day(tmp_path): + """Nothing was observed under the old name today: the station was not used, or is not the one in use.""" + log, clock = _log(tmp_path) + log.rename("Bench A", "Bench A2") + assert log.all_names("Bench A2") == frozenset({"Bench A2", "Bench A"}) + assert log.names("Bench A2") == frozenset({"Bench A2", "Bench A"}) + # The day has no take and no notes, and its file is written all the same: the rename must outlive a restart. + assert _day_file(tmp_path)["stations"]["Bench A2"] == {"segments": [], "notes": "", "aliases": ["Bench A"]} + later, _clock = _log(tmp_path, clock) + assert later.all_names("Bench A2") == frozenset({"Bench A2", "Bench A"}) + # It adds no time to the station's day and no state of its own. + report = later.report("Bench A2") + assert (report["active_seconds"], report["down_seconds"], report["state"]) == (0.0, 0.0, "down") + assert not later.took_today("Bench A2") + + +def test_renames_on_days_without_a_timeline_are_followed_one_after_another(tmp_path): + log, clock = _log(tmp_path) + log.rename("Bnech A", "Bench A") + clock.advance(24 * 3600) + log.rename("Bench A", "Bench A2") + clock.advance(24 * 3600) + # A third day, on which the station is used under its newest name. + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Bench A2") + assert log.all_names("Bench A2") == frozenset({"Bench A2", "Bench A", "Bnech A"}) + restarted, _clock = _log(tmp_path, clock) + assert restarted.all_names("Bench A2") == frozenset({"Bench A2", "Bench A", "Bnech A"}) + + +def test_a_station_renamed_while_another_is_in_use_keeps_the_other_stations_day_as_it_is(tmp_path): + log, clock = _log(tmp_path) + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Cart B") + before = _day_file(tmp_path)["stations"]["Cart B"] + log.rename("Bench A", "Bench A2") # not the station in use, and never observed today + stations = _day_file(tmp_path)["stations"] + assert stations["Cart B"] == before and stations["Bench A2"]["aliases"] == ["Bench A"] + assert log.all_names("Cart B") == frozenset({"Cart B"}) + # The station in use goes on being logged. + _run(log, clock, [(RECORDING, None, 60), (READY, None, 30)], station="Cart B") + assert log.report("Cart B")["active_seconds"] > 0 diff --git a/examples/egocap/tests/backend/test_station_yaml_startup.py b/examples/egocap/tests/backend/test_station_yaml_startup.py index 2aaeecf76a..e4c61f9b29 100644 --- a/examples/egocap/tests/backend/test_station_yaml_startup.py +++ b/examples/egocap/tests/backend/test_station_yaml_startup.py @@ -139,6 +139,131 @@ def test_invalid_station_config_blocks_recording_but_not_capture_preview(monkeyp assert client.get("/api/capture-status").status_code == 200 +def test_an_invalid_qc_file_blocks_recording_but_not_capture_preview(monkeypatch, tmp_path): + monkeypatch.delenv("EGOCAP_STATION_CONFIG", raising=False) + site = tmp_path / "site_checks.yaml" + site.write_text("guardrails:\n camera_min_fps_ratio: 2.0\n", encoding="utf-8") + monkeypatch.setenv("EGOCAP_QC_CONFIG", str(site)) + with TestClient(app_module.app) as client: + ready, reason = client.app.state.recording_context.coordinator._readiness_check() + assert (ready, reason) == (False, "quality-check configuration is invalid; see backend logs") + assert client.app.state.recording_context.snapshot()["not_ready_reason"] == reason + assert str(tmp_path) not in reason + assert client.app.state.settings.qc_policy is None and client.app.state.settings.qc_error == reason + # The preview has nothing to do with the thresholds and stays up. + assert client.get("/api/capture-status").status_code == 200 + + +def test_a_bad_data_check_key_in_the_station_file_blocks_recording_as_a_station_error(monkeypatch, tmp_path): + path = _write_station_yaml(tmp_path, "data_check:\n guardrails:\n freeze_seconds: never\n") + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(path)) + with TestClient(app_module.app) as client: + ready, reason = client.app.state.recording_context.coordinator._readiness_check() + assert (ready, reason) == (False, "station configuration is invalid; see backend logs") + assert client.get("/api/capture-status").status_code == 200 + + +def test_the_stations_data_check_section_reaches_the_recording_config_factory_as_its_policy(monkeypatch, tmp_path): + path = _write_station_yaml( + tmp_path, + "data_check:\n guardrails:\n camera_min_fps_ratio: 0.8\n quarantine: false\n", + ) + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(path)) + monkeypatch.delenv("EGOCAP_QC_CONFIG", raising=False) + seen = _spy_recording_config_factory(monkeypatch) + with TestClient(app_module.app) as client: + assert client.app.state.settings.qc_policy is seen["qc_policy"] + policy = seen["qc_policy"] + assert (policy.camera_min_fps_ratio, policy.quarantine, policy.freeze_seconds) == (0.8, False, 1.0) + assert policy.source.defaults_file == "data_check_config.yaml" + + +def test_no_station_file_judges_takes_by_the_shipped_defaults(monkeypatch): + monkeypatch.delenv("EGOCAP_STATION_CONFIG", raising=False) + monkeypatch.delenv("EGOCAP_QC_CONFIG", raising=False) + seen = _spy_recording_config_factory(monkeypatch) + with TestClient(app_module.app): + pass + assert seen["qc_policy"].quarantine is True and seen["qc_policy"].source.station_overrides == () + + +def test_the_aligner_is_told_the_cameras_only_when_a_session_opens_for_recording(monkeypatch, tmp_path): + path = _write_station_yaml( + tmp_path, f"recording:\n data_dir: {tmp_path / 'out'}\nalignment:\n index_source: head_human_camera\n" + ) + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(path)) + told = [] + real = app_module._recording_config_factory + + def spy(*args, **kwargs): + told.append(args[3]) + return real(*args, **kwargs) + + monkeypatch.setattr(app_module, "_recording_config_factory", spy) + with TestClient(app_module.app): + pass + # One factory records and tells the aligner which cameras the session has; the other only looks at what + # earlier sessions left pending, and must not tell it anything. + assert len(told) == 2 and told[0] is not None and told[1] is None + + +def test_only_the_factory_that_opens_sessions_writes_the_files_a_corrected_runs_sessions_carry(monkeypatch): + monkeypatch.delenv("EGOCAP_STATION_CONFIG", raising=False) + asked = [] + real = app_module._recording_config_factory + + def spy(*args, **kwargs): + asked.append((kwargs["session_files"], kwargs["opens_sessions"])) + return real(*args, **kwargs) + + monkeypatch.setattr(app_module, "_recording_config_factory", spy) + with TestClient(app_module.app) as client: + files = client.app.state.calibration._session_files + # Both are given the run's files, so both name them. The one that only looks at what earlier sessions left + # is built every few seconds, during a take too, and must not look for them: a copy found missing then + # would hold recording in the middle of that take. + assert asked == [(files, True), (files, False)] + + +def test_a_take_an_earlier_run_left_pending_is_listed_once_the_backend_has_started(monkeypatch, tmp_path): + import asyncio + import time + + from tests.backend.qc_takes import make_coordinator, offer, take_frames + + root = tmp_path / "out" + + async def leave_one_pending() -> str: + coordinator = make_coordinator(root) + coordinator.set_task("pour water") + episode = await coordinator.start_episode("alex") + offer(coordinator, take_frames(seconds=0.5)) + coordinator.on_capture_lost("capture is not running") + for _ in range(500): + if coordinator.pending_takes() and coordinator.snapshot().active_operation is None: + break + await asyncio.sleep(0.01) + await coordinator.close() + return episode.episode_id + + episode_id = asyncio.run(leave_one_pending()) + # The same station as the one that recorded the take: another station's sessions are not this one's to list. + path = _write_station_yaml( + tmp_path, f"meta:\n egocap_station_name: Bench A\nrecording:\n data_dir: {root}\n" + ) + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(path)) + with TestClient(app_module.app) as client: + context = client.app.state.recording_context + deadline = time.monotonic() + 10.0 + while not context.snapshot()["pending_takes"] and time.monotonic() < deadline: + time.sleep(0.05) + (pending,) = context.snapshot()["pending_takes"] + assert (pending["episode_id"], pending["current"], pending["phase"]) == (episode_id, False, "WRITING") + assert ( + pending["reason"] == "A capture source stopped while the take was recording: capture is not running." + ) + + def test_unconfigured_station_preserves_existing_development_default(monkeypatch): monkeypatch.delenv("EGOCAP_STATION_CONFIG", raising=False) with TestClient(app_module.app) as client: diff --git a/examples/egocap/tests/backend/test_streams_state.py b/examples/egocap/tests/backend/test_streams_state.py index e45737f66f..07bdd1f7dd 100644 --- a/examples/egocap/tests/backend/test_streams_state.py +++ b/examples/egocap/tests/backend/test_streams_state.py @@ -16,11 +16,14 @@ import pytest +import recording_service.recording_service as service_module from egocap.calibration import rectification_files, station_store from egocap.calibration.files import ROLE_INTRINSICS, ROLE_LENS_INTRINSICS, intrinsics_from_record from egocap.calibration.rectify import OutputGeometry, plan_rectification from egocap_web import app as app_module from egocap_web import streams_state +from egocap_web.recording_command import RecordingContext +from egocap_web.recording_session import RecordingSessionCoordinator from egocap_web.streams_state import ( LENS_CHANGED, SESSION_FILE_MISSING, @@ -34,6 +37,9 @@ streams_state_from_env, streams_unknown, ) +from recording_service import ConfigurationError, Disposition +from tests.backend import qc_takes +from tests.backend.test_takes_left_behind_wire import TOKEN, _lose_capture, _restart, _send from tests.recording.unit.calibration_rectify_helpers import fisheye_intrinsics, fisheye_record HEAD, WRIST = "head_camera", "left_wrist_camera" @@ -412,6 +418,162 @@ def test_the_recorder_is_told_to_copy_the_runs_files_into_every_session_and_to_r assert config.calibration_assets == assets +def test_the_configuration_that_only_looks_at_earlier_sessions_names_the_runs_files_and_writes_none( + tmp_path, monkeypatch, caplog +): + state, directory = corrected_run(tmp_path) + monkeypatch.setattr(app_module, "calibration_dir", lambda: directory) + files, run = SessionFiles(state, lambda: directory), state.path.parent + + def configuration(opens_sessions: bool): + factory = app_module._recording_config_factory + return factory(monitor(), None, tmp_path / "out", session_files=files, opens_sessions=opens_sessions)() + + # It is built every few seconds to list what earlier sessions left: it neither writes a copy nor looks for one. + looking = configuration(False) + assert sorted(path.name for path in run.iterdir()) == ["streams_state.json"] and files.problem is None + # A session about to record needs the copies, and writes them. + recording = configuration(True) + assert all(asset.path.is_file() for asset in recording.calibration_assets if asset.required) + # Both name the same files, so a take of this run is found recorded under the configuration that looks. + assert looking.calibration_assets == recording.calibration_assets + assert service_module._digest(looking) == service_module._digest(recording) + # A lens replaced since, with the run's copy of it gone, is the next session's to be held for: a look says + # nothing of it, and logs nothing however often it is repeated. + (directory / HEAD_FILE).write_bytes(lens_bytes(calibrated_at="2026-03-05T09:00:00+00:00")) + (run / f"session_{HEAD_LENS_FILE}").unlink() + with caplog.at_level(logging.INFO, logger=LOGGER): + assert configuration(False).calibration_assets == recording.calibration_assets + assert files.problem is None and caplog.records == [] + configuration(True) + assert files.problem == LENS_CHANGED.format(name=HEAD_FILE) + + +async def test_a_look_at_earlier_sessions_during_a_take_does_not_hold_the_take_for_a_file_that_went_missing( + tmp_path, monkeypatch +): + """A coordinator wired as the application wires it in a run that corrects the head camera: recording is + held while a file of the run's sessions cannot be had, and what earlier sessions left is read again from + time to time, during a take too.""" + state, directory = corrected_run(tmp_path) + monkeypatch.setattr(app_module, "calibration_dir", lambda: directory) + files, run = SessionFiles(state, lambda: directory), state.path.parent + assert files.ensure() is None + recorded = SimpleNamespace(camera_descriptors=(qc_takes.CAMERA,), native=SimpleNamespace(started=None)) + + def configuration(opens_sessions: bool): + return app_module._recording_config_factory( + recorded, + qc_takes.STATION, + tmp_path / "out", + video_encoder="opencv_mp4v", + session_files=files, + opens_sessions=opens_sessions, + ) + + coordinator = RecordingSessionCoordinator( + configuration(True), + scan_config_factory=configuration(False), + queue_capacity=8192, + readiness_check=app_module._held_without_session_files(files, qc_takes.ALWAYS_READY), + watch_seconds=0.0, + ) + coordinator.set_task("pour water") + episode = await coordinator.start_episode("alex") + frames = qc_takes.take_frames() + qc_takes.offer(coordinator, frames[: len(frames) // 2]) + # While the take records, the station's lens is replaced and the run's copy of it goes away. + (directory / HEAD_FILE).write_bytes(lens_bytes(calibrated_at="2026-03-05T09:00:00+00:00")) + (run / f"session_{HEAD_LENS_FILE}").unlink() + await coordinator.refresh_pending() + qc_takes.offer(coordinator, frames[len(frames) // 2 :]) + # The take was recorded whole in a session that carries the files it opened with: it is kept, not interrupted. + result = await coordinator.stop_episode(episode.episode_id) + assert result.disposition is Disposition.KEPT and files.problem is None + assert (result.final_path.parent / HEAD_LENS_FILE).read_bytes() == lens_bytes() + # The next session is the one that cannot carry the lens: it is refused, and recording is held from then on. + await coordinator.new_batch() + with pytest.raises(ConfigurationError): + await coordinator.start_episode("alex") + assert coordinator.readiness() == (False, LENS_CHANGED.format(name=HEAD_FILE)) + await coordinator.close(final=True) + + +CANNOT_REOPEN = ( + "This take's session cannot be reopened under the current settings: its source declarations or calibration " + "files have changed. The take was left on disk." +) + + +async def test_a_take_left_by_a_run_that_corrected_nothing_is_resolved_only_by_a_run_started_the_same_way( + tmp_path, monkeypatch +): + """Three backends, one after another, over the same recordings: the second corrects the head camera, so its + sessions carry files the first one's session does not hold, and a session is reopened only as it was + recorded.""" + root = tmp_path / "out" + + async def interrupted_take(context) -> str: + started = await _send(context, "start_episode") + qc_takes.offer(context.coordinator, qc_takes.take_frames()[:60]) + await _lose_capture(context) + return started["snapshot"]["current_episode_id"] + + plain = await _restart(root) + uncorrected = await interrupted_take(plain) + await plain.coordinator.close(final=True) + + state, directory = corrected_run(tmp_path) + monkeypatch.setattr(app_module, "calibration_dir", lambda: directory) + files = SessionFiles(state, lambda: directory) + assert files.ensure() is None + recorded = SimpleNamespace(camera_descriptors=(qc_takes.CAMERA,), native=SimpleNamespace(started=None)) + + def configuration(opens_sessions: bool): + return app_module._recording_config_factory( + recorded, + qc_takes.STATION, + root, + video_encoder="opencv_mp4v", + session_files=files, + opens_sessions=opens_sessions, + ) + + coordinator = RecordingSessionCoordinator( + configuration(True), + scan_config_factory=configuration(False), + queue_capacity=8192, + readiness_check=qc_takes.ALWAYS_READY, + watch_seconds=0.0, + ) + coordinator.set_task("pour water") + correcting = RecordingContext(coordinator=coordinator, control_token=TOKEN) + await coordinator.refresh_pending() + # The take is listed, and nothing is done to it: its session does not hold the files this run requires. + (row,) = correcting.snapshot()["pending_takes"] + assert (row["episode_id"], row["current"], row["recoverable"]) == (uncorrected, False, False) + before = qc_takes.tree(root) + for action in ("discard_pending", "recover_pending"): + reply = await _send(correcting, action, episode_id=uncorrected) + assert (reply["outcome"], reply["reason"]) == ("rejected", CANNOT_REOPEN) + assert qc_takes.tree(root) == before + # This run's own takes are resolved as ever, and one it leaves behind is the next backend's to list. + corrected = await interrupted_take(correcting) + await coordinator.close(final=True) + + # Started as the first take was recorded, a backend discards it; the corrected run's take it discards too, + # since the files its session holds are none this run requires. + again = await _restart(root) + assert sorted(row["episode_id"] for row in again.snapshot()["pending_takes"]) == sorted( + [uncorrected, corrected] + ) + for episode_id in (uncorrected, corrected): + reply = await _send(again, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + assert again.snapshot()["pending_takes"] == [] + await again.coordinator.close(final=True) + + def test_a_run_that_corrects_nothing_carries_the_stations_files_and_no_other(tmp_path, monkeypatch): directory = station(tmp_path, lens_bytes()) monkeypatch.setattr(app_module, "calibration_dir", lambda: directory) diff --git a/examples/egocap/tests/backend/test_take_outcome.py b/examples/egocap/tests/backend/test_take_outcome.py new file mode 100644 index 0000000000..aac5620b65 --- /dev/null +++ b/examples/egocap/tests/backend/test_take_outcome.py @@ -0,0 +1,952 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The operator's wording of what became of a take: every sentence the backend can send, and what it never sends. + +The sentences are compared whole, since the page shows them as they arrive. +""" + +from __future__ import annotations + +import dataclasses +from pathlib import Path + +import pytest + +from egocap.recording.dataset_check import CheckResult, Outcome, QualityReport, report_to_dict +from egocap.recording.episode_layout import EpisodeManifest +from egocap_web.take_outcome import ( + OUTCOMES, + describe_manifest, + describe_pending, + describe_result, + public_notes, +) +from recording_service import Disposition, EpisodeResult, PendingEpisode, QcDecision + +ROOT = Path("/data/recordings") +SESSION = "session_20261125-101500_abc123" + + +def _report(*results, warnings=()): + failed = [issue for r in results if r.outcome is not Outcome.PASSED for issue in r.issues] + outcome = Outcome.FAILED if failed else Outcome.PASSED + return QualityReport(outcome, tuple(failed), tuple(warnings), tuple(results)) + + +def _failed(name, issue, **measurements): + return CheckResult(name, Outcome.FAILED, (issue,), (), measurements) + + +def _result(disposition, *, decision=None, capture=None, integrity=None, issues=(), index=3, **paths): + return EpisodeResult( + session_id=SESSION, + episode_id=f"{SESSION}/episode_{index}", + episode_index=index, + disposition=disposition, + final_path=paths.get("final_path"), + pending_path=paths.get("pending_path"), + counts=(), + duration_seconds=12.345, + quality=integrity, + issues=tuple(issues), + qc_decision=decision, + capture_quality=capture, + output_index=paths.get("output_index"), + quarantine_path=paths.get("quarantine_path"), + ) + + +SLOW_CAMERA = _failed( + "camera_min_fps:head_human_camera", + "head_human_camera: 15.50 fps average is below 0.86 x 30.0 = 25.80", + fps=15.5, + minimum_fps=25.8, + expected_fps=30.0, +) +FROZEN_GLOVE = _failed( + "sustained_freeze:manus_glove/left_hand_pose", + "manus_glove/left_hand_pose: no motion for 1.80s (limit 1.0s, eps 1e-06)", + longest_still_s=1.8, + limit_s=1.0, +) +FROZEN_CONTROLLER = _failed( + "sustained_freeze:pico_controller/right_pose", + "pico_controller/right_pose: no motion for 2.25s (limit 1.0s, eps 1e-06)", + longest_still_s=2.25, + limit_s=1.0, +) + + +def test_the_outcomes_are_the_seven_the_page_shows(): + assert OUTCOMES == ( + "kept", + "flagged", + "quarantined", + "rejected", + "rejected_data_kept", + "discarded", + "interrupted", + ) + + +def test_a_kept_take_has_no_reason_and_lists_its_warnings(): + drops = _failed( + "frame_drops:head_human_camera", "raw", window_max=9, total=14, window_s=2.0, expected_fps=30.0 + ) + capture = _report(CheckResult("camera_min_fps:head_human_camera", Outcome.PASSED), drops) + described = describe_result( + _result( + Disposition.KEPT, decision=QcDecision.PASSED, capture=capture, final_path=ROOT / SESSION / "episode_3" + ) + ) + assert described == { + "episode_id": f"{SESSION}/episode_3", + "disposition": "KEPT", + "outcome": "kept", + "qc_decision": "PASSED", + "reasons": [], + "warnings": ["Camera head_human_camera dropped 9 frames within 2 s (14 in the whole take)."], + "media_removed": False, + "location": f"{SESSION}/episode_3", + "issues": [], + "duration_ms": 12345, + } + + +def test_a_take_kept_without_any_check_is_kept_with_a_skipped_decision(): + described = describe_result( + _result(Disposition.KEPT, decision=QcDecision.SKIPPED, final_path=ROOT / SESSION / "episode_3") + ) + assert (described["outcome"], described["qc_decision"], described["reasons"]) == ("kept", "SKIPPED", []) + + +def test_a_flagged_take_says_which_stream_froze_for_how_long_against_which_limit_and_what_to_check(): + described = describe_result( + _result( + Disposition.KEPT, + decision=QcDecision.FLAGGED_BAD, + capture=_report(FROZEN_GLOVE, FROZEN_CONTROLLER), + final_path=ROOT / SESSION / "episode_3", + ) + ) + assert (described["outcome"], described["disposition"], described["media_removed"]) == ( + "flagged", + "KEPT", + False, + ) + assert described["reasons"] == [ + "The left glove did not move for 1.8 s (limit 1 s). Check the glove's battery and connection.", + "The right controller did not move for 2.2 s (limit 1 s). " + "Check that the headset and both controllers are on, charged and in view.", + ] + + +def test_a_quarantined_take_carries_the_same_reasons_and_its_place_in_the_quarantine_folder(): + described = describe_result( + _result( + Disposition.QUARANTINED, + decision=QcDecision.FLAGGED_BAD, + capture=_report(FROZEN_GLOVE), + quarantine_path=ROOT / "_quarantine" / SESSION / "episode_3", + ) + ) + assert (described["outcome"], described["disposition"]) == ("quarantined", "QUARANTINED") + assert described["location"] == f"_quarantine/{SESSION}/episode_3" and described["media_removed"] is False + assert described["reasons"] == [ + "The left glove did not move for 1.8 s (limit 1 s). Check the glove's battery and connection." + ] + + +def test_a_camera_rejection_names_each_failing_camera_with_its_rate_and_the_limit(): + other = _failed("camera_min_fps:wrist_camera", "raw", fps=41.26, minimum_fps=51.6, expected_fps=60.0) + described = describe_result( + _result( + Disposition.REJECTED, + decision=QcDecision.REJECTED_CAMERA, + capture=_report(SLOW_CAMERA, other, FROZEN_GLOVE), + ) + ) + assert (described["outcome"], described["media_removed"], described["location"]) == ("rejected", True, None) + assert described["reasons"] == [ + "Camera head_human_camera averaged 15.5 fps, below the minimum of 25.8 fps (0.86 of 30 fps). " + "Check the camera's cable and the load on this PC, then record the take again.", + "Camera wrist_camera averaged 41.3 fps, below the minimum of 51.6 fps (0.86 of 60 fps). " + "Check the camera's cable and the load on this PC, then record the take again.", + ] + + +def test_a_frame_count_rejection_and_a_tracking_source_with_no_row_are_worded_too(): + parity = _failed("camera_frame_parity", "camera frame-count spread 60 exceeds 50: a=100, b=160", a=100, b=160) + rejected = describe_result( + _result(Disposition.REJECTED, decision=QcDecision.REJECTED_CAMERA, capture=_report(parity)) + ) + assert rejected["reasons"] == ["camera frame-count spread 60 exceeds 50: a=100, b=160"] + empty = _failed("tracking_gap:manus_glove", "raw", longest_gap_s=0.0, limit_s=1.0, rows=0) + flagged = describe_result( + _result( + Disposition.KEPT, decision=QcDecision.FLAGGED_BAD, capture=_report(empty), final_path=ROOT / "s" / "e" + ) + ) + assert flagged["reasons"] == [ + "The gloves recorded no row in the whole take. Check the glove's battery and connection." + ] + + +def test_an_integrity_rejection_keeps_the_data_and_gives_the_integrity_finding(): + integrity = QualityReport( + Outcome.FAILED, + ("manus_glove: required source has no rows",), + (), + (CheckResult("required_sources_nonempty", Outcome.FAILED, ("manus_glove: required source has no rows",)),), + ) + described = describe_result( + _result( + Disposition.REJECTED, + decision=QcDecision.SKIPPED, + integrity=integrity, + pending_path=ROOT / SESSION / "episode_3.pending", + ) + ) + assert (described["outcome"], described["media_removed"]) == ("rejected_data_kept", False) + assert described["location"] == f"{SESSION}/episode_3.pending" + assert described["reasons"] == [ + "The recorded data failed an integrity check: manus_glove: required source has no rows." + ] + + +def test_a_discarded_take_has_no_reason_and_its_media_is_gone(): + described = describe_result(_result(Disposition.DISCARDED)) + assert (described["outcome"], described["media_removed"], described["location"]) == ("discarded", True, None) + assert described["reasons"] == [] and described["qc_decision"] is None + + +def test_an_interrupted_take_gives_the_recorders_reason_as_a_fixed_sentence(): + described = describe_result( + _result( + Disposition.RECOVERY_REQUIRED, + issues=( + "recording pipeline failed during recording: capture lost: camera 'head_human_camera' is stale " + "or has no sample yet", + ), + pending_path=ROOT / SESSION / "episode_3.pending", + ) + ) + assert (described["outcome"], described["disposition"]) == ("interrupted", "RECOVERY_REQUIRED") + assert described["reasons"] == [ + "A capture source stopped while the take was recording: camera 'head_human_camera' is stale or has no " + "sample yet." + ] + assert described["issues"] == described["reasons"] and described["media_removed"] is False + + +def test_an_interrupted_take_with_no_note_still_has_a_reason(): + described = describe_result(_result(Disposition.RECOVERY_REQUIRED)) + assert described["reasons"] == ["The recorder reported a problem; see the backend log."] + + +def test_a_routed_take_is_located_at_its_slot_under_its_studio(): + described = describe_result( + _result( + Disposition.KEPT, + decision=QcDecision.PASSED, + final_path=ROOT / "Kitchen" / "2026-11-25-10-15-00" / "episode_7", + output_index=7, + ) + ) + assert described["location"] == "Kitchen/2026-11-25-10-15-00/episode_7" + + +@pytest.mark.parametrize( + ("result", "sentence"), + [ + ( + _failed("tracking_gap:pico_controller", "raw", longest_gap_s=1.52, limit_s=1.0, rows=240), + "The headset and controllers sent no data for 1.5 s (limit 1 s). " + "Check that the headset and both controllers are on, charged and in view.", + ), + ( + _failed("tracking_gap:manus_glove", "raw", longest_gap_s=0.0, limit_s=1.0, rows=1), + "The gloves recorded 1 row in the whole take. Check the glove's battery and connection.", + ), + ( + _failed("duration", "raw", duration_s=0.42, min_s=1.0, max_s=600.0), + "The take lasted 0.4 s; the limits are 1 s to 600 s.", + ), + ( + _failed("sustained_freeze:pico_controller/head_pose", "raw", longest_still_s=3.0, limit_s=1.5), + "The headset did not move for 3.0 s (limit 1.5 s). " + "Check that the headset and both controllers are on, charged and in view.", + ), + ( + _failed("sustained_freeze:other_source/pose", "raw", longest_still_s=3.0, limit_s=1.0), + "The other_source/pose did not move for 3.0 s (limit 1 s).", + ), + ( + _failed( + "avatar_hand_liveness:glove/left", "glove left hand: 0 live states (dead or disconnected glove)" + ), + "glove left hand: 0 live states (dead or disconnected glove)", + ), + (CheckResult("pico_body_joints:pico", Outcome.FAILED), "The pico_body_joints check failed."), + ], +) +def test_each_gate_that_marks_a_take_bad_has_its_own_sentence(result, sentence): + described = describe_result( + _result( + Disposition.KEPT, decision=QcDecision.FLAGGED_BAD, capture=_report(result), final_path=ROOT / "s" / "e" + ) + ) + assert described["reasons"] == [sentence] + + +@pytest.mark.parametrize( + ("result", "sentence"), + [ + ( + _failed("flat_motion:pico_controller/head_pose", "raw", longest_still_s=3.98, limit_s=2.0), + "The headset barely moved for 4.0 s (limit 2 s).", + ), + ( + _failed("dead_stream:manus_glove/right_hand_pose", "raw", std_mean=0.0, frac_identical=1.0), + "The right glove did not change for the whole take.", + ), + ( + _failed("zero_pose:manus_glove/left_hand_pose", "raw", zero_rows=12, rows=480), + "The left glove has a zeroed pose in 12 of 480 rows.", + ), + ( + _failed( + "camera_fps_deviation:head_human_camera", + "raw", + fps=23.95, + expected_fps=30.0, + deviation_pct=20.2, + limit_pct=10.0, + ), + "Camera head_human_camera averaged 23.9 fps, 20% below its declared 30 fps.", + ), + ( + _failed( + "camera_fps_deviation:head_human_camera", + "raw", + fps=60.0, + expected_fps=30.0, + deviation_pct=100.0, + limit_pct=10.0, + ), + "Camera head_human_camera averaged 60.0 fps, 100% above its declared 30 fps.", + ), + ( + _failed( + "resolution:head_human_camera", + "raw", + width=640, + height=480, + expected_width=1280, + expected_height=720, + ), + "Camera head_human_camera was encoded at 640x480, not the declared 1280x720.", + ), + ( + _failed("tracking_gap_warning:pico_controller", "raw", longest_gap_s=1.2, limit_s=1.0, rows=200), + "The headset and controllers sent no data for 1.2 s (limit 1 s). " + "Check that the headset and both controllers are on, charged and in view.", + ), + ( + _failed("duration_warning", "raw", duration_s=700.0, min_s=1.0, max_s=600.0), + "The take lasted 700.0 s; the limits are 1 s to 600 s.", + ), + ], +) +def test_each_warning_has_its_own_sentence(result, sentence): + described = describe_result( + _result(Disposition.KEPT, decision=QcDecision.PASSED, capture=_report(result), final_path=ROOT / "s" / "e") + ) + assert described["warnings"] == [sentence] and described["reasons"] == [] + + +def test_a_check_that_could_not_run_is_named_without_what_it_raised(): + raised = "resolution:head_human_camera could not run: OSError: [Errno 5] /data/recordings/s/e.pending/x.mp4" + errored = CheckResult("resolution:head_human_camera", Outcome.ERROR, (raised,)) + whole = CheckResult("duration_warning", Outcome.ERROR, ("duration_warning could not run: KeyError: 'x'",)) + described = describe_result( + _result( + Disposition.KEPT, + decision=QcDecision.PASSED, + capture=_report(errored, whole), + final_path=ROOT / "s" / "e", + ) + ) + assert described["warnings"] == [ + "The resolution check could not run for head_human_camera.", + "The duration_warning check could not run.", + ] + assert "/data" not in " ".join(described["warnings"]) + + +def test_a_report_stored_without_the_measurements_a_sentence_reads_falls_back_to_the_checkers_finding(): + old = _failed("sustained_freeze:pico_controller/head_pose", "pico_controller/head_pose: no motion for 2.00s") + described = describe_result( + _result( + Disposition.KEPT, decision=QcDecision.FLAGGED_BAD, capture=_report(old), final_path=ROOT / "s" / "e" + ) + ) + assert described["reasons"] == ["pico_controller/head_pose: no motion for 2.00s"] + + +@pytest.mark.parametrize( + ("note", "sentence"), + [ + ( + "recording pipeline failed before stop: capture lost: capture is not running", + "A capture source stopped while the take was recording: capture is not running.", + ), + ( + "recording pipeline failed during recording: capture lost: connection to ws://10.0.0.5:8082/ closed", + "A capture source stopped while the take was recording.", + ), + ( + "recording pipeline failed during recording: capture lost: " + "x" * 200, + "A capture source stopped while the take was recording.", + ), + ( + "recording pipeline failed during recording: queue overflow at /tmp/x", + "The recording pipeline failed while the take was recording; see the backend log.", + ), + ( + "write failed: [Errno 28] No space left on device: '/data/recordings/s/e.pending/cam.mp4'", + "Writing the take to disk failed; see the backend log.", + ), + ( + "count mismatch: cam: accepted 10, sealed 9", + "Not every accepted sample was written, so the take is incomplete.", + ), + ( + "quality check errored: cannot open staged dataset: /data/x", + "The integrity check could not read the take; see the backend log.", + ), + ( + "capture quality check errored: camera_min_fps:cam could not run: KeyError", + "A capture check could not run; recover the take to run the checks again.", + ), + ( + "the take was written and sealed, but its SEALED manifest could not be saved (disk full); it cannot " + "be resumed, so discard it with discard_pending and record again", + "The take was written but its record could not be saved.", + ), + ( + "checked step failed: [Errno 13] Permission denied: '/data/recordings/_quarantine'", + "Finishing the take failed part-way; see the backend log.", + ), + ("sealed step failed: unreadable", "Finishing the take failed part-way; see the backend log."), + ( + "discard failed: /data/recordings/s/episode_0 is finalized output", + "Discarding the take failed part-way; discard it again.", + ), + ("start failed: [Errno 2] /data", "The take failed to start; see the backend log."), + ( + "encoder release unconfirmed; data kept, restart the recorder", + "A video encoder did not confirm that it stopped; restart the backend before recording again.", + ), + ( + "interrupted while writing; completeness cannot be established", + "The recorder stopped while this take was being written.", + ), + ("recorded with a different configuration", "This take was recorded under different settings."), + ( + "group totals were not refreshed: /data/recordings/Kitchen/x/zarr.json is unreadable", + "The folder's totals were not refreshed; the next take recomputes them.", + ), + ( + "something nobody wrote a sentence for: /etc/passwd", + "The recorder reported a problem; see the backend log.", + ), + ], +) +def test_every_recorder_note_becomes_a_fixed_sentence_and_its_own_text_is_never_sent(note, sentence): + assert public_notes([note]) == [sentence] + assert "/data" not in sentence and "/tmp" not in sentence and "/etc" not in sentence + + +def test_recorder_notes_keep_their_order_and_are_not_repeated(): + notes = ["checked step failed: a", "write failed: b", "finalized step failed: c"] + assert public_notes(notes) == [ + "Finishing the take failed part-way; see the backend log.", + "Writing the take to disk failed; see the backend log.", + ] + + +def _pending(phase, *, recoverable, finalization=None, issues=(), recorded=(), **flags): + return PendingEpisode( + SESSION, + f"{SESSION}/episode_4", + 4, + ROOT / SESSION / "episode_4.pending", + phase, + recoverable, + tuple(issues), + "pour water", + "alex", + 7.5, + tuple(recorded), + finalization, + **flags, + ) + + +def test_a_pending_take_cut_off_while_writing_can_only_be_discarded_and_says_why(): + pending = _pending( + "WRITING", + recoverable=False, + recorded=("recording pipeline failed during recording: capture lost: capture is not running",), + issues=("interrupted while writing; completeness cannot be established",), + ) + assert describe_pending(pending, current=True) == { + "episode_id": f"{SESSION}/episode_4", + "session_id": SESSION, + "index": 4, + "phase": "WRITING", + "recoverable": False, + "recoverable_known": True, + "discardable": True, + "current": True, + "reason": "A capture source stopped while the take was recording: capture is not running.", + "recover_note": "This take was cut off while it was being written, so it is incomplete. " + "It can only be discarded.", + "task": "pour water", + "operator": "alex", + "duration_ms": 7500, + } + + +def test_a_take_left_by_a_killed_recorder_has_no_note_and_still_a_reason(): + pending = _pending( + "WRITING", recoverable=False, issues=("interrupted while writing; completeness cannot be established",) + ) + assert describe_pending(pending, current=False)["reason"] == ( + "The recorder stopped while this take was being written." + ) + assert describe_pending(_pending("SEALED", recoverable=True), current=False)["reason"] == ( + "The take was interrupted before it was finished." + ) + + +@pytest.mark.parametrize( + ("phase", "recoverable", "finalization", "note"), + [ + ("SEALED", True, None, "Recover runs the checks on this take and finishes it."), + ("CHECKED", True, "KEEP", "Recover finishes saving this take."), + ("CHECKED", True, "QUARANTINE", "Recover finishes setting this take aside in quarantine."), + ("CHECKED", True, "REMOVE", "The camera check rejected this take. Recover finishes removing its media."), + ( + "CHECKED", + True, + "RETAIN", + "The integrity check failed. Recover closes this take and leaves its data on disk.", + ), + ("CHECKED", True, "SOMETHING_NEWER", "Recover finishes this take."), + ( + "SEALED", + False, + None, + "This take can be finished once the station is set up as when it was recorded: the same cameras and " + "settings.", + ), + ], +) +def test_a_pending_take_says_what_recover_would_do_or_why_it_is_not_offered( + phase, recoverable, finalization, note +): + pending = _pending(phase, recoverable=recoverable, finalization=finalization) + assert describe_pending(pending, current=False)["recover_note"] == note + + +def _manifest(phase, **fields): + return EpisodeManifest( + session_id=SESSION, + episode_id=f"{SESSION}/episode_2", + episode_index=2, + config_digest="d", + task="t", + operator="o", + sources=[], + pending_path="episode_2.pending", + final_path="episode_2", + storage_phase=phase, + **fields, + ) + + +def test_the_days_summary_words_a_take_as_the_page_did_after_it(): + passed = {"outcome": "PASSED", "issues": [], "warnings": [], "check_results": []} + quarantined = _manifest( + "QUARANTINED", + quality=passed, + capture_quality=report_to_dict(_report(FROZEN_GLOVE)), + qc_decision="FLAGGED_BAD", + finalization="QUARANTINE", + ) + assert describe_manifest(quarantined) == { + "reasons": [ + "The left glove did not move for 1.8 s (limit 1 s). Check the glove's battery and connection." + ], + "warnings": [], + "issues": [], + "media_removed": False, + } + rejected = _manifest( + "REJECTED", + quality=passed, + capture_quality=report_to_dict(_report(SLOW_CAMERA)), + qc_decision="REJECTED_CAMERA", + finalization="REMOVE", + ) + described = describe_manifest(rejected) + assert described["media_removed"] is True and described["reasons"][0].startswith( + "Camera head_human_camera averaged 15.5 fps, below the minimum of 25.8 fps" + ) + + +def test_the_days_summary_gives_a_pending_takes_notes_as_its_reason_and_a_resolved_takes_only_as_notes(): + note = "checked step failed: [Errno 28] /data/recordings/x" + pending = describe_manifest(_manifest("CHECKED", issues=[note], finalization="KEEP")) + assert pending["reasons"] == ["Finishing the take failed part-way; see the backend log."] + kept = describe_manifest(_manifest("FINALIZED", issues=[note], finalization="KEEP")) + assert kept["reasons"] == [] and kept["issues"] == ["Finishing the take failed part-way; see the backend log."] + assert describe_manifest(_manifest("DISCARDED"))["media_removed"] is True + integrity = {"outcome": "FAILED", "issues": ["cam: mp4 missing"], "warnings": [], "check_results": []} + kept_data = describe_manifest(_manifest("REJECTED", quality=integrity, finalization="RETAIN")) + assert kept_data["media_removed"] is False + assert kept_data["reasons"] == ["The recorded data failed an integrity check: cam: mp4 missing."] + + +# --- text from outside the backend never reaches the page ----------------------------------- + + +@pytest.mark.parametrize( + "detail", + [ + "head_human_camera: X_LINK_ERROR device ABC123 at 192.0.2.7 disconnected", + "ValueError: invalid literal for int() with base 10: 'abc'", + "ERROR", + "unconfirmed", + "camera 'head_human_camera' is stale", # close to a readiness sentence, and not one + "Capture is not running", + "camera '../../etc' is stale or has no sample yet", + "camera 'a b' is stale or has no sample yet", + ], +) +def test_a_capture_reason_the_backend_did_not_write_is_replaced_by_the_fixed_sentence(detail): + for note in ( + f"recording pipeline failed before stop: capture lost: {detail}", + f"recording pipeline failed during recording: capture lost: {detail}", + ): + assert public_notes([note]) == ["A capture source stopped while the take was recording."] + pending = _pending( + "WRITING", recoverable=False, recorded=(f"recording pipeline failed: capture lost: {detail}",) + ) + described = describe_pending(pending, current=True) + assert described["reason"] == "A capture source stopped while the take was recording." + assert detail not in str(described) + + +@pytest.mark.parametrize( + ("detail", "said"), + [ + ("tracking source not yet accepted", "tracking source not yet accepted"), + ("capture is not running", "capture is not running"), + ("tracking source is stale or has no sample yet", "tracking source is stale or has no sample yet"), + ("no camera selected", "no camera selected"), + ( + "camera 'head_human_camera' is stale or has no sample yet", + "camera 'head_human_camera' is stale or has no sample yet", + ), + # What follows the sentence was not written for the page and is dropped. + ( + "tracking descriptor unsupported for recording: field 'head.position' has shape (4,)", + "tracking descriptor unsupported for recording", + ), + ("capture is not running; and then some", "capture is not running"), + ], +) +def test_a_capture_reason_is_passed_on_only_as_the_readiness_sentence_it_begins_with(detail, said): + note = f"recording pipeline failed during recording: capture lost: {detail}" + assert public_notes([note]) == [f"A capture source stopped while the take was recording: {said}."] + + +def test_a_note_about_an_encoder_is_said_as_well_as_the_note_it_was_appended_to(): + """The recorder appends it to whatever note it was writing; it must not be lost behind that note.""" + restart = "A video encoder did not confirm that it stopped; restart the backend before recording again." + stale = "camera 'head_human_camera' is stale or has no sample yet" + assert public_notes( + [f"recording pipeline failed before stop: capture lost: {stale}; encoder release unconfirmed"] + ) == [f"A capture source stopped while the take was recording: {stale}.", restart] + assert public_notes(["write failed: boom; encoder release failed: [Errno 5] /data/x"]) == [ + "Writing the take to disk failed; see the backend log.", + restart, + ] + assert public_notes(["checked step failed: io; encoder release unconfirmed"]) == [ + "Finishing the take failed part-way; see the backend log.", + restart, + ] + assert public_notes(["something else; encoder release unconfirmed"]) == [ + "The recorder reported a problem; see the backend log.", + restart, + ] + assert public_notes(["encoder release unconfirmed; data kept, restart the recorder"]) == [restart] + described = describe_result( + _result( + Disposition.RECOVERY_REQUIRED, + issues=(f"recording pipeline failed before stop: capture lost: {stale}; encoder release unconfirmed",), + pending_path=ROOT / "s" / "e.pending", + ) + ) + assert described["reasons"][-1] == restart and described["issues"][-1] == restart + + +# --- the rows that are not an ordinary pending take --------------------------------------------- + + +def test_a_complete_take_held_back_by_the_settings_says_what_it_needs_and_never_to_discard_it(): + for phase, finalization in (("SEALED", None), ("CHECKED", "KEEP"), ("CHECKED", "QUARANTINE")): + pending = _pending( + phase, + recoverable=False, + finalization=finalization, + issues=("recorded with a different configuration",), + ) + described = describe_pending(pending, current=False) + assert (described["recoverable"], described["recoverable_known"]) == (False, True) + assert described["discardable"] is True + assert described["recover_note"] == ( + "This take can be finished once the station is set up as when it was recorded: the same cameras and " + "settings." + ) + assert "discard" not in (described["recover_note"] + described["reason"]).lower() + # While no camera is accepted the settings cannot be compared: nothing is said either way. + unknown = describe_pending(pending, current=False, cameras_known=False) + assert (unknown["recoverable"], unknown["recoverable_known"]) == (False, False) + assert unknown["discardable"] is True + assert ( + unknown["recover_note"] == "Whether this take can be finished is known once the cameras are connected." + ) + + +def test_what_does_not_depend_on_the_cameras_is_said_whether_or_not_one_is_accepted(): + writing = _pending( + "WRITING", recoverable=False, issues=("interrupted while writing; completeness cannot be established",) + ) + ready = _pending("CHECKED", recoverable=True, finalization="KEEP") + for pending in (writing, ready): + assert describe_pending(pending, current=False, cameras_known=False) == describe_pending( + pending, current=False + ) + + +def test_a_take_rejected_for_integrity_says_its_state_and_offers_discard_only(): + pending = _pending( + "REJECTED", + recoverable=False, + finalization="RETAIN", + issues=("rejected by the integrity check; its data was kept",), + recorded=("group totals were not refreshed: x",), + ) + described = describe_pending(pending, current=False) + assert (described["phase"], described["recoverable"], described["discardable"]) == ("REJECTED", False, True) + assert described["reason"] == "This take failed its integrity check; its data was kept on disk." + assert described["recover_note"] == ( + "This take failed its integrity check and cannot be recovered. Discard removes its data." + ) + + +def test_a_take_whose_discard_began_says_so_and_offers_discard_only(): + pending = _pending( + "SEALED", + recoverable=False, + issues=("discard failed: [Errno 5] /data/x", "a discard of this take was started and did not finish"), + discard_requested=True, + ) + described = describe_pending(pending, current=True) + assert (described["recoverable"], described["discardable"]) == (False, True) + assert described["reason"] == "A discard of this take was started and did not finish." + assert described["recover_note"] == ( + "A discard of this take was started, so its data may be incomplete. Discard it again to finish." + ) + # Not a matter of the cameras: it is said the same while none is accepted. + assert describe_pending(pending, current=True, cameras_known=False) == described + assert public_notes(pending.issues) == [ + "Discarding the take failed part-way; discard it again.", + "A discard of this take was started and did not finish.", + ] + + +def test_a_record_found_in_another_sessions_directory_offers_nothing(): + pending = _pending( + "WRITING", + recoverable=False, + issues=("written for another session; this session directory was copied or renamed",), + recorded=("recording pipeline failed during recording: capture lost: capture is not running",), + misplaced=True, + ) + described = describe_pending(pending, current=False) + assert (described["recoverable"], described["discardable"]) == (False, False) + assert described["reason"] == ( + "This take's record was written for another session: its folder was copied or renamed by hand." + ) + # What to do about it, in a sentence; without the session's name when the record does not give it. + assert described["recover_note"] == ( + "Nothing is done with this take from this page. On the recordings disk, delete its folder if it is a " + "copy, or give the folder back the name it had before if it was renamed." + ) + assert public_notes(pending.issues) == [described["reason"]] + named = describe_pending( + dataclasses.replace(pending, written_for="session_20261126-081500_abc123"), current=False + ) + assert named["recover_note"] == ( + "Nothing is done with this take from this page. On the recordings disk, delete its folder if it is a " + "copy, or give the folder back the name session_20261126-081500_abc123 if it was renamed." + ) + + +def test_the_days_summary_says_a_rejected_takes_data_is_gone_once_its_discard_was_asked_for(): + failed = {"outcome": "FAILED", "issues": ["cam: no rows"], "warnings": [], "check_results": []} + kept = _manifest("REJECTED", quality=failed, finalization="RETAIN") + assert describe_manifest(kept)["media_removed"] is False + asked = _manifest("REJECTED", quality=failed, finalization="RETAIN", discard_requested=True) + assert describe_manifest(asked)["media_removed"] is True + + +def test_a_take_too_short_for_a_rate_says_how_many_frames_in_how_long_and_that_the_rule_did_not_judge_it(): + def warning(frames, span): + result = _failed( + "camera_rate_measurable:head_human_camera", "too short", frames=frames, span_s=span, needed_s=1 / 3 + ) + report = _report(result, warnings=("too short",)) + kept = _result(Disposition.KEPT, decision=QcDecision.PASSED, capture=report, final_path=ROOT / "s" / "e") + return describe_result(kept)["warnings"] + + assert warning(1, 0.0) == [ + "Camera head_human_camera recorded 1 frame in 0.00 s, too short to measure its rate (that takes 0.33 s), " + "so the camera rate rule did not judge this take." + ] + assert warning(7, 0.2333)[0].startswith("Camera head_human_camera recorded 7 frames in 0.23 s, too short") + + +# --- the one fact about the disk, and a discard that was refused --------------------------------- + +FULL = "The recordings disk is full. Free space, then record again." +QUOTA = "The disk quota for the recordings is used up. Free space or raise the quota, then record again." +READ_ONLY = "The recordings folder is read-only. Make it writable, then record again." +DENIED = "The backend may not write to the recordings folder. Fix its permissions, then record again." + + +@pytest.mark.parametrize( + ("note", "sentences"), + [ + ( + "write failed [storage: full]: [Errno 28] No space left on device: '/data/recordings/s/cam.mp4'", + ["Writing the take to disk failed; see the backend log.", FULL], + ), + ( + "checked step failed [storage: quota]: [Errno 122] Disk quota exceeded: '/data/recordings/s'", + ["Finishing the take failed part-way; see the backend log.", QUOTA], + ), + ( + "start failed [storage: read-only]: [Errno 30] Read-only file system: '/data/recordings/s'", + ["The take failed to start; see the backend log.", READ_ONLY], + ), + ( + "discard failed [storage: denied]: [Errno 13] Permission denied: '/data/recordings/s/e.pending'", + ["Discarding the take failed part-way; discard it again.", DENIED], + ), + ( + "the take was written and sealed [storage: full], but its SEALED manifest could not be saved " + "([Errno 28] No space left on device); it cannot be resumed, so discard it with discard_pending and " + "record again", + ["The take was written but its record could not be saved.", FULL], + ), + ( + "sealed step failed [storage: full]: [Errno 28] No space left; encoder release unconfirmed", + [ + "Finishing the take failed part-way; see the backend log.", + FULL, + "A video encoder did not confirm that it stopped; restart the backend before recording again.", + ], + ), + ], +) +def test_a_note_that_carries_the_recorders_word_for_the_disk_says_it_in_a_sentence(note, sentences): + assert public_notes([note]) == sentences + assert "/data" not in " ".join(sentences) and "Errno" not in " ".join(sentences) + + +@pytest.mark.parametrize( + "note", + [ + # The system's text says the disk is full; the recorder did not, so nothing is concluded from it. + "write failed: [Errno 28] No space left on device: '/data/recordings/s/cam.mp4'", + "checked step failed: could not write '/data/x [storage: full]/y'", + "write failed: boom [storage: full]", + "write failed [storage: something-new]: x", + "recording pipeline failed during recording: write failed [storage: full]: x", + ], +) +def test_the_disk_is_named_only_from_the_recorders_own_mark_at_the_head_of_a_note(note): + assert not {FULL, QUOTA, READ_ONLY, DENIED} & set(public_notes([note])) + + +def test_a_discard_that_was_refused_is_not_called_a_discard_to_repeat(): + saved = "discard refused: the take is already in its final place; recover it to finish" + assert public_notes([saved]) == [ + "This take is already saved; only its last record is missing. Use Recover to finish it." + ] + foreign = "discard refused: the directory under the take's name is not the take's own" + assert public_notes([foreign]) == [ + "The folder under this take's name is not the take's own, so nothing was removed. It has to be looked at " + "by hand; see the backend log." + ] + assert "discard it again" not in " ".join(public_notes([saved, foreign])) + assert public_notes(["discard failed: [Errno 5] /data/x"]) == [ + "Discarding the take failed part-way; discard it again." + ] + + +def _camera_reasons(**measurements): + """The reasons of a take rejected by the camera rule, from what the rule stored about the camera.""" + result = _failed( + "camera_min_fps:head_human_camera", + "the finding as the checker wrote it", + minimum_fps=25.8, + expected_fps=30.0, + **measurements, + ) + rejected = _result(Disposition.REJECTED, decision=QcDecision.REJECTED_CAMERA, capture=_report(result)) + return describe_result(rejected)["reasons"] + + +def test_a_camera_that_recorded_a_part_of_the_take_says_how_many_frames_and_how_many_the_take_holds(): + check = "Check the camera's cable and the load on this PC, then record the take again." + counted = dict(span_s=0.0, take_s=1.5, take_frames=45.0, needed_frames=36.12) + assert _camera_reasons(frames=1, **counted) == [ + f"Camera head_human_camera recorded 1 frame; a take of 1.5 s holds about 45. {check}" + ] + # Its rate while it ran was fine, so the rate is not what the operator is told. + ran_a_ninth = dict(fps=30.0, frames=11, span_s=0.333, take_s=3.0, take_frames=90.0, needed_frames=74.82) + assert _camera_reasons(**ran_a_ninth) == [ + f"Camera head_human_camera recorded 11 frames; a take of 3.0 s holds about 90. {check}" + ] + + +def test_a_camera_that_was_slow_while_it_ran_is_told_its_rate_also_when_it_is_short_of_frames_too(): + both = dict(fps=16.63, frames=57, span_s=3.37, take_s=3.98, take_frames=119.5, needed_frames=100.2) + assert _camera_reasons(**both) == [ + "Camera head_human_camera averaged 16.6 fps, below the minimum of 25.8 fps (0.86 of 30 fps). Check the " + "camera's cable and the load on this PC, then record the take again." + ] + + +def test_a_stored_camera_result_without_the_frame_counts_is_told_in_the_checkers_own_words(): + # A record written before the take's frame count was stored: nothing to build the sentence from. + assert _camera_reasons(frames=1, span_s=0.0, take_s=1.5) == ["the finding as the checker wrote it"] diff --git a/examples/egocap/tests/backend/test_takes_left_behind_wire.py b/examples/egocap/tests/backend/test_takes_left_behind_wire.py new file mode 100644 index 0000000000..588c63c084 --- /dev/null +++ b/examples/egocap/tests/backend/test_takes_left_behind_wire.py @@ -0,0 +1,1121 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What the page is told about the takes that wait for the operator, and what its two commands may do to them. + +The recording output is shared and can hold anything: another recorder's live take, a take that only needs the +station set up as before, a folder the backend may not read, a quarantine folder that cannot be used, a session +directory copied by hand. Every scenario is run through the command handler the WebSocket uses, against the real +coordinator and the real recording service, with takes built in the test (see qc_takes.py). Where a command could +delete, the whole output is compared file by file before and after. +""" + +from __future__ import annotations + +import asyncio +import errno +import json +import logging +import os +import shutil +import threading +import time +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import recording_service.output_scan as output_scan +import recording_service.recording_service as service_module +from egocap.recording import episode_layout, route +from egocap.recording.capture_qc_policy import resolve_policy +from egocap.recording.episode_layout import read_manifest +from egocap.recording.episode_store import EpisodeStore +from egocap_web import recording_adapter +from egocap_web.recording_command import RecordingContext, handle_recording_command, parse_recording_command +from tests.backend.qc_takes import CAMERA, changed, config_factory, make_coordinator, offer, take_frames, tree + +TOKEN = "" +OTHER_CAMERA = SimpleNamespace(name="wrist_camera", width=64, height=48, fps=30.0) +NEEDS_SAME_SETUP = ( + "This take can be finished once the station is set up as when it was recorded: the same cameras and settings." +) +NOT_KNOWN_YET = "Whether this take can be finished is known once the cameras are connected." +OPEN_ELSEWHERE = "That take's session is open in another recorder." +#: How far apart the coordinator's two looks at a beat are in the tests about another recorder, and how often a +#: recorder beats there: the production values are 2.5 s and 1 s. +WATCH, BEAT = 0.25, 0.02 +MISPLACED = ( + "This take's record was written for another session: its folder was copied or renamed by hand. " + "Nothing was changed." +) +HEAD_FROZEN = ( + "The headset did not move for 2.0 s (limit 1 s). " + "Check that the headset and both controllers are on, charged and in view." +) + + +def _context(coordinator) -> RecordingContext: + coordinator.set_task("pour water") + return RecordingContext(coordinator=coordinator, control_token=TOKEN) + + +async def _send(context: RecordingContext, action: str, **payload) -> dict: + """One command through the handler the WebSocket uses; returns the whole reply.""" + command = parse_recording_command( + { + "request_id": "r", + "action": action, + "payload": {"batch_id": context.batch_id, **payload}, + "operator_token": "alex", + "control_token": TOKEN, + } + ) + return await handle_recording_command(command, context) + + +async def _take(context: RecordingContext, frames=None) -> dict: + """Record one take from Record to Stop through the commands; returns the snapshot after Stop.""" + started = await _send(context, "start_episode") + assert started["outcome"] == "ok", started["reason"] + offer(context.coordinator, take_frames() if frames is None else frames) + stopped = await _send(context, "stop_episode", episode_id=started["snapshot"]["current_episode_id"]) + assert stopped["outcome"] == "ok", stopped["reason"] + return stopped["snapshot"] + + +async def _restart(root: Path, **kwargs) -> RecordingContext: + """A new backend over the same output; it reads what was left.""" + context = _context(make_coordinator(root, **kwargs)) + await context.coordinator.refresh_pending() + return context + + +async def _lose_capture(context: RecordingContext) -> None: + """Lose a capture source during the take being recorded, and wait until the take is retained.""" + context.coordinator.on_capture_lost("capture is not running") + for _ in range(1000): + if context.coordinator.pending_takes() and context.coordinator.snapshot().active_operation is None: + return + await asyncio.sleep(0.01) + raise AssertionError("the take was not retained") + + +def _rows(snapshot: dict) -> dict[str, dict]: + return {row["episode_id"]: row for row in snapshot["pending_takes"]} + + +def _no_path_or_state_name(reply: dict, root: Path) -> None: + """No sentence sent to the page names a directory above the recording output, a recorder state or an error.""" + result = reply["snapshot"]["last_result"] or {} + sentences = [reply["reason"] or ""] + sentences += [*result.get("reasons", []), *result.get("warnings", []), *result.get("issues", [])] + sentences += [row[key] for row in reply["snapshot"]["pending_takes"] for key in ("reason", "recover_note")] + said = json.dumps(sentences) + assert str(root) not in said and str(root.parent) not in said + assert "RECOVERY_REQUIRED" not in said and "Errno" not in said and "Error" not in said + # Nothing else in the reply holds a directory above the recording output either. + assert str(root) not in json.dumps(reply) + + +# --- another recorder's live take ------------------------------------------------------------ + + +async def test_a_take_another_recorder_is_writing_is_not_offered_and_cannot_be_discarded(tmp_path): + root = tmp_path / "out" + theirs, ours = _context(make_coordinator(root)), _context(make_coordinator(root)) + started = await _send(theirs, "start_episode") + live = started["snapshot"]["current_episode_id"] + offer(theirs.coordinator, take_frames(seconds=1.0)) + await ours.coordinator.refresh_pending() + # Its record says WRITING, which is also what an interrupted take looks like. It is not listed. + assert ours.snapshot()["pending_takes"] == [] + before = tree(root) + for action in ("discard_pending", "recover_pending"): + reply = await _send(ours, action, episode_id=live) + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + assert tree(root) == before + stopped = await _send(theirs, "stop_episode", episode_id=live) + assert stopped["snapshot"]["last_result"]["outcome"] == "kept" + await theirs.coordinator.close() + await ours.coordinator.close() + + +@pytest.fixture +def another_machine(monkeypatch): + """A second recorder on a shared disk where no lock reaches from one machine to the other, beating fast.""" + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", BEAT) + monkeypatch.setattr(episode_layout.fcntl, "flock", lambda *_: None) + + +async def _two_looks(context: RecordingContext) -> None: + """What the backend's periodic read does over a few seconds: two looks, a watch time apart.""" + await context.coordinator.refresh_pending() + await asyncio.sleep(WATCH + 2 * BEAT) + await context.coordinator.refresh_pending() + + +async def test_where_no_lock_reaches_a_take_being_recorded_elsewhere_is_never_listed_or_discarded( + tmp_path, another_machine +): + """Both backends carry the same station name, and the lock of one is not seen by the other.""" + root = tmp_path / "out" + theirs = _context(make_coordinator(root)) + ours = _context(make_coordinator(root, watch_seconds=WATCH)) + started = await _send(theirs, "start_episode") + live = started["snapshot"]["current_episode_id"] + offer(theirs.coordinator, take_frames(seconds=1.0)) + before = tree(root) + for _ in range(3): + await _two_looks(ours) + # Its record says WRITING, like a take a dead recorder left; its beat says its recorder is there. + assert ours.snapshot()["pending_takes"] == [] + reply = await _send(ours, "discard_pending", episode_id=live) + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + assert {path: digest for path, digest in tree(root).items() if "session.lock" not in path} == before + # The other recorder never noticed, and its take is whole. + stopped = await _send(theirs, "stop_episode", episode_id=live) + assert stopped["snapshot"]["last_result"]["outcome"] == "kept" + assert (root / stopped["snapshot"]["last_result"]["location"] / f"{CAMERA.name}.mp4").is_file() + await theirs.coordinator.close() + await ours.coordinator.close() + + +async def test_where_no_lock_reaches_a_take_whose_checks_are_running_elsewhere_is_never_listed_or_discarded( + tmp_path, another_machine, monkeypatch +): + """The take sits sealed and nothing is written to it for as long as its checks run.""" + root = tmp_path / "out" + theirs = _context(make_coordinator(root)) + ours = _context(make_coordinator(root, watch_seconds=WATCH)) + checking, finish = threading.Event(), threading.Event() + real_check = service_module.check_capture_quality + + def slow_check(*args): + checking.set() + finish.wait(20.0) + return real_check(*args) + + monkeypatch.setattr(service_module, "check_capture_quality", slow_check) + started = await _send(theirs, "start_episode") + live = started["snapshot"]["current_episode_id"] + offer(theirs.coordinator, take_frames()) + stopping = asyncio.ensure_future(_send(theirs, "stop_episode", episode_id=live)) + while not checking.is_set(): + await asyncio.sleep(0.01) + session, index = live.split("/") + assert read_manifest(root / session / ".recording" / f"{index}.json").storage_phase == "SEALED" + for _ in range(3): + await _two_looks(ours) + assert ours.snapshot()["pending_takes"] == [] + for action in ("discard_pending", "recover_pending"): + reply = await _send(ours, action, episode_id=live) + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + assert (root / session / f"{index}.pending").is_dir() + finish.set() + stopped = await stopping + assert stopped["snapshot"]["last_result"]["outcome"] == "kept" and (root / live).is_dir() + await theirs.coordinator.close() + await ours.coordinator.close() + + +async def test_a_listed_take_whose_session_another_recorder_has_since_opened_is_not_acted_on( + tmp_path, another_machine +): + """Listed while nobody held its session; then another machine opens that session to resolve it itself.""" + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + session = episode_id.split("/")[0] + ours = _context(make_coordinator(root, watch_seconds=WATCH)) + await _two_looks(ours) + assert list(_rows(ours.snapshot())) == [episode_id] + other = service_module.RecordingService(config_factory(root)()) + await other.open_session(session) + await asyncio.sleep(3 * BEAT) + before = tree(root) + for action in ("discard_pending", "recover_pending"): + reply = await _send(ours, action, episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", OPEN_ELSEWHERE) + _no_path_or_state_name(reply, root) + assert {path: digest for path, digest in tree(root).items() if "session.lock" not in path} == { + path: digest for path, digest in before.items() if "session.lock" not in path + } + assert (root / session / "episode_0.pending").is_dir() + # Once that recorder is gone and the session has been at rest for a watch time, the command acts. + await other.close() + await _two_looks(ours) + await asyncio.sleep(WATCH) + reply = await _send(ours, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + assert reply["snapshot"]["last_result"]["outcome"] == "discarded" + await ours.coordinator.close() + + +async def test_a_command_for_a_take_whose_session_was_just_seen_waits_for_its_own_second_look(tmp_path): + """The list is read with one look here; the command then looks twice itself before it reopens the session.""" + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + context = _context(make_coordinator(root, watch_seconds=WATCH)) + await context.coordinator.refresh_pending() + assert context.snapshot()["pending_takes"] == [] # a first look lists nothing + await asyncio.sleep(WATCH + 0.05) # the read the coordinator schedules itself after a first look + assert list(_rows(context.snapshot())) == [episode_id] + # A session just released by this very backend needs no wait at all. + started = asyncio.get_running_loop().time() + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + assert asyncio.get_running_loop().time() - started < WATCH + await context.coordinator.close() + + +async def test_a_take_whose_files_carry_times_in_the_future_is_listed_and_discarded_from_the_page(tmp_path): + """The clock was set back after the take was recorded, or the file server's clock runs ahead.""" + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + session = root / episode_id.split("/")[0] + ahead = time.time() + 3600 + for path in (session, *session.rglob("*")): + os.utime(path, (ahead, ahead)) + context = _context(make_coordinator(root, watch_seconds=WATCH)) + await _two_looks(context) + assert list(_rows(context.snapshot())) == [episode_id] + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + assert reply["snapshot"]["last_result"]["outcome"] == "discarded" and reply["snapshot"]["pending_takes"] == [] + assert not (session / "episode_0.pending").exists() + await context.coordinator.close() + + +# --- every name the station has had --------------------------------------------------------------- + + +async def test_a_take_left_before_the_station_was_renamed_is_still_listed_and_discarded(tmp_path): + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) # recorded as "Bench A" + # The station is "Bench A2" now. With only that name the take would be on no page at all. + forgetful = _context(make_coordinator(root, station="Bench A2")) + await forgetful.coordinator.refresh_pending() + assert forgetful.snapshot()["pending_takes"] == [] + await forgetful.coordinator.close() + renamed = _context(make_coordinator(root, station="Bench A2", station_names=lambda: {"Bench A2", "Bench A"})) + await renamed.coordinator.refresh_pending() + assert list(_rows(renamed.snapshot())) == [episode_id] + reply = await _send(renamed, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + await renamed.coordinator.close() + + +async def test_a_take_left_before_a_rename_made_on_a_day_without_a_timeline_is_still_listed_and_discarded( + tmp_path, +): + """The names come from the real uptime log, which never observed the station on the day of the rename.""" + from egocap_web.station_uptime import UPTIME_DIR, UptimeLog + + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) # recorded as "Bench A" + UptimeLog(root / UPTIME_DIR).rename("Bench A", "Bench A2") + # A backend started afterwards reads the rename from the log's file. + uptime = UptimeLog(root / UPTIME_DIR) + assert uptime.all_names("Bench A2") == {"Bench A2", "Bench A"} + renamed = _context( + make_coordinator(root, station="Bench A2", station_names=lambda: uptime.all_names("Bench A2")) + ) + await renamed.coordinator.refresh_pending() + assert list(_rows(renamed.snapshot())) == [episode_id] + reply = await _send(renamed, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + await renamed.coordinator.close() + + +async def test_a_take_left_before_the_station_had_a_name_is_listed_once_it_has_one(tmp_path): + root = tmp_path / "out" + unnamed = _context(make_coordinator(root, station=None)) + await _send(unnamed, "start_episode") + offer(unnamed.coordinator, take_frames(seconds=1.0)) + await _lose_capture(unnamed) + episode_id = unnamed.snapshot()["pending_takes"][0]["episode_id"] + await unnamed.coordinator.close() + named = await _restart(root, station="Bench A") + assert list(_rows(named.snapshot())) == [episode_id] + reply = await _send(named, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + await named.coordinator.close() + + +async def test_a_take_another_station_left_in_the_same_output_is_not_this_stations_to_resolve(tmp_path): + root = tmp_path / "out" + theirs = _context(make_coordinator(root, station="Bench B")) + started = await _send(theirs, "start_episode") + offer(theirs.coordinator, take_frames(seconds=1.0)) + episode_id = started["snapshot"]["current_episode_id"] + await _lose_capture(theirs) + await theirs.coordinator.close() + ours = await _restart(root) + assert ours.snapshot()["pending_takes"] == [] + reply = await _send(ours, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + # Its own station still sees it. + back = await _restart(root, station="Bench B") + assert list(_rows(back.snapshot())) == [episode_id] + await ours.coordinator.close() + await back.coordinator.close() + + +# --- a take that passed its checks is never called a take to discard ---------------------------- + + +async def _a_good_take_stopped_between_its_checks_and_its_rename(root: Path, monkeypatch) -> str: + context = _context(make_coordinator(root)) + with monkeypatch.context() as patched: + patched.setattr( + service_module, "write_episode_attributes", lambda *_: (_ for _ in ()).throw(OSError("io error")) + ) + snapshot = await _take(context) + (left,) = snapshot["pending_takes"] + assert (left["phase"], left["recoverable"]) == ("CHECKED", True) + manifest = read_manifest(root / left["session_id"] / ".recording" / "episode_0.json") + assert (manifest.finalization, manifest.qc_decision) == ("KEEP", "PASSED") + await context.coordinator.close() + return left["episode_id"] + + +async def test_while_no_camera_is_accepted_nothing_is_said_about_whether_a_good_take_can_be_recovered( + tmp_path, monkeypatch +): + root = tmp_path / "out" + episode_id = await _a_good_take_stopped_between_its_checks_and_its_rename(root, monkeypatch) + context = await _restart(root, cameras=()) # CaptureServer is not connected yet + row = _rows(context.snapshot())[episode_id] + assert (row["recoverable"], row["recoverable_known"], row["discardable"]) == (False, False, True) + assert row["recover_note"] == NOT_KNOWN_YET + before = tree(root) + reply = await _send(context, "recover_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", NOT_KNOWN_YET) + assert tree(root) == before + for text in (row["recover_note"], row["reason"], reply["reason"]): + assert "discard" not in text.lower() + await context.coordinator.close() + + +async def test_with_other_cameras_a_good_take_says_what_it_needs_and_with_the_same_ones_it_is_saved( + tmp_path, monkeypatch +): + root = tmp_path / "out" + episode_id = await _a_good_take_stopped_between_its_checks_and_its_rename(root, monkeypatch) + other_day = await _restart(root, cameras=(OTHER_CAMERA,)) + row = _rows(other_day.snapshot())[episode_id] + assert (row["recoverable"], row["recoverable_known"]) == (False, True) and row[ + "recover_note" + ] == NEEDS_SAME_SETUP + before = tree(root) + reply = await _send(other_day, "recover_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", NEEDS_SAME_SETUP) + assert tree(root) == before + for text in (row["recover_note"], row["reason"], reply["reason"]): + assert "discard" not in text.lower() + await other_day.coordinator.close() + same_setup = await _restart(root) + row = _rows(same_setup.snapshot())[episode_id] + assert row["recoverable"] is True and row["recover_note"] == "Recover finishes saving this take." + reply = await _send(same_setup, "recover_pending", episode_id=episode_id) + assert reply["outcome"] == "ok" and reply["snapshot"]["last_result"]["outcome"] == "kept" + assert reply["snapshot"]["pending_takes"] == [] + await same_setup.coordinator.close() + + +# --- one unreadable entry breaks nothing -------------------------------------------------------- + + +def _unreadable(monkeypatch, name: str) -> None: + """Make the folder ``name`` of the output one the reader of the output may not look into.""" + + def stat(path, *args, **kwargs): + if name in Path(path).parts: + raise PermissionError(errno.EACCES, "Permission denied", str(path)) + return os.stat(path, *args, **kwargs) + + # Only the reader's own view of the file system: everything else in the test still sees the folder. + monkeypatch.setattr(output_scan, "os", SimpleNamespace(scandir=os.scandir, stat=stat)) + + +async def _a_take_left_interrupted(root: Path) -> str: + context = _context(make_coordinator(root)) + await _send(context, "start_episode") + offer(context.coordinator, take_frames(seconds=1.0)) + await _lose_capture(context) + episode_id = context.snapshot()["pending_takes"][0]["episode_id"] + await context.coordinator.close() + return episode_id + + +async def test_a_folder_the_backend_may_not_read_does_not_hide_the_takes_left_behind(tmp_path, monkeypatch): + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + closed = root / "lost+found" + closed.mkdir() + # A folder with no permission at all, as a data disk has. The superuser can look into it all the same, so + # the reader's own view of it is closed as well: the test means the same whoever runs it. + closed.chmod(0o000) + _unreadable(monkeypatch, "lost+found") + try: + context = _context(make_coordinator(root)) + await context.coordinator.refresh_pending() + assert list(_rows(context.snapshot())) == [episode_id] + # New batch reads the output too: it rotates the batch and says nothing of any directory. + batch = context.batch_id + reply = await _send(context, "new_batch") + assert (reply["outcome"], reply["reason"]) == ("ok", None) and reply["snapshot"]["batch_id"] != batch + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + after = reply["snapshot"] + assert after["last_result"]["outcome"] == "discarded" and after["pending_takes"] == [] + _no_path_or_state_name(reply, root) + session, index = episode_id.split("/") + assert not (root / session / f"{index}.pending").exists() + await context.coordinator.close() + finally: + closed.chmod(0o700) + + +async def test_when_the_output_cannot_be_read_a_new_batch_still_rotates_and_a_discard_is_still_reported( + tmp_path, monkeypatch +): + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + context = await _restart(root) + assert list(_rows(context.snapshot())) == [episode_id] + await _take(context) # a session of this batch is open, so New batch has something to close + + def cannot_read(self, **_kwargs): + raise PermissionError(errno.EACCES, "Permission denied", str(root / "lost+found" / ".recording")) + + monkeypatch.setattr(service_module.RecordingService, "pending_under_output_root", cannot_read) + batch = context.batch_id + reply = await _send(context, "new_batch") + assert (reply["outcome"], reply["reason"]) == ("ok", None) + assert reply["snapshot"]["batch_id"] != batch and reply["snapshot"]["saved_count"] == 0 + _no_path_or_state_name(reply, root) + # The list could not be read again, so it shows what was last read: the take is still there to resolve. + assert list(_rows(reply["snapshot"])) == [episode_id] + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + result = reply["snapshot"]["last_result"] + assert (result["episode_id"], result["outcome"], result["media_removed"]) == (episode_id, "discarded", True) + # What the discard did is what the page shows, although the read after it failed too. + assert reply["snapshot"]["pending_takes"] == [] + _no_path_or_state_name(reply, root) + session, index = episode_id.split("/") + assert read_manifest(root / session / ".recording" / f"{index}.json").storage_phase == "DISCARDED" + assert not (root / session / f"{index}.pending").exists() + await context.coordinator.close() + + +async def test_a_read_that_keeps_failing_keeps_the_last_list_and_is_reported_once(tmp_path, monkeypatch, caplog): + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + context = await _restart(root) + real_read = service_module.RecordingService.pending_under_output_root + + def cannot_read(self, **_kwargs): + raise PermissionError(errno.EACCES, "Permission denied") + + with caplog.at_level(logging.WARNING, logger="isaaccapture.egocap.recording_session"): + with monkeypatch.context() as patched: + patched.setattr(service_module.RecordingService, "pending_under_output_root", cannot_read) + for _ in range(4): # what the periodic duty does every few seconds + await context.coordinator.refresh_pending() + assert list(_rows(context.snapshot())) == [episode_id] + reported = [r for r in caplog.records if "were not read" in r.getMessage()] + assert len(reported) == 1 + # Once the output can be read again, a later failure is news again. + await context.coordinator.refresh_pending() + monkeypatch.setattr(service_module.RecordingService, "pending_under_output_root", cannot_read) + await context.coordinator.refresh_pending() + assert len([r for r in caplog.records if "were not read" in r.getMessage()]) == 2 + monkeypatch.setattr(service_module.RecordingService, "pending_under_output_root", real_read) + await context.coordinator.close() + + +# --- the recorder's own beat: a session that would look closed to another machine ---------------- + +BEAT_STOPPED = ( + "The recorder has not been able to write to the recordings folder for a few seconds. " + "Check the recordings disk; if this stays, finish any take in progress and restart the backend." +) +BEAT_STOPPED_DURING_THE_TAKE = ( + "The recorder could not write to the recordings folder for a few seconds during this take. If another " + "PC shares that folder, check there that the take was not treated as left behind." +) + + +@pytest.fixture +def short_watch(monkeypatch): + """A beat every 20 ms, and a recorder that counts its beat as missing after 300 ms without one.""" + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + monkeypatch.setattr(episode_layout, "BEAT_WATCH_SECONDS", 0.3) + + +async def _eventually(condition, seconds: float = 5.0) -> None: + deadline = time.monotonic() + seconds + while not condition(): + assert time.monotonic() < deadline, "the condition never came true" + await asyncio.sleep(0.005) + + +async def test_record_is_refused_in_a_sentence_while_the_recorders_beat_is_missing_and_works_again_after( + tmp_path, monkeypatch, short_watch +): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + await _take(context) # the session is open from here on, idle between takes + assert context.snapshot()["ready_to_record"] is True + real_beat, broken = episode_layout.SessionLock.beat, threading.Event() + + def beat(lock): + if broken.is_set(): + raise RuntimeError("nothing a beat expects") # not an operating-system error + real_beat(lock) + + monkeypatch.setattr(episode_layout.SessionLock, "beat", beat) + broken.set() + # No command is sent: the page is told by the snapshot it is pushed when readiness changes. + await _eventually(lambda: context.snapshot()["ready_to_record"] is False) + snapshot = context.snapshot() + assert snapshot["not_ready_reason"] == BEAT_STOPPED and snapshot["episode_phase"] == "IDLE" + reply = await _send(context, "start_episode") + assert (reply["outcome"], reply["reason"]) == ("rejected", BEAT_STOPPED) + _no_path_or_state_name(reply, root) + # The thread that beats did not end with the failure: the beat comes back, and so does Record. + broken.clear() + await _eventually(lambda: context.snapshot()["ready_to_record"] is True) + after = context.snapshot() + assert after["not_ready_reason"] is None and after["revision"] > snapshot["revision"] + assert (await _take(context))["last_result"]["outcome"] == "kept" + await context.coordinator.close() + + +async def test_a_take_during_which_the_beat_hung_is_not_interrupted_and_says_what_happened( + tmp_path, monkeypatch, short_watch +): + """A stalled disk: one beat's write does not return for a while. The take goes on and is kept.""" + root = tmp_path / "out" + context = _context(make_coordinator(root)) + assert (await _take(context))["last_result"]["issues"] == [] + real_utime, hanging, let_go = os.utime, threading.Event(), threading.Event() + + def utime(target, *args, **kwargs): + if not let_go.is_set(): + hanging.set() + let_go.wait(5.0) + return real_utime(target, *args, **kwargs) + + started = await _send(context, "start_episode") + assert started["outcome"] == "ok" + monkeypatch.setattr(episode_layout.os, "utime", utime) + await _eventually(hanging.is_set) + offer(context.coordinator, take_frames()) + await _eventually(lambda: context.snapshot()["not_ready_reason"] == BEAT_STOPPED) + # The take is still being recorded: a missing beat interrupts nothing. + assert context.snapshot()["episode_phase"] == "RECORDING" + let_go.set() + stopped = await _send(context, "stop_episode", episode_id=started["snapshot"]["current_episode_id"]) + result = stopped["snapshot"]["last_result"] + assert (stopped["outcome"], result["outcome"]) == ("ok", "kept") + assert result["issues"] == [BEAT_STOPPED_DURING_THE_TAKE] + _no_path_or_state_name(stopped, root) + # With the beat back, the next take has nothing to say about it. + await _eventually(lambda: context.snapshot()["ready_to_record"] is True) + assert (await _take(context))["last_result"]["issues"] == [] + await context.coordinator.close() + + +# --- the one fact the operator can act on: what the recordings disk refused ---------------------- + +FULL = "The recordings disk is full. Free space, then record again." + + +def _full(root: Path) -> OSError: + return OSError( + errno.ENOSPC, "No space left on device", str(root / "session" / ".recording" / "episode_1.json") + ) + + +async def test_a_full_disk_is_named_when_record_is_pressed(tmp_path, monkeypatch): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + await _take(context) + with monkeypatch.context() as patched: + patched.setattr(service_module, "write_manifest", lambda *a, **k: (_ for _ in ()).throw(_full(root))) + reply = await _send(context, "start_episode") + assert (reply["outcome"], reply["reason"]) == ("rejected", FULL) + _no_path_or_state_name(reply, root) + # Nothing was left half started: with room on the disk again, Record works. + assert (await _take(context))["last_result"]["outcome"] == "kept" + await context.coordinator.close() + + +async def test_a_disk_that_fills_during_a_take_is_named_in_the_result_and_on_the_takes_row(tmp_path, monkeypatch): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + with monkeypatch.context() as patched: + patched.setattr(EpisodeStore, "append_video", lambda self, *a, **k: (_ for _ in ()).throw(_full(root))) + snapshot = await _take(context) + result = snapshot["last_result"] + assert result["outcome"] == "interrupted" + assert result["reasons"][:2] == ["Writing the take to disk failed; see the backend log.", FULL] + (row,) = snapshot["pending_takes"] + assert row["reason"] == FULL + assert str(root) not in json.dumps(snapshot) and "Errno" not in json.dumps(snapshot) + while context.coordinator.snapshot().active_operation is not None: # the failed take is still being settled + await asyncio.sleep(0.01) + reply = await _send(context, "discard_pending", episode_id=row["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ("ok", None) and reply["snapshot"]["pending_takes"] == [] + await context.coordinator.close() + + +async def test_a_disk_that_is_full_when_a_take_is_finished_is_named_and_recover_saves_the_take( + tmp_path, monkeypatch +): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + with monkeypatch.context() as patched: + patched.setattr(service_module, "finalize_episode_dir", lambda *a, **k: (_ for _ in ()).throw(_full(root))) + snapshot = await _take(context) + result = snapshot["last_result"] + assert result["outcome"] == "interrupted" + assert result["reasons"] == ["Finishing the take failed part-way; see the backend log.", FULL] + (row,) = snapshot["pending_takes"] + assert (row["reason"], row["recoverable"]) == (FULL, True) + reply = await _send(context, "recover_pending", episode_id=row["episode_id"]) + assert reply["outcome"] == "ok" and reply["snapshot"]["last_result"]["outcome"] == "kept" + await context.coordinator.close() + + +async def test_a_take_already_saved_whose_last_record_failed_is_never_told_to_be_discarded_again( + tmp_path, monkeypatch +): + """The take is in its final place; only its last checkpoint is missing. Discard cannot remove it, ever.""" + root = tmp_path / "out" + context = _context(make_coordinator(root)) + real_write = service_module.write_manifest + + def fail_the_last_checkpoint(session_path, manifest): + if manifest.storage_phase == "FINALIZED": + raise OSError(errno.EIO, "Input/output error") + real_write(session_path, manifest) + + with monkeypatch.context() as patched: + patched.setattr(service_module, "write_manifest", fail_the_last_checkpoint) + snapshot = await _take(context) + (row,) = snapshot["pending_takes"] + assert (row["phase"], row["recoverable"], row["recover_note"]) == ( + "CHECKED", + True, + "Recover finishes saving this take.", + ) + before = tree(root) + reply = await _send(context, "discard_pending", episode_id=row["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + result = reply["snapshot"]["last_result"] + assert result["outcome"] == "interrupted" + assert result["reasons"][-1] == ( + "This take is already saved; only its last record is missing. Use Recover to finish it." + ) + assert "discard it again" not in json.dumps(reply) + removed, added, _modified = changed(before, tree(root)) + assert removed == set() and added == set() + reply = await _send(context, "recover_pending", episode_id=row["episode_id"]) + assert reply["outcome"] == "ok" and reply["snapshot"]["last_result"]["outcome"] == "kept" + await context.coordinator.close() + + +async def test_a_full_disk_found_by_a_sync_that_names_no_file_is_still_named_when_record_is_pressed( + tmp_path, monkeypatch +): + """As the system reports it: the sync of the take's first record fails, and the error names no file.""" + root = tmp_path / "out" + context = _context(make_coordinator(root)) + await _take(context) + + def no_room(*_args, **_kwargs): + raise OSError(errno.ENOSPC, "No space left on device") + + with monkeypatch.context() as patched: + patched.setattr(episode_layout.os, "fsync", no_room) + reply = await _send(context, "start_episode") + assert (reply["outcome"], reply["reason"]) == ("rejected", FULL) + _no_path_or_state_name(reply, root) + assert (await _take(context))["last_result"]["outcome"] == "kept" + await context.coordinator.close() + + +GENERAL = "The recording command failed; see the backend log." + + +async def test_a_calibration_file_that_cannot_be_read_is_not_put_on_the_recordings_folder(tmp_path, monkeypatch): + """A real permission failure, in the calibration folder: the recordings folder is fine.""" + root, calibration = tmp_path / "out", tmp_path / "calibration" + calibration.mkdir() + unreadable = calibration / "head_camera_intrinsics.json" + unreadable.write_text("{}") + unreadable.chmod(0) + monkeypatch.setenv("EGOCAP_CALIBRATION_DIR", str(calibration)) + context = _context(make_coordinator(root)) + try: + reply = await _send(context, "start_episode") + finally: + unreadable.chmod(0o600) + assert (reply["outcome"], reply["reason"]) == ("rejected", GENERAL) + assert os.access(root, os.W_OK) # the folder the old sentence sent the operator to + _no_path_or_state_name(reply, root) + assert str(calibration) not in json.dumps(reply) + await context.coordinator.close() + + +async def test_an_encoder_program_that_cannot_be_run_is_not_put_on_the_recordings_folder(tmp_path, monkeypatch): + """A real permission failure, on the encoder program: a file of its name without the execute bit.""" + from egocap.recording.capture_qc_policy import CaptureQcPolicy + from egocap_web import app as app_module + from egocap_web.recording_session import RecordingSessionCoordinator + + root, programs = tmp_path / "out", tmp_path / "bin" + programs.mkdir() + (programs / "ffmpeg").write_text("#!/bin/sh\nexit 0\n") + (programs / "ffmpeg").chmod(0o644) + monkeypatch.setenv("PATH", str(programs)) + monitor = SimpleNamespace(camera_descriptors=(CAMERA,), native=SimpleNamespace(started=None)) + factory = app_module._recording_config_factory( + monitor, "Bench A", root, video_encoder="ffmpeg_h264", qc_policy=CaptureQcPolicy() + ) + coordinator = RecordingSessionCoordinator( + factory, queue_capacity=8192, readiness_check=lambda: (True, None), watch_seconds=0.0 + ) + context = _context(coordinator) + reply = await _send(context, "start_episode") + assert (reply["outcome"], reply["reason"]) == ("rejected", GENERAL) + # The take that failed to start waits to be discarded, and its row does not name the recordings folder. + (row,) = reply["snapshot"]["pending_takes"] + assert row["reason"] == "The take failed to start; see the backend log." + _no_path_or_state_name(reply, root) + assert str(programs) not in json.dumps(reply) + discarded = await _send(context, "discard_pending", episode_id=row["episode_id"]) + assert discarded["outcome"] == "ok" and discarded["snapshot"]["pending_takes"] == [] + await context.coordinator.close() + + +# --- a quarantine folder that cannot be used ---------------------------------------------------- + + +async def test_record_is_refused_in_a_sentence_about_the_folder_while_the_quarantine_folder_is_a_link(tmp_path): + root, elsewhere = tmp_path / "out", tmp_path / "another_disk" + root.mkdir() + elsewhere.mkdir() + (root / "_quarantine").symlink_to(elsewhere, target_is_directory=True) + context = _context(make_coordinator(root)) + reply = await _send(context, "start_episode") + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "The quarantine folder in the recording output is a link, so a take marked bad could not be set aside. " + "Make it a plain folder on the recordings disk.", + ) + _no_path_or_state_name(reply, root) + assert [p.name for p in root.iterdir()] == ["_quarantine"] and list(elsewhere.iterdir()) == [] + # Refused before anything was recorded, and Record works as soon as the folder is a folder. + (root / "_quarantine").unlink() + snapshot = await _take(context, take_frames(frozen_head=True)) + assert snapshot["last_result"]["outcome"] == "quarantined" + await context.coordinator.close() + + +async def test_a_take_whose_quarantine_folder_went_bad_is_never_left_where_neither_command_works(tmp_path): + root, elsewhere = tmp_path / "out", tmp_path / "another_disk" + elsewhere.mkdir() + context = _context(make_coordinator(root)) + kept = await _take(context) + session = kept["last_result"]["episode_id"].split("/")[0] + started = await _send(context, "start_episode") + offer(context.coordinator, take_frames(frozen_head=True)) + (root / "_quarantine").symlink_to(elsewhere, target_is_directory=True) # replaced while the take records + stopped = await _send(context, "stop_episode", episode_id=started["snapshot"]["current_episode_id"]) + snapshot = stopped["snapshot"] + assert snapshot["last_result"]["outcome"] == "interrupted" + (row,) = snapshot["pending_takes"] + assert (row["phase"], row["current"]) == ("CHECKED", True) + before = tree(root) + reply = await _send(context, "recover_pending", episode_id=row["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "This take cannot be set aside: the quarantine folder in the recording output is a link. Make it a plain " + "folder on the recordings disk. The take was left as it is; it can also be discarded.", + ) + _no_path_or_state_name(reply, root) + assert tree(root) == before + reply = await _send(context, "discard_pending", episode_id=row["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + after = reply["snapshot"] + assert after["last_result"]["outcome"] == "discarded" and after["last_result"]["reasons"] == [HEAD_FROZEN] + assert after["pending_takes"] == [] and after["episode_phase"] == "IDLE" + removed, added, modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session}/episode_1.pending/") for path in removed) + assert added == set() and modified == {f"{session}/.recording/episode_1.json"} + assert list(elsewhere.iterdir()) == [] + await context.coordinator.close() + + +async def test_a_stamp_that_cannot_be_written_once_does_not_strand_the_first_bad_take_of_a_session( + tmp_path, monkeypatch +): + """The disk is full for a moment while the session's quarantine folder is made.""" + root = tmp_path / "out" + context = _context(make_coordinator(root)) + real_write, failed = route.write_json_atomic, [] + + def full_for_a_moment(path, data): + if not failed and path.parent.name == route.QUARANTINE_CLAIM: + failed.append(path) + raise OSError(errno.ENOSPC, "No space left on device", str(path)) + return real_write(path, data) + + monkeypatch.setattr(route, "write_json_atomic", full_for_a_moment) + snapshot = await _take(context, take_frames(frozen_head=True)) + assert failed and snapshot["last_result"]["outcome"] == "interrupted" + (row,) = snapshot["pending_takes"] + assert row["recoverable"] is True + reply = await _send(context, "recover_pending", episode_id=row["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + after = reply["snapshot"] + assert after["last_result"]["outcome"] == "quarantined" and after["pending_takes"] == [] + assert (root / after["last_result"]["location"]).is_dir() + assert (await _take(context))["last_result"]["outcome"] == "kept" # Record works again + await context.coordinator.close() + + +async def test_a_take_whose_place_in_quarantine_is_taken_can_be_discarded_and_record_works_again(tmp_path): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + first = await _take(context, take_frames(frozen_head=True)) + session = first["last_result"]["episode_id"].split("/")[0] + in_the_way = root / "_quarantine" / session / "episode_1" + in_the_way.mkdir() + (in_the_way / "notes.txt").write_text("put here by hand") + snapshot = await _take(context, take_frames(frozen_head=True)) + assert snapshot["last_result"]["outcome"] == "interrupted" + episode_id = snapshot["pending_takes"][0]["episode_id"] + again = await _send(context, "recover_pending", episode_id=episode_id) + assert again["outcome"] == "ok" and again["snapshot"]["last_result"]["outcome"] == "interrupted" + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert reply["outcome"] == "ok" and reply["snapshot"]["last_result"]["outcome"] == "discarded" + assert reply["snapshot"]["pending_takes"] == [] + assert (in_the_way / "notes.txt").read_text() == "put here by hand" + assert (await _take(context))["last_result"]["outcome"] == "kept" + await context.coordinator.close() + + +# --- a session directory copied or renamed by hand ---------------------------------------------- + + +async def test_the_takes_of_a_copied_session_directory_are_shown_and_no_command_acts_on_them(tmp_path): + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + session = episode_id.split("/")[0] + shutil.copytree(root / session, root / f"{session}_copy") + context = await _restart(root) + rows = _rows(context.snapshot()) + copy_id = f"{session}_copy/episode_0" + assert sorted(rows) == sorted([episode_id, copy_id]) + assert (rows[episode_id]["discardable"], rows[episode_id]["session_id"]) == (True, session) + copied = rows[copy_id] + assert (copied["recoverable"], copied["discardable"], copied["session_id"]) == ( + False, + False, + f"{session}_copy", + ) + assert copied["reason"] == ( + "This take's record was written for another session: its folder was copied or renamed by hand." + ) + # The row says what to do about it, and names the session the folder is a copy of. + assert copied["recover_note"] == ( + "Nothing is done with this take from this page. On the recordings disk, delete its folder if it is a " + f"copy, or give the folder back the name {session} if it was renamed." + ) + before = tree(root) + for action in ("discard_pending", "recover_pending"): + reply = await _send(context, action, episode_id=copy_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", MISPLACED) + assert tree(root) == before + # The original is discarded by its own row, and only its own files go. + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert reply["outcome"] == "ok" and list(_rows(reply["snapshot"])) == [copy_id] + removed, _added, _modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session}/episode_0.pending/") for path in removed) + assert (root / f"{session}_copy" / "episode_0.pending").is_dir() + await context.coordinator.close() + + +async def test_the_take_of_a_renamed_session_directory_is_shown_as_what_it_is(tmp_path): + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + (root / episode_id.split("/")[0]).rename(root / "renamed_by_hand") + context = await _restart(root) + (row,) = context.snapshot()["pending_takes"] + assert (row["episode_id"], row["discardable"], row["recoverable"]) == ( + "renamed_by_hand/episode_0", + False, + False, + ) + before = tree(root) + for action in ("discard_pending", "recover_pending"): + reply = await _send(context, action, episode_id=row["episode_id"]) + assert (reply["outcome"], reply["reason"]) == ("rejected", MISPLACED) + assert tree(root) == before + await context.coordinator.close() + + +# --- a take rejected for integrity whose data was kept ------------------------------------------ + + +async def _an_integrity_rejection(root: Path, monkeypatch) -> tuple[RecordingContext, dict]: + policy = resolve_policy({}, {"guardrails": {"gloves_expected": True}}) + context = _context(make_coordinator(root, policy)) + with monkeypatch.context() as patched: + patched.setattr(recording_adapter, "build_manus_glove_fields", lambda tracking: None) + snapshot = await _take(context) + assert snapshot["last_result"]["outcome"] == "rejected_data_kept" + return context, snapshot + + +async def test_a_take_rejected_for_integrity_is_listed_with_its_state_offers_discard_only_and_blocks_nothing( + tmp_path, monkeypatch +): + root = tmp_path / "out" + context, snapshot = await _an_integrity_rejection(root, monkeypatch) + episode_id = snapshot["last_result"]["episode_id"] + session = episode_id.split("/")[0] + (row,) = snapshot["pending_takes"] + assert row == { + "episode_id": episode_id, + "session_id": session, + "index": 0, + "phase": "REJECTED", + "recoverable": False, + "recoverable_known": True, + "discardable": True, + "current": False, + "reason": "This take failed its integrity check; its data was kept on disk.", + "recover_note": "This take failed its integrity check and cannot be recovered. Discard removes its data.", + "task": "pour water", + "operator": "alex", + "duration_ms": 2000, + } + assert snapshot["episode_phase"] == "IDLE" and snapshot["ready_to_record"] is True + reply = await _send(context, "recover_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "This take failed its integrity check and cannot be recovered. It can only be discarded.", + ) + # It is not removed while another take is being recorded. + started = await _send(context, "start_episode") + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", "Finish or discard the take being recorded first.") + await _send(context, "discard_episode", episode_id=started["snapshot"]["current_episode_id"]) + before = tree(root) + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + after = reply["snapshot"] + result = after["last_result"] + assert (result["outcome"], result["media_removed"], result["location"]) == ("discarded", True, None) + assert result["reasons"] == [ + "The recorded data failed an integrity check: manus_glove: required source has no rows." + ] + assert after["pending_takes"] == [] and after["rejected_count"] == 1 + removed, added, modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session}/episode_0.pending/") for path in removed) + assert added == set() and modified == {f"{session}/.recording/episode_0.json"} + await context.coordinator.close() + + +async def test_a_take_rejected_for_integrity_is_a_row_of_the_session_that_recorded_it_only(tmp_path, monkeypatch): + """After New batch, and after a restart, it is not a row: its data stays where it was, as it always has.""" + root = tmp_path / "out" + context, snapshot = await _an_integrity_rejection(root, monkeypatch) + episode_id = snapshot["last_result"]["episode_id"] + session, index = episode_id.split("/") + assert [row["phase"] for row in snapshot["pending_takes"]] == ["REJECTED"] + reply = await _send(context, "new_batch") + assert reply["outcome"] == "ok" and reply["snapshot"]["pending_takes"] == [] + assert (root / session / f"{index}.pending").is_dir() + reply = await _send(context, "discard_pending", episode_id=episode_id) + assert (reply["outcome"], reply["reason"]) == ("rejected", "That take is no longer pending.") + await context.coordinator.close() + restarted = await _restart(root) + assert restarted.snapshot()["pending_takes"] == [] and restarted.snapshot()["ready_to_record"] is True + assert (root / session / f"{index}.pending").is_dir() + await restarted.coordinator.close() + + +# --- a take too short for its camera's rate ----------------------------------------------------- + + +async def test_a_take_with_one_camera_frame_is_kept_and_told_why_the_rate_rule_said_nothing(tmp_path): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + frames = [frame for frame in take_frames(seconds=0.2) if getattr(frame, "jpeg", None) is None] + frames.insert(1, next(frame for frame in take_frames(seconds=0.2) if getattr(frame, "jpeg", None) is not None)) + snapshot = await _take(context, frames) + result = snapshot["last_result"] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == ("kept", "PASSED", False) + assert (root / result["location"] / f"{CAMERA.name}.mp4").is_file() + assert ( + f"Camera {CAMERA.name} recorded 1 frame in 0.00 s, too short to measure its rate (that takes 0.33 s), " + "so the camera rate rule did not judge this take." + ) in result["warnings"] + assert "The take lasted 0.2 s; the limits are 1 s to 600 s." in result["warnings"] + assert snapshot["saved_count"] == 1 and snapshot["rejected_count"] == 0 + await context.coordinator.close() + + +async def test_a_take_of_ordinary_length_whose_camera_delivered_one_frame_is_rejected_not_saved(tmp_path): + """One frame of the forty-six due in 1.5 s: there is no rate to give, and the take held about 45.""" + root = tmp_path / "out" + kept_takes = [] + coordinator = make_coordinator(root) + coordinator.on_episode_kept = kept_takes.append # what hands a kept take to time alignment + context = _context(coordinator) + frames = [frame for frame in take_frames(seconds=1.5) if getattr(frame, "jpeg", None) is None] + frames.insert(1, next(frame for frame in take_frames(seconds=1.5) if getattr(frame, "jpeg", None) is not None)) + snapshot = await _take(context, frames) + result = snapshot["last_result"] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == ( + "rejected", + "REJECTED_CAMERA", + True, + ) + assert result["reasons"] == [ + f"Camera {CAMERA.name} recorded 1 frame; a take of 1.5 s holds about 45. Check the camera's cable and " + "the load on this PC, then record the take again." + ] + assert not any("too short to measure" in warning for warning in result["warnings"]) + assert (snapshot["saved_count"], snapshot["rejected_count"]) == (0, 1) and kept_takes == [] + session = result["episode_id"].split("/")[0] + assert not (root / session / "episode_0").exists() and not (root / session / "episode_0.pending").exists() + await context.coordinator.close() + + +@pytest.mark.parametrize("action", ["start_episode", "new_batch"]) +async def test_a_waiting_take_is_named_as_such_never_by_the_recorders_state_name(tmp_path, action): + root = tmp_path / "out" + context = _context(make_coordinator(root)) + await _send(context, "start_episode") + offer(context.coordinator, take_frames(seconds=1.0)) + await _lose_capture(context) + reply = await _send(context, action) + _no_path_or_state_name(reply, root) + if action == "start_episode": + assert (reply["outcome"], reply["reason"]) == ( + "rejected", + "A take is waiting to be recovered or discarded. Resolve it, or start a new batch, before recording.", + ) + else: + assert reply["outcome"] == "ok" + await context.coordinator.close() diff --git a/examples/egocap/tests/backend/test_viser_scene.py b/examples/egocap/tests/backend/test_viser_scene.py index b9f3412fd2..9d05e6f81e 100644 --- a/examples/egocap/tests/backend/test_viser_scene.py +++ b/examples/egocap/tests/backend/test_viser_scene.py @@ -831,8 +831,10 @@ def spy(*args, **kwargs): monkeypatch.setattr(app_module, "_recording_config_factory", spy) async with app_module.lifespan(app_module.FastAPI()): (aligner,) = _FakeAligner.instances - (args,) = factory_args - assert args[3] == aligner.note_video_sources + # The factory that opens a session for recording tells the aligner its cameras; the one that only looks + # at takes earlier sessions left pending tells it nothing. + recording, scan = factory_args + assert recording[3] == aligner.note_video_sources and scan[3] is None async def test_no_video_source_callback_is_passed_without_an_index_camera(monkeypatch, tmp_path): diff --git a/examples/egocap/tests/capture_server/test_camera_poll_cadence.py b/examples/egocap/tests/capture_server/test_camera_poll_cadence.py new file mode 100644 index 0000000000..6b007f98ec --- /dev/null +++ b/examples/egocap/tests/capture_server/test_camera_poll_cadence.py @@ -0,0 +1,320 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The camera adapter asks its queue several times per frame interval, so no frame is lost to a poll that +comes a moment early. + +The real adapter is driven against the mock queue, and against a queue that overwrites its one slot the way a +device does, in the hard case: the frame clock exactly in phase with the adapter's poll clock, and polls that +land a little before and a little after each frame. Time is a clock the adapter's own sleeps move, so every +instant is exact and nothing waits in real time. One test runs the real server and counts in real time. +""" + +from __future__ import annotations + +import asyncio +import itertools + +import pytest + +from capture_server import protocol as p +from capture_server.acquisition import CameraSourceError, DepthAIAdapter +from capture_server.acquisition import depthai as depthai_adapter +from capture_server.client import CaptureClient +from capture_server.mock import mock_depthai as dai +from tests.support.capture_server import start_capture_server, stop_capture_server + +SEED = 7 +WIDTH, HEIGHT = 64, 48 +#: How late each poll wakes, in seconds, repeating. At 10 fps the adapter's polls are 0.025 s apart. The mock +#: fixes its frame grid at the first poll, which is 0.012 s late, so later polls due on a frame land before it +#: (those less late than that) and after it (the others). One wakes later than a whole poll interval. +LATENESS = (0.012, 0.0, 0.02, 0.004, 0.016, 0.001, 0.04, 0.008, 0.0, 0.023) + + +class _Clock: + def __init__(self, t: float = 1000.0) -> None: + self.t = t + + def monotonic(self) -> float: + return self.t + + +@pytest.fixture +def clock(monkeypatch) -> _Clock: + """A clock that only the adapter's sleeps move: each ends late by the next entry of ``LATENESS``.""" + clock = _Clock() + real_sleep = asyncio.sleep + lateness = itertools.cycle(LATENESS) + + async def sleep(delay, *args, **kwargs): + clock.t += delay + next(lateness) + await real_sleep(0) + + monkeypatch.setattr(asyncio, "sleep", sleep) + return clock + + +def _camera(fps: float) -> p.CameraStreamConfig: + return p.CameraStreamConfig( + stream_id=1, + name="cam0", + type=p.CameraType.OAK_D_COLOR, + required=True, + width=WIDTH, + height=HEIGHT, + fps=fps, + jpeg_quality=80, + ) + + +def _frame_bytes(number: int) -> bytes: + """The mock's frame of that number (counting from one): each has its own colour.""" + return dai._jpeg_bytes(width=WIDTH, height=HEIGHT, seed=SEED, frame_num=number) + + +def _mock_adapter(clock: _Clock, fps: float = 10.0) -> DepthAIAdapter: + """The real adapter on the mock pipeline, both on the same clock.""" + + def pipeline(): + return dai.Pipeline(device_id="mock-oakd-1", seed=SEED, clock=clock) + + return DepthAIAdapter(sdk=dai, pipeline_factory=pipeline, camera=_camera(fps), clock=clock) + + +class _DeviceQueue: + """A camera's encoded-frame queue as a device keeps it: one slot, refilled on the device's own clock + whether or not anyone asks. A frame not taken before the next is ready is overwritten and gone, which + shows as a gap in the numbers of the frames handed out.""" + + def __init__(self, clock: _Clock, interval: float, first_at: float) -> None: + self._clock, self._interval, self._first_at = clock, interval, first_at + self._last = -1 + self.taken: list[int] = [] + + def setMaxSize(self, max_size: int) -> None: + assert max_size == 1 + + def setBlocking(self, blocking: bool) -> None: + assert blocking is False + + def tryGet(self): + now = self._clock.monotonic() + if now < self._first_at: + return None + latest = int((now - self._first_at) / self._interval + 1e-9) + if latest == self._last: + return None + self._last = latest + self.taken.append(latest) + return dai.EncodedFrame( + data=_frame_bytes(latest + 1), width=WIDTH, height=HEIGHT, sequence_num=latest, timestamp_s=now + ) + + +def _device_adapter(clock: _Clock, queue: _DeviceQueue, fps: float = 10.0) -> DepthAIAdapter: + """The real adapter on a pipeline whose encoder output is the device-like queue.""" + + class Pipeline(dai.Pipeline): + def _create_output_queue(self, *, resolution): + return queue + + def pipeline(): + return Pipeline(device_id="mock-oakd-1", seed=SEED, clock=clock) + + return DepthAIAdapter(sdk=dai, pipeline_factory=pipeline, camera=_camera(fps), clock=clock) + + +async def _poll(adapter: DepthAIAdapter, clock: _Clock, polls: int) -> list[tuple[float, object]]: + """Ask the adapter ``polls`` times; each entry is the instant of the poll and what it returned.""" + asked = [] + for _ in range(polls): + result = await adapter.next_camera_jpeg() + asked.append((clock.t, result)) + return asked + + +def _delivered(asked) -> list[tuple[float, int, bytes]]: + """The polls that returned a frame, as (instant, timestamp in ns, bytes).""" + return [(at, result[0], result[1]) for at, result in asked if result is not None] + + +async def test_every_due_frame_is_delivered_once_when_the_frame_grid_is_in_phase_with_jittering_polls(clock): + adapter = _mock_adapter(clock) + await adapter.enter() + try: + asked = await _poll(adapter, clock, 600) + finally: + await adapter.close() + frames = _delivered(asked) + interval, first = 0.1, frames[0][0] + # The mock's grid starts at the first poll: a frame is due every interval from there. Each one due by the + # last poll must have been delivered. + due = int((asked[-1][0] - first) / interval + 1e-9) + 1 + assert due > 150 + assert len(frames) == due + # In order, none twice and none missing: the mock numbers its frames, and each number has its own bytes. + assert [data for _at, _stamp, data in frames] == [_frame_bytes(number) for number in range(1, due + 1)] + # Each frame was taken in the interval it became due in, within a poll interval and the latest wake of it. + waits = [at - (first + slot * interval) for slot, (at, _stamp, _data) in enumerate(frames)] + assert min(waits) >= -1e-9 and max(waits) <= 0.025 + max(LATENESS) + 1e-9 + # The timestamp is the instant of the poll that took the frame. + assert all(stamp == int(at * 1_000_000_000) for at, stamp, _data in frames) + # Every other poll was empty and reported nothing, and none of them made the camera look unhealthy. + assert sum(result is None for _at, result in asked) == 600 - due + status = adapter.camera_status() + assert (status.status, status.reason, status.error) == (p.DeviceState.CONNECTED, p.StatusReason.NONE, "") + + +async def test_polls_land_on_both_sides_of_the_frames_in_this_drive(clock): + adapter = _mock_adapter(clock) + await adapter.enter() + try: + asked = await _poll(adapter, clock, 600) + finally: + await adapter.close() + frames = _delivered(asked) + first = frames[0][0] + waits = [round(at - (first + slot * 0.1), 6) for slot, (at, _stamp, _data) in enumerate(frames)] + # Some frames were taken by the poll due on them (it woke after the frame), others only by the next poll, a + # quarter interval on (the poll due on them woke before the frame): the hard case is really exercised. + assert any(wait < 0.02 for wait in waits[1:]) and any(wait > 0.02 for wait in waits[1:]) + + +async def test_asking_once_per_frame_interval_loses_frames_in_the_same_drive(clock, monkeypatch): + # The control for the test above: with the cadence this adapter must not have, the same clock and the same + # mock lose frames, so the drive is one in which frames can be lost. + monkeypatch.setattr(depthai_adapter, "_POLLS_PER_FRAME", 1) + adapter = _mock_adapter(clock) + await adapter.enter() + try: + asked = await _poll(adapter, clock, 150) + finally: + await adapter.close() + frames = _delivered(asked) + due = int((asked[-1][0] - frames[0][0]) / 0.1 + 1e-9) + 1 + assert len(frames) < 0.9 * due + + +async def test_no_frame_is_overwritten_in_a_device_queue_in_phase_with_jittering_polls(clock): + # The device's frames are ready on the adapter's own poll grid, 0.012 s after each fourth deadline: polls + # that wake sooner than that find the slot not yet refilled. + queue = _DeviceQueue(clock, 0.1, first_at=clock.t + 0.025 + 0.012) + adapter = _device_adapter(clock, queue) + await adapter.enter() + try: + asked = await _poll(adapter, clock, 600) + finally: + await adapter.close() + frames = _delivered(asked) + due = int((asked[-1][0] - (1000.0 + 0.025 + 0.012)) / 0.1 + 1e-9) + 1 + assert due > 150 + # The numbers of the frames handed out have no gap: the slot was emptied before each refill. + assert queue.taken == list(range(due)) + assert [data for _at, _stamp, data in frames] == [_frame_bytes(number) for number in range(1, due + 1)] + + +async def test_asking_once_per_frame_interval_lets_the_device_queue_overwrite_frames(clock, monkeypatch): + monkeypatch.setattr(depthai_adapter, "_POLLS_PER_FRAME", 1) + queue = _DeviceQueue(clock, 0.1, first_at=clock.t + 0.1 + 0.012) + adapter = _device_adapter(clock, queue) + await adapter.enter() + try: + await _poll(adapter, clock, 150) + finally: + await adapter.close() + assert queue.taken != list(range(queue.taken[-1] + 1)) + assert len(queue.taken) < 0.9 * (queue.taken[-1] + 1) + + +@pytest.mark.parametrize( + ("fps", "timeout"), + [ + (10.0, 5.0), + (30.0, 5.0), + # A slow camera: five frame intervals are ten seconds. Five poll intervals would be two and a half. + (0.5, 10.0), + ], +) +async def test_a_silent_camera_fails_after_the_same_time_whatever_the_poll_cadence(clock, fps, timeout): + queue = _DeviceQueue(clock, 1.0 / fps, first_at=float("inf")) + adapter = _device_adapter(clock, queue, fps) + await adapter.enter() + started = clock.t + try: + empty = 0 + with pytest.raises(CameraSourceError, match=r"no frame from the camera for \d+\.\ds") as failure: + while True: + assert await adapter.next_camera_jpeg() is None + empty += 1 + # Until the timeout every empty poll reports nothing and leaves the camera connected. + assert clock.t - started <= timeout + assert adapter.camera_status().status == p.DeviceState.CONNECTED + # It fails at the first poll past the timeout, which is at most one poll interval and one late wake on. + silent = clock.t - started + poll_interval = 1.0 / fps / 4 + assert timeout < silent <= timeout + poll_interval + max(LATENESS) + 1e-9 + assert str(failure.value) == f"no frame from the camera for {silent:.1f}s" + assert failure.value.camera_name == "cam0" + # There were more empty polls than frame intervals: the queue was asked more than once per interval. + assert empty > timeout * fps + status = adapter.camera_status() + assert (status.status, status.reason) == (p.DeviceState.DEGRADED, p.StatusReason.NO_CURRENT_DATA) + finally: + await adapter.close() + + +async def test_the_no_frame_timeout_counts_from_the_last_frame_not_from_the_last_poll(clock): + # Frames stop after the first; the empty polls that follow must not keep the camera alive. + class OneFrameQueue(_DeviceQueue): + def tryGet(self): + return super().tryGet() if not self.taken else None + + queue = OneFrameQueue(clock, 0.1, first_at=clock.t) + adapter = _device_adapter(clock, queue) + await adapter.enter() + try: + first = None + with pytest.raises(CameraSourceError, match="no frame from the camera"): + while True: + result = await adapter.next_camera_jpeg() + if result is not None: + first = clock.t + assert queue.taken == [0] and first is not None + assert 5.0 < clock.t - first <= 5.0 + 0.025 + max(LATENESS) + 1e-9 + finally: + await adapter.close() + + +def test_the_queue_is_asked_four_times_per_frame_interval_and_frame_measures_stay_on_the_frame_interval(): + adapter = DepthAIAdapter(sdk=None, pipeline_factory=lambda: None, camera=_camera(20.0)) + assert depthai_adapter._POLLS_PER_FRAME == 4 + assert adapter._interval == pytest.approx(0.05) and adapter._poll_interval == pytest.approx(0.0125) + + +async def test_the_server_publishes_one_frame_per_camera_frame_not_one_per_poll(unused_tcp_port): + # Real time, through the real server and client: the mock camera is declared at 30 fps. + running = await start_capture_server(unused_tcp_port) + try: + images, stopped, finished = [], [], asyncio.Event() + client = CaptureClient(f"ws://127.0.0.1:{unused_tcp_port}") + await client.start( + sources=(p.SourceType.HEAD,), + cameras=({"name": "camera_left", "type": p.CameraType.OAK_D_COLOR},), + on_capture_image=images.append, + on_stopped=lambda result: (stopped.append(result), finished.set()), + ) + await asyncio.sleep(1.5) + await client.stop() + await asyncio.wait_for(finished.wait(), timeout=5) + finally: + await stop_capture_server(running) + assert [image.sequence for image in images] == list(range(len(images))) + span = (images[-1].capture_time_ns - images[0].capture_time_ns) / 1e9 + rate = (len(images) - 1) / span + # Every frame, and no more than every frame: the empty polls between frames are counted nowhere. + assert 0.95 * 30.0 < rate < 1.05 * 30.0 + camera = next(counters for counters in stopped[0].streams if counters.stream_id != 0) + assert camera.produced == camera.sent + camera.dropped + assert len(images) <= camera.produced <= len(images) + 3 diff --git a/examples/egocap/tests/capture_server/test_mock_sdks.py b/examples/egocap/tests/capture_server/test_mock_sdks.py index 5a5745adca..359cf23b80 100644 --- a/examples/egocap/tests/capture_server/test_mock_sdks.py +++ b/examples/egocap/tests/capture_server/test_mock_sdks.py @@ -541,6 +541,75 @@ def test_camera_optional_failure_fault_raises_from_fill(): pipeline.stop() +def _poll_at(queue, clock, start: float, offsets) -> list[bool]: + """Poll at ``start`` plus each offset; True where a frame came.""" + got = [] + for offset in offsets: + clock.t = start + offset + got.append(queue.tryGet() is not None) + return got + + +def _after_each_frame(count: int, later: float = 0.0) -> list[float]: + """Poll offsets one frame interval apart at 10 fps, each 0.03 s after a frame becomes due. + + ``later`` moves every poll but the first a little further. A stall cycle starts at the first frame asked for + with the fault on, so that keeps the later polls clear of the instants at which a stall begins or ends: no + result then hangs on the last bit of a float. + """ + return [0.13 + 0.1 * k + (later if k else 0.0) for k in range(count)] + + +def test_camera_stall_fault_delivers_for_a_second_then_withholds_for_a_second_and_a_half_and_repeats(): + pipeline, queue, clock = _build_pipeline(faults={"camera_stall"}) + try: + assert queue.tryGet() is not None # the cycle starts with this first frame, at time zero + got = _poll_at(queue, clock, 0.0, _after_each_frame(59)) + # A second with frames, a second and a half without, and again: no stall reaches the two seconds after + # which the backend calls a camera stale. + assert got == [True] * 9 + [False] * 15 + [True] * 10 + [False] * 15 + [True] * 10 + # The rate a take spanning the first two cycles would record is under half the declared 10 fps. + frames, span = 1 + got[:49].count(True), 0.13 + 0.1 * 48 + assert (frames - 1) / span < 0.4 * 10.0 + finally: + pipeline.stop() + + +def test_camera_stall_fault_never_raises_and_keeps_the_frame_numbers_unbroken(): + pipeline, queue, clock = _build_pipeline(faults={"camera_stall"}) + try: + numbers = [] + for offset in [0.0, *_after_each_frame(39)]: + clock.t = offset + frame = queue.tryGet() + if frame is not None: + numbers.append(frame.getSequenceNum()) + assert numbers == list(range(1, 21)) + finally: + pipeline.stop() + + +def test_camera_stall_fault_switched_on_live_starts_with_a_delivering_second_and_off_delivers_at_once(): + pipeline, queue, clock = _build_pipeline() + try: + assert queue.tryGet() is not None + assert _poll_at(queue, clock, 0.0, _after_each_frame(30)) == [True] * 30 + pipeline.set_faults({"camera_stall"}) + # The cycle begins at the first frame asked for with the fault on, not when the pipeline started. + assert _poll_at(queue, clock, 3.0, _after_each_frame(20, later=0.02)) == [True] * 10 + [False] * 10 + pipeline.set_faults(None) + assert _poll_at(queue, clock, 5.0, _after_each_frame(5)) == [True] * 5 + # Switched on again, the cycle starts over with its delivering second. + pipeline.set_faults({"camera_stall"}) + assert _poll_at(queue, clock, 5.5, _after_each_frame(12, later=0.02)) == [True] * 10 + [False] * 2 + finally: + pipeline.stop() + + +def test_camera_stall_is_a_known_camera_fault(): + assert dai.KNOWN_FAULTS == {"camera_required_failure", "camera_optional_failure", "camera_stall"} + + def test_queue_closes_and_stops_producing_after_pipeline_stop(): pipeline, queue, clock = _build_pipeline() pipeline.stop() diff --git a/examples/egocap/tests/recording/unit/test_capture_qc.py b/examples/egocap/tests/recording/unit/test_capture_qc.py index 26fe1663af..2b567ecd13 100644 --- a/examples/egocap/tests/recording/unit/test_capture_qc.py +++ b/examples/egocap/tests/recording/unit/test_capture_qc.py @@ -31,8 +31,11 @@ CAMERA = VideoSourceSpec("cam", 64, 48, 60.0) -def _episode(tmp_path, *, cam_fps=60.0, cam_frames=61, pose_rate=10.0, pose=None, name="ep"): - """A staged episode: camera times at ``cam_fps``; tracker rows at ``pose_rate`` Hz with ``pose`` values.""" +def _episode(tmp_path, *, cam_fps=60.0, cam_frames=181, pose_rate=10.0, pose=None, name="ep"): + """A staged episode: camera times at ``cam_fps``; tracker rows at ``pose_rate`` Hz with ``pose`` values. + + By default both last three seconds: 181 camera frames at 60 fps and 31 tracker rows at 10 Hz. + """ root = zarr.open_group(str(tmp_path / name), mode="w") root.create_group("cam").create_array("capture_time", data=np.arange(cam_frames) / cam_fps) rows = 31 if pose is None else len(pose) @@ -63,9 +66,14 @@ def test_healthy_capture_passes_with_measured_evidence(tmp_path): "sustained_freeze:tracker/pose", "flat_motion:tracker/pose", "dead_stream:tracker/pose", + "zero_pose:tracker/pose", "frame_drops:cam", + "camera_rate_measurable:cam", + "camera_fps_deviation:cam", } - assert results["camera_min_fps:cam"].evidence == ("60.00 fps average (minimum 51.60)",) + assert results["camera_min_fps:cam"].evidence == ( + "60.00 fps average (minimum 51.60); 181 of 180.0 frames in a 3.00s take (needs 152.2)", + ) assert results["sustained_freeze:tracker/pose"].evidence == ("longest still window 0.00s (limit 1.0s)",) assert decide(report) is QcDecision.PASSED @@ -80,10 +88,14 @@ def test_camera_minimum_fps_threshold_is_the_native_ratio_of_expected(tmp_path, assert decide(report) is (QcDecision.PASSED if passes else QcDecision.REJECTED_CAMERA) -def test_a_camera_with_fewer_than_two_frames_counts_as_zero_fps(tmp_path): - """One frame has no duration, so its rate is 0 and the gate fails (native convention).""" +def test_a_camera_with_one_frame_in_a_take_that_lasted_three_seconds_is_rejected(tmp_path): + """One frame has no rate, and the take held 180: the camera delivered next to nothing.""" report = check_capture_quality(_episode(tmp_path, cam_frames=1), _config()) - assert _by_name(report)["camera_min_fps:cam"].outcome is Outcome.FAILED + camera = _by_name(report)["camera_min_fps:cam"] + assert camera.outcome is Outcome.FAILED + assert camera.issues == ("cam: 1 frame(s) recorded of the 180.0 a 3.00s take holds at 60.0 fps (needs 152.2)",) + assert "fps" not in camera.measurements and camera.measurements["take_s"] == pytest.approx(3.0) + assert camera.measurements["take_frames"] == pytest.approx(180.0) assert decide(report) is QcDecision.REJECTED_CAMERA @@ -187,7 +199,7 @@ def test_evidence_round_trips_and_an_older_report_without_it_still_loads(tmp_pat @pytest.mark.parametrize( ("overrides", "problem"), [ - ({"camera_expected_fps": (), "pose_streams": ()}, "names no camera, parity, pose stream"), + ({"camera_expected_fps": (), "pose_streams": ()}, "names no check to run"), ({"camera_expected_fps": (("nope", 60.0),)}, "unknown video source 'nope'"), ({"camera_expected_fps": (("cam", 0.0),)}, "'cam' must be a finite number > 0"), ({"camera_expected_fps": (("cam", float("inf")),)}, "'cam' must be a finite number > 0"), diff --git a/examples/egocap/tests/recording/unit/test_capture_qc_gaps_and_advisories.py b/examples/egocap/tests/recording/unit/test_capture_qc_gaps_and_advisories.py new file mode 100644 index 0000000000..2eda860346 --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_capture_qc_gaps_and_advisories.py @@ -0,0 +1,486 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The tracking-gap, duration, zero-pose, camera-rate-deviation and resolution checks, and their switches. + +Explicit arrays with known answers, written to real Zarr groups (and one real encoded video) and read back by +the production checker. Each check is exercised on both sides of its threshold. +""" + +import cv2 +import numpy as np +import pytest +import zarr + +from egocap.recording.capture_measure import longest_gap_seconds, video_frame_size, zeroed_pose_rows +from egocap.recording.capture_qc import ( + ALGORITHM_VERSION, + CaptureQcConfig, + PolicySource, + QcDecision, + advisory_results, + check_capture_quality, + decide, + deciding_results, + policy_to_dict, + quality_attributes, +) +from egocap.recording.dataset_check import CheckResult, Outcome, QualityReport +from egocap.recording.episode_store import FieldSpec, NumericSourceSpec, VideoSourceSpec + +TRACKER = NumericSourceSpec("tracker", (FieldSpec("pose", "float64", (4, 4)),)) +CAMERA = VideoSourceSpec("cam", 64, 48, 60.0) + + +def _moving_poses(rows): + """Homogeneous transforms whose translation changes every row.""" + poses = np.broadcast_to(np.eye(4), (rows, 4, 4)).copy() + poses[:, 0, 3] = np.arange(rows, dtype=np.float64) + return poses + + +def _episode(tmp_path, *, cam_times=None, tracker_times=None, poses=None, name="ep"): + """A staged episode with one camera and one tracker; defaults are 2 s of healthy data at 60 Hz and 10 Hz. + + A camera left to the default records for as long as the tracker did, at 60 Hz (2 s when the tracker has + no span of its own). + """ + root = zarr.open_group(str(tmp_path / name), mode="w") + tracker_times = np.arange(21) / 10.0 if tracker_times is None else np.asarray(tracker_times, dtype=np.float64) + seconds = float(tracker_times[-1] - tracker_times[0]) if len(tracker_times) > 1 else 2.0 + whole_take = np.arange(int(round(seconds * 60.0)) + 1) / 60.0 + cam_times = whole_take if cam_times is None else np.asarray(cam_times, dtype=np.float64) + root.create_group("cam").create_array("capture_time", data=cam_times) + tracker = root.create_group("tracker") + tracker.create_array("capture_time", data=tracker_times) + tracker.create_array("pose", data=_moving_poses(len(tracker_times)) if poses is None else poses) + return tmp_path / name + + +def _write_video(path, width, height, frames=3): + """A real encoded file of the given frame size.""" + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 30.0, (width, height)) + for _ in range(frames): + writer.write(np.zeros((height, width, 3), dtype=np.uint8)) + writer.release() + + +def _config(**overrides): + base = dict( + camera_expected_fps=(("cam", 60.0),), + pose_streams=(("tracker", "pose"),), + tracking_gap_sources=("tracker",), + duration_limits_s=(1.0, 600.0), + ) + return CaptureQcConfig(**{**base, **overrides}) + + +def _by_name(report): + return {r.name: r for r in report.check_results} + + +def test_the_algorithm_version_names_the_rules_with_the_added_checks(): + assert ALGORITHM_VERSION == 4 + + +def test_a_healthy_take_passes_every_added_check_and_stores_its_measurements(tmp_path): + report = check_capture_quality(_episode(tmp_path), _config()) + results = _by_name(report) + assert report.outcome is Outcome.PASSED and not report.warnings and decide(report) is QcDecision.PASSED + assert results["tracking_gap_warning:tracker"].measurements == { + "longest_gap_s": pytest.approx(0.1), + "limit_s": 1.0, + "rows": 21, + } + assert results["duration_warning"].measurements == { + "duration_s": pytest.approx(2.0), + "min_s": 1.0, + "max_s": 600.0, + } + assert results["zero_pose:tracker/pose"].measurements == {"zero_rows": 0, "rows": 21} + deviation = results["camera_fps_deviation:cam"].measurements + assert deviation["fps"] == pytest.approx(60.0) and deviation["deviation_pct"] == pytest.approx(0.0) + assert deviation["expected_fps"] == 60.0 and deviation["limit_pct"] == 10.0 + assert results["camera_min_fps:cam"].measurements == { + "fps": pytest.approx(60.0), + "minimum_fps": pytest.approx(51.6), + "expected_fps": 60.0, + "frames": 121, + "span_s": pytest.approx(2.0), + "take_s": pytest.approx(2.0), + "take_frames": pytest.approx(120.0), + "needed_frames": pytest.approx(0.86 * 117), + } + assert results["sustained_freeze:tracker/pose"].measurements == {"longest_still_s": 0.0, "limit_s": 1.0} + + +@pytest.mark.parametrize(("hole", "fails"), [(0.9, False), (1.0, True), (1.5, True)]) +def test_a_hole_in_the_rows_is_a_tracking_gap_at_the_limit_and_above(tmp_path, hole, fails): + times = np.concatenate([np.arange(6) / 10.0, 0.5 + hole + np.arange(6) / 10.0]) + report = check_capture_quality(_episode(tmp_path, tracker_times=times), _config()) + gap = _by_name(report)["tracking_gap_warning:tracker"] + assert (gap.outcome is Outcome.FAILED) is fails + assert gap.measurements["longest_gap_s"] == pytest.approx(hole) + assert not fails or gap.issues == (f"tracker: no row for {hole:.2f}s (limit 1.0s)",) + + +def test_a_hole_in_the_rows_is_seen_by_the_gap_check_and_not_by_the_freeze_check(tmp_path): + times = np.concatenate([np.arange(6) / 10.0, 2.0 + np.arange(6) / 10.0]) + report = check_capture_quality(_episode(tmp_path, tracker_times=times), _config()) + results = _by_name(report) + assert results["sustained_freeze:tracker/pose"].outcome is Outcome.PASSED + assert results["sustained_freeze:tracker/pose"].measurements["longest_still_s"] == 0.0 + assert results["tracking_gap_warning:tracker"].outcome is Outcome.FAILED + + +def test_a_tracking_gap_only_warns_by_default_and_marks_the_take_bad_when_switched_on(tmp_path): + times = np.concatenate([np.arange(6) / 10.0, 2.0 + np.arange(6) / 10.0]) + path = _episode(tmp_path, tracker_times=times) + warned = check_capture_quality(path, _config()) + assert decide(warned) is QcDecision.PASSED and warned.outcome is Outcome.PASSED + assert warned.warnings == ("tracker: no row for 1.50s (limit 1.0s)",) and not warned.issues + gated = check_capture_quality(path, _config(tracking_gap_marks_bad=True)) + assert "tracking_gap_warning:tracker" not in _by_name(gated) + assert _by_name(gated)["tracking_gap:tracker"].outcome is Outcome.FAILED + assert decide(gated) is QcDecision.FLAGGED_BAD and gated.issues == ("tracker: no row for 1.50s (limit 1.0s)",) + + +@pytest.mark.parametrize("rows", [0, 1]) +def test_a_tracking_source_with_fewer_than_two_rows_is_a_gap_finding(tmp_path, rows): + path = _episode(tmp_path, tracker_times=np.arange(rows) / 10.0) + gap = _by_name(check_capture_quality(path, _config()))["tracking_gap_warning:tracker"] + assert gap.outcome is Outcome.FAILED and gap.issues == (f"tracker: only {rows} row(s) recorded",) + assert gap.measurements["rows"] == rows and gap.measurements["longest_gap_s"] == 0.0 + + +def test_a_gating_tracking_gap_counts_in_the_stored_tracking_verdict(tmp_path): + times = np.concatenate([np.arange(6) / 10.0, 2.0 + np.arange(6) / 10.0]) + report = check_capture_quality(_episode(tmp_path, tracker_times=times), _config(tracking_gap_marks_bad=True)) + attributes = quality_attributes(decide(report), report, None) + assert attributes["bad_episode"] is True and attributes["freeze_check_passed"] is False + assert attributes["freeze_check_issues"] == ["tracker: no row for 1.50s (limit 1.0s)"] + + +@pytest.mark.parametrize( + ("seconds", "limits", "fails"), + [(2.0, (1.0, 600.0), False), (2.0, (2.0, 600.0), False), (2.0, (2.5, 600.0), True), (2.0, (0.5, 1.5), True)], +) +def test_duration_is_judged_against_both_limits_inclusive(tmp_path, seconds, limits, fails): + report = check_capture_quality(_episode(tmp_path), _config(duration_limits_s=limits)) + duration = _by_name(report)["duration_warning"] + assert (duration.outcome is Outcome.FAILED) is fails + assert duration.measurements["duration_s"] == pytest.approx(seconds) + assert not fails or duration.issues == (f"the take lasted 2.00s, outside {limits[0]}s to {limits[1]}s",) + + +def test_duration_is_the_longest_span_of_one_source_never_a_difference_across_sources(tmp_path): + # The camera's clock starts 100 s after the tracker's: a span taken across the two would be over 100 s. + path = _episode(tmp_path, cam_times=100.0 + np.arange(61) / 60.0, tracker_times=np.arange(31) / 10.0) + duration = _by_name(check_capture_quality(path, _config()))["duration_warning"] + assert duration.measurements["duration_s"] == pytest.approx(3.0) and duration.outcome is Outcome.PASSED + + +def test_duration_only_warns_by_default_and_marks_the_take_bad_when_switched_on(tmp_path): + path = _episode(tmp_path) + warned = check_capture_quality(path, _config(duration_limits_s=(5.0, 600.0))) + assert decide(warned) is QcDecision.PASSED and warned.warnings == ( + "the take lasted 2.00s, outside 5.0s to 600.0s", + ) + gated = check_capture_quality(path, _config(duration_limits_s=(5.0, 600.0), duration_marks_bad=True)) + assert "duration_warning" not in _by_name(gated) and _by_name(gated)["duration"].outcome is Outcome.FAILED + assert decide(gated) is QcDecision.FLAGGED_BAD + # The take's length is not a tracking fault, so the tracking verdict stays as the tracking gates left it. + assert quality_attributes(QcDecision.FLAGGED_BAD, gated, None)["freeze_check_passed"] is True + + +def test_a_take_with_no_rows_at_all_has_no_duration(tmp_path): + path = _episode(tmp_path, cam_times=[], tracker_times=[]) + duration = _by_name(check_capture_quality(path, _config()))["duration_warning"] + assert duration.outcome is Outcome.FAILED and duration.measurements["duration_s"] == 0.0 + + +def test_without_duration_limits_no_duration_check_runs(tmp_path): + names = set(_by_name(check_capture_quality(_episode(tmp_path), _config(duration_limits_s=None)))) + assert not {"duration", "duration_warning"} & names + + +@pytest.mark.parametrize( + ("fps", "fails", "side"), [(65.0, False, ""), (67.0, True, "above"), (53.0, True, "below")] +) +def test_camera_rate_deviation_warns_in_either_direction_past_the_limit(tmp_path, fps, fails, side): + path = _episode(tmp_path, cam_times=np.arange(121) / fps) + report = check_capture_quality(path, _config()) + deviation = _by_name(report)["camera_fps_deviation:cam"] + assert (deviation.outcome is Outcome.FAILED) is fails + assert not fails or f"{side} the expected 60.0 (limit 10.0%)" in deviation.issues[0] + # 53 fps is above the 51.6 minimum, so only the two-sided warning sees it; neither case changes the decision. + assert decide(report) is QcDecision.PASSED and (report.warnings == deviation.issues if fails else True) + + +def test_a_rate_declared_too_low_is_caught_by_the_deviation_warning_only(tmp_path): + # The camera really runs at 60 while 30 was declared: the one-sided minimum passes and cannot see it. + report = check_capture_quality(_episode(tmp_path), _config(camera_expected_fps=(("cam", 30.0),))) + results = _by_name(report) + assert results["camera_min_fps:cam"].outcome is Outcome.PASSED + assert results["camera_fps_deviation:cam"].outcome is Outcome.FAILED + assert results["camera_fps_deviation:cam"].measurements["deviation_pct"] == pytest.approx(100.0) + + +def test_zeroed_pose_rows_are_counted_and_warned_without_changing_the_decision(tmp_path): + poses = _moving_poses(21) + poses[[3, 7, 8]] = 0.0 + report = check_capture_quality(_episode(tmp_path, poses=poses), _config(freeze_seconds=5.0)) + zero = _by_name(report)["zero_pose:tracker/pose"] + assert zero.outcome is Outcome.FAILED and zero.measurements == {"zero_rows": 3, "rows": 21} + assert zero.issues == ("tracker/pose: 3 of 21 rows hold a zeroed pose (below 0.0001)",) + assert decide(report) is QcDecision.PASSED and zero.issues[0] in report.warnings + + +def test_a_row_is_zeroed_when_any_one_of_its_transforms_is(tmp_path): + hand = np.broadcast_to(np.eye(4), (5, 25, 4, 4)).copy() + hand[2, 11] = 0.0 # one finger joint of one row + hand[4, :] = 5e-5 # every joint below the tolerance + assert zeroed_pose_rows(hand, 1e-4) == 2 + assert zeroed_pose_rows(hand, 1e-5) == 1 + + +def test_zeroed_rows_of_a_field_that_is_not_made_of_transforms_are_judged_whole(): + values = np.ones((4, 3)) + values[1] = 0.0 + values[2, 0] = 0.0 # one zero element is not a zeroed row + assert zeroed_pose_rows(values, 1e-4) == 1 + assert zeroed_pose_rows(np.zeros((0, 4, 4)), 1e-4) == 0 + assert zeroed_pose_rows(np.float64(0.0), 1e-4) == 0 + + +def test_longest_gap_needs_two_rows_and_reports_the_widest_interval(): + assert longest_gap_seconds(np.array([])) == 0.0 and longest_gap_seconds(np.array([4.0])) == 0.0 + assert longest_gap_seconds(np.array([0.0, 0.1, 0.9, 1.0])) == pytest.approx(0.8) + + +def test_resolution_passes_when_the_encoded_size_is_the_declared_one(tmp_path): + path = _episode(tmp_path) + _write_video(path / "cam.mp4", 64, 48) + report = check_capture_quality(path, _config(camera_expected_size=(("cam", (64, 48)),))) + resolution = _by_name(report)["resolution:cam"] + assert resolution.outcome is Outcome.PASSED + assert resolution.measurements == {"width": 64, "height": 48, "expected_width": 64, "expected_height": 48} + + +def test_resolution_warns_when_the_encoded_size_differs_and_never_decides(tmp_path): + path = _episode(tmp_path) + _write_video(path / "cam.mp4", 32, 24) + report = check_capture_quality(path, _config(camera_expected_size=(("cam", (64, 48)),))) + resolution = _by_name(report)["resolution:cam"] + assert resolution.outcome is Outcome.FAILED + assert resolution.issues == ("cam: encoded frames are 32x24, declared 64x48",) + assert report.warnings == resolution.issues and decide(report) is QcDecision.PASSED + + +@pytest.mark.parametrize("content", [None, b"not a video"]) +def test_a_missing_or_unreadable_video_is_an_error_of_the_resolution_check_not_a_pass(tmp_path, content): + path = _episode(tmp_path) + if content is not None: + (path / "cam.mp4").write_bytes(content) + report = check_capture_quality(path, _config(camera_expected_size=(("cam", (64, 48)),))) + resolution = _by_name(report)["resolution:cam"] + assert resolution.outcome is Outcome.ERROR + # The finding is stored with the take and can reach the operator, so it must not hold the file's location. + assert resolution.issues == ( + "resolution:cam could not run: ValueError: the video file is missing or cannot be opened", + ) + assert str(tmp_path) not in resolution.issues[0] + assert report.warnings == resolution.issues and decide(report) is QcDecision.PASSED + + +def test_video_frame_size_reads_the_header_and_refuses_a_missing_file(tmp_path): + _write_video(tmp_path / "v.mp4", 48, 32) + assert video_frame_size(tmp_path / "v.mp4") == (48, 32) + with pytest.raises(ValueError, match="missing or cannot be opened") as raised: + video_frame_size(tmp_path / "absent.mp4") + assert str(tmp_path) not in str(raised.value) + + +def test_a_default_size_resolves_to_the_sources_own_and_an_explicit_size_wins(): + video = (CAMERA, VideoSourceSpec("other", 32, 24, 30.0)) + config = _config(camera_expected_size=(("cam", None), ("other", (640, 480)), ("ghost", None))) + assert config.resolved(video).camera_expected_size == ( + ("cam", (64, 48)), + ("other", (640, 480)), + ("ghost", None), + ) + + +def test_checking_with_an_unresolved_size_or_rate_is_an_error_for_that_check_not_a_crash(tmp_path): + config = _config(camera_expected_fps=(("cam", None),), camera_expected_size=(("cam", None),)) + results = _by_name(check_capture_quality(_episode(tmp_path), config)) + for name in ("resolution:cam", "camera_fps_deviation:cam"): + assert results[name].outcome is Outcome.ERROR and "unresolved" in results[name].issues[0] + + +def test_a_check_that_cannot_read_its_data_is_an_error_and_a_gating_one_retains_the_take(tmp_path): + path = _episode(tmp_path) + config = _config(tracking_gap_sources=("ghost",), pose_streams=(("ghost", "pose"),), freeze_enabled=False) + warned = _by_name(check_capture_quality(path, config)) + assert warned["tracking_gap_warning:ghost"].outcome is Outcome.ERROR + assert warned["zero_pose:ghost/pose"].outcome is Outcome.ERROR + assert decide(check_capture_quality(path, config)) is QcDecision.PASSED + gated = check_capture_quality(path, _config(tracking_gap_sources=("ghost",), tracking_gap_marks_bad=True)) + assert _by_name(gated)["tracking_gap:ghost"].outcome is Outcome.ERROR and decide(gated) is QcDecision.ERROR + + +def test_a_source_without_timestamps_makes_the_duration_check_an_error(tmp_path): + path = _episode(tmp_path) + zarr.open_group(str(path), mode="r+").create_group("stray") + report = check_capture_quality(path, _config(duration_marks_bad=True)) + assert _by_name(report)["duration"].outcome is Outcome.ERROR and decide(report) is QcDecision.ERROR + + +def test_warnings_of_every_added_check_together_never_change_the_decision(tmp_path): + poses = _moving_poses(12) + poses[0] = 0.0 + times = np.concatenate([np.arange(6) / 10.0, 2.0 + np.arange(6) / 10.0]) + path = _episode(tmp_path, cam_times=np.arange(176) / 70.0, tracker_times=times, poses=poses) + _write_video(path / "cam.mp4", 32, 24) + config = _config(duration_limits_s=(10.0, 600.0), camera_expected_size=(("cam", (64, 48)),)) + report = check_capture_quality(path, config) + failed = {name for name, r in _by_name(report).items() if r.outcome is Outcome.FAILED} + assert failed == { + "tracking_gap_warning:tracker", + "duration_warning", + "zero_pose:tracker/pose", + "camera_fps_deviation:cam", + "resolution:cam", + } + assert report.outcome is Outcome.PASSED and not report.issues and len(report.warnings) == 5 + assert decide(report) is QcDecision.PASSED + assert quality_attributes(QcDecision.PASSED, report, None)["bad_episode"] is False + + +def test_switching_a_gate_off_leaves_its_streams_to_the_advisories(tmp_path): + frozen = np.broadcast_to(np.eye(4), (21, 4, 4)).copy() + path = _episode(tmp_path, cam_times=np.arange(121) / 30.0, poses=frozen) + judged = check_capture_quality(path, _config()) + assert decide(judged) is QcDecision.REJECTED_CAMERA + report = check_capture_quality( + path, _config(camera_min_fps_enabled=False, freeze_enabled=False, dead_stream_enabled=False) + ) + names = set(_by_name(report)) + assert not {"camera_min_fps:cam", "sustained_freeze:tracker/pose", "dead_stream:tracker/pose"} & names + assert {"frame_drops:cam", "camera_fps_deviation:cam", "flat_motion:tracker/pose"} <= names + assert decide(report) is QcDecision.PASSED and report.warnings + + +def test_an_unreadable_episode_reports_only_the_gates_that_are_switched_on(tmp_path): + every = _config(tracking_gap_marks_bad=True, duration_marks_bad=True) + report = check_capture_quality(tmp_path / "missing", every) + assert {r.name for r in report.check_results} == { + "camera_min_fps:cam", + "sustained_freeze:tracker/pose", + "tracking_gap:tracker", + "duration", + } + assert decide(report) is QcDecision.ERROR + none = _config(camera_min_fps_enabled=False, freeze_enabled=False) + assert check_capture_quality(tmp_path / "missing", none).check_results == () + + +@pytest.mark.parametrize( + ("overrides", "problem"), + [ + ({"tracking_gap_sources": ("nope",)}, "tracking_gap_sources names unknown numeric source 'nope'"), + ({"tracking_gap_seconds": 0.0}, "tracking_gap_seconds must be a finite number > 0"), + ({"zero_pose_eps": -1.0}, "zero_pose_eps must be a finite number > 0"), + ({"fps_deviation_pct": float("inf")}, "fps_deviation_pct must be a finite number > 0"), + ({"duration_limits_s": (5.0, 5.0)}, "duration_limits_s must be a finite (shortest, longest)"), + ({"duration_limits_s": (-1.0, 5.0)}, "duration_limits_s must be a finite (shortest, longest)"), + ({"duration_limits_s": (1.0, float("inf"))}, "duration_limits_s must be a finite (shortest, longest)"), + ({"camera_expected_size": (("nope", None),)}, "camera_expected_size names unknown video source 'nope'"), + ({"camera_expected_size": (("cam", (0, 48)),)}, "camera_expected_size for 'cam' must be a positive width"), + ( + {"camera_expected_size": (("cam", (64.0, 48)),)}, + "camera_expected_size for 'cam' must be a positive width", + ), + ], +) +def test_configuration_problems_of_the_added_checks_are_named(overrides, problem): + problems = _config(**overrides).problems((TRACKER,), (CAMERA,)) + assert any(problem in p for p in problems), problems + + +def test_a_configuration_with_every_added_check_declared_has_no_problems(): + config = _config(camera_expected_size=(("cam", None),)) + assert config.problems((TRACKER,), (CAMERA,)) == [] + + +@pytest.mark.parametrize( + "only", + [ + {"tracking_gap_sources": ("tracker",)}, + {"duration_limits_s": (1.0, 2.0)}, + {"camera_expected_size": (("cam", None),)}, + ], +) +def test_declaring_any_one_added_check_is_enough_to_have_something_to_run(only): + assert CaptureQcConfig(**only).problems((TRACKER,), (CAMERA,)) == [] + assert CaptureQcConfig().problems((TRACKER,), (CAMERA,)) == ["capture QC names no check to run"] + + +def test_the_stored_policy_holds_the_added_thresholds_and_where_the_values_came_from(): + source = PolicySource( + "data_check_config.yaml", + "digest", + (("guardrails.camera_expected_fps", (("cam", 30.0),)), ("guardrails.freeze_seconds", 2.0)), + ) + policy = policy_to_dict(_config(source=source, camera_expected_size=(("cam", (64, 48)),))) + assert policy["tracking_gap_seconds"] == 1.0 and policy["tracking_gap_marks_bad"] is False + assert policy["zero_pose_eps"] == 1e-4 and policy["fps_deviation_pct"] == 10.0 + assert policy["duration_limits_s"] == (1.0, 600.0) and policy["duration_marks_bad"] is False + assert policy["camera_expected_size"] == (("cam", (64, 48)),) + assert policy["source"] == { + "defaults_file": "data_check_config.yaml", + "defaults_sha256": "digest", + "station_overrides": {"guardrails.camera_expected_fps": {"cam": 30.0}, "guardrails.freeze_seconds": 2.0}, + } + assert policy_to_dict(_config())["source"] == { + "defaults_file": "", + "defaults_sha256": "", + "station_overrides": {}, + } + + +def _results(*named): + return QualityReport(Outcome.PASSED, (), (), tuple(CheckResult(name, outcome) for name, outcome in named)) + + +def test_the_results_behind_a_decision_are_the_failed_gates_of_the_class_that_decided(): + report = _results( + ("camera_min_fps:cam", Outcome.FAILED), + ("camera_frame_parity", Outcome.PASSED), + ("sustained_freeze:t/pose", Outcome.FAILED), + ("tracking_gap:t", Outcome.FAILED), + ("duration", Outcome.FAILED), + ("avatar_hand_liveness:t/left", Outcome.ERROR), + ("tracking_gap_warning:t", Outcome.FAILED), + ("frame_drops:cam", Outcome.FAILED), + ) + names = lambda decision: [r.name for r in deciding_results(report, decision)] # noqa: E731 + assert names(QcDecision.REJECTED_CAMERA) == ["camera_min_fps:cam"] + assert names(QcDecision.FLAGGED_BAD) == ["sustained_freeze:t/pose", "tracking_gap:t", "duration"] + assert names(QcDecision.ERROR) == ["avatar_hand_liveness:t/left"] + assert names(QcDecision.PASSED) == [] and names(QcDecision.SKIPPED) == [] + assert deciding_results(None, QcDecision.FLAGGED_BAD) == () + + +def test_the_advisory_results_are_the_warnings_that_did_not_pass_never_a_gate(): + report = _results( + ("camera_min_fps:cam", Outcome.FAILED), + ("duration", Outcome.FAILED), + ("duration_warning", Outcome.FAILED), + ("tracking_gap_warning:t", Outcome.PASSED), + ("zero_pose:t/pose", Outcome.FAILED), + ("resolution:cam", Outcome.ERROR), + ) + assert [r.name for r in advisory_results(report)] == ["duration_warning", "zero_pose:t/pose", "resolution:cam"] + assert advisory_results(None) == () diff --git a/examples/egocap/tests/recording/unit/test_capture_qc_policy.py b/examples/egocap/tests/recording/unit/test_capture_qc_policy.py new file mode 100644 index 0000000000..a9061fa32a --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_capture_qc_policy.py @@ -0,0 +1,322 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The capture-QC policy loader: the shipped defaults file, a station's overrides, and what a session runs.""" + +import dataclasses +import hashlib + +import pytest +import yaml + +from egocap.recording import capture_qc_policy as policy_module +from egocap.recording.capture_qc import CaptureQcConfig, PolicySource +from egocap.recording.capture_qc_policy import ( + SHIPPED_POLICY_FILE, + CaptureQcPolicy, + CaptureQcPolicyError, + capture_config_for, + effective_mapping, + load_policy, + resolve_policy, + validate_section, +) +from egocap.recording.episode_store import FieldSpec, NumericSourceSpec, VideoSourceSpec + +TRACKING = (("tracker", "head"), ("tracker", "left")) +GLOVES = (("glove", "left_hand"), ("glove", "right_hand")) +NUMERIC = ( + NumericSourceSpec("tracker", (FieldSpec("head", "float64", (4, 4)), FieldSpec("left", "float64", (4, 4)))), + NumericSourceSpec( + "glove", (FieldSpec("left_hand", "float64", (25, 4, 4)), FieldSpec("right_hand", "float64", (25, 4, 4))) + ), +) +VIDEO = (VideoSourceSpec("cam_a", 64, 48, 60.0), VideoSourceSpec("cam_b", 64, 48, 30.0)) + + +def _thresholds(policy): + """A policy without the record of where its values came from.""" + return dataclasses.replace(policy, source=PolicySource()) + + +def _flat_keys(mapping, prefix=""): + """Every leaf key of a nested mapping, dotted.""" + keys = set() + for name, value in mapping.items(): + if isinstance(value, dict): + keys |= _flat_keys(value, f"{prefix}{name}.") + else: + keys.add(f"{prefix}{name}") + return keys + + +def test_the_shipped_file_resolves_to_exactly_the_built_in_values(): + assert _thresholds(load_policy()) == CaptureQcPolicy() + + +def test_the_shipped_file_documents_every_key_a_defaults_file_may_hold(): + documented = _flat_keys(yaml.safe_load(SHIPPED_POLICY_FILE.read_text())) + assert documented == set(policy_module._FILE_KEYS) + + +def test_every_policy_field_is_reachable_from_a_key_and_no_key_is_orphaned(): + reachable = {name for name, _ in (*policy_module._FILE_KEYS.values(), *policy_module._STATION_KEYS.values())} + assert reachable | {"source"} == {f.name for f in dataclasses.fields(CaptureQcPolicy)} + + +def test_the_built_in_numbers_are_the_checkers_own_defaults(): + policy, checker = CaptureQcPolicy(), CaptureQcConfig() + config = capture_config_for(policy, ("cam_a",), TRACKING) + # Built from the policy, every threshold the two share is the checker's default: one authority per number. + shared = { + f.name + for f in dataclasses.fields(CaptureQcConfig) + if isinstance(getattr(checker, f.name), (int, float)) and not isinstance(getattr(checker, f.name), bool) + } + assert shared and all(getattr(config, name) == getattr(checker, name) for name in shared) + + +def test_quarantine_is_on_and_no_gate_is_switched_to_trial_by_default(): + policy = CaptureQcPolicy() + assert policy.enabled and policy.quarantine and policy.camera_min_fps_enabled and policy.freeze_enabled + assert not policy.tracking_gap_marks_bad and not policy.duration_marks_bad and not policy.gloves_expected + assert not hasattr(policy, "camera_min_fps_rejects") + + +def test_the_loaded_policy_names_its_file_by_base_name_and_digest_only(): + source = load_policy().source + assert source.defaults_file == "data_check_config.yaml" + assert source.defaults_sha256 == hashlib.sha256(SHIPPED_POLICY_FILE.read_bytes()).hexdigest() + assert source.station_overrides == () + + +def test_a_station_section_overrides_one_key_and_leaves_the_rest(): + policy = load_policy(station={"guardrails": {"camera_min_fps_ratio": 0.8}}) + assert policy.camera_min_fps_ratio == 0.8 + assert dataclasses.replace(_thresholds(policy), camera_min_fps_ratio=0.86) == CaptureQcPolicy() + assert policy.source.station_overrides == (("guardrails.camera_min_fps_ratio", 0.8),) + + +def test_the_station_section_wins_over_the_file_which_wins_over_the_built_in_value(tmp_path): + path = tmp_path / "site.yaml" + path.write_text("guardrails:\n freeze_seconds: 2.0\n flat_seconds: 3.0\nduration:\n marks_bad: true\n") + policy = load_policy(path, {"guardrails": {"freeze_seconds": 4, "quarantine": False}}) + assert (policy.freeze_seconds, policy.flat_seconds, policy.duration_marks_bad) == (4.0, 3.0, True) + assert policy.quarantine is False and policy.tracking_gap_seconds == 1.0 + assert policy.source.defaults_file == "site.yaml" + assert policy.source.station_overrides == ( + ("guardrails.freeze_seconds", 4.0), + ("guardrails.quarantine", False), + ) + + +def test_an_empty_file_and_an_empty_section_set_nothing(tmp_path): + (tmp_path / "empty.yaml").write_text("# nothing configured\n") + assert _thresholds(load_policy(tmp_path / "empty.yaml", {})) == CaptureQcPolicy() + assert _thresholds(resolve_policy()) == CaptureQcPolicy() + assert _thresholds(resolve_policy({"guardrails": None, "duration": {"default": None}})) == CaptureQcPolicy() + + +def test_whole_numbers_are_accepted_for_thresholds_and_stored_as_floats(): + policy = resolve_policy({"guardrails": {"freeze_seconds": 2, "camera_min_fps_ratio": 1}}) + assert policy.freeze_seconds == 2.0 and isinstance(policy.freeze_seconds, float) + assert policy.camera_min_fps_ratio == 1.0 + + +@pytest.mark.parametrize( + ("section", "named"), + [ + ({"guardrails": {"camera_min_fps_rejects": False}}, "unknown key 'guardrails.camera_min_fps_rejects'"), + ({"guardrails": {"frozen_seconds": 1.0}}, "unknown key 'guardrails.frozen_seconds'"), + ({"timestamp": {"coverage_threshold": 0.9}}, "unknown key 'timestamp.coverage_threshold'"), + ({"pico_body_joints": {"enabled": True}}, "unknown key 'pico_body_joints'"), + ({"duration": {"default": {"shortest": 1}}}, "unknown key 'duration.default.shortest'"), + ({"guardrails": {"enabled": "yes"}}, "guardrails.enabled must be true or false, got 'yes'"), + ({"guardrails": {"quarantine": 1}}, "guardrails.quarantine must be true or false, got 1"), + ({"guardrails": {"freeze_seconds": "1.0"}}, "guardrails.freeze_seconds must be a finite number > 0"), + ({"guardrails": {"freeze_seconds": True}}, "guardrails.freeze_seconds must be a finite number > 0"), + ({"guardrails": {"freeze_seconds": 0}}, "guardrails.freeze_seconds must be a finite number > 0, got 0"), + ({"guardrails": {"freeze_eps": float("inf")}}, "guardrails.freeze_eps must be a finite number > 0"), + ( + {"guardrails": {"camera_min_fps_ratio": 1.5}}, + "guardrails.camera_min_fps_ratio must be a number > 0 and", + ), + ({"guardrails": {"camera_min_fps_ratio": 0}}, "guardrails.camera_min_fps_ratio must be a number > 0 and"), + ({"guardrails": {"dead_frac_identical": "0.9"}}, "guardrails.dead_frac_identical must be a number > 0"), + ({"guardrails": {"max_dropped_frames": 1.5}}, "guardrails.max_dropped_frames must be an integer >= 0"), + ({"guardrails": {"max_dropped_frames": -1}}, "guardrails.max_dropped_frames must be an integer >= 0"), + ( + {"guardrails": {"camera_frame_parity_max_diff": True}}, + "camera_frame_parity_max_diff must be an integer", + ), + ({"timestamp": {"fps_deviation_pct": -5}}, "timestamp.fps_deviation_pct must be a finite number > 0"), + ({"duration": {"default": {"min_duration_s": -1}}}, "duration.default.min_duration_s must be a finite"), + ({"duration": {"default": {"min_duration_s": "1"}}}, "duration.default.min_duration_s must be a finite"), + ( + {"duration": {"default": {"max_duration_s": 0.5}}}, + "max_duration_s must be above min_duration_s, got 0.5", + ), + ({"guardrails": [1, 2]}, "guardrails must be a mapping"), + ({"duration": {"default": 600}}, "duration.default must be a mapping"), + (["guardrails"], "the data-check configuration must be a mapping"), + ], +) +def test_an_unknown_key_a_wrong_type_and_an_out_of_range_value_are_each_refused_by_name(section, named): + with pytest.raises(CaptureQcPolicyError) as raised: + resolve_policy(section) + assert named in str(raised.value) + # The same key is refused the same way in a station's section. + with pytest.raises(CaptureQcPolicyError): + resolve_policy({}, section) + + +def test_the_duration_bounds_are_checked_on_the_merged_result(): + with pytest.raises(CaptureQcPolicyError, match="max_duration_s must be above min_duration_s"): + resolve_policy( + {"duration": {"default": {"max_duration_s": 30}}}, {"duration": {"default": {"min_duration_s": 60}}} + ) + + +def test_a_camera_rate_override_belongs_to_a_station_section_only(): + rates = {"guardrails": {"camera_expected_fps": {"cam_a": 30}}} + assert resolve_policy({}, rates).camera_expected_fps == (("cam_a", 30.0),) + with pytest.raises(CaptureQcPolicyError, match="allowed only in a station's data_check section"): + resolve_policy(rates) + assert validate_section(rates, station=True) == {"guardrails.camera_expected_fps": (("cam_a", 30.0),)} + + +@pytest.mark.parametrize( + ("rates", "named"), + [ + ([("cam_a", 30)], "must map camera names to rates in Hz"), + ({1: 30}, "must map camera names to rates in Hz"), + ({"": 30}, "must map camera names to rates in Hz"), + ({"cam_a": 0}, "rate for 'cam_a' must be a finite number > 0"), + ({"cam_a": "60"}, "rate for 'cam_a' must be a finite number > 0"), + ({"cam_a": True}, "rate for 'cam_a' must be a finite number > 0"), + ], +) +def test_a_malformed_camera_rate_override_is_refused_by_name(rates, named): + with pytest.raises(CaptureQcPolicyError) as raised: + resolve_policy({}, {"guardrails": {"camera_expected_fps": rates}}) + assert "guardrails.camera_expected_fps" in str(raised.value) and named in str(raised.value) + + +@pytest.mark.parametrize( + ("content", "named"), + [ + (b"guardrails:\n freeze_seconds: 1.0\n freeze_seconds: 2.0\n", "duplicate key 'freeze_seconds'"), + (b"guardrails: [unclosed\n", "cannot be read"), + (b"\xff\xfe not utf-8", "cannot be read"), + (b"? [a, b]\n: 1\n", "cannot be read"), + ], +) +def test_a_file_that_cannot_be_parsed_is_refused_and_named_without_its_directory(tmp_path, content, named): + path = tmp_path / "broken.yaml" + path.write_bytes(content) + with pytest.raises(CaptureQcPolicyError) as raised: + load_policy(path) + assert named in str(raised.value) and str(tmp_path) not in str(raised.value) + + +def test_a_missing_file_is_refused_and_named_by_base_name(): + with pytest.raises(CaptureQcPolicyError, match="data-check file absent.yaml cannot be read"): + load_policy(SHIPPED_POLICY_FILE.with_name("absent.yaml")) + + +def test_switching_capture_qc_off_yields_no_configuration(): + assert capture_config_for(resolve_policy({"guardrails": {"enabled": False}}), ("cam_a",), TRACKING) is None + + +def test_the_session_configuration_declares_every_camera_and_the_tracking_streams(): + config = capture_config_for(CaptureQcPolicy(), ("cam_a", "cam_b"), TRACKING, GLOVES) + assert config.camera_expected_fps == (("cam_a", None), ("cam_b", None)) + assert config.camera_expected_size == (("cam_a", None), ("cam_b", None)) + assert config.pose_streams == TRACKING and config.tracking_gap_sources == ("tracker",) + assert config.duration_limits_s == (1.0, 600.0) and config.camera_parity == () + assert config.problems(NUMERIC, VIDEO) == [] + resolved = config.resolved(VIDEO) + assert resolved.camera_expected_fps == (("cam_a", 60.0), ("cam_b", 30.0)) + assert resolved.camera_expected_size == (("cam_a", (64, 48)), ("cam_b", (64, 48))) + + +def test_glove_streams_are_judged_only_where_the_station_expects_gloves(): + expected = capture_config_for( + resolve_policy({"guardrails": {"gloves_expected": True}}), ("cam_a",), TRACKING, GLOVES + ) + assert expected.pose_streams == TRACKING + GLOVES and expected.tracking_gap_sources == ("tracker", "glove") + assert expected.problems(NUMERIC, VIDEO) == [] + + +def test_every_switch_and_threshold_of_the_policy_reaches_the_session_configuration(): + section = { + "guardrails": { + "camera_min_fps_enabled": False, + "camera_min_fps_ratio": 0.5, + "camera_frame_parity_enabled": True, + "camera_frame_parity_max_diff": 7, + "freeze_enabled": False, + "freeze_seconds": 3.0, + "freeze_eps": 0.01, + "tracking_gap_seconds": 4.0, + "tracking_gap_marks_bad": True, + "max_dropped_frames": 9, + "drop_window_s": 5.0, + "flat_seconds": 6.0, + "flat_motion_eps": 0.02, + "zero_pose_eps": 0.03, + "dead_stream_enabled": False, + "dead_std_eps": 0.04, + "dead_frac_identical": 0.5, + }, + "timestamp": {"fps_deviation_pct": 25.0}, + "duration": {"default": {"min_duration_s": 2.0, "max_duration_s": 90.0}, "marks_bad": True}, + "resolution": {"enabled": False}, + } + config = capture_config_for(resolve_policy(section), ("cam_a", "cam_b"), TRACKING) + assert (config.camera_min_fps_enabled, config.camera_min_fps_ratio) == (False, 0.5) + assert config.camera_parity == ("cam_a", "cam_b") and config.camera_parity_max_diff == 7 + assert (config.freeze_enabled, config.freeze_seconds, config.freeze_eps) == (False, 3.0, 0.01) + assert (config.tracking_gap_seconds, config.tracking_gap_marks_bad) == (4.0, True) + assert (config.max_dropped_frames, config.drop_window_s) == (9, 5.0) + assert (config.flat_seconds, config.flat_eps, config.zero_pose_eps) == (6.0, 0.02, 0.03) + assert (config.dead_stream_enabled, config.dead_std_eps, config.dead_frac_identical) == (False, 0.04, 0.5) + assert config.fps_deviation_pct == 25.0 + assert (config.duration_limits_s, config.duration_marks_bad) == ((2.0, 90.0), True) + assert config.camera_expected_size == () + assert config.problems(NUMERIC, VIDEO) == [] + + +def test_frame_parity_needs_two_cameras_to_compare(): + policy = resolve_policy({"guardrails": {"camera_frame_parity_enabled": True}}) + assert capture_config_for(policy, ("cam_a",), TRACKING).camera_parity == () + + +def test_a_station_rate_replaces_the_declared_one_and_a_rate_for_an_unrecorded_camera_is_refused_at_open(): + policy = resolve_policy({}, {"guardrails": {"camera_expected_fps": {"cam_a": 30, "ghost": 15}}}) + config = capture_config_for(policy, ("cam_a", "cam_b"), TRACKING) + assert config.camera_expected_fps == (("cam_a", 30.0), ("cam_b", None), ("ghost", 15.0)) + assert config.problems(NUMERIC, VIDEO) == ["camera_expected_fps names unknown video source 'ghost'"] + assert config.resolved(VIDEO).camera_expected_fps[:2] == (("cam_a", 30.0), ("cam_b", 30.0)) + + +def test_the_session_configuration_carries_where_the_values_came_from(): + policy = load_policy(station={"guardrails": {"quarantine": False}}) + assert capture_config_for(policy, ("cam_a",), TRACKING).source == policy.source + + +def test_the_effective_mapping_has_the_shape_of_the_file_with_the_resolved_values(): + policy = resolve_policy( + {"guardrails": {"freeze_seconds": 2.0}}, {"guardrails": {"camera_expected_fps": {"cam_a": 30}}} + ) + effective = effective_mapping(policy) + assert effective["guardrails"]["freeze_seconds"] == 2.0 and effective["guardrails"]["quarantine"] is True + assert effective["guardrails"]["camera_expected_fps"] == {"cam_a": 30.0} + assert effective["duration"] == { + "default": {"min_duration_s": 1.0, "max_duration_s": 600.0}, + "marks_bad": False, + } + assert effective["timestamp"] == {"fps_deviation_pct": 10.0} and effective["resolution"] == {"enabled": True} + # Everything the file documents is reported, plus the station-only key. + assert _flat_keys(effective_mapping(CaptureQcPolicy())) == set(policy_module._FILE_KEYS) diff --git a/examples/egocap/tests/recording/unit/test_capture_qc_short_takes.py b/examples/egocap/tests/recording/unit/test_capture_qc_short_takes.py new file mode 100644 index 0000000000..0371fa6b32 --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_capture_qc_short_takes.py @@ -0,0 +1,444 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A camera rate that cannot be measured is not a rate under the limit, and a camera that recorded a fraction +of a take that lasted has failed, however good its rate while it ran. + +Explicit camera timestamps with known answers, written to real Zarr groups and read back by the production +checker. The rate rule asks two things of a camera: its rate over its own frames, when they span ten frame +intervals of its expected rate; and, in a take of thirteen intervals or more, that it recorded the minimum share +of the frames a take of that length holds, less three intervals. A take too short for both is not judged. The +edges are exercised on both sides at every camera rate in use. +""" + +import numpy as np +import pytest +import zarr + +from egocap.recording import capture_measure, capture_qc +from egocap.recording.capture_measure import average_fps +from egocap.recording.capture_qc import CaptureQcConfig, QcDecision, check_capture_quality, decide +from egocap.recording.dataset_check import Outcome + +FPS = 30.0 + + +def _episode(tmp_path, cam_times, *, tracker_seconds=None, name="ep"): + """A staged episode: the camera's frames at ``cam_times``, and a moving tracker. + + The tracker spans the same time as the camera's frames unless ``tracker_seconds`` says how long the take + really lasted. + """ + root = zarr.open_group(str(tmp_path / name), mode="w") + cam_times = np.asarray(cam_times, dtype=np.float64) + root.create_group("cam").create_array("capture_time", data=cam_times) + seconds = float(cam_times[-1] - cam_times[0]) if tracker_seconds is None and len(cam_times) else 0.0 + seconds = seconds if tracker_seconds is None else tracker_seconds + rows = max(2, int(seconds * 60) + 1) + tracker = root.create_group("tracker") + tracker.create_array("capture_time", data=np.arange(rows) * (seconds / (rows - 1) if seconds else 0.0)) + poses = np.broadcast_to(np.eye(4), (rows, 4, 4)).copy() + poses[:, 0, 3] = np.arange(rows, dtype=np.float64) + tracker.create_array("pose", data=poses) + return tmp_path / name + + +def _config(**overrides): + base = dict( + camera_expected_fps=(("cam", FPS),), + pose_streams=(("tracker", "pose"),), + duration_limits_s=(1.0, 600.0), + ) + return CaptureQcConfig(**{**base, **overrides}) + + +def _by_name(report): + return {r.name: r for r in report.check_results} + + +def _frames(due, dropped=()): + """The capture times of ``due`` frames at the camera's rate, without the ones at the ``dropped`` positions.""" + return [i / FPS for i in range(due) if i not in dropped] + + +def test_the_threshold_is_ten_frame_intervals_of_the_expected_rate(): + intervals, measurable = capture_qc.MIN_RATE_INTERVALS, capture_measure.rate_measurable + assert intervals == 10 + assert not measurable(np.asarray(_frames(10)), FPS, intervals) # nine intervals + assert measurable(np.asarray(_frames(11)), FPS, intervals) # ten intervals + assert not measurable(np.asarray([]), FPS, intervals) + assert not measurable(np.asarray([5.0]), FPS, intervals) + # The span is what counts, not the number of frames: two frames far apart are a rate, a low one. + assert measurable(np.asarray([0.0, 2.0]), FPS, intervals) + + +def test_the_bare_average_of_fewer_than_two_frames_is_zero_which_is_why_it_is_never_asked_for(): + assert average_fps(np.asarray([5.0])) == 0.0 and average_fps(np.asarray([])) == 0.0 + assert average_fps(np.asarray([1.0, 1.0])) == 0.0 # two frames with one stamp have no duration either + + +@pytest.mark.parametrize("frames", [0, 1]) +def test_a_take_with_no_camera_frame_or_one_is_not_rejected_as_zero_fps(tmp_path, frames): + report = check_capture_quality(_episode(tmp_path, _frames(frames)), _config()) + results = _by_name(report) + camera = results["camera_min_fps:cam"] + assert camera.outcome is Outcome.PASSED and camera.issues == () + assert camera.evidence == ("too short to measure a rate",) and "fps" not in camera.measurements + assert decide(report) is QcDecision.PASSED + measurable = results["camera_rate_measurable:cam"] + assert measurable.outcome is Outcome.FAILED + assert measurable.issues == ( + f"cam: {frames} frame(s) over 0.00s is too short to measure a rate (it takes 10 frame intervals, 0.33s)", + ) + assert measurable.measurements == {"frames": frames, "span_s": 0.0, "needed_s": pytest.approx(1 / 3)} + # The warning about the rate is on the take, and the duration check says that the take is too short. + assert measurable.issues[0] in report.warnings + assert "the take lasted 0.00s, outside 1.0s to 600.0s" in report.warnings + assert results["duration_warning"].outcome is Outcome.FAILED + deviation = results["camera_fps_deviation:cam"] + assert deviation.outcome is Outcome.PASSED and "fps" not in deviation.measurements + + +def test_seven_frames_with_one_dropped_are_too_short_to_judge_and_the_take_is_kept(tmp_path): + """Eight frames were due in 0.23 s and one was dropped: over that span one frame alone would reject.""" + times = _frames(8, dropped=(4,)) + assert (len(times) - 1) / (times[-1] - times[0]) == pytest.approx(25.71, abs=0.01) # under the 25.8 minimum + report = check_capture_quality(_episode(tmp_path, times), _config()) + assert _by_name(report)["camera_min_fps:cam"].outcome is Outcome.PASSED + assert decide(report) is QcDecision.PASSED + assert any("too short to measure a rate" in warning for warning in report.warnings) + + +def test_just_under_the_threshold_a_starved_camera_is_not_judged(tmp_path): + """Nine frame intervals: half the frames are missing, and the rule still says nothing.""" + times = _frames(10, dropped=(1, 3, 5, 7)) + report = check_capture_quality(_episode(tmp_path, times), _config()) + results = _by_name(report) + assert results["camera_min_fps:cam"].outcome is Outcome.PASSED + assert results["camera_rate_measurable:cam"].outcome is Outcome.FAILED + assert decide(report) is QcDecision.PASSED + + +def test_at_the_threshold_the_same_starved_camera_is_judged_and_rejected(tmp_path): + """Ten frame intervals: the rate is measured, and five frames missing of eleven are far under the minimum.""" + times = _frames(11, dropped=(1, 3, 5, 7, 9)) + report = check_capture_quality(_episode(tmp_path, times), _config()) + results = _by_name(report) + camera = results["camera_min_fps:cam"] + assert camera.outcome is Outcome.FAILED and camera.measurements["fps"] == pytest.approx(15.0) + assert results["camera_rate_measurable:cam"].outcome is Outcome.PASSED + assert decide(report) is QcDecision.REJECTED_CAMERA + + +def test_at_the_threshold_one_dropped_frame_is_within_the_minimum_and_two_are_not(tmp_path): + one = check_capture_quality(_episode(tmp_path, _frames(11, dropped=(5,)), name="one"), _config()) + assert _by_name(one)["camera_min_fps:cam"].measurements["fps"] == pytest.approx(27.0) + assert decide(one) is QcDecision.PASSED + two = check_capture_quality(_episode(tmp_path, _frames(11, dropped=(4, 6)), name="two"), _config()) + assert _by_name(two)["camera_min_fps:cam"].measurements["fps"] == pytest.approx(24.0) + assert decide(two) is QcDecision.REJECTED_CAMERA + + +def test_a_camera_that_delivered_two_frames_over_a_long_take_is_still_rejected(tmp_path): + """Few frames are not a short span: this camera ran for two seconds and delivered next to nothing.""" + report = check_capture_quality(_episode(tmp_path, [0.0, 2.0]), _config()) + camera = _by_name(report)["camera_min_fps:cam"] + assert camera.outcome is Outcome.FAILED and camera.measurements["fps"] == pytest.approx(0.5) + assert decide(report) is QcDecision.REJECTED_CAMERA + + +def test_the_measurability_check_needs_the_cameras_resolved_rate(tmp_path): + report = check_capture_quality(_episode(tmp_path, _frames(31)), _config(camera_expected_fps=(("cam", None),))) + measurable = _by_name(report)["camera_rate_measurable:cam"] + assert measurable.outcome is Outcome.ERROR and "unresolved" in measurable.issues[0] + + +# --- the take lasted and the camera did not -------------------------------------------------- + + +@pytest.mark.parametrize( + ("label", "cam_times", "take_seconds", "frames", "span"), + [ + ("one frame in a 2 s take", [0.0], 2.0, 1, 0.0), + ("two frames 0.30 s apart in a 2 s take, then nothing", [0.0, 0.30], 2.0, 2, 0.30), + ("three frames in the first 0.2 s of a 2 s take", [0.0, 0.1, 0.2], 2.0, 3, 0.2), + ("nine frames at full rate in the first 0.27 s of a 60 s take", _frames(9), 60.0, 9, 8 / FPS), + ("five frames bunched at the end of a 2 s take", [1.87 + i / FPS for i in range(5)], 2.0, 5, 4 / FPS), + ("one frame in a 1.5 s take", [0.7], 1.5, 1, 0.0), + ], +) +def test_a_camera_that_delivered_next_to_nothing_in_a_take_that_lasted_is_rejected( + tmp_path, label, cam_times, take_seconds, frames, span +): + report = check_capture_quality(_episode(tmp_path, cam_times, tracker_seconds=take_seconds), _config()) + results = _by_name(report) + camera = results["camera_min_fps:cam"] + assert camera.outcome is Outcome.FAILED, label + full, needed = FPS * take_seconds, 0.86 * (FPS * take_seconds - 3) + assert camera.issues == ( + f"cam: {frames} frame(s) recorded of the {full:.1f} a {take_seconds:.2f}s take holds at {FPS} fps " + f"(needs {needed:.1f})", + ) + assert camera.measurements["frames"] == frames and camera.measurements["span_s"] == pytest.approx(span) + assert camera.measurements["take_s"] == pytest.approx(take_seconds) and "fps" not in camera.measurements + assert camera.measurements["take_frames"] == pytest.approx(full) + assert camera.measurements["needed_frames"] == pytest.approx(needed) + assert decide(report) is QcDecision.REJECTED_CAMERA + # The rule judged the take, so nothing says it was too short to measure. + assert results["camera_rate_measurable:cam"].outcome is Outcome.PASSED + assert not any("too short to measure" in warning for warning in report.warnings) + + +def test_a_take_only_a_little_longer_than_the_floor_does_not_fail_a_healthy_camera(tmp_path): + """A healthy camera's first frame comes up to an interval after the take starts and its last up to one + before it ends: in a take of twelve intervals its nine intervals of frames are all there could be.""" + cam_times = [1 / FPS + i / FPS for i in range(10)] # nine intervals, one interval in from each end + report = check_capture_quality(_episode(tmp_path, cam_times, tracker_seconds=11.5 / FPS), _config()) + results = _by_name(report) + assert results["camera_min_fps:cam"].outcome is Outcome.PASSED + assert results["camera_min_fps:cam"].evidence == ("too short to measure a rate",) + assert results["camera_rate_measurable:cam"].outcome is Outcome.FAILED + assert decide(report) is QcDecision.PASSED + + +RATES = (10.0, 15.0, 24.0, 29.97, 30.0, 59.94, 60.0, 120.0) + + +def _two_frames(tmp_path, fps, camera_intervals, take_intervals, name): + """A camera with a first and a last frame ``camera_intervals`` apart, in a take of ``take_intervals``.""" + path = _episode( + tmp_path, [100.0, 100.0 + camera_intervals / fps], tracker_seconds=take_intervals / fps, name=name + ) + config = _config(camera_expected_fps=(("cam", fps),), duration_limits_s=None) + report = check_capture_quality(path, config) + return _by_name(report)["camera_min_fps:cam"], decide(report) + + +@pytest.mark.parametrize("fps", RATES) +def test_the_cameras_own_edge_is_at_ten_intervals_at_every_rate(tmp_path, fps): + """In a take as long as the camera's own frames: ten intervals are judged, anything under 9.99 is not.""" + for intervals in (10.0, 9.995, 10.5, 12.0): + camera, decision = _two_frames(tmp_path, fps, intervals, intervals, f"judged{intervals}") + # Two frames that far apart are a rate, and a very low one. + assert camera.outcome is Outcome.FAILED and "fps" in camera.measurements, (fps, intervals) + assert decision is QcDecision.REJECTED_CAMERA + for intervals in (9.98, 9.9, 9.5, 9.4, 5.0): + camera, decision = _two_frames(tmp_path, fps, intervals, intervals, f"short{intervals}") + assert camera.outcome is Outcome.PASSED and camera.evidence == ("too short to measure a rate",), ( + fps, + intervals, + ) + assert decision is QcDecision.PASSED + + +@pytest.mark.parametrize("fps", RATES) +def test_the_takes_edge_is_at_thirteen_intervals_at_every_rate(tmp_path, fps): + """A camera whose frames span five intervals: the take must have lasted thirteen for that to be a failure.""" + for take in (13.0, 12.995, 13.5, 40.0): + camera, decision = _two_frames(tmp_path, fps, 5.0, take, f"lasted{take}") + assert camera.outcome is Outcome.FAILED and camera.measurements["frames"] == 2, (fps, take) + assert camera.measurements["take_s"] == pytest.approx(take / fps) + assert decision is QcDecision.REJECTED_CAMERA + for take in (12.98, 12.9, 12.0, 10.0, 5.0): + camera, decision = _two_frames(tmp_path, fps, 5.0, take, f"brief{take}") + assert camera.outcome is Outcome.PASSED and camera.evidence == ("too short to measure a rate",), ( + fps, + take, + ) + assert decision is QcDecision.PASSED + + +@pytest.mark.parametrize("fps", RATES) +def test_a_full_take_of_exactly_ten_intervals_is_judged_and_kept_at_every_rate(tmp_path, fps): + times = [100.0 + i / fps for i in range(11)] + config = _config(camera_expected_fps=(("cam", fps),), duration_limits_s=None) + report = check_capture_quality(_episode(tmp_path, times), config) + camera = _by_name(report)["camera_min_fps:cam"] + assert camera.outcome is Outcome.PASSED and camera.measurements["fps"] == pytest.approx(fps) + every_other = check_capture_quality(_episode(tmp_path, times[::2], name="half"), config) + assert decide(every_other) is QcDecision.REJECTED_CAMERA + + +def test_the_edge_tolerance_is_a_hundredth_of_an_interval(): + covers = capture_measure.covers_intervals + assert capture_measure.INTERVAL_TOLERANCE == 0.01 and capture_qc.CAMERA_PHASE_INTERVALS == 3 + assert covers(10 / 30.0, 30.0, 10) and covers(9.99 / 30.0, 30.0, 10) and not covers(9.98 / 30.0, 30.0, 10) + # The products that differ between rates: ten intervals compute a hair under ten at some and over at others. + assert all(covers(10 * (1 / fps), fps, 10) for fps in RATES) + + +# --- one question with no cliff: the frames recorded against the frames the take holds -------- + + +def _take(tmp_path, cameras, intervals, fps, name="take"): + """A take of ``intervals`` frame intervals at ``fps``, by its tracker, with each camera's frames where given. + + ``cameras`` maps a camera name to the positions of its frames, in frame intervals of ``fps`` from the take's + first sample (a camera of another rate gives fractional positions). The tracker holds a first and a last + row only: it is what says how long the take lasted. + """ + root = zarr.open_group(str(tmp_path / name), mode="w") + root.create_group("tracker").create_array("capture_time", data=np.asarray([0.0, intervals / fps])) + for camera, positions in cameras.items(): + stamps = np.asarray(list(positions), dtype=np.float64) / fps + root.create_group(camera).create_array("capture_time", data=stamps) + return tmp_path / name + + +def _judged(tmp_path, cameras, intervals, fps, rates=None, name="take"): + """Every camera's result and the decision for one such take; ``rates`` gives a camera another rate.""" + expected = tuple((camera, (rates or {}).get(camera, fps)) for camera in cameras) + config = CaptureQcConfig(camera_expected_fps=expected, duration_limits_s=None) + report = check_capture_quality(_take(tmp_path, cameras, intervals, fps, name), config) + results = _by_name(report) + return {camera: results[f"camera_min_fps:{camera}"] for camera in cameras}, decide(report) + + +@pytest.mark.parametrize("fps", RATES) +def test_a_camera_that_ran_for_ten_intervals_of_a_take_of_ninety_is_rejected_at_either_end(tmp_path, fps): + """Its rate while it ran is perfect, which is exactly what the rate over its own frames cannot see past.""" + for label, positions in (("first", range(11)), ("last", range(80, 91))): + cameras, decision = _judged(tmp_path, {"cam": positions}, 90, fps, name=label) + camera = cameras["cam"] + assert camera.outcome is Outcome.FAILED and decision is QcDecision.REJECTED_CAMERA, (fps, label) + assert camera.measurements["fps"] == pytest.approx(fps) # nothing wrong with the rate + assert camera.measurements["frames"] == 11 + assert camera.measurements["take_frames"] == pytest.approx(90) + assert camera.measurements["needed_frames"] == pytest.approx(0.86 * 87) + assert len(camera.issues) == 1 and "11 frame(s) recorded of the 90.0" in camera.issues[0] + + +@pytest.mark.parametrize("fps", RATES) +def test_nine_intervals_of_a_take_of_ninety_get_the_same_verdict_as_ten(tmp_path, fps): + """The camera's own span crossing ten intervals changes which questions are asked, not the answer.""" + cameras, decision = _judged(tmp_path, {"cam": range(10)}, 90, fps) + assert cameras["cam"].outcome is Outcome.FAILED and decision is QcDecision.REJECTED_CAMERA + assert "fps" not in cameras["cam"].measurements and cameras["cam"].measurements["frames"] == 10 + + +@pytest.mark.parametrize("fps", RATES) +def test_a_camera_that_lost_nothing_and_started_three_intervals_late_in_a_take_just_over_the_floor_is_kept( + tmp_path, fps +): + positions = [3.2 + i for i in range(10)] # ten frames at full rate, the last at 12.2 of 13.1 intervals + cameras, decision = _judged(tmp_path, {"cam": positions}, 13.1, fps) + camera = cameras["cam"] + assert camera.outcome is Outcome.PASSED and decision is QcDecision.PASSED, fps + assert camera.measurements["frames"] == 10 + assert camera.measurements["needed_frames"] == pytest.approx(0.86 * 10.1) + + +def test_tracking_alone_says_how_long_the_take_was_when_every_camera_stopped_early(tmp_path): + """Three seconds of tracking, and both cameras delivered the first second at full rate, then nothing.""" + cameras, decision = _judged(tmp_path, {"left": range(31), "right": range(31)}, 90, 30.0) + assert decision is QcDecision.REJECTED_CAMERA + for camera in cameras.values(): + assert camera.outcome is Outcome.FAILED and camera.measurements["take_s"] == pytest.approx(3.0) + assert camera.measurements["fps"] == pytest.approx(30.0) and camera.measurements["frames"] == 31 + + +def test_each_camera_is_asked_at_its_own_rate_in_a_take_with_two_rates(tmp_path): + """A three second take: the 30 fps camera recorded all of it, the 10 fps one its first 1.05 s.""" + slow = [3.0 * i for i in range(11)] # eleven frames 0.1 s apart, given in intervals of the 30 fps camera + cameras, decision = _judged(tmp_path, {"fast": range(91), "slow": slow}, 90, 30.0, rates={"slow": 10.0}) + assert decision is QcDecision.REJECTED_CAMERA + assert cameras["fast"].outcome is Outcome.PASSED + assert cameras["fast"].measurements["take_frames"] == pytest.approx(90) + slow_result = cameras["slow"] + assert slow_result.outcome is Outcome.FAILED and slow_result.measurements["fps"] == pytest.approx(10.0) + assert slow_result.measurements["frames"] == 11 + assert slow_result.measurements["take_frames"] == pytest.approx(30) # three seconds at its own 10 fps + assert slow_result.measurements["needed_frames"] == pytest.approx(0.86 * 27) + # With both cameras whole the take is kept: 31 frames of the slow one against the 23.2 it needs. + cameras, decision = _judged( + tmp_path, {"fast": range(91), "slow": [3.0 * i for i in range(31)]}, 90, 30.0, {"slow": 10.0}, "whole" + ) + assert decision is QcDecision.PASSED and all(c.outcome is Outcome.PASSED for c in cameras.values()) + + +def test_a_take_long_enough_for_one_cameras_rate_and_too_short_for_the_others_asks_only_the_first(tmp_path): + """One second: thirty intervals of the 30 fps camera, ten of the 10 fps one, which is under thirteen.""" + cameras, decision = _judged( + tmp_path, {"fast": range(5), "slow": [0.0]}, 30, 30.0, rates={"slow": 10.0}, name="short for slow" + ) + assert cameras["fast"].outcome is Outcome.FAILED and decision is QcDecision.REJECTED_CAMERA + slow = cameras["slow"] + assert slow.outcome is Outcome.PASSED and slow.evidence == ("too short to measure a rate",) + assert "frames" not in slow.measurements + + +#: Takes of this many intervals in which a camera that loses nothing starts late, or stops early, by so many. +#: The ones a full rate does not save: the camera then recorded under 0.86 of the take less three intervals. +REJECTED_WHEN_OFF_BY = {(15, 15), (30, 15)} + + +@pytest.mark.parametrize("fps", RATES) +@pytest.mark.parametrize("intervals", [15, 30, 300, 3000]) +def test_a_late_start_or_an_early_stop_costs_the_frames_it_is_worth_and_no_more(tmp_path, fps, intervals): + for off in (1, 3, 5, 15): + late, early = range(off, intervals + 1), range(0, intervals - off + 1) + for label, positions in (("late", late), ("early", early)): + cameras, decision = _judged(tmp_path, {"cam": positions}, intervals, fps, name=f"{label}{off}") + rejected = (intervals, off) in REJECTED_WHEN_OFF_BY + assert (cameras["cam"].outcome is Outcome.FAILED) == rejected, (fps, intervals, off, label) + assert (decision is QcDecision.REJECTED_CAMERA) == rejected + assert cameras["cam"].measurements["frames"] == intervals - off + 1 + + +@pytest.mark.parametrize("fps", RATES) +def test_the_frames_needed_are_exact_on_both_sides_at_every_rate(tmp_path, fps): + # A take of 53 intervals needs 0.86 x 50 = 43 frames: a whole number, where rounding would show. + enough, decision = _judged(tmp_path, {"cam": range(43)}, 53, fps, name="43") + assert enough["cam"].outcome is Outcome.PASSED and decision is QcDecision.PASSED, fps + assert enough["cam"].measurements["needed_frames"] == pytest.approx(43.0) + short, decision = _judged(tmp_path, {"cam": range(42)}, 53, fps, name="42") + assert short["cam"].outcome is Outcome.FAILED and decision is QcDecision.REJECTED_CAMERA, fps + # A take of 90 intervals needs 74.82: 75 frames are enough and 74 are not. + assert _judged(tmp_path, {"cam": range(75)}, 90, fps, name="75")[1] is QcDecision.PASSED + assert _judged(tmp_path, {"cam": range(74)}, 90, fps, name="74")[1] is QcDecision.REJECTED_CAMERA + + +@pytest.mark.parametrize("fps", RATES) +def test_the_count_is_asked_from_thirteen_intervals_of_take_on_at_every_rate(tmp_path, fps): + # At thirteen intervals 8.6 frames are needed: nine are enough, eight are not, and neither is a rate. + for take in (13.0, 12.995): + assert _judged(tmp_path, {"cam": range(9)}, take, fps, name=f"nine{take}")[1] is QcDecision.PASSED + cameras, decision = _judged(tmp_path, {"cam": range(8)}, take, fps, name=f"eight{take}") + assert cameras["cam"].outcome is Outcome.FAILED and decision is QcDecision.REJECTED_CAMERA, (fps, take) + # Under thirteen the count is not asked, of eight frames or of one. + for take in (12.98, 12.0): + for frames in (8, 1): + cameras, decision = _judged(tmp_path, {"cam": range(frames)}, take, fps, name=f"{frames}in{take}") + assert cameras["cam"].evidence == ("too short to measure a rate",) and decision is QcDecision.PASSED + + +def test_the_formula_is_one_function_and_says_nothing_of_a_take_too_short(): + needed = capture_qc.frames_needed + assert needed(53 / 30.0, 30.0, 0.86) == pytest.approx((53.0, 43.0)) + assert needed(3.0, 10.0, 0.5) == pytest.approx((30.0, 13.5)) + assert needed(12.98 / 30.0, 30.0, 0.86) is None and needed(0.0, 30.0, 0.86) is None + assert needed(12.995 / 30.0, 30.0, 0.86) == pytest.approx((12.995, 0.86 * 9.995)) + + +def test_a_camera_slow_over_a_whole_take_fails_both_questions_and_says_both(tmp_path): + # Every other frame of a three second take: 15 fps over its own frames, and 46 frames of the 74.8 needed. + cameras, decision = _judged(tmp_path, {"cam": range(0, 91, 2)}, 90, 30.0) + camera = cameras["cam"] + assert camera.outcome is Outcome.FAILED and decision is QcDecision.REJECTED_CAMERA + assert camera.issues == ( + "cam: 15.00 fps average is below 0.86 x 30.0 = 25.80", + "cam: 46 frame(s) recorded of the 90.0 a 3.00s take holds at 30.0 fps (needs 74.8)", + ) + assert camera.evidence == ( + "15.00 fps average (minimum 25.80); 46 of 90.0 frames in a 3.00s take (needs 74.8)", + ) + + +def test_a_whole_camera_in_a_long_take_passes_both_questions(tmp_path): + cameras, decision = _judged(tmp_path, {"cam": range(1, 120)}, 120, 30.0) # one interval in at each end + camera = cameras["cam"] + assert camera.outcome is Outcome.PASSED and camera.issues == () and decision is QcDecision.PASSED + assert camera.evidence == ( + "30.00 fps average (minimum 25.80); 119 of 120.0 frames in a 4.00s take (needs 100.6)", + ) diff --git a/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py b/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py index 0bf0b4634b..4c1406dc5d 100644 --- a/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py +++ b/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py @@ -392,3 +392,45 @@ def test_count_trajectories_skips_non_episode_dirs_and_empty_attrs(tmp_path): (session_dir / "episode_x").mkdir() # fails int() parse (session_dir / "episode_0").mkdir() # no zarr.json assert count_trajectories(tmp_path, "2026-01-01") == {} + + +def test_every_take_of_a_folder_stamped_as_quarantine_is_excluded_even_before_its_list_is_written(tmp_path): + """The recorder stopped after the take arrived and before the folder's list of discarded takes was written.""" + folder = tmp_path / "_quarantine" / "session_20260101-100000_abc123" + _write_zarr_json(folder, {"quarantine": True, "discarded_episode_indices": [], "discarded_reasons": {}}) + _write_session_config(folder, "station_01") + _write_zarr_json(folder / "episode_1", {"episode_duration": 4.0, "recorded_at": "2026-01-01; 10-00-00"}) + counted = count_trajectories(tmp_path, "2026-01-01")["_quarantine/session_20260101-100000_abc123"] + assert (counted["total"], counted["valid"], counted["excluded"]) == (1, 0, 1) + assert (counted["valid_seconds"], counted["excluded_seconds"]) == (0.0, 4.0) + breakdown = compute_station_data_breakdown(tmp_path, "station_01", "2026-01-01") + assert breakdown == {"total_seconds": 4.0, "valid_seconds": 0.0, "excluded_seconds": 4.0} + + +def test_a_take_that_says_it_was_quarantined_is_excluded_whatever_its_folder_says(tmp_path): + """The folder's own stamp is unreadable; the take still carries the fact itself.""" + folder = tmp_path / "_quarantine" / "session_20260101-100000_abc123" + folder.mkdir(parents=True) + (folder / "zarr.json").write_text("{ not json") + _write_session_config(folder, "station_01") + attributes = {"episode_duration": 4.0, "recorded_at": "2026-01-01; 10-00-00", "quarantined": True} + _write_zarr_json(folder / "episode_0", attributes) + counted = count_trajectories(tmp_path, "2026-01-01")["_quarantine/session_20260101-100000_abc123"] + assert (counted["valid"], counted["excluded"]) == (0, 1) + assert compute_station_data_breakdown(tmp_path, "station_01", "2026-01-01")["valid_seconds"] == 0.0 + + +def test_an_ordinary_folder_still_counts_by_its_list_of_discarded_takes(tmp_path): + _build_session( + tmp_path, + "Kitchen", + "2026-01-01-10-00-00", + "station_01", + episodes={ + 0: {"episode_duration": 5.0, "recorded_at": "2026-01-01; 10-00-00", "quarantined": False}, + 1: {"episode_duration": 3.0, "recorded_at": "2026-01-01; 10-05-00", "quarantined": False}, + }, + discarded=[1], + ) + counted = count_trajectories(tmp_path, "2026-01-01")["Kitchen/2026-01-01-10-00-00"] + assert (counted["valid"], counted["excluded"]) == (1, 1) diff --git a/examples/egocap/tests/recording/unit/test_day_report.py b/examples/egocap/tests/recording/unit/test_day_report.py index f86a04b7a5..683981c422 100644 --- a/examples/egocap/tests/recording/unit/test_day_report.py +++ b/examples/egocap/tests/recording/unit/test_day_report.py @@ -70,6 +70,7 @@ def _dispositions(report: dict) -> dict[str, int]: ("FINALIZED", {}, "kept"), ("FINALIZED", {"qc_decision": "PASSED"}, "kept"), ("FINALIZED", {"qc_decision": "FLAGGED_BAD"}, "flagged"), + ("QUARANTINED", {"qc_decision": "FLAGGED_BAD", "finalization": "QUARANTINE"}, "quarantined"), ("REJECTED", {"qc_decision": "REJECTED_CAMERA"}, "rejected"), ("DISCARDED", {}, "discarded"), ("WRITING", {}, "pending"), @@ -123,11 +124,153 @@ def test_totals_come_from_the_manifests_with_each_takes_real_disposition(tmp_pat "operator": "alex", "issues": ["sustained_freeze"], "qc_decision": "FLAGGED_BAD", + "reasons": [], + "warnings": [], "location": f"{SESSION}/episode_1", } assert recorded_seconds(report) == (29.0, 12.5) +def _capture_report(*results, warnings=()): + """A stored capture report: (name, outcome, issues) per check.""" + failed = [issue for _name, outcome, issues in results if outcome != "PASSED" for issue in issues] + return { + "outcome": "FAILED" if failed else "PASSED", + "issues": failed, + "warnings": list(warnings), + "check_results": [{"name": n, "outcome": o, "issues": list(i)} for n, o, i in results], + } + + +def test_quarantined_takes_are_counted_apart_from_kept_flagged_and_rejected_ones(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED", duration=10.0, qc_decision="PASSED")) + _take(session, _manifest(1, "FINALIZED", duration=6.0, qc_decision="FLAGGED_BAD")) + _take(session, _manifest(2, "QUARANTINED", duration=7.0, qc_decision="FLAGGED_BAD", finalization="QUARANTINE")) + _take(session, _manifest(3, "QUARANTINED", duration=5.0, qc_decision="FLAGGED_BAD", finalization="QUARANTINE")) + _take(session, _manifest(4, "REJECTED", duration=3.0, qc_decision="REJECTED_CAMERA", finalization="REMOVE")) + report = build_day_report(tmp_path, DAY) + assert _dispositions(report) == {"kept": 1, "flagged": 1, "quarantined": 2, "rejected": 1} + assert report["totals"]["by_disposition"]["quarantined"] == {"count": 2, "seconds": 12.0} + assert list(report["totals"]["by_disposition"]) == [ + "kept", + "flagged", + "quarantined", + "rejected", + "discarded", + "pending", + "recording", + ] + # Only kept and unflagged time is valid data: a quarantined take's time is never part of it. + assert recorded_seconds(report) == (31.0, 10.0) + + +def test_a_quarantined_take_is_located_in_the_quarantine_folder_and_dated_from_its_episode(tmp_path): + session = _session(tmp_path) + _take( + session, + _manifest(2, "QUARANTINED", qc_decision="FLAGGED_BAD", finalization="QUARANTINE"), + day="2026-03-10", + ) + folder = tmp_path / "_quarantine" / SESSION + (folder / "episode_2").mkdir(parents=True) + (folder / "zarr.json").write_text( + json.dumps({"attributes": {ROUTE_ATTR: route_id(SESSION, f"_quarantine/{SESSION}")}}) + ) + (folder / "episode_2" / "zarr.json").write_text( + json.dumps({"attributes": {"recorded_at": f"{DAY}; 09-00-00"}}) + ) + (take,) = build_day_report(tmp_path, DAY)["sessions"][0]["episodes"] + assert take["disposition"] == "quarantined" and take["location"] == f"_quarantine/{SESSION}/episode_2" + + +def test_the_quarantine_folder_is_not_read_as_a_session(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "QUARANTINED", qc_decision="FLAGGED_BAD", finalization="QUARANTINE")) + (tmp_path / "_quarantine" / SESSION / "episode_0").mkdir(parents=True) + assert [s["session_id"] for s in build_day_report(tmp_path, DAY)["sessions"]] == [SESSION] + + +def test_each_take_carries_the_findings_that_decided_its_outcome_and_its_warnings(tmp_path): + session = _session(tmp_path) + frozen = ("sustained_freeze:glove/left", "FAILED", ["glove/left: no motion for 1.80s (limit 1.0s, eps 1e-06)"]) + slow = ("camera_min_fps:cam", "FAILED", ["cam: 30.00 fps average is below 0.86 x 60.0 = 51.60"]) + healthy = ("camera_min_fps:cam", "PASSED", []) + unread = ("sustained_freeze:glove/right", "ERROR", ["sustained_freeze:glove/right could not run"]) + _take( + session, + _manifest( + 0, + "QUARANTINED", + qc_decision="FLAGGED_BAD", + finalization="QUARANTINE", + quality={"outcome": "PASSED", "issues": []}, + capture_quality=_capture_report( + healthy, frozen, unread, warnings=["cam: 9 dropped frames in 2s (> 6)"] + ), + ), + ) + _take( + session, + _manifest( + 1, + "REJECTED", + qc_decision="REJECTED_CAMERA", + finalization="REMOVE", + quality={"outcome": "PASSED", "issues": []}, + capture_quality=_capture_report(slow, frozen), + ), + ) + _take( + session, + _manifest( + 2, + "REJECTED", + finalization="RETAIN", + quality={"outcome": "FAILED", "issues": ["cam: mp4 missing"]}, + ), + ) + _take( + session, + _manifest( + 3, + "FINALIZED", + qc_decision="PASSED", + finalization="KEEP", + quality={"outcome": "PASSED", "issues": []}, + capture_quality=_capture_report(healthy, warnings=["the take lasted 0.50s, outside 1.0s to 600.0s"]), + ), + ) + _take(session, _manifest(4, "WRITING")) + _take(session, _manifest(5, "FINALIZED", quality={"outcome": "PASSED", "issues": []}, finalization="KEEP")) + takes = build_day_report(tmp_path, DAY)["sessions"][0]["episodes"] + assert [(t["reasons"], t["warnings"]) for t in takes] == [ + # Only the failed gate decided; the one that could not run did not. + (["glove/left: no motion for 1.80s (limit 1.0s, eps 1e-06)"], ["cam: 9 dropped frames in 2s (> 6)"]), + # The camera failure decided; the freeze measured beside it did not. + (["cam: 30.00 fps average is below 0.86 x 60.0 = 51.60"], []), + (["cam: mp4 missing"], []), + ([], ["the take lasted 0.50s, outside 1.0s to 600.0s"]), + ([], []), + ([], []), + ] + + +def test_an_application_can_word_each_takes_record_from_its_manifest(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED", qc_decision="PASSED")) + seen = [] + + def describe(manifest): + seen.append(manifest.episode_id) + return {"reasons": ["worded by the application"], "outcome": "kept"} + + (take,) = build_day_report(tmp_path, DAY, describe=describe)["sessions"][0]["episodes"] + assert seen == [f"{SESSION}/episode_0"] + assert take["reasons"] == ["worded by the application"] and take["outcome"] == "kept" + assert take["warnings"] == [] and take["disposition"] == "kept" + + def test_a_take_belongs_to_the_day_it_was_recorded_not_the_day_its_session_opened(tmp_path): session = _session(tmp_path) # Finalized after midnight: its own recorded_at outranks the manifest's checkpoint time. @@ -295,3 +438,80 @@ def reading(session_path): # No take of the day can be in a session opened on a later day, so that one is never opened. assert later not in opened and set(opened) == {"legacy_session", earlier.name, SESSION} assert [s["session_id"] for s in build_day_report(tmp_path, "2026-03-10")["sessions"]] == [later] + + +def test_a_problem_names_the_file_and_never_a_directory(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED")) + good = json.loads(manifest_path(session, 0).read_text()) + (session / ".recording" / "episode_1.json").write_text(json.dumps({**good, "schema_version": 99})) + (only,) = build_day_report(tmp_path, DAY)["sessions"] + assert only["problems"] == ["episode_1.json: unsupported manifest schema_version 99"] + assert str(tmp_path) not in json.dumps(only) + + +def test_a_file_that_is_no_take_record_is_called_that_without_the_interpreters_words_or_a_class_name(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED")) + good = json.loads(manifest_path(session, 0).read_text()) + sidecar = session / ".recording" + # A field nobody declared, text that is not JSON, and a list where an object belongs. + (sidecar / "episode_1.json").write_text(json.dumps({**good, "surprise_field": 1})) + (sidecar / "episode_2.json").write_text('{"schema_version": 5, "episode_index": ') + (sidecar / "episode_3.json").write_text("[1, 2, 3]") + (only,) = build_day_report(tmp_path, DAY)["sessions"] + assert only["problems"] == [ + "episode_1.json: not a take record", + "episode_2.json: not a take record", + "episode_3.json: not a take record", + ] + assert [e["index"] for e in only["episodes"]] == [0] + + +def test_a_copied_session_directory_reports_its_records_as_problems_and_counts_no_take_twice(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED")) + copy = _session(tmp_path, "session_20260309-081500_copy00") + (copy / ".recording" / "episode_0.json").write_bytes(manifest_path(session, 0).read_bytes()) + report = build_day_report(tmp_path, DAY) + assert report["totals"]["episodes"] == 1 + by_session = {s["session_id"]: s for s in report["sessions"]} + assert [e["episode_id"] for e in by_session[SESSION]["episodes"]] == [f"{SESSION}/episode_0"] + assert by_session["session_20260309-081500_copy00"]["episodes"] == [] + assert by_session["session_20260309-081500_copy00"]["problems"] == [ + "episode_0.json: written for another session; this session directory was copied or renamed" + ] + + +def test_an_entry_of_the_output_that_cannot_be_looked_into_does_not_cost_the_day_its_report(tmp_path, monkeypatch): + """A file system's own folder, or another account's: asking whether it holds a session is refused.""" + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED")) + (tmp_path / "lost+found").mkdir() + real_is_dir = Path.is_dir + + def is_dir(self): + if "lost+found" in self.parts: + raise PermissionError(13, "Permission denied", str(self)) + return real_is_dir(self) + + monkeypatch.setattr(Path, "is_dir", is_dir) + report = build_day_report(tmp_path, DAY) + assert [s["session_id"] for s in report["sessions"]] == [SESSION] and report["totals"]["episodes"] == 1 + + +def test_a_session_whose_records_cannot_be_listed_is_passed_over_and_the_rest_is_reported(tmp_path, monkeypatch): + readable = _session(tmp_path) + _take(readable, _manifest(0, "FINALIZED")) + locked = _session(tmp_path, "session_20260309-090000_locked") + real_scan = day_report.scan_manifests + + def scan(session_path): + if session_path == locked: + raise PermissionError(13, "Permission denied", str(session_path)) + return real_scan(session_path) + + monkeypatch.setattr(day_report, "scan_manifests", scan) + report = build_day_report(tmp_path, DAY) + assert [s["session_id"] for s in report["sessions"]] == [SESSION] + assert str(tmp_path) not in json.dumps(report) diff --git a/examples/egocap/tests/recording/unit/test_episode_store.py b/examples/egocap/tests/recording/unit/test_episode_store.py index a029708183..d0f78e3f34 100644 --- a/examples/egocap/tests/recording/unit/test_episode_store.py +++ b/examples/egocap/tests/recording/unit/test_episode_store.py @@ -168,6 +168,8 @@ def test_duplicate_source_names_and_existing_pending_dir_are_refused(tmp_path: P def test_manifest_round_trip_atomic_and_unsupported_version_reported(tmp_path: Path) -> None: """A checkpoint reads back equal with no temp file left; an unknown schema version is reported, not guessed.""" manifest = _manifest(3) + tmp_path = tmp_path / manifest.session_id # a record is read only in the directory of its own session + tmp_path.mkdir() write_manifest(tmp_path, manifest) assert read_manifest(manifest_path(tmp_path, 3)) == manifest assert not list((tmp_path / ".recording").glob("*.tmp")) @@ -185,6 +187,8 @@ def test_manifest_round_trip_atomic_and_unsupported_version_reported(tmp_path: P def test_a_damaged_older_record_is_listed_as_unreadable_not_raised(tmp_path: Path) -> None: """A checked older record whose results are missing or damaged must not fail the whole scan.""" + tmp_path = tmp_path / _manifest(1).session_id # a record is read only in the directory of its own session + tmp_path.mkdir() write_manifest(tmp_path, _manifest(1)) good = json.loads(manifest_path(tmp_path, 1).read_text()) older = {**good, "schema_version": 2, "storage_phase": "CHECKED"} @@ -468,10 +472,10 @@ def test_current_records_are_validated_strictly(tmp_path: Path, changes) -> None read_manifest(_checked_record(tmp_path, **changes)) -def test_schema_version_four_is_written_and_readable_versions_include_it(tmp_path: Path) -> None: +def test_the_current_schema_version_is_written_and_every_earlier_one_is_still_readable(tmp_path: Path) -> None: write_manifest(tmp_path, _manifest(0)) - assert json.loads(manifest_path(tmp_path, 0).read_text())["schema_version"] == 4 == MANIFEST_SCHEMA_VERSION - assert set(READABLE_SCHEMA_VERSIONS) == {1, 2, 3, 4} + assert json.loads(manifest_path(tmp_path, 0).read_text())["schema_version"] == 5 == MANIFEST_SCHEMA_VERSION + assert set(READABLE_SCHEMA_VERSIONS) == {1, 2, 3, 4, 5} def test_a_version_three_manifest_without_continuity_reads_as_no_evidence(tmp_path: Path) -> None: @@ -503,9 +507,42 @@ def test_continuity_evidence_round_trips_through_json_with_int_and_str_identitie def test_a_version_newer_than_this_reader_is_still_refused(tmp_path: Path) -> None: + tmp_path = tmp_path / _manifest(0).session_id # a record is read only in the directory of its own session + tmp_path.mkdir() write_manifest(tmp_path, _manifest(0)) data = json.loads(manifest_path(tmp_path, 0).read_text()) data["schema_version"] = MANIFEST_SCHEMA_VERSION + 1 manifest_path(tmp_path, 1).write_text(json.dumps(data)) found, problems = scan_manifests(tmp_path) assert [m.episode_index for m in found] == [0] and "schema_version" in problems[0] + + +# --- a write of the take's data that fails names where it was writing ---------------------------- + + +def _no_room(*_args, **_kwargs): + """What the system raises when a write or a sync finds the disk full: an error that names no file.""" + raise OSError(28, "No space left on device") + + +def test_rows_that_cannot_be_written_name_the_directory_of_their_source(tmp_path, monkeypatch): + spec = NumericSourceSpec("tracker", (FieldSpec("pose", "float64", (3,)),)) + pending = tmp_path / "episode_0.pending" + store = EpisodeStore(pending, (spec,), ()) + store.append_numeric("tracker", 1.0, 1.0, {"pose": np.zeros(3)}) + monkeypatch.setattr(zarr.Array, "append", _no_room) + with pytest.raises(OSError) as raised: + store.seal() # the buffered row is written here + assert raised.value.errno == 28 + assert Path(raised.value.filename).parent == pending / "tracker" + + +def test_a_take_that_cannot_be_synced_names_its_own_directory(tmp_path, monkeypatch): + from egocap.recording import episode_store + + pending = tmp_path / "episode_0.pending" + store = EpisodeStore(pending, (NumericSourceSpec("tracker", (FieldSpec("pose", "float64", (3,)),)),), ()) + monkeypatch.setattr(episode_store, "fsync_tree", _no_room) + with pytest.raises(OSError) as raised: + store.seal() + assert raised.value.filename == str(pending) diff --git a/examples/egocap/tests/recording/unit/test_quarantine_layout.py b/examples/egocap/tests/recording/unit/test_quarantine_layout.py new file mode 100644 index 0000000000..fcc3fb6ef4 --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_quarantine_layout.py @@ -0,0 +1,349 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Where a quarantined take is published, the folder that holds it, and the guards on both. + +Everything runs on real directories and real JSON metadata files; no filesystem call is substituted. +""" + +import json +from pathlib import Path + +import pytest + +from egocap.recording.capture_qc import QcDecision, finalization_for +from egocap.recording.dataset_check import Outcome +from egocap.recording.episode_layout import ( + FINALIZATION_KEEP, + FINALIZATION_QUARANTINE, + FINALIZATION_REMOVE, + FINALIZATION_RETAIN, + MANIFEST_SCHEMA_VERSION, + PHASES, + QUARANTINE_DIR, + READABLE_SCHEMA_VERSIONS, + ROUTE_ATTR, + EpisodeManifest, + final_dir, + finalize_episode_dir, + locate_episode, + quarantine_destination, + quarantine_group, + read_manifest, + remove_owned_episode, + route_id, + scan_manifests, + write_manifest, +) +from egocap.recording.route import claim_quarantine_group, refresh_group_totals +from egocap.studio.studio_path_names import sanitize_studio_dir_name + +SESSION_ID = "session_1" + + +def _session(tmp_path: Path, session_id: str = SESSION_ID) -> Path: + session = tmp_path / "out" / session_id + (session / ".recording").mkdir(parents=True) + return session + + +def _manifest( + index: int = 0, *, session_id: str = SESSION_ID, phase: str = "CHECKED", **changes +) -> EpisodeManifest: + manifest = EpisodeManifest( + session_id=session_id, + episode_id=f"{session_id}/episode_{index}", + episode_index=index, + config_digest="d", + task="stack blocks", + operator="op", + sources=[], + pending_path=f"episode_{index}.pending", + final_path=f"episode_{index}", + storage_phase=phase, + quality={"outcome": "PASSED"}, + qc_decision="FLAGGED_BAD", + finalization=FINALIZATION_QUARANTINE, + ) + for name, value in changes.items(): + setattr(manifest, name, value) + return manifest + + +def _pending(session: Path, manifest: EpisodeManifest) -> Path: + pending = session / manifest.pending_path + pending.mkdir() + (pending / "zarr.json").write_text(json.dumps({"attributes": {"recording_episode_id": manifest.episode_id}})) + (pending / "cam.mp4").write_bytes(b"frames") + return pending + + +def _attrs(path: Path) -> dict: + return json.loads((path / "zarr.json").read_text())["attributes"] + + +def _episode(group: Path, index: int, **attributes) -> Path: + path = group / f"episode_{index}" + path.mkdir(parents=True) + (path / "zarr.json").write_text(json.dumps({"attributes": attributes, "zarr_format": 3, "node_type": "group"})) + return path + + +# --- the finalization intent ----------------------------------------------------------------- + + +def test_only_a_take_marked_bad_is_quarantined_and_only_where_the_switch_is_on(): + assert finalization_for(Outcome.PASSED, QcDecision.FLAGGED_BAD, True) == FINALIZATION_QUARANTINE + assert finalization_for(Outcome.PASSED, QcDecision.FLAGGED_BAD, False) == FINALIZATION_KEEP + assert finalization_for(Outcome.PASSED, QcDecision.FLAGGED_BAD) == FINALIZATION_KEEP + for decision in (QcDecision.PASSED, QcDecision.SKIPPED, QcDecision.ERROR): + assert finalization_for(Outcome.PASSED, decision, True) == FINALIZATION_KEEP + + +def test_the_switch_never_keeps_a_camera_rejection_or_moves_data_that_failed_integrity(): + assert finalization_for(Outcome.PASSED, QcDecision.REJECTED_CAMERA, True) == FINALIZATION_REMOVE + for integrity in (Outcome.FAILED, Outcome.ERROR): + for decision in QcDecision: + assert finalization_for(integrity, decision, True) == FINALIZATION_RETAIN + + +# --- the manifest ---------------------------------------------------------------------------- + + +def test_the_quarantined_phase_and_intent_are_part_of_the_current_manifest_schema(tmp_path): + assert MANIFEST_SCHEMA_VERSION == 5 and MANIFEST_SCHEMA_VERSION in READABLE_SCHEMA_VERSIONS + assert "QUARANTINED" in PHASES + session = _session(tmp_path) + write_manifest(session, _manifest(phase="QUARANTINED")) + (stored,), problems = scan_manifests(session) + assert problems == [] and stored.storage_phase == "QUARANTINED" + assert stored.finalization == FINALIZATION_QUARANTINE and stored.schema_version == 5 + + +def test_a_reader_of_the_previous_schema_would_refuse_the_record_rather_than_misread_it(tmp_path): + session = _session(tmp_path) + write_manifest(session, _manifest(phase="QUARANTINED")) + path = session / ".recording" / "episode_0.json" + data = json.loads(path.read_text()) + assert data["schema_version"] == 5 # what an older reader checks first, and does not know + data["storage_phase"] = "SOMEWHERE_ELSE" + path.write_text(json.dumps(data)) + with pytest.raises(ValueError, match="unsupported storage_phase"): + read_manifest(path) + + +def test_older_manifests_are_still_read(tmp_path): + session = _session(tmp_path) + write_manifest(session, _manifest(phase="FINALIZED", finalization=FINALIZATION_KEEP, qc_decision="PASSED")) + path = session / ".recording" / "episode_0.json" + data = json.loads(path.read_text()) + data["schema_version"] = 4 + path.write_text(json.dumps(data)) + assert read_manifest(path).storage_phase == "FINALIZED" + + +# --- the path -------------------------------------------------------------------------------- + + +def test_a_quarantined_take_lives_under_the_quarantine_folder_by_session_and_take_index(tmp_path): + session = _session(tmp_path) + manifest = _manifest(3) + assert quarantine_group(SESSION_ID) == "_quarantine/session_1" + assert quarantine_destination(manifest) == "_quarantine/session_1/episode_3" + assert final_dir(session, manifest) == (tmp_path / "out").resolve() / QUARANTINE_DIR / SESSION_ID / "episode_3" + + +def test_a_routed_slot_is_never_used_for_a_take_whose_intent_is_quarantine(tmp_path): + session = _session(tmp_path) + manifest = _manifest(studio="Kitchen", assignment={"group": "Kitchen/2026-10-20-09-30-00", "slot": 0}) + assert final_dir(session, manifest).parent.parent.name == QUARANTINE_DIR + + +def test_the_path_is_built_from_the_session_and_the_index_never_from_other_manifest_data(tmp_path): + session = _session(tmp_path) + with pytest.raises(ValueError, match="not the canonical"): + final_dir(session, _manifest(final_path="../../elsewhere")) + with pytest.raises(ValueError, match="is not the session"): + final_dir(session, _manifest(session_id="session_2")) + with pytest.raises(ValueError, match="is not the session"): + final_dir(session, _manifest(session_id="../outside")) + + +def test_a_symlinked_quarantine_root_session_folder_or_episode_is_refused(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + outside = tmp_path / "outside" + outside.mkdir() + root = tmp_path / "out" / QUARANTINE_DIR + root.symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + final_dir(session, manifest) + root.unlink() + root.mkdir() + (root / SESSION_ID).symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + final_dir(session, manifest) + (root / SESSION_ID).unlink() + claim_quarantine_group(session, SESSION_ID) + (root / SESSION_ID / "episode_0").symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + final_dir(session, manifest) + assert list(outside.iterdir()) == [] + + +def test_a_folder_not_stamped_as_this_sessions_quarantine_is_refused(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + group = tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + _episode(group, 4, recording_episode_id="someone/episode_4") + with pytest.raises(PermissionError, match="not the quarantine folder"): + final_dir(session, manifest) # it holds something and has no stamp at all + (group / "zarr.json").write_text(json.dumps({"attributes": {ROUTE_ATTR: "session_2|_quarantine/session_2"}})) + with pytest.raises(PermissionError, match="not the quarantine folder"): + final_dir(session, manifest) + (group / "zarr.json").write_text("not json") + with pytest.raises(PermissionError): + final_dir(session, manifest) + + +# --- publishing and recovery by identity ----------------------------------------------------- + + +def test_a_take_is_renamed_into_quarantine_and_found_there_after_a_crash_before_its_checkpoint(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + group = claim_quarantine_group(session, SESSION_ID) + _pending(session, manifest) + assert locate_episode(session, manifest) == "pending" + final = finalize_episode_dir(session, manifest) + assert final == group.resolve() / "episode_0" and (final / "cam.mp4").read_bytes() == b"frames" + assert not (session / manifest.pending_path).exists() and not (session / "episode_0").exists() + # The rename happened and the QUARANTINED checkpoint did not: the manifest still says CHECKED. + assert locate_episode(session, manifest) == "final" + assert finalize_episode_dir(session, manifest) == final # the repeat changes nothing + + +def test_a_quarantine_slot_held_by_another_take_is_a_collision_not_an_overwrite(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + group = claim_quarantine_group(session, SESSION_ID) + _pending(session, manifest) + other = _episode(group, 0, recording_episode_id="session_1/episode_9") + with pytest.raises(FileExistsError, match="both"): + finalize_episode_dir(session, manifest) + (session / manifest.pending_path / "cam.mp4").unlink() + (session / manifest.pending_path / "zarr.json").unlink() + (session / manifest.pending_path).rmdir() + with pytest.raises(FileExistsError, match="not owned"): + locate_episode(session, manifest) + assert _attrs(other) == {"recording_episode_id": "session_1/episode_9"} + + +@pytest.mark.parametrize("phase", ["CHECKED", "QUARANTINED"]) +def test_removal_never_deletes_quarantined_output(tmp_path, phase): + session = _session(tmp_path) + manifest = _manifest() + claim_quarantine_group(session, SESSION_ID) + _pending(session, manifest) + final = finalize_episode_dir(session, manifest) + manifest.storage_phase = phase + with pytest.raises(PermissionError, match="finalized output"): + remove_owned_episode(session, manifest) + assert (final / "cam.mp4").read_bytes() == b"frames" + + +def test_a_quarantined_manifest_refuses_removal_even_when_its_folder_was_taken_away(tmp_path): + session = _session(tmp_path) + manifest = _manifest(phase="QUARANTINED") + stray = _pending(session, manifest) # a directory of the take's pending name that is not this take's to lose + with pytest.raises(PermissionError, match="finalized output"): + remove_owned_episode(session, manifest) + assert (stray / "cam.mp4").exists() + + +def test_a_take_still_pending_with_the_quarantine_intent_can_be_discarded(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + group = claim_quarantine_group(session, SESSION_ID) + earlier = _episode(group, 7, recording_episode_id="session_1/episode_7") + _pending(session, manifest) + remove_owned_episode(session, manifest) + assert not (session / manifest.pending_path).exists() + assert earlier.is_dir() and sorted(p.name for p in group.iterdir()) == ["episode_7", "zarr.json"] + + +# --- the folder ------------------------------------------------------------------------------ + + +def test_the_quarantine_folder_is_created_once_and_stamped_as_this_sessions(tmp_path): + session = _session(tmp_path) + group = claim_quarantine_group(session, SESSION_ID) + assert group == tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + stamp = _attrs(group) + assert stamp[ROUTE_ATTR] == route_id(SESSION_ID, "_quarantine/session_1") and stamp["quarantine"] is True + assert stamp["discarded_episode_indices"] == [] and stamp["discarded_reasons"] == {} + before = (group / "zarr.json").read_bytes() + assert claim_quarantine_group(session, SESSION_ID) == group + assert (group / "zarr.json").read_bytes() == before + + +def test_each_session_has_its_own_quarantine_folder(tmp_path): + first, second = _session(tmp_path), _session(tmp_path, "session_2") + assert claim_quarantine_group(first, SESSION_ID) != claim_quarantine_group(second, "session_2") + assert sorted(p.name for p in (tmp_path / "out" / QUARANTINE_DIR).iterdir()) == ["session_1", "session_2"] + + +def test_an_empty_folder_with_no_stamp_is_replaced_by_the_stamped_one(tmp_path): + session = _session(tmp_path) + (tmp_path / "out" / QUARANTINE_DIR / SESSION_ID).mkdir(parents=True) + group = claim_quarantine_group(session, SESSION_ID) + assert _attrs(group)[ROUTE_ATTR] == route_id(SESSION_ID, "_quarantine/session_1") + assert sorted(p.name for p in group.iterdir()) == ["zarr.json"] + + +def test_a_folder_that_holds_something_without_this_sessions_stamp_is_never_adopted(tmp_path): + session = _session(tmp_path) + group = tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + _episode(group, 0, recording_episode_id="someone/episode_0") + with pytest.raises(PermissionError, match="not the quarantine folder"): + claim_quarantine_group(session, SESSION_ID) # holds data, has no stamp + assert not (session / ".recording" / "quarantine_claim").exists() + (group / "zarr.json").write_text(json.dumps({"attributes": {ROUTE_ATTR: "session_2|_quarantine/session_2"}})) + with pytest.raises(PermissionError, match="not the quarantine folder"): + claim_quarantine_group(session, SESSION_ID) + assert (group / "episode_0").is_dir() + + +def test_a_symlinked_quarantine_root_or_session_folder_is_refused_before_anything_is_written(tmp_path): + session = _session(tmp_path) + outside = tmp_path / "outside" + outside.mkdir() + root = tmp_path / "out" / QUARANTINE_DIR + root.symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + claim_quarantine_group(session, SESSION_ID) + root.unlink() + root.mkdir() + (root / SESSION_ID).symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + claim_quarantine_group(session, SESSION_ID) + assert list(outside.iterdir()) == [] + + +def test_the_folders_totals_list_every_quarantined_episode_as_discarded_with_its_reasons(tmp_path): + session = _session(tmp_path) + group = claim_quarantine_group(session, SESSION_ID) + _episode(group, 2, episode_duration=1800.0, episode_length=50, bad_episode=True, capture_qc_issues=["frozen"]) + _episode(group, 5, episode_duration=1800.0, bad_episode=True, capture_qc_issues=["gap", "short"]) + totals = refresh_group_totals(group) + assert totals["num_episodes"] == 2 and totals["total_data_time_hours"] == 1.0 + assert totals["discarded_episode_indices"] == [2, 5] + assert totals["discarded_reasons"] == {"2": "frozen", "5": "gap; short"} + assert totals[ROUTE_ATTR] == route_id(SESSION_ID, "_quarantine/session_1") and totals["quarantine"] is True + + +@pytest.mark.parametrize("name", ["_quarantine", " _quarantine ", "__quarantine", "_quarantine_", "/_quarantine"]) +def test_no_studio_name_becomes_the_quarantine_folder(name): + # Routing publishes into the sanitized studio name; the quarantine folder must never be one. + assert sanitize_studio_dir_name(name) != QUARANTINE_DIR diff --git a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py new file mode 100644 index 0000000000..f21e65d15c --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py @@ -0,0 +1,749 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""No take ends where it can be neither finished nor discarded, and no record acts outside its own session. + +Each test builds the state a failure or an odd recording output leaves on real directories, then shows what the +layout rules allow: which take may be finished, which may be removed, and that a removal takes that take's own +pending directory and nothing else. +""" + +import errno +import fcntl +import json +import logging +import os +import threading +import time +from pathlib import Path + +import pytest + +from egocap.recording import episode_layout, route +from egocap.recording.episode_layout import ( + FINALIZATION_KEEP, + FINALIZATION_QUARANTINE, + FINALIZATION_RETAIN, + QUARANTINE_DIR, + ROUTE_ATTR, + EpisodeManifest, + SessionLock, + final_dir, + finalize_episode_dir, + locate_episode, + read_manifest, + remove_owned_episode, + route_id, + scan_manifests, + write_manifest, +) +from egocap.recording.route import claim_quarantine_group + +SESSION_ID = "session_1" + + +def _session(tmp_path: Path, session_id: str = SESSION_ID) -> Path: + session = tmp_path / "out" / session_id + (session / ".recording").mkdir(parents=True) + return session + + +def _manifest( + index: int = 0, *, session_id: str = SESSION_ID, phase: str = "CHECKED", **changes +) -> EpisodeManifest: + manifest = EpisodeManifest( + session_id=session_id, + episode_id=f"{session_id}/episode_{index}", + episode_index=index, + config_digest="d", + task="stack blocks", + operator="op", + sources=[], + pending_path=f"episode_{index}.pending", + final_path=f"episode_{index}", + storage_phase=phase, + quality={"outcome": "PASSED"}, + qc_decision="FLAGGED_BAD", + finalization=FINALIZATION_QUARANTINE, + ) + for name, value in changes.items(): + setattr(manifest, name, value) + return manifest + + +def _pending(session: Path, manifest: EpisodeManifest) -> Path: + pending = session / manifest.pending_path + pending.mkdir() + (pending / "zarr.json").write_text(json.dumps({"attributes": {"recording_episode_id": manifest.episode_id}})) + (pending / "cam.mp4").write_bytes(b"frames") + return pending + + +def _tree(root: Path) -> dict[str, bytes]: + """Every file under ``root`` with its bytes, so two of these show exactly what an operation changed.""" + return {p.relative_to(root).as_posix(): p.read_bytes() for p in sorted(root.rglob("*")) if p.is_file()} + + +def _attrs(path: Path) -> dict: + return json.loads((path / "zarr.json").read_text())["attributes"] + + +# --- the quarantine folder never exists without its stamp ------------------------------------ + + +def test_the_folder_appears_in_one_step_already_stamped(tmp_path, monkeypatch): + session = _session(tmp_path) + group = tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + seen = [] + real_rename = os.rename + + def watched_rename(source, target, *args, **kwargs): + if Path(target) == group: + # The instant before the folder appears, and what it is the instant after. + seen.append(("before", group.exists())) + real_rename(source, target, *args, **kwargs) + seen.append(("after", _attrs(group)[ROUTE_ATTR])) + else: + real_rename(source, target, *args, **kwargs) + + monkeypatch.setattr(os, "rename", watched_rename) + claim_quarantine_group(session, SESSION_ID) + assert seen == [("before", False), ("after", route_id(SESSION_ID, "_quarantine/session_1"))] + assert not (session / ".recording" / route.QUARANTINE_CLAIM).exists() + + +@pytest.mark.parametrize("fails_at", ["mkdir", "stamp", "rename"]) +def test_a_claim_that_fails_at_any_step_leaves_no_unstamped_folder_and_can_be_repeated( + tmp_path, monkeypatch, fails_at +): + session = _session(tmp_path) + group = tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + staging = session / ".recording" / route.QUARANTINE_CLAIM + with monkeypatch.context() as patched: + if fails_at == "mkdir": + real_mkdir = os.mkdir + + def mkdir(path, *args, **kwargs): + if Path(path) == staging: + raise OSError(errno.ENOSPC, "no space left on device") + real_mkdir(path, *args, **kwargs) + + patched.setattr(os, "mkdir", mkdir) + elif fails_at == "stamp": + + def no_stamp(path, data): + raise OSError(errno.ENOSPC, "no space left on device") + + patched.setattr(route, "write_json_atomic", no_stamp) + else: + + def no_rename(source, target, *args, **kwargs): + raise OSError(errno.EIO, "input/output error") + + patched.setattr(os, "rename", no_rename) + with pytest.raises(OSError): + claim_quarantine_group(session, SESSION_ID) + # Whatever failed, the folder is not there half made: a take of this session can still be located. + assert not group.exists() + manifest = _manifest() + _pending(session, manifest) + assert locate_episode(session, manifest) == "pending" + claimed = claim_quarantine_group(session, SESSION_ID) + assert _attrs(claimed)[ROUTE_ATTR] == route_id(SESSION_ID, "_quarantine/session_1") + assert finalize_episode_dir(session, manifest) == claimed / "episode_0" + + +def test_what_an_interrupted_claim_left_in_the_sidecar_is_cleared_and_nothing_else_there_is(tmp_path): + session = _session(tmp_path) + write_manifest(session, _manifest()) + staging = session / ".recording" / route.QUARANTINE_CLAIM + staging.mkdir() + (staging / "zarr.abc.tmp").write_text("half a stamp") + before = _tree(session) + claim_quarantine_group(session, SESSION_ID) + after = _tree(session) + assert set(before) - set(after) == {".recording/quarantine_claim/zarr.abc.tmp"} + assert {name: after[name] for name in after} == {name: before[name] for name in after} + assert not staging.exists() + + +def test_an_empty_unstamped_folder_counts_as_absent_so_the_take_is_neither_lost_nor_stuck(tmp_path): + """What a claim interrupted between creating the folder and stamping it used to leave.""" + session = _session(tmp_path) + manifest = _manifest() + pending = _pending(session, manifest) + group = tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + group.mkdir(parents=True) + assert final_dir(session, manifest) == group / "episode_0" + assert locate_episode(session, manifest) == "pending" + # Recover: the claim replaces the empty folder and the take is renamed into it. + assert claim_quarantine_group(session, SESSION_ID) == group + assert finalize_episode_dir(session, manifest) == group / "episode_0" and not pending.exists() + assert (group / "episode_0" / "cam.mp4").read_bytes() == b"frames" + + +def test_a_take_is_never_renamed_into_a_folder_that_was_not_claimed(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + pending = _pending(session, manifest) + (tmp_path / "out" / QUARANTINE_DIR / SESSION_ID).mkdir(parents=True) + with pytest.raises(PermissionError, match="has not been claimed"): + finalize_episode_dir(session, manifest) + assert (pending / "cam.mp4").read_bytes() == b"frames" + + +def test_a_folder_that_cannot_be_renamed_onto_for_another_reason_reports_that_reason(tmp_path): + session = _session(tmp_path) + root = tmp_path / "out" / QUARANTINE_DIR + root.mkdir() + (root / SESSION_ID).write_text("a file where the folder should be") + with pytest.raises(NotADirectoryError): + claim_quarantine_group(session, SESSION_ID) + assert (root / SESSION_ID).read_text() == "a file where the folder should be" + assert not (session / ".recording" / route.QUARANTINE_CLAIM).exists() + + +def test_a_discard_clears_what_an_interrupted_claim_left_and_nothing_else_in_the_sidecar(tmp_path): + session = _session(tmp_path) + write_manifest(session, _manifest()) + route.discard_quarantine_claim(session) # nothing was left: nothing happens + staging = session / ".recording" / route.QUARANTINE_CLAIM + staging.mkdir() + (staging / "zarr.json").write_text("{}") + before = _tree(session) + route.discard_quarantine_claim(session) + after = _tree(session) + assert set(before) - set(after) == {".recording/quarantine_claim/zarr.json"} and not staging.exists() + assert {name: before[name] for name in after} == after + + +@pytest.mark.parametrize("put_there", ["a link to a directory", "a file"]) +def test_a_discard_removes_nothing_through_a_link_or_a_file_under_the_claims_name(tmp_path, put_there): + session = _session(tmp_path) + write_manifest(session, _manifest()) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + (elsewhere / "kept.bin").write_bytes(b"someone's data") + staging = session / ".recording" / route.QUARANTINE_CLAIM + if put_there == "a file": + staging.write_text("not a claim") + else: + staging.symlink_to(elsewhere, target_is_directory=True) + before = _tree(tmp_path) + route.discard_quarantine_claim(session) + # Whatever is under the name stays, and what a link names is never reached. + assert _tree(tmp_path) == before and (elsewhere / "kept.bin").read_bytes() == b"someone's data" + assert staging.is_symlink() or staging.is_file() + + +# --- a pending directory that is the take's own can always be discarded ----------------------- + + +def _expect_only_the_pending_directory_removed(session: Path, manifest: EpisodeManifest) -> None: + root = session.parent + before = _tree(root) + remove_owned_episode(session, manifest) + after = _tree(root) + assert set(before) - set(after) == { + f"{SESSION_ID}/episode_0.pending/zarr.json", + f"{SESSION_ID}/episode_0.pending/cam.mp4", + } + assert {name: before[name] for name in after} == after + assert not (session / manifest.pending_path).exists() + + +def test_a_take_is_discarded_though_the_quarantine_folder_is_a_link(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + _pending(session, manifest) + elsewhere = tmp_path / "other_disk" + elsewhere.mkdir() + (elsewhere / "kept.bin").write_bytes(b"someone else's") + (tmp_path / "out" / QUARANTINE_DIR).symlink_to(elsewhere, target_is_directory=True) + with pytest.raises(ValueError, match="symlink"): + locate_episode(session, manifest) # it cannot be finished there + _expect_only_the_pending_directory_removed(session, manifest) + assert (elsewhere / "kept.bin").read_bytes() == b"someone else's" + + +def test_a_take_is_discarded_though_the_quarantine_folder_is_a_file(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + _pending(session, manifest) + (tmp_path / "out" / QUARANTINE_DIR).write_text("not a folder") + _expect_only_the_pending_directory_removed(session, manifest) + assert (tmp_path / "out" / QUARANTINE_DIR).read_text() == "not a folder" + + +def test_a_take_is_discarded_though_something_else_holds_its_place_in_quarantine(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + group = claim_quarantine_group(session, SESSION_ID) + other = group / "episode_0" + other.mkdir() + (other / "zarr.json").write_text(json.dumps({"attributes": {"recording_episode_id": "someone/episode_0"}})) + _pending(session, manifest) + with pytest.raises(FileExistsError, match="refusing to choose"): + locate_episode(session, manifest) # recover never overwrites what is there + _expect_only_the_pending_directory_removed(session, manifest) + assert _attrs(other) == {"recording_episode_id": "someone/episode_0"} + + +def test_a_take_is_discarded_though_its_quarantine_folder_is_stamped_for_another_session(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + _pending(session, manifest) + group = tmp_path / "out" / QUARANTINE_DIR / SESSION_ID + group.mkdir(parents=True) + (group / "zarr.json").write_text(json.dumps({"attributes": {ROUTE_ATTR: "session_2|_quarantine/session_2"}})) + with pytest.raises(PermissionError, match="not the quarantine folder"): + locate_episode(session, manifest) + _expect_only_the_pending_directory_removed(session, manifest) + + +def test_a_pending_directory_that_is_not_the_takes_own_is_still_never_removed(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + stray = session / manifest.pending_path + stray.mkdir() + (stray / "zarr.json").write_text(json.dumps({"attributes": {"recording_episode_id": "session_1/episode_9"}})) + (stray / "cam.mp4").write_bytes(b"another take's frames") + (tmp_path / "out" / QUARANTINE_DIR).write_text("not a folder") + with pytest.raises(PermissionError, match="not owned"): + remove_owned_episode(session, manifest) + assert (stray / "cam.mp4").read_bytes() == b"another take's frames" + + +def test_with_no_pending_directory_a_take_already_in_its_final_place_is_refused_not_marked_gone(tmp_path): + session = _session(tmp_path) + manifest = _manifest() + claim_quarantine_group(session, SESSION_ID) + _pending(session, manifest) + final = finalize_episode_dir(session, manifest) + # Said as what it is, so that a caller can tell the operator the take is saved and not "try again". + with pytest.raises(episode_layout.AlreadyPublished, match="finalized output"): + remove_owned_episode(session, manifest) # still CHECKED: the rename happened, its checkpoint did not + with pytest.raises(episode_layout.AlreadyPublished): + episode_layout.discardable_pending(session, _manifest(phase="QUARANTINED")) + assert (final / "cam.mp4").read_bytes() == b"frames" + remove_owned_episode(session, _manifest(1)) # nothing pending and nothing published: nothing to do + + +# --- the quarantine location is judged before a take needs it --------------------------------- + + +def test_a_quarantine_location_that_is_absent_or_a_plain_folder_is_no_problem(tmp_path): + out = tmp_path / "out" + out.mkdir() + assert episode_layout.quarantine_location_problem(out) is None + (out / QUARANTINE_DIR).mkdir() + assert episode_layout.quarantine_location_problem(out) is None + assert episode_layout.quarantine_location_problem(out, SESSION_ID) is None + (out / QUARANTINE_DIR / SESSION_ID).mkdir() + assert episode_layout.quarantine_location_problem(out, SESSION_ID) is None + + +def test_a_quarantine_location_that_is_a_link_or_a_file_is_named_without_any_directory(tmp_path): + out, elsewhere = tmp_path / "out", tmp_path / "elsewhere" + out.mkdir() + elsewhere.mkdir() + (out / QUARANTINE_DIR).symlink_to(elsewhere, target_is_directory=True) + assert episode_layout.quarantine_location_problem(out) == "is a link" + (out / QUARANTINE_DIR).unlink() + (out / QUARANTINE_DIR).write_text("x") + assert episode_layout.quarantine_location_problem(out) == "is not a directory" + (out / QUARANTINE_DIR).unlink() + (out / QUARANTINE_DIR).mkdir() + (out / QUARANTINE_DIR / SESSION_ID).symlink_to(elsewhere, target_is_directory=True) + assert episode_layout.quarantine_location_problem(out) is None # the session's folder is asked for by name + assert episode_layout.quarantine_location_problem(out, SESSION_ID) == "is a link" + + +def test_a_quarantine_location_on_another_file_system_is_a_problem(tmp_path, monkeypatch): + out = tmp_path / "out" + (out / QUARANTINE_DIR).mkdir(parents=True) + # Another file system cannot be mounted in a test, so the device the system reports is substituted. + monkeypatch.setattr(episode_layout, "_device", lambda path: 7 if path.name == QUARANTINE_DIR else 1) + assert episode_layout.quarantine_location_problem(out) == "is on another file system" + + +def test_the_device_of_a_folder_is_the_one_the_system_reports(tmp_path): + assert episode_layout._device(tmp_path) == os.stat(tmp_path).st_dev + + +# --- a discard records its intent before it deletes ------------------------------------------- + + +def test_older_records_have_no_discard_intent(tmp_path): + session = _session(tmp_path) + write_manifest(session, _manifest()) + path = session / ".recording" / "episode_0.json" + data = json.loads(path.read_text()) + assert data["discard_requested"] is False + del data["discard_requested"] + path.write_text(json.dumps(data)) + assert read_manifest(path).discard_requested is False + + +@pytest.mark.parametrize( + ("phase", "finalization"), + [ + ("SEALED", None), + ("CHECKED", FINALIZATION_KEEP), + ("CHECKED", FINALIZATION_QUARANTINE), + ("REJECTED", FINALIZATION_RETAIN), + ], +) +def test_the_emptied_directory_of_a_take_being_discarded_is_still_its_own(tmp_path, phase, finalization): + """What a discard leaves when it stops between deleting the ownership stamp and removing the directory.""" + session = _session(tmp_path) + manifest = _manifest( + phase=phase, finalization=finalization, quality=None if phase == "SEALED" else {"outcome": "PASSED"} + ) + emptied = session / manifest.pending_path + emptied.mkdir() + with pytest.raises(PermissionError, match="not owned"): + remove_owned_episode(session, manifest) # no intent on record: an empty directory proves nothing + manifest.discard_requested = True + remove_owned_episode(session, manifest) + assert not emptied.exists() + + +def test_the_discard_intent_does_not_make_a_directory_with_content_the_takes_own(tmp_path): + session = _session(tmp_path) + manifest = _manifest(discard_requested=True) + foreign = session / manifest.pending_path + foreign.mkdir() + (foreign / "cam.mp4").write_bytes(b"unstamped frames") + with pytest.raises(PermissionError, match="not owned"): + remove_owned_episode(session, manifest) + with pytest.raises(PermissionError, match="not owned"): + locate_episode(session, manifest) + assert (foreign / "cam.mp4").read_bytes() == b"unstamped frames" + + +def test_a_take_being_discarded_is_located_by_its_emptied_directory(tmp_path): + session = _session(tmp_path) + manifest = _manifest(phase="SEALED", finalization=None, quality=None, discard_requested=True) + (session / manifest.pending_path).mkdir() + assert locate_episode(session, manifest) == "pending" + + +# --- a record acts only in the session it was written for ------------------------------------- + + +def test_records_of_a_copied_session_directory_are_reported_and_not_returned(tmp_path): + session = _session(tmp_path) + write_manifest(session, _manifest(0, phase="WRITING", quality=None, finalization=None)) + write_manifest(session, _manifest(1)) + copy = tmp_path / "out" / "session_1_copy" + (copy / ".recording").mkdir(parents=True) + for name in ("episode_0.json", "episode_1.json"): + (copy / ".recording" / name).write_bytes((session / ".recording" / name).read_bytes()) + own, no_problems = scan_manifests(session) + assert [m.episode_index for m in own] == [0, 1] and no_problems == [] + found, problems = scan_manifests(copy) + assert found == [] + assert problems == [ + "episode_0.json: written for another session; this session directory was copied or renamed", + "episode_1.json: written for another session; this session directory was copied or renamed", + ] + scan = episode_layout.scan_session(copy) + assert [m.episode_id for m in scan.misplaced] == ["session_1/episode_0", "session_1/episode_1"] + assert scan.manifests == () and list(scan.problems) == problems + + +def test_a_diagnostic_names_the_file_and_never_the_directory_it_is_in(tmp_path, monkeypatch): + session = _session(tmp_path) + write_manifest(session, _manifest(0)) + sidecar = session / ".recording" + data = json.loads((sidecar / "episode_0.json").read_text()) + (sidecar / "episode_1.json").write_text(json.dumps({**data, "schema_version": 99})) + (sidecar / "episode_2.json").write_text("{ not json") + (sidecar / "episode_3.json").write_text(json.dumps({**data, "episode_index": 3, "surprise": 1})) + (sidecar / "episode_4.json").write_text("[]") + (sidecar / "episode_5.json").write_text(json.dumps(data)) + real_read = Path.read_text + + def read_text(self, *args, **kwargs): + if self.name == "episode_5.json": + raise PermissionError(errno.EACCES, "Permission denied", str(self)) + return real_read(self, *args, **kwargs) + + monkeypatch.setattr(Path, "read_text", read_text) + older = {**data, "episode_index": 6, "pending_path": "episode_6.pending", "final_path": "episode_6"} + del older["finalization"] + (sidecar / "episode_6.json").write_text(json.dumps({**older, "schema_version": 2, "quality": "oops"})) + found, problems = scan_manifests(session) + assert [m.episode_index for m in found] == [0] + # What this code decided about a record is said in its own words; what a parser, the interpreter or the + # system said about a file that is no record is not repeated. + assert problems == [ + "episode_1.json: unsupported manifest schema_version 99", + "episode_2.json: not a take record", + "episode_3.json: not a take record", + "episode_4.json: not a take record", + "episode_5.json: the file cannot be read", + "episode_6.json: schema 2 record's check results are missing or damaged", + ] + said = " ".join(problems) + assert str(tmp_path) not in said + for theirs in ("Error", "__init__", "line 1", "object has no attribute", "Expecting", "Errno", "KeyError"): + assert theirs not in said + + +def test_a_session_whose_config_cannot_be_read_is_told_apart_from_one_that_names_no_station(tmp_path): + session = _session(tmp_path) + # Not there yet (a session has its sidecar before its config), or there and not readable as YAML. + assert episode_layout.frozen_station(session) == (False, None) + config = session / "config.yaml" + config.write_text(": :\n - [") + assert episode_layout.frozen_station(session) == (False, None) + config.write_text("meta:\n egocap_station_name: Bench A\n") + assert episode_layout.frozen_station(session) == (True, "Bench A") + # Read, and it names no station: that is a fact about the session, not a failed read. + for unnamed in ( + "meta: {}\n", + "meta:\n egocap_station_name: ''\n", + "meta:\n egocap_station_name: 4\n", + "- a\n", + ): + config.write_text(unnamed) + assert episode_layout.frozen_station(session) == (True, None) + + +# --- telling a recorder that holds a session from a reader that only looks --------------------- + + +def test_a_session_nobody_holds_is_free_and_one_a_recorder_holds_is_not(tmp_path): + session = _session(tmp_path) + assert episode_layout.session_lock_is_free(session) # never opened: there is no lock file, and none is made + assert not (session / ".recording" / "session.lock").exists() + lock = SessionLock(session) + assert not episode_layout.session_lock_is_free(session) + lock.release() + assert episode_layout.session_lock_is_free(session) + SessionLock(session).release() # the probe kept nothing + + +# --- the beat: a session that is open says so wherever its directory can be seen --------------- + + +def _wait_for(condition, seconds: float = 5.0) -> bool: + """Whether ``condition`` came true within ``seconds``, asked every few milliseconds.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(0.005) + return False + + +def test_a_session_that_is_held_changes_its_beat_and_one_that_was_released_does_not(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + session = _session(tmp_path) + assert episode_layout.session_beat(session) is None # nobody ever opened it + lock = SessionLock(session) + first = episode_layout.session_beat(session) + assert first is not None and first[0] # the first beat is written at once + # It keeps changing for as long as the session is held, whatever else the holder does. + assert _wait_for(lambda: episode_layout.session_beat(session) != first) + second = episode_layout.session_beat(session) + assert _wait_for(lambda: episode_layout.session_beat(session) != second) + lock.release() + last = episode_layout.session_beat(session) + time.sleep(0.2) # ten beat periods + assert episode_layout.session_beat(session) == last + lock.release() # twice is harmless + + +def test_a_new_holder_never_writes_a_beat_an_earlier_holder_wrote(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) # only the beat written at once + session = _session(tmp_path) + seen = set() + for _ in range(5): + lock = SessionLock(session) + seen.add(episode_layout.session_beat(session)[0]) + lock.release() + assert len(seen) == 5 + + +def test_a_recorder_that_is_turned_away_leaves_the_holders_beat_as_it_is(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) + monkeypatch.setattr(episode_layout.time, "sleep", lambda seconds: None) + session = _session(tmp_path) + holder = SessionLock(session) + before = episode_layout.session_beat(session) + with pytest.raises(BlockingIOError): + SessionLock(session) + assert episode_layout.session_beat(session) == before + holder.release() + + +def test_a_beat_that_cannot_be_written_is_skipped_and_the_next_one_is_written(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + session = _session(tmp_path) + real_utime, failures = os.utime, [] + + def utime(target, *args, **kwargs): + if len(failures) < 3: + failures.append(target) + raise OSError(errno.EIO, "input/output error") + return real_utime(target, *args, **kwargs) + + lock = SessionLock(session) + monkeypatch.setattr(episode_layout.os, "utime", utime) + assert _wait_for(lambda: len(failures) == 3) + after_failures = episode_layout.session_beat(session) + assert _wait_for(lambda: episode_layout.session_beat(session) != after_failures) + lock.release() + lock.beat() # after the release there is nothing to write to, and nothing is raised + + +def _beating(session: Path) -> list[threading.Thread]: + """The threads that beat right now; a test holds one session at a time.""" + return [thread for thread in threading.enumerate() if thread.name == "session-beat" and thread.is_alive()] + + +def test_a_beat_that_fails_with_anything_at_all_is_logged_once_and_the_thread_goes_on_beating( + tmp_path, monkeypatch, caplog +): + """Not an operating-system error: nothing a beat can raise may end the thread that beats.""" + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + monkeypatch.setattr(episode_layout, "BEAT_WATCH_SECONDS", 0.3) + session = _session(tmp_path) + real_beat, failures, broken = SessionLock.beat, [], threading.Event() + + def beat(lock): + if broken.is_set(): + failures.append(lock) + raise RuntimeError("nothing a beat expects") + real_beat(lock) + + lock = SessionLock(session) + assert len(_beating(session)) == 1 and lock.silence() is None and lock.stalls == 0 + monkeypatch.setattr(SessionLock, "beat", beat) + with caplog.at_level(logging.ERROR, logger="isaaccapture.egocap.episode_layout"): + broken.set() + assert _wait_for(lambda: len(failures) >= 5) + assert len(_beating(session)) == 1 # five failures on, the same thread is still trying + # The holder knows its beat has been missing for as long as a reader watches. + assert _wait_for(lambda: lock.silence() is not None) and lock.silence() >= 0.3 + stopped_at = episode_layout.session_beat(session) + broken.clear() + assert _wait_for(lambda: episode_layout.session_beat(session) != stopped_at) + assert _wait_for(lambda: lock.silence() is None) + # The beat that got through came a watch time after the one before it: one stall. + assert lock.stalls == 1 + said = [record for record in caplog.records if "beat could not be written" in record.getMessage()] + assert len(said) == 1 and said[0].exc_info is not None # once, with what was raised + # A failure that begins after a beat got through is said again. + so_far = len(failures) + broken.set() + assert _wait_for(lambda: len(failures) > so_far + 2) + said = [record for record in caplog.records if "beat could not be written" in record.getMessage()] + assert len(said) == 2 + broken.clear() + lock.release() + assert _wait_for(lambda: _beating(session) == []) + + +def test_a_beat_that_hangs_in_its_write_is_known_to_the_holder_while_it_hangs(tmp_path, monkeypatch): + """A stalled disk: one beat's write does not return for a while. Nothing else of the holder waits for it.""" + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + monkeypatch.setattr(episode_layout, "BEAT_WATCH_SECONDS", 0.3) + session = _session(tmp_path) + real_utime, hanging, let_go = os.utime, threading.Event(), threading.Event() + + def utime(target, *args, **kwargs): + if not let_go.is_set(): + hanging.set() + let_go.wait(5.0) + return real_utime(target, *args, **kwargs) + + lock = SessionLock(session) + monkeypatch.setattr(episode_layout.os, "utime", utime) + assert hanging.wait(2.0) + # Asked from another thread while the beat is stuck: answered at once, with a time that grows. + assert _wait_for(lambda: lock.silence() is not None) + first = lock.silence() + time.sleep(0.05) + assert lock.silence() > first and lock.stalls == 0 + let_go.set() + assert _wait_for(lambda: lock.silence() is None) + assert lock.stalls == 1 # the late beat is counted once it is written + lock.release() + + +def test_a_look_at_the_beat_reads_no_clock(tmp_path, monkeypatch): + """The value is compared with an earlier look, never with the time: stamps in the future change nothing.""" + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) + session = _session(tmp_path) + lock = SessionLock(session) + lock.release() + ahead = time.time() + 3600 + os.utime(session / ".recording" / "session.lock", (ahead, ahead)) + first = episode_layout.session_beat(session) + assert episode_layout.session_beat(session) == first + + +def test_a_recorder_is_not_turned_away_by_a_reader_that_held_the_lock_for_an_instant(tmp_path, monkeypatch): + session = _session(tmp_path) + probe = open(session / ".recording" / "session.lock", "w") # noqa: SIM115 - released inside the wait below + fcntl.flock(probe, fcntl.LOCK_EX | fcntl.LOCK_NB) + waited = [] + + def the_probe_lets_go(seconds): + waited.append(seconds) + fcntl.flock(probe, fcntl.LOCK_UN) + probe.close() + + monkeypatch.setattr(episode_layout.time, "sleep", the_probe_lets_go) + lock = SessionLock(session) + assert waited == [episode_layout._PROBE_GRACE_SECONDS] + lock.release() + + +def test_a_recorder_is_still_turned_away_by_another_recorder_that_keeps_the_lock(tmp_path, monkeypatch): + session = _session(tmp_path) + owner = SessionLock(session) + monkeypatch.setattr(episode_layout.time, "sleep", lambda seconds: None) + with pytest.raises(BlockingIOError): + SessionLock(session) + owner.release() + + +# --- a failed write is given the name of the file it was writing ------------------------------- + + +def _no_room(*_args, **_kwargs): + """What the system raises when a write or a sync finds the disk full: an error that names no file.""" + raise OSError(errno.ENOSPC, "No space left on device") + + +@pytest.mark.parametrize("write", [episode_layout.write_json_atomic, episode_layout.write_yaml_atomic]) +def test_a_record_that_cannot_be_synced_names_the_record_and_leaves_no_temporary_file( + tmp_path, monkeypatch, write +): + target = tmp_path / "sidecar" / "episode_0.json" + target.parent.mkdir() + monkeypatch.setattr(episode_layout.os, "fsync", _no_room) + with pytest.raises(OSError) as raised: + write(target, {"a": 1}) + assert raised.value.errno == errno.ENOSPC and raised.value.filename == str(target) + assert list(target.parent.iterdir()) == [] + + +def test_a_failure_that_names_its_own_file_keeps_that_name(tmp_path): + elsewhere = str(tmp_path / "elsewhere" / "program") + with pytest.raises(PermissionError) as raised, episode_layout.naming_the_file(tmp_path / "record.json"): + raise PermissionError(errno.EACCES, "Permission denied", elsewhere) + assert raised.value.filename == elsewhere + # A failure that is not the system's is passed on as it is. + with pytest.raises(ValueError, match="not a file matter"), episode_layout.naming_the_file(tmp_path / "x"): + raise ValueError("not a file matter") + # So is one raised without the system's error number: naming a file would replace its only text. + with pytest.raises(OSError, match="said in words") as worded, episode_layout.naming_the_file(tmp_path / "x"): + raise OSError("said in words") + assert worded.value.filename is None and str(worded.value) == "said in words" diff --git a/examples/egocap/tests/recording_service/synthetic.py b/examples/egocap/tests/recording_service/synthetic.py new file mode 100644 index 0000000000..d081999d66 --- /dev/null +++ b/examples/egocap/tests/recording_service/synthetic.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Helpers that record takes built in the test through the public RecordingService API. + +One tracker and one small camera, so the capture checks have something to judge without a recorded episode. The +defects a test asks for (a hole in the camera's frames, a pose that never changes) are constructed explicitly. +""" + +import asyncio +import hashlib +from pathlib import Path + +import numpy as np + +from recording_service import ( + CaptureQcConfig, + FieldSpec, + NumericSample, + NumericSourceSpec, + PixelFormat, + QcConfig, + RecordingService, + ServiceConfig, + SubmissionStatus, + VideoSample, + VideoSourceSpec, +) + +TRACKER = NumericSourceSpec("tracker", (FieldSpec("pose", "float64", (4, 4)),)) +#: Written by OpenCV, so no encoder process is involved. +CAMERA = VideoSourceSpec("cam", 64, 48, 30.0, "opencv_mp4v", False) +#: The camera gate and the freeze gate at their default limits, plus the checks that need a declaration. +CAPTURE = CaptureQcConfig( + camera_expected_fps=(("cam", None),), + pose_streams=(("tracker", "pose"),), + tracking_gap_sources=("tracker",), + duration_limits_s=(1.0, 600.0), + camera_expected_size=(("cam", None),), +) + + +def make_config(output_root: Path, *, capture: CaptureQcConfig | None = CAPTURE, **overrides) -> ServiceConfig: + """A service configuration over the synthetic tracker and camera.""" + qc = QcConfig(required_sources=("tracker", "cam"), capture=capture) + return ServiceConfig(output_root, (TRACKER,), (CAMERA,), qc=qc, **overrides) + + +def take_samples(*, seconds: float = 2.0, camera_hole: float = 0.0, frozen: bool = False, start: float = 100.0): + """A take's samples in capture-time order: the tracker at 20 Hz and the camera at its declared 30 Hz. + + ``camera_hole`` withholds that many seconds of camera frames from the middle of the take; ``frozen`` holds + the pose at its first value. + """ + samples = [] + for i in range(int(seconds * 20) + 1): + pose = np.eye(4) + pose[0, 3] = 0.0 if frozen else 0.01 * i + samples.append(NumericSample("tracker", start + i / 20.0, start + i / 20.0, {"pose": pose})) + hole_from = seconds / 2.0 - camera_hole / 2.0 + for i in range(int(seconds * 30) + 1): + at = i / 30.0 + # The frames at both edges of the hole are kept, so the camera's own span still covers the whole take. + if camera_hole and hole_from < at < hole_from + camera_hole: + continue + image = np.full((48, 64, 3), i % 255, dtype=np.uint8) + samples.append(VideoSample("cam", image, PixelFormat.BGR8, start + at, start + at)) + return sorted(samples, key=lambda s: s.capture_time) + + +async def submit_all(service: RecordingService, episode_id: str, samples) -> None: + """Submit every sample, retrying the same one while the queue is full.""" + for sample in samples: + while service.submit_sample(episode_id, sample).status is SubmissionStatus.FULL: + await asyncio.sleep(0.005) + + +async def record(service: RecordingService, samples=None, task: str = "t"): + """Record one take to its result on an open session.""" + episode = await service.start_episode(task, "op") + await submit_all(service, episode.episode_id, take_samples() if samples is None else samples) + return await service.stop_episode(episode.episode_id) + + +def tree(root: Path) -> dict[str, str]: + """Every file under ``root`` by relative path, with a digest of its bytes; lock files are left out. + + Comparing two of these shows exactly which files an operation removed, added or changed. + """ + return { + path.relative_to(root).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(root.rglob("*")) + if path.is_file() and path.name != "session.lock" + } + + +def changed(before: dict[str, str], after: dict[str, str]) -> tuple[set[str], set[str], set[str]]: + """What differs between two :func:`tree` results, as (removed, added, modified) relative paths.""" + removed, added = set(before) - set(after), set(after) - set(before) + modified = {path for path in set(before) & set(after) if before[path] != after[path]} + return removed, added, modified diff --git a/examples/egocap/tests/recording_service/test_capture_check_exemption.py b/examples/egocap/tests/recording_service/test_capture_check_exemption.py new file mode 100644 index 0000000000..9b64dc9a8e --- /dev/null +++ b/examples/egocap/tests/recording_service/test_capture_check_exemption.py @@ -0,0 +1,114 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A take started as exempt from the capture checks is finalized unjudged; every other take is judged. + +Takes are built in the test (see synthetic.py) and recorded through the real service and the real backend. +""" + +import zarr +from synthetic import make_config, submit_all, take_samples + +import recording_service.recording_service as impl +from egocap.recording.episode_layout import read_manifest +from recording_service import Disposition, NumericSample, QcDecision, RecordingService + +#: A take the checks would reject (a camera at half its rate) and mark bad (a pose that never changes). +DEFECTIVE = take_samples(camera_hole=1.0, frozen=True) + + +async def _record(service, samples, **start): + episode = await service.start_episode("t", "op", **start) + await submit_all(service, episode.episode_id, samples) + return await service.stop_episode(episode.episode_id) + + +async def test_an_exempt_take_is_kept_unjudged_and_its_metadata_says_it_was_exempt(tmp_path, own): + service = own(RecordingService(make_config(tmp_path / "out", quarantine=True))) + session = await service.open_session() + result = await _record(service, DEFECTIVE, exempt_from_capture_checks=True) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.SKIPPED + assert result.capture_quality is None and result.final_path == session.session_path / "episode_0" + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["capture_qc_exempt"] is True and attrs["domain_checks"] == "SKIPPED" + assert attrs["capture_qc_decision"] == "SKIPPED" and attrs["capture_qc_results"] == [] + assert attrs["bad_episode"] is False and attrs["quarantined"] is False + assert attrs["integrity_check_passed"] is True + manifest = read_manifest(session.session_path / ".recording" / "episode_0.json") + assert manifest.capture_checks_exempt is True and manifest.capture_quality is None + assert not (tmp_path / "out" / "_quarantine").exists() + + +async def test_the_same_take_started_the_ordinary_way_is_judged(tmp_path, own): + service = own(RecordingService(make_config(tmp_path / "out", quarantine=True))) + await service.open_session() + rejected = await _record(service, DEFECTIVE) + assert rejected.disposition is Disposition.REJECTED and rejected.qc_decision is QcDecision.REJECTED_CAMERA + explicit = await _record(service, take_samples(frozen=True), exempt_from_capture_checks=False) + assert explicit.disposition is Disposition.QUARANTINED + kept = await _record(service, take_samples()) + attrs = zarr.open_group(str(kept.final_path), mode="r").attrs + assert attrs["capture_qc_exempt"] is False and attrs["capture_qc_decision"] == "PASSED" + + +async def test_the_exemption_is_for_one_take_only(tmp_path, own): + service = own(RecordingService(make_config(tmp_path / "out"))) + await service.open_session() + assert (await _record(service, DEFECTIVE, exempt_from_capture_checks=True)).disposition is Disposition.KEPT + following = await _record(service, DEFECTIVE) + assert following.disposition is Disposition.REJECTED + + +async def test_an_exempt_take_is_still_checked_for_storage_integrity(tmp_path, own): + service = own(RecordingService(make_config(tmp_path / "out"))) + await service.open_session() + tracker_only = [sample for sample in take_samples() if isinstance(sample, NumericSample)] + result = await _record(service, tracker_only, exempt_from_capture_checks=True) + assert result.disposition is Disposition.REJECTED + assert "cam: required source has no rows" in result.quality.issues + + +async def test_an_exempt_take_recovered_after_a_restart_is_still_exempt(tmp_path, own, monkeypatch): + root = tmp_path / "out" + service = own(RecordingService(make_config(root))) + session = await service.open_session() + real_check = impl.check_episode + monkeypatch.setattr(impl, "check_episode", lambda *_: (_ for _ in ()).throw(OSError("busy"))) + left = await _record(service, DEFECTIVE, exempt_from_capture_checks=True) + assert left.disposition is Disposition.RECOVERY_REQUIRED + await service.close() + monkeypatch.setattr(impl, "check_episode", real_check) + restarted = own(RecordingService(make_config(root))) + await restarted.open_session(session.session_id) + recovered = await restarted.recover_episode(left.episode_id) + assert recovered.disposition is Disposition.KEPT and recovered.qc_decision is QcDecision.SKIPPED + assert zarr.open_group(str(recovered.final_path), mode="r").attrs["capture_qc_exempt"] is True + + +def test_a_manifest_written_before_the_flag_existed_reads_as_not_exempt(tmp_path): + import json + + from egocap.recording.episode_layout import EpisodeManifest, write_manifest + + session = tmp_path / "session_1" + (session / ".recording").mkdir(parents=True) + write_manifest( + session, + EpisodeManifest( + session_id="session_1", + episode_id="session_1/episode_0", + episode_index=0, + config_digest="d", + task="t", + operator="o", + sources=[], + pending_path="episode_0.pending", + final_path="episode_0", + ), + ) + path = session / ".recording" / "episode_0.json" + data = json.loads(path.read_text()) + del data["capture_checks_exempt"] + path.write_text(json.dumps(data)) + assert read_manifest(path).capture_checks_exempt is False diff --git a/examples/egocap/tests/recording_service/test_capture_session.py b/examples/egocap/tests/recording_service/test_capture_session.py index 7fbe2b97e7..3d67a84b93 100644 --- a/examples/egocap/tests/recording_service/test_capture_session.py +++ b/examples/egocap/tests/recording_service/test_capture_session.py @@ -6,8 +6,10 @@ import pytest import zarr +from synthetic import make_config, submit_all, take_samples from recording_service import ( + Disposition, FieldSpec, NumericSample, NumericSourceSpec, @@ -60,3 +62,22 @@ async def test_capture_session_for_an_unknown_episode_is_refused(tmp_path, own): await service.open_session() with pytest.raises(StateError, match="no active episode"): service.set_episode_capture_session("not-an-episode", FACTS) + + +@pytest.mark.parametrize(("quarantine", "set_apart"), [(True, True), (False, False)]) +async def test_a_take_the_capture_checks_marked_bad_carries_the_capture_session_wherever_it_is_put( + tmp_path, own, quarantine, set_apart +): + # A take whose tracked pose never changes is marked bad: set apart in quarantine, or kept and flagged. + service = own(RecordingService(make_config(tmp_path / "out", quarantine=quarantine))) + await service.open_session() + episode = await service.start_episode("t", "op") + service.set_episode_capture_session(episode.episode_id, FACTS) + await submit_all(service, episode.episode_id, take_samples(frozen=True)) + result = await service.stop_episode(episode.episode_id) + assert (result.disposition is Disposition.QUARANTINED) is set_apart + where = result.quarantine_path if set_apart else result.final_path + attrs = zarr.open_group(str(where), mode="r").attrs + assert attrs["bad_episode"] is True and attrs["quarantined"] is set_apart + # What the capture side said of the take is kept with it: a take set apart is looked at later to see why. + assert attrs["capture_session"] == FACTS diff --git a/examples/egocap/tests/recording_service/test_config_digest.py b/examples/egocap/tests/recording_service/test_config_digest.py index 6facee360e..997572e5c3 100644 --- a/examples/egocap/tests/recording_service/test_config_digest.py +++ b/examples/egocap/tests/recording_service/test_config_digest.py @@ -9,11 +9,13 @@ must match. """ +import dataclasses from pathlib import Path import pytest import recording_service.recording_service as impl +from egocap.recording.capture_qc import PolicySource from egocap.recording.episode_layout import EpisodeManifest from egocap.recording.episode_store import FieldSpec, NumericSourceSpec, VideoSourceSpec from recording_service import CaptureQcConfig, QcConfig, RecordingService, ServiceConfig @@ -63,6 +65,31 @@ def test_a_changed_threshold_or_algorithm_version_changes_the_full_digest_but_no assert impl._digest(base) != before and impl._layout_digest(base) == impl._layout_digest(stricter) +def test_where_the_thresholds_were_read_from_does_not_change_either_digest(): + base = _config() + edited_file = dataclasses.replace( + base.qc.capture, source=PolicySource("site.yaml", "another digest", (("guardrails.freeze_seconds", 1.0),)) + ) + assert impl._digest(base) == impl._digest(_config(capture=edited_file)) + assert impl._layout_digest(base) == impl._layout_digest(_config(capture=edited_file)) + + +def test_each_added_check_declaration_and_threshold_changes_the_full_digest_only(): + base = _config() + for change in ( + {"tracking_gap_sources": ("tracker",)}, + {"tracking_gap_marks_bad": True}, + {"duration_limits_s": (1.0, 600.0)}, + {"camera_expected_size": (("cam", None),)}, + {"zero_pose_eps": 1e-3}, + {"fps_deviation_pct": 20.0}, + {"camera_min_fps_enabled": False}, + ): + changed = _config(capture=dataclasses.replace(base.qc.capture, **change)) + assert impl._digest(base) != impl._digest(changed), change + assert impl._layout_digest(base) == impl._layout_digest(changed), change + + def test_a_changed_source_declaration_changes_the_layout_digest(): other = NumericSourceSpec("tracker", (FieldSpec("pose", "float64", (4,)),)) assert impl._layout_digest(_config()) != impl._layout_digest(_config(numeric=(other,))) diff --git a/examples/egocap/tests/recording_service/test_configuration.py b/examples/egocap/tests/recording_service/test_configuration.py index d9fffb1f21..87b6185267 100644 --- a/examples/egocap/tests/recording_service/test_configuration.py +++ b/examples/egocap/tests/recording_service/test_configuration.py @@ -25,7 +25,6 @@ @pytest.mark.parametrize( "overrides,message", [ - ({"quarantine": True}, "quarantine"), ({"numeric_sources": (), "video_sources": ()}, "at least one"), ({"numeric_sources": (NUMERIC, NUMERIC)}, "duplicate"), ({"numeric_sources": (NumericSourceSpec("../x", NUMERIC.fields),)}, "safe path"), @@ -62,3 +61,12 @@ async def test_bad_configuration_is_refused_before_any_effect(tmp_path: Path, ov with pytest.raises(ConfigurationError, match=message): await service.open_session() assert not any((tmp_path / "out").glob("*")) if (tmp_path / "out").exists() else True + + +async def test_the_quarantine_switch_is_an_accepted_configuration_that_creates_nothing_by_itself( + tmp_path: Path, own +): + service = own(RecordingService(ServiceConfig(tmp_path / "out", (NUMERIC,), (VIDEO,), quarantine=True))) + session = await service.open_session() + # The quarantine folder is claimed only when a take is first sent there. + assert [entry.name for entry in (tmp_path / "out").iterdir()] == [session.session_id] diff --git a/examples/egocap/tests/recording_service/test_no_stuck_take.py b/examples/egocap/tests/recording_service/test_no_stuck_take.py new file mode 100644 index 0000000000..55ad1e1d28 --- /dev/null +++ b/examples/egocap/tests/recording_service/test_no_stuck_take.py @@ -0,0 +1,389 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""No take ends where neither a recovery nor a discard resolves it, wherever the recorder stops or fails. + +Finishing or discarding a take is a sequence of file-changing calls (rename, replace, mkdir, unlink, rmdir). Each +scenario here is run once to count those calls and then once per call, with the recorder stopped dead just before +that call: from then on nothing it does reaches the disk, which is what a killed process leaves behind. A new +recorder is then started on what is on disk, twice (on two copies): once trying a recovery first and then a +discard, once the other way round. After both commands the take must be resolved in either order, the session +must be able to record again, and nothing may have changed outside that take's own files. + +A second run makes just that one call fail with an ordinary error and lets the recorder go on: its own failure +handling runs, and the same recorder is then asked to recover and to discard the take. + +Takes are built in the test (see synthetic.py) and recorded through the real service and the real backend. They +are a fraction of a second long, with the limits of the checks set to match, because every scenario is repeated +once per file-changing call; what a scenario needs on disk before its operation is recorded once and copied. +""" + +import contextlib +import dataclasses +import errno +import os +import shutil +from pathlib import Path + +import pytest +from synthetic import CAPTURE, changed, make_config, submit_all, take_samples + +import recording_service.recording_service as impl +from egocap.recording.dataset_check import CheckResult, Outcome, QualityReport +from egocap.recording.episode_layout import read_identity, read_manifest +from recording_service import Disposition, NumericSample, RecordingPhase, RecordingService, StateError + +#: Short takes, and the checks' limits scaled down to them: a pose still for 0.2 s is frozen. +QUICK_CHECKS = dataclasses.replace(CAPTURE, freeze_seconds=0.2, duration_limits_s=(0.1, 600.0)) +GOOD = take_samples(seconds=0.4) +FROZEN = take_samples(seconds=0.4, frozen=True) +STARVED = take_samples(seconds=0.4, camera_hole=0.25) +NO_CAMERA = [sample for sample in GOOD if isinstance(sample, NumericSample)] + +_FILE_CHANGING = ("rename", "replace", "mkdir", "unlink", "rmdir") + + +class _Killed(BaseException): + """Stands for the recorder's process dying: nothing that handles an ordinary failure may run.""" + + +@contextlib.contextmanager +def _file_steps(stop_before: int | None = None, fail_only: int | None = None): + """Count the file-changing calls made inside the block, and make one of them the last or a failed one. + + With ``stop_before`` the recorder is stopped dead: from the call with that number on, every file-changing + call raises instead of running, so whatever cleanup or failure handling the recorder attempts afterwards + leaves the disk as a kill would have. With ``fail_only`` just the call with that number fails, with an + ordinary error, and everything after it runs. + """ + real = {name: getattr(os, name) for name in _FILE_CHANGING} + state = {"calls": 0, "killed_before": None} + + def counted(name): + def call(*args, **kwargs): + state["calls"] += 1 + where = f"{name}({Path(str(args[0])).name})" + if stop_before is not None and state["calls"] >= stop_before: + if state["killed_before"] is None: + state["killed_before"] = where + raise _Killed(name) + if state["calls"] == fail_only: + state["killed_before"] = where + raise OSError(errno.EIO, f"injected failure of {name}") + return real[name](*args, **kwargs) + + return call + + for name in _FILE_CHANGING: + setattr(os, name, counted(name)) + try: + yield state + finally: + for name, function in real.items(): + setattr(os, name, function) + + +def _abandon(service: RecordingService) -> None: + """What the system does when a recorder's process dies: the lock it held is released and its threads end.""" + if service._lock is not None: + service._lock.release() + for take in (service._take, *service._retained.values()): + if take is not None: + take.executor.shutdown(wait=False) + + +def _config(root: Path): + return make_config(root, capture=QUICK_CHECKS, quarantine=True) + + +def _signatures(root: Path) -> dict[str, tuple[int, int]]: + """Every file under ``root`` by relative path with its size and the time it was last written. + + A copy made by :func:`_reopen` keeps both, so a file that differs from the original's was written since. This + is compared instead of the bytes because it is done several times per file-changing call. Lock files are left + out: opening a session rewrites its own. + """ + found = {} + for path in root.rglob("*"): + if path.is_file() and path.name != "session.lock": + status = path.stat() + found[path.relative_to(root).as_posix()] = (status.st_size, status.st_mtime_ns) + return found + + +def _only_session(root: Path) -> str: + (session,) = (entry.name for entry in root.iterdir() if entry.name.startswith("session_")) + return session + + +async def _reopen(template: Path, root: Path) -> tuple[RecordingService, str]: + """A recorder on a fresh copy of what the scenario needs on disk, with its one session open again.""" + shutil.copytree(template, root) + service, session_id = RecordingService(_config(root)), _only_session(root) + await service.open_session(session_id) + return service, session_id + + +async def _start(service: RecordingService, samples) -> str: + episode = await service.start_episode("t", "op") + await submit_all(service, episode.episode_id, samples) + return episode.episode_id + + +# --- the scenarios ---------------------------------------------------------------------------------------- +# +# Each has two parts. ``before`` records, once, what must be on disk before the operation: other takes that +# nothing under test may touch, and for a discard of a take left behind, that take. ``begin`` gets a recorder on +# a fresh copy of that and returns the take and the operation that is then stopped part-way. + + +async def _other_takes(root: Path, *, quarantined: bool = True) -> RecordingService: + """A session that already holds a kept take and, unless told otherwise, a quarantined one. + + Nothing under test may touch them, and with the second the session's quarantine folder already exists. + """ + service = RecordingService(_config(root)) + await service.open_session() + wanted = [(GOOD, Disposition.KEPT)] + ([(FROZEN, Disposition.QUARANTINED)] if quarantined else []) + for samples, expected in wanted: + assert (await service.stop_episode(await _start(service, samples))).disposition is expected + return service + + +async def _nothing_more(root: Path, _monkeypatch) -> None: + await (await _other_takes(root)).close() + + +async def _no_quarantine_folder_yet(root: Path, _monkeypatch) -> None: + await (await _other_takes(root, quarantined=False)).close() + + +def _left_pending(samples, left_as: str): + """``before`` for a take left pending in the phase ``left_as``.""" + + async def before(root: Path, monkeypatch) -> None: + service = await _other_takes(root) + with monkeypatch.context() as patched: + if left_as == "WRITING": + await service.interrupt_episode(await _start(service, samples), "the capture pipeline stopped") + elif left_as == "REJECTED": + # No camera frame at all fails the integrity check, which keeps the data. + rejected = await service.stop_episode(await _start(service, samples)) + assert rejected.disposition is Disposition.REJECTED + else: + if left_as == "SEALED": + # A capture check that cannot run leaves the take sealed and unjudged. + failed = CheckResult( + "camera_min_fps:cam", Outcome.ERROR, ("camera_min_fps:cam could not run",) + ) + report = QualityReport(Outcome.ERROR, failed.issues, (), (failed,)) + patched.setattr(impl, "check_capture_quality", lambda *_: report) + else: + # The checks ran and recorded their intent; the step after them failed. + patched.setattr( + impl, "write_episode_attributes", lambda *_: (_ for _ in ()).throw(OSError("io")) + ) + stopped = await service.stop_episode(await _start(service, samples)) + assert stopped.disposition is Disposition.RECOVERY_REQUIRED + session_id = service.snapshot().session.session_id + assert read_manifest(root / session_id / ".recording" / "episode_2.json").storage_phase == left_as + await service.close() + + return before + + +def _stop(samples): + """``begin``: record one more take; the operation is its stop.""" + + async def begin(service: RecordingService, _session_id: str): + episode_id = await _start(service, samples) + return episode_id, lambda: service.stop_episode(episode_id) + + return begin + + +async def _start_a_take(service: RecordingService, session_id: str): + """``begin``: the operation is the start of the next take, which is the third of its session.""" + return f"{session_id}/episode_2", lambda: service.start_episode("t", "op") + + +async def _discard_while_recording(service: RecordingService, _session_id: str): + episode_id = await _start(service, GOOD) + return episode_id, lambda: service.discard_episode(episode_id) + + +async def _discard_what_was_left(service: RecordingService, session_id: str): + episode_id = f"{session_id}/episode_2" + return episode_id, lambda: service.discard_pending(episode_id) + + +SCENARIOS = { + "a take is started": (_nothing_more, _start_a_take), + "a kept take is finished": (_nothing_more, _stop(GOOD)), + "a rejected take's media is removed": (_nothing_more, _stop(STARVED)), + "the first bad take of a session is quarantined": (_no_quarantine_folder_yet, _stop(FROZEN)), + "a later bad take of a session is quarantined": (_nothing_more, _stop(FROZEN)), + "the take being recorded is discarded": (_nothing_more, _discard_while_recording), + "an interrupted take is discarded": (_left_pending(GOOD, "WRITING"), _discard_what_was_left), + "a sealed take is discarded": (_left_pending(GOOD, "SEALED"), _discard_what_was_left), + "a checked take that was to be kept is discarded": (_left_pending(GOOD, "CHECKED"), _discard_what_was_left), + "a checked take that was to be quarantined is discarded": ( + _left_pending(FROZEN, "CHECKED"), + _discard_what_was_left, + ), + "a take rejected for integrity is discarded": (_left_pending(NO_CAMERA, "REJECTED"), _discard_what_was_left), +} + + +# --- after the stop: a new recorder on what is on disk ------------------------------------------------------- + + +def _waiting(service: RecordingService) -> set[str]: + return {p.episode_id for p in (*service.pending_episodes(), *service.retained_rejections())} + + +async def _resolve( + root: Path, session_id: str, episode_id: str, order: tuple[str, str], service: RecordingService | None = None +) -> tuple[list[str], list[str]]: + """Try the two commands in ``order``; returns what each did, and the problems found. + + Without ``service`` a new recorder reopens the session, as after a restart; with one, the recorder that + just failed is asked. + """ + if service is None: + service = RecordingService(_config(root)) + await service.open_session(session_id) + index = episode_id.split("/")[1] + notes, problems = [], [] + try: + for command in order: + if episode_id not in _waiting(service): + break + act = service.recover_episode if command == "recover" else service.discard_pending + try: + notes.append(f"{command}: {(await act(episode_id)).disposition.name}") + except StateError as exc: + notes.append(f"{command}: refused ({str(exc)[:60]})") + pending_dir = root / session_id / f"{index}.pending" + if service.pending_episodes(): + problems.append("the take is still pending after both commands") + elif service.snapshot().phase is not RecordingPhase.IDLE: + problems.append(f"the recorder is left {service.snapshot().phase.name}") + # Nothing of an interrupted quarantine claim may stay in the sidecar once the take is resolved. + if (root / session_id / ".recording" / "quarantine_claim").exists(): + problems.append("a claim directory is left in the sidecar") + record_file = root / session_id / ".recording" / f"{index}.json" + if not record_file.exists(): + # Stopped before the take had a record: then it must have left no directory either. + if pending_dir.exists(): + problems.append("a pending directory is left that no record accounts for") + return notes, problems + manifest = read_manifest(record_file) + # What the record says became of the take must be what is on disk. + published = { + "FINALIZED": root / session_id / index, + "QUARANTINED": root / "_quarantine" / session_id / index, + }.get(manifest.storage_phase) + if published is not None and read_identity(published) != episode_id: + problems.append(f"the record says {manifest.storage_phase} and the take is not there") + if manifest.storage_phase == "DISCARDED" and pending_dir.exists(): + problems.append("the record says DISCARDED and the pending directory is still there") + if manifest.storage_phase == "REJECTED" and manifest.finalization == "REMOVE" and pending_dir.exists(): + problems.append("the record says the media was removed and the pending directory is still there") + finally: + closed = await service.close() + if not closed.released: + problems.append("the recorder did not release the session") + return notes, problems + + +def _outside_the_take(before: dict, after: dict, session_id: str, episode_id: str) -> set[str]: + """Every changed path that is not one of the take's own: its directories, its record, its quarantine folder.""" + index = episode_id.split("/")[1] + own = ( + f"{session_id}/{index}.pending/", + f"{session_id}/{index}/", + f"{session_id}/.recording/{index}.", + f"_quarantine/{session_id}/{index}/", + f"_quarantine/{session_id}/zarr.", # the folder's stamp and totals + f"_quarantine/{session_id}/config.", # the session's frozen configuration, copied once + ) + removed, added, modified = changed(before, after) + return {path for path in removed | added | modified if not path.startswith(own)} + + +@pytest.mark.parametrize("name", SCENARIOS) +async def test_stopped_before_any_file_changing_call_the_take_is_still_resolved_and_nothing_else_changes( + tmp_path, monkeypatch, name +): + before, begin = SCENARIOS[name] + template = tmp_path / "template" + await before(template, monkeypatch) + untouched = _signatures(template) + # Once without a stop, to count the calls of this scenario. + service, session_id = await _reopen(template, tmp_path / "count") + _episode, operation = await begin(service, session_id) + with _file_steps() as counted: + await operation() + await service.close() + assert counted["calls"] > 3, "the operation changed no file: nothing was tested" + problems = [] + for step in range(1, counted["calls"] + 1): + root, copy = tmp_path / f"step{step}", tmp_path / f"step{step}-discard-first" + service, session_id = await _reopen(template, root) + episode_id, operation = await begin(service, session_id) + with _file_steps(stop_before=step) as stopped, pytest.raises(_Killed): + await operation() + _abandon(service) + shutil.copytree(root, copy) + for where, order in ((root, ("recover", "discard")), (copy, ("discard", "recover"))): + notes, found = await _resolve(where, session_id, episode_id, order) + touched = _outside_the_take(untouched, _signatures(where), session_id, episode_id) + if touched: + found.append(f"files changed outside the take: {sorted(touched)}") + if found: + stopped_at = f"stopped before call {step}, {stopped['killed_before']}, {order[0]} first" + problems.append(f"{stopped_at}: {found} after {notes}") + assert problems == [], "\n".join(problems) + + +#: The operations named for a failure that is not a kill: the first bad take of a session, which creates the +#: session's quarantine folder, and every discard of a take found on disk. +FAILED_ONCE = ( + "the first bad take of a session is quarantined", + "an interrupted take is discarded", + "a sealed take is discarded", + "a checked take that was to be kept is discarded", + "a checked take that was to be quarantined is discarded", + "a take rejected for integrity is discarded", +) + + +@pytest.mark.parametrize("name", FAILED_ONCE) +async def test_one_failed_file_changing_call_never_leaves_a_take_the_same_recorder_cannot_resolve( + tmp_path, monkeypatch, name +): + before, begin = SCENARIOS[name] + template = tmp_path / "template" + await before(template, monkeypatch) + untouched = _signatures(template) + service, session_id = await _reopen(template, tmp_path / "count") + _episode, operation = await begin(service, session_id) + with _file_steps() as counted: + await operation() + await service.close() + problems = [] + for step in range(1, counted["calls"] + 1): + root = tmp_path / f"step{step}" + service, session_id = await _reopen(template, root) + episode_id, operation = await begin(service, session_id) + with _file_steps(fail_only=step) as failed: + await operation() # the recorder handles the failure itself: the take is finished or left pending + notes, found = await _resolve(root, session_id, episode_id, ("recover", "discard"), service) + touched = _outside_the_take(untouched, _signatures(root), session_id, episode_id) + if touched: + found.append(f"files changed outside the take: {sorted(touched)}") + if found: + problems.append(f"call {step} failed, {failed['killed_before']}: {found} after {notes}") + assert problems == [], "\n".join(problems) diff --git a/examples/egocap/tests/recording_service/test_quarantine_location.py b/examples/egocap/tests/recording_service/test_quarantine_location.py new file mode 100644 index 0000000000..04579d8099 --- /dev/null +++ b/examples/egocap/tests/recording_service/test_quarantine_location.py @@ -0,0 +1,208 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A quarantine folder that cannot take a take is refused when a session opens, and never strands a take. + +A take is quarantined by one rename out of its session, so the folder must be a plain directory on the file +system of the recordings. Each test puts something else in its place, before a session opens or while one is +open, and shows that recording is refused in a sentence that names no directory, that a recovery says why it +cannot finish, and that a discard still removes the take's own pending directory and nothing else. + +Takes are built in the test (see synthetic.py) and recorded through the real service and the real backend. +""" + +import errno +import os +from pathlib import Path + +import pytest +from synthetic import changed, make_config, record, submit_all, take_samples, tree + +from egocap.recording import episode_layout +from recording_service import ConfigurationError, Disposition, RecordingPhase, RecordingService, StateError + +FROZEN = take_samples(frozen=True) + + +def _a_link(root: Path, tmp_path: Path) -> None: + elsewhere = tmp_path / "another_disk" + elsewhere.mkdir(exist_ok=True) + (root / "_quarantine").symlink_to(elsewhere, target_is_directory=True) + + +def _a_file(root: Path, _tmp_path: Path) -> None: + (root / "_quarantine").write_text("not a folder") + + +@pytest.mark.parametrize( + ("put", "problem"), [(_a_link, "is a link"), (_a_file, "is not a directory")], ids=["a link", "a file"] +) +async def test_no_session_is_opened_for_recording_where_a_bad_take_could_not_be_set_aside( + tmp_path, own, put, problem +): + root = tmp_path / "out" + root.mkdir() + put(root, tmp_path) + before = sorted(p.name for p in root.iterdir()) + service = own(RecordingService(make_config(root, quarantine=True))) + with pytest.raises(ConfigurationError) as refused: + await service.open_session() + assert str(refused.value) == ( + f"quarantine location {problem}: it must be a plain directory on the same file system as the recordings" + ) + assert str(tmp_path) not in str(refused.value) + # Refused before anything was made: no session directory, and the recorder can open once the folder is fixed. + assert sorted(p.name for p in root.iterdir()) == before + (root / "_quarantine").unlink() + session = await service.open_session() + assert (await record(service, FROZEN)).disposition is Disposition.QUARANTINED and session.session_path.is_dir() + + +async def test_a_quarantine_folder_on_another_file_system_is_refused_too(tmp_path, own, monkeypatch): + root = tmp_path / "out" + (root / "_quarantine").mkdir(parents=True) + # Another file system cannot be mounted in a test, so the device the system reports is substituted. + monkeypatch.setattr(episode_layout, "_device", lambda path: 7 if path.name == "_quarantine" else 1) + service = own(RecordingService(make_config(root, quarantine=True))) + with pytest.raises(ConfigurationError, match="quarantine location is on another file system"): + await service.open_session() + + +async def test_a_station_that_does_not_quarantine_is_not_stopped_by_what_is_at_that_name(tmp_path, own): + root = tmp_path / "out" + root.mkdir() + _a_file(root, tmp_path) + service = own(RecordingService(make_config(root))) + await service.open_session() + assert (await record(service, FROZEN)).disposition is Disposition.KEPT # kept in its session, flagged + + +async def test_a_folder_replaced_while_the_session_is_open_refuses_the_next_take_before_it_starts(tmp_path, own): + root = tmp_path / "out" + service = own(RecordingService(make_config(root, quarantine=True))) + await service.open_session() + assert (await record(service, FROZEN)).disposition is Disposition.QUARANTINED + (root / "_quarantine").rename(root / "_quarantine_moved") + _a_link(root, tmp_path) + before = tree(root) + with pytest.raises(ConfigurationError, match="quarantine location is a link"): + await service.start_episode("t", "op") + assert tree(root) == before and service.snapshot().phase is RecordingPhase.IDLE + # The same for this session's own folder inside a plain quarantine folder. + (root / "_quarantine").unlink() + (root / "_quarantine").mkdir() + session_id = service.snapshot().session.session_id + (root / "_quarantine" / session_id).symlink_to(tmp_path / "another_disk", target_is_directory=True) + with pytest.raises(ConfigurationError, match="quarantine location is a link"): + await service.start_episode("t", "op") + + +async def _a_bad_take_stopped_after_the_folder_went_bad(service, root, tmp_path, put): + """Start a take, put something else where the quarantine folder goes, then stop it.""" + episode = await service.start_episode("t", "op") + await submit_all(service, episode.episode_id, FROZEN) + put(root, tmp_path) + stopped = await service.stop_episode(episode.episode_id) + assert stopped.disposition is Disposition.RECOVERY_REQUIRED + (pending,) = service.pending_episodes() + assert (pending.storage_phase, pending.finalization) == ("CHECKED", "QUARANTINE") + return episode.episode_id + + +@pytest.mark.parametrize( + ("put", "problem"), [(_a_link, "is a link"), (_a_file, "is not a directory")], ids=["a link", "a file"] +) +async def test_a_take_whose_quarantine_folder_went_bad_says_why_on_recover_and_is_still_discarded( + tmp_path, own, put, problem +): + root = tmp_path / "out" + service = own(RecordingService(make_config(root, quarantine=True))) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + episode_id = await _a_bad_take_stopped_after_the_folder_went_bad(service, root, tmp_path, put) + before = tree(root) + with pytest.raises(StateError) as refused: + await service.recover_episode(episode_id) + assert f"cannot be set aside: the quarantine location {problem}" in str(refused.value) + assert tree(root) == before + discarded = await service.discard_pending(episode_id) + assert discarded.disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session.session_id}/episode_1.pending/") for path in removed) + assert added == set() and modified == {f"{session.session_id}/.recording/episode_1.json"} + assert service.pending_episodes() == () and service.snapshot().phase is RecordingPhase.IDLE + + +async def test_after_a_restart_such_a_take_is_still_discarded_though_the_session_could_not_record(tmp_path, own): + root = tmp_path / "out" + first = RecordingService(make_config(root, quarantine=True)) + session = await first.open_session() + episode_id = await _a_bad_take_stopped_after_the_folder_went_bad(first, root, tmp_path, _a_link) + await first.close() + # Reopening a session to resolve what it left is not refused: only recording into it is. + restarted = own(RecordingService(make_config(root, quarantine=True))) + await restarted.open_session(session.session_id) + with pytest.raises(StateError, match="the quarantine location is a link"): + await restarted.recover_episode(episode_id) + assert (await restarted.discard_pending(episode_id)).disposition is Disposition.DISCARDED + assert not (session.session_path / "episode_0.pending").exists() + with pytest.raises(ConfigurationError, match="quarantine location is a link"): + await restarted.start_episode("t", "op") + assert list((tmp_path / "another_disk").iterdir()) == [] + + +async def test_once_the_folder_is_put_right_the_same_take_is_recovered_into_it(tmp_path, own): + root = tmp_path / "out" + service = own(RecordingService(make_config(root, quarantine=True))) + session = await service.open_session() + episode_id = await _a_bad_take_stopped_after_the_folder_went_bad(service, root, tmp_path, _a_file) + (root / "_quarantine").unlink() + recovered = await service.recover_episode(episode_id) + assert recovered.disposition is Disposition.QUARANTINED + assert recovered.quarantine_path == root / "_quarantine" / session.session_id / "episode_0" + + +async def test_a_take_whose_place_in_quarantine_is_held_by_something_else_is_not_overwritten_and_is_discardable( + tmp_path, own +): + root = tmp_path / "out" + service = own(RecordingService(make_config(root, quarantine=True))) + session = await service.open_session() + assert (await record(service, FROZEN)).disposition is Disposition.QUARANTINED + in_the_way = root / "_quarantine" / session.session_id / "episode_1" + in_the_way.mkdir() + (in_the_way / "notes.txt").write_text("put here by hand") + stopped = await record(service, FROZEN) + assert stopped.disposition is Disposition.RECOVERY_REQUIRED + again = await service.recover_episode(stopped.episode_id) + assert again.disposition is Disposition.RECOVERY_REQUIRED # it will not overwrite what is there + before = tree(root) + assert (await service.discard_pending(stopped.episode_id)).disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session.session_id}/episode_1.pending/") for path in removed) + assert added == set() and modified == {f"{session.session_id}/.recording/episode_1.json"} + assert (in_the_way / "notes.txt").read_text() == "put here by hand" + + +async def test_a_rename_the_file_system_refuses_leaves_the_take_recoverable_later_and_discardable_now( + tmp_path, own, monkeypatch +): + """The folder came to be on another file system after the session opened: a rename cannot cross to it.""" + root = tmp_path / "out" + service = own(RecordingService(make_config(root, quarantine=True))) + session = await service.open_session() + real_rename = os.rename + + def rename(source, target, *args, **kwargs): + if Path(target).name == "episode_0" and "_quarantine" in Path(target).parts: + raise OSError(errno.EXDEV, "Invalid cross-device link") + return real_rename(source, target, *args, **kwargs) + + monkeypatch.setattr(os, "rename", rename) + stopped = await record(service, FROZEN) + assert stopped.disposition is Disposition.RECOVERY_REQUIRED + assert (await service.recover_episode(stopped.episode_id)).disposition is Disposition.RECOVERY_REQUIRED + assert (session.session_path / "episode_0.pending" / "cam.mp4").is_file() # nothing was copied or lost + monkeypatch.setattr(os, "rename", real_rename) + assert (await service.recover_episode(stopped.episode_id)).disposition is Disposition.QUARANTINED diff --git a/examples/egocap/tests/recording_service/test_quarantine_service.py b/examples/egocap/tests/recording_service/test_quarantine_service.py new file mode 100644 index 0000000000..fa1a6e40ca --- /dev/null +++ b/examples/egocap/tests/recording_service/test_quarantine_service.py @@ -0,0 +1,370 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A take the capture checks mark bad is quarantined where the switch is on, and kept flagged where it is off. + +Takes are built in the test (see synthetic.py) and recorded through the real service and the real backend. +""" + +import dataclasses +import json +import time +from pathlib import Path + +import pytest +import yaml +import zarr +from synthetic import CAPTURE, changed, make_config, record, take_samples, tree + +import recording_service.recording_service as impl +from egocap.analytics.count_daily_trajectories import count_trajectories +from egocap.recording.episode_layout import ROUTE_ATTR, read_manifest, route_id +from recording_service import ( + CalibrationAsset, + Disposition, + QcDecision, + RecordingPhase, + RecordingService, + RoutingConfig, + StateError, +) + + +def _manifest(session_path: Path, index: int = 0): + return read_manifest(session_path / ".recording" / f"episode_{index}.json") + + +def _attrs(path: Path) -> dict: + return json.loads((path / "zarr.json").read_text())["attributes"] + + +async def _open(config, own): + service = own(RecordingService(config)) + return service, await service.open_session() + + +async def test_with_the_switch_on_a_frozen_take_is_finalized_in_the_quarantine_folder(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True, station_label="Bench A"), own) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.QUARANTINED and result.qc_decision is QcDecision.FLAGGED_BAD + expected = root / "_quarantine" / session.session_id / "episode_0" + assert result.quarantine_path == expected and expected.is_dir() + assert result.final_path is None and result.pending_path is None and result.output_index is None + # The session holds no episode folder for it, pending or final. + assert not (session.session_path / "episode_0").exists() + assert not (session.session_path / "episode_0.pending").exists() + manifest = _manifest(session.session_path) + assert (manifest.storage_phase, manifest.finalization) == ("QUARANTINED", "QUARANTINE") + assert service.snapshot().phase is RecordingPhase.IDLE and service.pending_episodes() == () + + +async def test_a_quarantined_episode_says_what_failed_and_that_it_was_set_apart(tmp_path, own): + service, _session = await _open(make_config(tmp_path / "out", quarantine=True), own) + result = await record(service, take_samples(frozen=True)) + attrs = zarr.open_group(str(result.quarantine_path), mode="r").attrs + assert attrs["quarantined"] is True and attrs["bad_episode"] is True + assert attrs["capture_qc_decision"] == "FLAGGED_BAD" and attrs["freeze_check_passed"] is False + assert attrs["freeze_check_issues"] == ["tracker/pose: no motion for 2.00s (limit 1.0s, eps 1e-06)"] + assert attrs["capture_qc_issues"] == attrs["freeze_check_issues"] + assert attrs["integrity_check_passed"] is True and attrs["episode_duration"] == pytest.approx(2.0) + + +async def test_the_quarantine_folder_is_this_sessions_and_carries_its_config_and_totals(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True, station_label="Bench A"), own) + await record(service, take_samples(frozen=True)) + folder = root / "_quarantine" / session.session_id + stamp = _attrs(folder) + assert stamp[ROUTE_ATTR] == route_id(session.session_id, f"_quarantine/{session.session_id}") + assert stamp["quarantine"] is True and stamp["num_episodes"] == 1 + assert stamp["discarded_episode_indices"] == [0] + assert stamp["discarded_reasons"] == {"0": "tracker/pose: no motion for 2.00s (limit 1.0s, eps 1e-06)"} + assert yaml.safe_load((folder / "config.yaml").read_text()) == yaml.safe_load( + (session.session_path / "config.yaml").read_text() + ) + + +async def test_with_the_switch_off_the_same_take_is_kept_in_its_session_and_flagged(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root), own) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.FLAGGED_BAD + assert result.final_path == session.session_path / "episode_0" and result.quarantine_path is None + assert not (root / "_quarantine").exists() + attrs = zarr.open_group(str(result.final_path), mode="r").attrs + assert attrs["bad_episode"] is True and attrs["quarantined"] is False + manifest = _manifest(session.session_path) + assert (manifest.storage_phase, manifest.finalization) == ("FINALIZED", "KEEP") + + +async def test_with_the_switch_on_a_healthy_take_is_kept_in_its_session_as_before(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + result = await record(service) + assert result.disposition is Disposition.KEPT and result.qc_decision is QcDecision.PASSED + assert result.final_path == session.session_path / "episode_0" and not (root / "_quarantine").exists() + assert zarr.open_group(str(result.final_path), mode="r").attrs["quarantined"] is False + + +async def test_with_the_switch_on_a_camera_rejection_is_still_removed_not_quarantined(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + result = await record(service, take_samples(camera_hole=1.0, frozen=True)) + assert result.disposition is Disposition.REJECTED and result.qc_decision is QcDecision.REJECTED_CAMERA + assert not (root / "_quarantine").exists() and not (session.session_path / "episode_0.pending").exists() + + +async def test_two_quarantined_takes_of_a_session_share_its_folder_under_their_own_take_index(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + first = await record(service, take_samples(frozen=True)) + kept = await record(service) + second = await record(service, take_samples(frozen=True)) + folder = root / "_quarantine" / session.session_id + assert (first.quarantine_path, second.quarantine_path) == (folder / "episode_0", folder / "episode_2") + assert kept.final_path == session.session_path / "episode_1" + assert _attrs(folder)["discarded_episode_indices"] == [0, 2] and _attrs(folder)["num_episodes"] == 2 + + +async def test_a_quarantined_take_takes_no_slot_in_a_routed_group(tmp_path, own): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True, routing=RoutingConfig()), own) + bad = await record(service, take_samples(frozen=True)) + good = await record(service) + assert bad.quarantine_path == root / "_quarantine" / session.session_id / "episode_0" + assert _manifest(session.session_path, 0).assignment is None + # The kept take gets the first slot of its group: the quarantined attempt left no gap in the numbering. + assert good.disposition is Disposition.KEPT and good.output_index == 0 + assert good.final_path.parent.parent.name == "_unmatched" and good.final_path.name == "episode_0" + + +async def test_the_quarantine_folder_gets_the_sessions_preserved_calibration_files(tmp_path, own): + asset = tmp_path / "head_camera_intrinsics.json" + asset.write_text('{"fx": 1.0}') + config = make_config( + tmp_path / "out", quarantine=True, calibration_assets=(CalibrationAsset(asset.name, asset),) + ) + service, session = await _open(config, own) + result = await record(service, take_samples(frozen=True)) + assert (result.quarantine_path.parent / asset.name).read_text() == '{"fx": 1.0}' + + +async def test_a_failure_between_the_rename_and_the_checkpoint_recovers_to_the_same_place( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + real_write = impl.write_manifest + + def fail_the_quarantined_checkpoint(session_path, manifest): + if manifest.storage_phase == "QUARANTINED": + raise OSError("disk full") + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", fail_the_quarantined_checkpoint) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.RECOVERY_REQUIRED + quarantined = root / "_quarantine" / session.session_id / "episode_0" + # The rename happened; the durable record still says CHECKED with the quarantine intent. + assert quarantined.is_dir() and not (session.session_path / "episode_0.pending").exists() + assert (_manifest(session.session_path).storage_phase, _manifest(session.session_path).finalization) == ( + "CHECKED", + "QUARANTINE", + ) + (pending,) = service.pending_episodes() + assert pending.recoverable and pending.storage_phase == "CHECKED" + before = tree(quarantined) + monkeypatch.setattr(impl, "write_manifest", real_write) + recovered = await service.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.QUARANTINED and recovered.quarantine_path == quarantined + assert tree(quarantined) == before # found by identity: the data was not written again + assert _manifest(session.session_path).storage_phase == "QUARANTINED" + assert not (session.session_path / "episode_0").exists() + + +async def test_after_a_restart_the_renamed_take_is_recovered_by_identity_whatever_the_switch_says_now( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + real_write = impl.write_manifest + + def fail_the_quarantined_checkpoint(session_path, manifest): + if manifest.storage_phase == "QUARANTINED": + raise OSError("disk full") + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", fail_the_quarantined_checkpoint) + result = await record(service, take_samples(frozen=True)) + await service.close() + monkeypatch.setattr(impl, "write_manifest", real_write) + # The station switched quarantine off in between: a checked take still finishes by its recorded intent. + restarted = own(RecordingService(make_config(root))) + await restarted.open_session(session.session_id) + (pending,) = restarted.pending_episodes() + assert pending.recoverable + recovered = await restarted.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.QUARANTINED + assert recovered.quarantine_path == root / "_quarantine" / session.session_id / "episode_0" + + +async def test_a_failure_before_the_rename_leaves_the_take_pending_and_recovery_quarantines_it( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + real_claim = impl.claim_quarantine_group + + def fail_the_claim(session_path, session_id): + raise OSError("read-only file system") + + monkeypatch.setattr(impl, "claim_quarantine_group", fail_the_claim) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.RECOVERY_REQUIRED + assert (session.session_path / "episode_0.pending").is_dir() and not (root / "_quarantine").exists() + monkeypatch.setattr(impl, "claim_quarantine_group", real_claim) + recovered = await service.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.QUARANTINED and recovered.quarantine_path.is_dir() + + +async def test_discard_never_deletes_quarantined_output(tmp_path, own, monkeypatch): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + real_write = impl.write_manifest + + def fail_the_quarantined_checkpoint(session_path, manifest): + if manifest.storage_phase == "QUARANTINED": + raise OSError("disk full") + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", fail_the_quarantined_checkpoint) + result = await record(service, take_samples(frozen=True)) + monkeypatch.setattr(impl, "write_manifest", real_write) + quarantined = root / "_quarantine" / session.session_id / "episode_0" + before, episode_before = tree(root), tree(quarantined) + # The take is listed as pending (its checkpoint is missing), but its data is already published. + refused = await service.discard_pending(result.episode_id) + assert refused.disposition is Disposition.RECOVERY_REQUIRED + # Said as a refusal, with what to do instead: the take is saved, and a second discard would fare no better. + assert refused.issues[-1] == "discard refused: the take is already in its final place; recover it to finish" + removed, added, _modified = changed(before, tree(root)) + assert removed == set() and added == set() and quarantined.is_dir() + # Once it is durably quarantined it is not pending at all, so there is nothing to discard. + await service.recover_episode(result.episode_id) + with pytest.raises(StateError, match="no pending episode"): + await service.discard_pending(result.episode_id) + assert episode_before and tree(quarantined) == episode_before + + +async def test_a_take_pending_with_the_quarantine_intent_can_still_be_discarded(tmp_path, own, monkeypatch): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + earlier = await record(service, take_samples(frozen=True)) + monkeypatch.setattr(impl, "write_episode_attributes", lambda *_: (_ for _ in ()).throw(OSError("io error"))) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.RECOVERY_REQUIRED + before = tree(root) + discarded = await service.discard_pending(result.episode_id) + assert discarded.disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + pending = f"{session.session_id}/episode_1.pending/" + assert removed and all(path.startswith(pending) for path in removed) and added == set() + assert modified == {f"{session.session_id}/.recording/episode_1.json"} + assert earlier.quarantine_path.is_dir() + + +def test_the_switch_is_part_of_the_full_digest_only_when_it_is_on(): + off, on = make_config(Path("out")), make_config(Path("out"), quarantine=True) + assert impl._digest(off) == impl._digest(dataclasses.replace(off, quarantine=False)) + assert impl._digest(off) != impl._digest(on) + # A checked take already recorded where it goes, so the switch is not part of what it must still match. + assert impl._layout_digest(off) == impl._layout_digest(on) + without_capture = make_config(Path("out"), capture=None) + assert impl._digest(without_capture) == impl._layout_digest(off) + + +async def test_a_sealed_take_recorded_under_the_other_switch_setting_cannot_be_recovered( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service, session = await _open(make_config(root), own) + # The capture check cannot run, so the take stays SEALED and is still to be judged. + unreadable = dataclasses.replace(CAPTURE, pose_streams=(("tracker", "pose"),)) + monkeypatch.setattr(impl, "check_capture_quality", lambda *_: (_ for _ in ()).throw(OSError("unreadable"))) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.RECOVERY_REQUIRED + await service.close() + monkeypatch.undo() + switched = own(RecordingService(make_config(root, quarantine=True, capture=unreadable))) + await switched.open_session(session.session_id) + (pending,) = switched.pending_episodes() + assert pending.storage_phase == "SEALED" and not pending.recoverable + with pytest.raises(StateError, match="different configuration"): + await switched.recover_episode(result.episode_id) + + +# --- a quarantined take is never counted as valid --------------------------------------------- + + +async def test_the_folders_totals_list_the_take_before_its_record_says_quarantined(tmp_path, own, monkeypatch): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + folder = root / "_quarantine" / session.session_id + seen = {} + real_write = impl.write_manifest + + def at_the_quarantined_checkpoint(session_path, manifest): + if manifest.storage_phase == "QUARANTINED": + seen["discarded"] = _attrs(folder)["discarded_episode_indices"] + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", at_the_quarantined_checkpoint) + assert (await record(service, take_samples(frozen=True))).disposition is Disposition.QUARANTINED + assert seen["discarded"] == [0] + + +async def test_a_recorder_stopped_before_the_totals_leaves_the_take_pending_and_a_recovery_writes_them( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + folder = root / "_quarantine" / session.session_id + + class Stopped(BaseException): + """Stands for the recorder's process dying: nothing after it runs.""" + + def stop_here(group_dir): + raise Stopped + + with monkeypatch.context() as patched: + patched.setattr(impl, "refresh_group_totals", stop_here) + with pytest.raises(Stopped): + await record(service, take_samples(frozen=True)) + service._lock.release() # what the system does when the process dies + # The take is in the folder, the folder does not list it yet, and its record is still waiting. + assert (folder / "episode_0").is_dir() and _attrs(folder)["discarded_episode_indices"] == [] + assert _manifest(session.session_path).storage_phase == "CHECKED" + counted = count_trajectories(root, time.strftime("%Y-%m-%d"))[f"_quarantine/{session.session_id}"] + assert (counted["valid"], counted["excluded"]) == (0, 1) # never valid, even in this state + restarted = own(RecordingService(make_config(root, quarantine=True))) + await restarted.open_session(session.session_id) + (pending,) = restarted.pending_episodes() + recovered = await restarted.recover_episode(pending.episode_id) + assert recovered.disposition is Disposition.QUARANTINED + assert _attrs(folder)["discarded_episode_indices"] == [0] and _attrs(folder)["num_episodes"] == 1 + + +async def test_totals_that_cannot_be_written_do_not_make_a_quarantined_take_count_as_valid( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service, session = await _open(make_config(root, quarantine=True), own) + monkeypatch.setattr(impl, "refresh_group_totals", lambda group_dir: (_ for _ in ()).throw(OSError("io error"))) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.QUARANTINED + assert any("group totals were not refreshed" in issue for issue in result.issues) + assert _attrs(root / "_quarantine" / session.session_id)["discarded_episode_indices"] == [] + counted = count_trajectories(root, time.strftime("%Y-%m-%d"))[f"_quarantine/{session.session_id}"] + assert (counted["total"], counted["valid"], counted["excluded"]) == (1, 0, 1) diff --git a/examples/egocap/tests/recording_service/test_removal_scope.py b/examples/egocap/tests/recording_service/test_removal_scope.py new file mode 100644 index 0000000000..d7a8a19e6b --- /dev/null +++ b/examples/egocap/tests/recording_service/test_removal_scope.py @@ -0,0 +1,495 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Every path that deletes recorded media deletes only the take it was asked about, and survives a failure. + +Removing a take's media cannot be undone, so each deleting path (a camera rejection, discarding a pending take, +discarding the take being recorded) is run inside an output root that already holds other sessions, kept and +quarantined takes and stray files, and the whole tree is compared file by file before and after. A removal that +fails part-way must leave the take pending with its decision recorded, so that a recovery, in this process or +after a restart, finishes it. + +Takes are built in the test (see synthetic.py) and recorded through the real service and the real backend. +""" + +import dataclasses +import shutil +from pathlib import Path + +import pytest +from synthetic import changed, make_config, record, submit_all, take_samples, tree + +import recording_service.recording_service as impl +from egocap.recording import episode_layout +from egocap.recording.episode_layout import read_manifest +from recording_service import Disposition, QcConfig, QcDecision, RecordingPhase, RecordingService, StateError + +REJECTED_TAKE = take_samples(camera_hole=1.0) + + +async def _populated(tmp_path, own): + """An open session inside an output root that already holds data no removal may touch. + + Another session with a kept take, and in the open session a kept take (episode_0) and a quarantined one + (episode_1), plus files that belong to no take. + """ + root = tmp_path / "out" + other = own(RecordingService(make_config(root, quarantine=True))) + await other.open_session() + assert (await record(other)).disposition is Disposition.KEPT + await other.close() + service = own(RecordingService(make_config(root, quarantine=True))) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + assert (await record(service, take_samples(frozen=True))).disposition is Disposition.QUARANTINED + (root / "notes.txt").write_text("operator notes") + (session.session_path / "sidecar.txt").write_text("belongs to no take") + return root, service, session + + +def _manifest(session, index): + return read_manifest(session.session_path / ".recording" / f"episode_{index}.json") + + +def _under(session, index): + """The relative-path prefix of one take's pending directory, and of its manifest.""" + return ( + f"{session.session_id}/episode_{index}.pending/", + f"{session.session_id}/.recording/episode_{index}.json", + ) + + +async def test_a_camera_rejection_removes_the_rejected_takes_own_media_and_nothing_else( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + seen = {} + real_remove = impl.remove_owned_episode + + def remove(session_path, manifest): + seen["before_removal"] = tree(root) + real_remove(session_path, manifest) + + monkeypatch.setattr(impl, "remove_owned_episode", remove) + result = await record(service, REJECTED_TAKE) + assert result.disposition is Disposition.REJECTED and result.qc_decision is QcDecision.REJECTED_CAMERA + assert result.final_path is None and result.pending_path is None and result.quarantine_path is None + after = tree(root) + pending, manifest = _under(session, 2) + # What the removal took away: every file of the rejected take's pending directory, its video among them. + removed, added, modified = changed(seen["before_removal"], after) + assert removed and all(path.startswith(pending) for path in removed) + assert f"{pending}cam.mp4" in removed and added == set() and modified == {manifest} + assert not (session.session_path / "episode_2.pending").exists() + # Against the tree as it was before the take started, only the take's manifest is new: no other file of the + # session, of the other session, of the quarantine folder or beside them was removed or rewritten. + assert changed(before_take, after) == (set(), {manifest}, set()) + assert (_manifest(session, 2).storage_phase, _manifest(session, 2).finalization) == ("REJECTED", "REMOVE") + assert service.snapshot().phase is RecordingPhase.IDLE and service.pending_episodes() == () + + +async def test_the_rejected_takes_reports_stay_in_its_manifest_after_its_media_is_gone(tmp_path, own): + _root, service, session = await _populated(tmp_path, own) + result = await record(service, REJECTED_TAKE) + manifest = _manifest(session, 2) + assert manifest.qc_decision == "REJECTED_CAMERA" and manifest.quality["outcome"] == "PASSED" + assert manifest.capture_quality["issues"] == list(result.capture_quality.issues) + # A camera that withheld a second of a two second take is slow over its own frames and short of the take's. + assert manifest.capture_quality["issues"] == [ + "cam: 15.50 fps average is below 0.86 x 30.0 = 25.80", + "cam: 32 frame(s) recorded of the 60.0 a 2.00s take holds at 30.0 fps (needs 49.0)", + ] + assert manifest.capture_policy["camera_min_fps_ratio"] == 0.86 + + +def _fail_removal_after(monkeypatch, deleted_directories: int): + """Let a removal delete that many of the take's directories, then fail it; returns a function that lets + later removals through. Only the removal itself is affected, not other uses of the same library call.""" + real_remove, real_rmtree = impl.remove_owned_episode, shutil.rmtree + state = {"failing": True} + + def remove(session_path, manifest): + if not state["failing"]: + return real_remove(session_path, manifest) + deleted = 0 + + def rmtree(path, *args, **kwargs): + nonlocal deleted + if deleted >= deleted_directories: + raise OSError("device error") + deleted += 1 + real_rmtree(path, *args, **kwargs) + + episode_layout.shutil.rmtree = rmtree + try: + return real_remove(session_path, manifest) + finally: + episode_layout.shutil.rmtree = real_rmtree + + monkeypatch.setattr(impl, "remove_owned_episode", remove) + return lambda: state.update(failing=False) + + +async def test_a_removal_that_fails_part_way_leaves_the_take_pending_and_recovery_finishes_it( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + restore = _fail_removal_after(monkeypatch, 1) + result = await record(service, REJECTED_TAKE) + assert result.disposition is Disposition.RECOVERY_REQUIRED and result.qc_decision is QcDecision.REJECTED_CAMERA + pending_dir = session.session_path / "episode_2.pending" + pending, manifest = _under(session, 2) + # Part of the take is gone, the rest is still there with the stamp that proves whose it is, and the decision + # to remove it is on disk. + left = sorted(entry.name for entry in pending_dir.iterdir()) + assert "zarr.json" in left and len([name for name in left if name in ("cam", "tracker")]) == 1 + assert (_manifest(session, 2).storage_phase, _manifest(session, 2).finalization) == ("CHECKED", "REMOVE") + removed, added, modified = changed(before_take, tree(root)) + assert removed == set() and modified == set() and all(p.startswith(pending) or p == manifest for p in added) + (listed,) = service.pending_episodes() + assert listed.recoverable and listed.storage_phase == "CHECKED" + # A new take is refused until the pending one is resolved. + with pytest.raises(StateError): + await service.start_episode("t") + restore() + recovered = await service.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.REJECTED and not pending_dir.exists() + assert changed(before_take, tree(root)) == (set(), {manifest}, set()) + assert service.snapshot().phase is RecordingPhase.IDLE and service.pending_episodes() == () + + +async def test_after_a_restart_the_half_removed_take_is_listed_and_recovery_finishes_the_removal( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + restore = _fail_removal_after(monkeypatch, 1) + result = await record(service, REJECTED_TAKE) + assert result.disposition is Disposition.RECOVERY_REQUIRED + await service.close() + restore() + restarted = own(RecordingService(make_config(root, quarantine=True))) + await restarted.open_session(session.session_id) + (listed,) = restarted.pending_episodes() + assert listed.episode_id == result.episode_id and listed.recoverable + with pytest.raises(StateError, match="unresolved pending episodes"): + await restarted.start_episode("t") + recovered = await restarted.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.REJECTED and recovered.qc_decision is QcDecision.REJECTED_CAMERA + _pending, manifest = _under(session, 2) + assert changed(before_take, tree(root)) == (set(), {manifest}, set()) + # The session records again. + assert (await record(restarted)).disposition is Disposition.KEPT + + +async def test_a_removal_interrupted_after_the_last_file_is_finished_from_the_empty_directory( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + real_rmdir = Path.rmdir + pending_dir = session.session_path / "episode_2.pending" + + def rmdir(self): + if self == pending_dir: + raise OSError("interrupted") + real_rmdir(self) + + monkeypatch.setattr(Path, "rmdir", rmdir) + result = await record(service, REJECTED_TAKE) + assert result.disposition is Disposition.RECOVERY_REQUIRED + # Everything was deleted, the ownership stamp last; only the emptied directory is left. + assert pending_dir.is_dir() and not any(pending_dir.iterdir()) + monkeypatch.setattr(Path, "rmdir", real_rmdir) + recovered = await service.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.REJECTED and not pending_dir.exists() + _pending, manifest = _under(session, 2) + assert changed(before_take, tree(root)) == (set(), {manifest}, set()) + + +async def test_a_removal_that_finished_without_its_last_checkpoint_is_closed_by_recovery( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + real_write = impl.write_manifest + + def fail_the_rejected_checkpoint(session_path, manifest): + if manifest.storage_phase == "REJECTED": + raise OSError("disk full") + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", fail_the_rejected_checkpoint) + result = await record(service, REJECTED_TAKE) + assert result.disposition is Disposition.RECOVERY_REQUIRED + assert not (session.session_path / "episode_2.pending").exists() + assert _manifest(session, 2).storage_phase == "CHECKED" + monkeypatch.setattr(impl, "write_manifest", real_write) + recovered = await service.recover_episode(result.episode_id) + assert recovered.disposition is Disposition.REJECTED + _pending, manifest = _under(session, 2) + assert changed(before_take, tree(root)) == (set(), {manifest}, set()) + + +async def test_a_half_removed_take_can_also_be_discarded_and_only_its_own_remains_go(tmp_path, own, monkeypatch): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + restore = _fail_removal_after(monkeypatch, 1) + result = await record(service, REJECTED_TAKE) + restore() + discarded = await service.discard_pending(result.episode_id) + assert discarded.disposition is Disposition.DISCARDED + _pending, manifest = _under(session, 2) + assert changed(before_take, tree(root)) == (set(), {manifest}, set()) + assert _manifest(session, 2).storage_phase == "DISCARDED" + + +async def _interrupted_take(service): + """A take cut off while it was being written: pending, and its completeness unknown.""" + episode = await service.start_episode("t", "op") + await submit_all(service, episode.episode_id, take_samples(seconds=1.0)) + result = await service.interrupt_episode(episode.episode_id, "the capture pipeline stopped") + assert result.disposition is Disposition.RECOVERY_REQUIRED + return result + + +async def test_discarding_a_pending_take_removes_that_takes_own_data_and_nothing_else(tmp_path, own): + root, service, session = await _populated(tmp_path, own) + result = await _interrupted_take(service) + before = tree(root) + pending, manifest = _under(session, 2) + assert any(path.startswith(pending) for path in before) + discarded = await service.discard_pending(result.episode_id) + assert discarded.disposition is Disposition.DISCARDED and discarded.pending_path is None + removed, added, modified = changed(before, tree(root)) + assert removed == {path for path in before if path.startswith(pending)} and removed + assert added == set() and modified == {manifest} + assert not (session.session_path / "episode_2.pending").exists() + assert service.snapshot().phase is RecordingPhase.IDLE and service.pending_episodes() == () + + +async def test_a_discard_that_fails_part_way_leaves_the_take_pending_and_a_second_discard_finishes( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + result = await _interrupted_take(service) + before = tree(root) + pending, manifest = _under(session, 2) + restore = _fail_removal_after(monkeypatch, 1) + failed = await service.discard_pending(result.episode_id) + assert failed.disposition is Disposition.RECOVERY_REQUIRED + removed, added, modified = changed(before, tree(root)) + assert all(path.startswith(pending) for path in removed) and added == set() and modified <= {manifest} + assert (session.session_path / "episode_2.pending" / "zarr.json").is_file() + assert _manifest(session, 2).storage_phase == "WRITING" + (listed,) = service.pending_episodes() + assert not listed.recoverable # a take cut off while writing can only be discarded + restore() + discarded = await service.discard_pending(result.episode_id) + assert discarded.disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + assert removed == {path for path in before if path.startswith(pending)} + assert added == set() and modified == {manifest} + + +async def test_after_a_restart_a_take_left_while_writing_is_listed_and_can_only_be_discarded(tmp_path, own): + root, service, session = await _populated(tmp_path, own) + result = await _interrupted_take(service) + await service.close() + restarted = own(RecordingService(make_config(root, quarantine=True))) + await restarted.open_session(session.session_id) + (listed,) = restarted.pending_episodes() + assert (listed.storage_phase, listed.recoverable) == ("WRITING", False) + assert (listed.task, listed.operator) == ("t", "op") + with pytest.raises(StateError, match="still marked WRITING"): + await restarted.recover_episode(result.episode_id) + before = tree(root) + pending, manifest = _under(session, 2) + assert (await restarted.discard_pending(result.episode_id)).disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + assert removed == {path for path in before if path.startswith(pending)} and removed + assert added == set() and modified == {manifest} + + +async def test_discarding_the_take_being_recorded_removes_that_takes_own_data_and_nothing_else(tmp_path, own): + root, service, session = await _populated(tmp_path, own) + before_take = tree(root) + episode = await service.start_episode("t", "op") + await submit_all(service, episode.episode_id, take_samples(seconds=1.0)) + discarded = await service.discard_episode(episode.episode_id) + assert discarded.disposition is Disposition.DISCARDED + _pending, manifest = _under(session, 2) + assert changed(before_take, tree(root)) == (set(), {manifest}, set()) + assert not (session.session_path / "episode_2.pending").exists() + + +# --- what earlier sessions left behind ------------------------------------------------------- + + +async def test_the_output_is_scanned_for_pending_takes_of_every_session_without_opening_any(tmp_path, own): + root, service, session = await _populated(tmp_path, own) + interrupted = await _interrupted_take(service) + await service.close() + another = RecordingService(make_config(root, quarantine=True)) + other_session = await another.open_session() + second = await _interrupted_take(another) + await another.close() + before = tree(root) + scanner = RecordingService(make_config(root, quarantine=True)) + found = scanner.pending_under_output_root() + assert [(p.episode_id, p.storage_phase, p.recoverable) for p in found] == sorted( + [(interrupted.episode_id, "WRITING", False), (second.episode_id, "WRITING", False)] + ) + by_id = {p.episode_id: p for p in found} + listed = by_id[interrupted.episode_id] + assert listed.pending_path == session.session_path / "episode_2.pending" + assert (listed.task, listed.operator, listed.finalization) == ("t", "op", None) + assert listed.recorded_issues == ("the capture pipeline stopped",) + assert listed.issues == ("interrupted while writing; completeness cannot be established",) + # A caller that has one session open leaves it out: that session's own service answers for it. + skipped = scanner.pending_under_output_root(skip_session=other_session.session_id) + assert [p.episode_id for p in skipped] == [interrupted.episode_id] + # Reading changed nothing and kept no lock: either session can still be opened and its take resolved. + assert tree(root) == before + reopened = own(RecordingService(make_config(root, quarantine=True))) + await reopened.open_session(other_session.session_id) + assert (await reopened.discard_pending(second.episode_id)).disposition is Disposition.DISCARDED + + +async def test_the_scan_says_whether_a_judged_take_can_be_finished_under_the_scanning_configuration( + tmp_path, own, monkeypatch +): + root, service, session = await _populated(tmp_path, own) + restore = _fail_removal_after(monkeypatch, 1) + result = await record(service, REJECTED_TAKE) + restore() + await service.close() + (same,) = RecordingService(make_config(root, quarantine=True)).pending_under_output_root() + assert (same.episode_id, same.storage_phase, same.recoverable) == (result.episode_id, "CHECKED", True) + assert same.finalization == "REMOVE" and same.duration_seconds == pytest.approx(2.0) + # A checked take needs only the same data layout, so another capture policy does not strand it... + (other_policy,) = RecordingService(make_config(root, capture=None)).pending_under_output_root() + assert other_policy.recoverable + # ...while another set of sources does. + other_layout = dataclasses.replace( + make_config(root), video_sources=(), qc=QcConfig(required_sources=("tracker",)) + ) + (stranded,) = RecordingService(other_layout).pending_under_output_root() + assert not stranded.recoverable and stranded.issues == ("recorded with a different configuration",) + + +def test_an_output_that_does_not_exist_or_holds_no_session_has_nothing_pending(tmp_path): + assert RecordingService(make_config(tmp_path / "missing")).pending_under_output_root() == () + root = tmp_path / "out" + (root / "_quarantine" / "session_1").mkdir(parents=True) + (root / "Kitchen" / "2026-10-20-09-30-00").mkdir(parents=True) + (root / ".hidden" / ".recording").mkdir(parents=True) + (root / "notes.txt").write_text("not a session") + assert RecordingService(make_config(root)).pending_under_output_root() == () + + +# --- a discard says what it is about to do before it deletes --------------------------------- + + +async def test_a_discard_records_its_intent_before_it_deletes_anything(tmp_path, own, monkeypatch): + root, service, session = await _populated(tmp_path, own) + interrupted = await _interrupted_take(service) + seen = {} + real_remove = impl.remove_owned_episode + + def remove(session_path, manifest): + # What is on disk at the moment the removal starts. + seen["record"] = _manifest(session, 2) + seen["data"] = sorted(p.name for p in (session.session_path / "episode_2.pending").iterdir()) + return real_remove(session_path, manifest) + + monkeypatch.setattr(impl, "remove_owned_episode", remove) + assert _manifest(session, 2).discard_requested is False + assert (await service.discard_pending(interrupted.episode_id)).disposition is Disposition.DISCARDED + assert seen["record"].discard_requested is True and seen["record"].storage_phase == "WRITING" + assert "zarr.json" in seen["data"] and "cam.mp4" in seen["data"] + assert _manifest(session, 2).storage_phase == "DISCARDED" + + +async def test_a_take_whose_discard_began_is_never_recovered_and_is_discarded_by_a_second_discard( + tmp_path, own, monkeypatch +): + """A sealed take: nothing but the intent on record says that its data may be partly gone.""" + root, service, session = await _populated(tmp_path, own) + real_check = impl.check_capture_quality + monkeypatch.setattr(impl, "check_capture_quality", lambda *_: (_ for _ in ()).throw(RuntimeError("busy"))) + sealed = await record(service) + monkeypatch.setattr(impl, "check_capture_quality", real_check) + assert sealed.disposition is Disposition.RECOVERY_REQUIRED and _manifest(session, 2).storage_phase == "SEALED" + restore = _fail_removal_after(monkeypatch, 1) + assert (await service.discard_pending(sealed.episode_id)).disposition is Disposition.RECOVERY_REQUIRED + restore() + (pending,) = service.pending_episodes() + assert pending.discard_requested and not pending.recoverable and pending.storage_phase == "SEALED" + assert pending.issues[-1] == "a discard of this take was started and did not finish" + before = tree(root) + with pytest.raises(StateError, match="a discard of episode .* was started"): + await service.recover_episode(sealed.episode_id) + assert tree(root) == before + assert (await service.discard_pending(sealed.episode_id)).disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + pending_prefix, manifest_path = _under(session, 2) + assert all(path.startswith(pending_prefix) for path in removed) and added == set() + assert modified == {manifest_path} and service.snapshot().phase is RecordingPhase.IDLE + + +async def test_after_a_restart_a_discard_stopped_after_the_last_file_is_finished_from_the_empty_directory( + tmp_path, own +): + """The state a kill leaves between deleting the ownership stamp and removing the directory.""" + root, service, session = await _populated(tmp_path, own) + real_check = impl.check_capture_quality + impl.check_capture_quality = lambda *_: (_ for _ in ()).throw(RuntimeError("busy")) + try: + sealed = await record(service) + finally: + impl.check_capture_quality = real_check + await service.close() + manifest = _manifest(session, 2) + manifest.discard_requested = True + episode_layout.write_manifest(session.session_path, manifest) + pending_dir = session.session_path / "episode_2.pending" + shutil.rmtree(pending_dir) + pending_dir.mkdir() + restarted = own(RecordingService(make_config(root, quarantine=True))) + await restarted.open_session(session.session_id) + (pending,) = restarted.pending_episodes() + assert pending.discard_requested and not pending.recoverable + before = tree(root) + assert (await restarted.discard_pending(sealed.episode_id)).disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + assert removed == set() and added == set() and modified == {_under(session, 2)[1]} + assert not pending_dir.exists() and restarted.pending_episodes() == () + + +async def test_a_discard_that_is_refused_leaves_no_intent_behind_so_the_take_can_still_be_recovered( + tmp_path, own, monkeypatch +): + """The take is already in its final place; only its last checkpoint is missing.""" + root, service, session = await _populated(tmp_path, own) + real_write = impl.write_manifest + + def fail_the_last_checkpoint(session_path, manifest): + if manifest.storage_phase == "FINALIZED" and manifest.episode_index == 2: + raise OSError("disk full") + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", fail_the_last_checkpoint) + result = await record(service) + monkeypatch.setattr(impl, "write_manifest", real_write) + assert result.disposition is Disposition.RECOVERY_REQUIRED and (session.session_path / "episode_2").is_dir() + before = tree(root) + refused = await service.discard_pending(result.episode_id) + assert refused.disposition is Disposition.RECOVERY_REQUIRED + assert _manifest(session, 2).discard_requested is False + removed, added, _modified = changed(before, tree(root)) + assert removed == set() and added == set() + assert (await service.recover_episode(result.episode_id)).disposition is Disposition.KEPT diff --git a/examples/egocap/tests/recording_service/test_session_config.py b/examples/egocap/tests/recording_service/test_session_config.py index ae0fef6846..b20ad754c2 100644 --- a/examples/egocap/tests/recording_service/test_session_config.py +++ b/examples/egocap/tests/recording_service/test_session_config.py @@ -151,6 +151,7 @@ def _pre_frame_type_digest(config: ServiceConfig) -> str: del qc["capture"] else: qc["capture_algorithm_version"] = impl.ALGORITHM_VERSION + del qc["capture"]["source"] # where the thresholds were read from is not part of the digest canonical = { **({"routing": True} if config.routing is not None else {}), "numeric": [ diff --git a/examples/egocap/tests/recording_service/test_short_take_verdicts.py b/examples/egocap/tests/recording_service/test_short_take_verdicts.py new file mode 100644 index 0000000000..8ac1459ace --- /dev/null +++ b/examples/egocap/tests/recording_service/test_short_take_verdicts.py @@ -0,0 +1,196 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A take too short for its camera's rate to be measured is not rejected for that rate, and a camera that +recorded a fraction of a take that lasted is, however good its rate while it ran. + +Rejecting a take removes its media, so the rate rule measures a rate only over frames spanning ten frame +intervals of the camera's expected rate, and counts a camera's frames against the take's length only in a take +of thirteen intervals or more. Takes on both sides are recorded through the real service; the files of the ones +that are kept are checked to be there, and the media of the ones that are rejected to be gone. + +Takes are built in the test (see synthetic.py). +""" + +import numpy as np +import pytest +from synthetic import CAMERA, make_config, record + +from recording_service import ( + Disposition, + NumericSample, + Outcome, + PixelFormat, + QcDecision, + RecordingService, + VideoSample, +) + +INTERVAL = 1.0 / CAMERA.fps + + +def _take( + frames_due: int, + dropped: tuple[int, ...] = (), + start: float = 100.0, + seconds: float | None = None, + late: float = 0.0, +): + """A take whose camera had ``frames_due`` frames to deliver at its rate and dropped the ones listed. + + The tracker moves throughout and covers the same span, or ``seconds`` when the take lasted longer than the + camera's frames. ``late`` is how many frame intervals after the take's first sample the camera began. + """ + samples = [] + span = max(frames_due - 1, 1) * INTERVAL if seconds is None else seconds + for i in range(int(span * 60) + 2): + pose = np.eye(4) + pose[0, 3] = 0.01 * i + at = start + min(i / 60.0, span) + samples.append(NumericSample("tracker", at, at, {"pose": pose})) + for i in range(frames_due): + if i not in dropped: + image = np.full((48, 64, 3), i % 255, dtype=np.uint8) + at = start + (late + i) * INTERVAL + samples.append(VideoSample("cam", image, PixelFormat.BGR8, at, at)) + return sorted(samples, key=lambda sample: sample.capture_time) + + +def _results(result): + return {check.name: check for check in result.capture_quality.check_results} + + +async def _recorder(tmp_path, own): + service = own(RecordingService(make_config(tmp_path / "out", quarantine=True))) + await service.open_session() + return service + + +async def test_a_take_with_one_camera_frame_is_kept_and_told_it_is_too_short_not_removed_as_zero_fps( + tmp_path, own +): + service = await _recorder(tmp_path, own) + result = await record(service, _take(1)) + assert (result.disposition, result.qc_decision) == (Disposition.KEPT, QcDecision.PASSED) + assert (result.final_path / "cam.mp4").is_file() and result.pending_path is None + results = _results(result) + assert results["camera_min_fps:cam"].outcome is Outcome.PASSED + assert results["camera_min_fps:cam"].evidence == ("too short to measure a rate",) + assert results["camera_rate_measurable:cam"].outcome is Outcome.FAILED + warnings = result.capture_quality.warnings + assert ( + "cam: 1 frame(s) over 0.00s is too short to measure a rate (it takes 10 frame intervals, 0.33s)" + in warnings + ) + assert any(warning.startswith("the take lasted 0.") and "outside 1.0s" in warning for warning in warnings) + + +async def test_seven_of_eight_frames_in_a_quarter_second_are_kept(tmp_path, own): + """The rate over those seven frames is under the minimum, and one frame is all that separates it.""" + service = await _recorder(tmp_path, own) + result = await record(service, _take(8, dropped=(4,))) + assert (result.disposition, result.qc_decision) == (Disposition.KEPT, QcDecision.PASSED) + assert (result.final_path / "cam.mp4").is_file() + + +@pytest.mark.parametrize( + ("frames_due", "dropped", "disposition", "decision"), + [ + (10, (1, 3, 5, 7), Disposition.KEPT, QcDecision.PASSED), # nine intervals: not judged + (11, (1, 3, 5, 7, 9), Disposition.REJECTED, QcDecision.REJECTED_CAMERA), # ten intervals: judged + ], + ids=["just under the threshold", "at the threshold"], +) +async def test_a_starved_camera_is_judged_from_ten_frame_intervals_on( + tmp_path, own, frames_due, dropped, disposition, decision +): + service = await _recorder(tmp_path, own) + result = await record(service, _take(frames_due, dropped)) + assert (result.disposition, result.qc_decision) == (disposition, decision) + session = service.snapshot().session.session_path + if disposition is Disposition.REJECTED: + assert not (session / "episode_0.pending").exists() and not (session / "episode_0").exists() + assert _results(result)["camera_min_fps:cam"].measurements["fps"] == pytest.approx(15.0) + else: + assert (session / "episode_0" / "cam.mp4").is_file() + + +@pytest.mark.parametrize( + ("label", "frames_due", "dropped", "seconds", "said"), + [ + ("one frame in a 2 s take", 1, (), 2.0, "cam: 1 frame(s) recorded of the 60.0 a 2.00s take holds"), + ( + "nine frames in the first 0.27 s of a 2 s take", + 9, + (), + 2.0, + "cam: 9 frame(s) recorded of the 60.0 a 2.00s take holds", + ), + ( + "one frame in a take of half a second", + 1, + (), + 0.5, + "cam: 1 frame(s) recorded of the 15.0 a 0.50s take holds", + ), + ], +) +async def test_a_camera_that_delivered_next_to_nothing_in_a_take_that_lasted_is_rejected_and_its_media_removed( + tmp_path, own, label, frames_due, dropped, seconds, said +): + service = await _recorder(tmp_path, own) + result = await record(service, _take(frames_due, dropped, seconds=seconds)) + assert (result.disposition, result.qc_decision) == (Disposition.REJECTED, QcDecision.REJECTED_CAMERA), label + (issue,) = _results(result)["camera_min_fps:cam"].issues + needed = 0.86 * (seconds * CAMERA.fps - 3) + assert issue.startswith(said) and issue.endswith(f"at {CAMERA.fps} fps (needs {needed:.1f})") + session = service.snapshot().session.session_path + assert not (session / "episode_0.pending").exists() and not (session / "episode_0").exists() + assert result.final_path is None and result.pending_path is None + + +@pytest.mark.parametrize("late", [0.0, 80.0], ids=["the first ten intervals", "the last ten intervals"]) +async def test_a_camera_that_ran_at_full_rate_for_a_ninth_of_the_take_is_rejected_and_its_media_removed( + tmp_path, own, late +): + """Ten intervals of frames in a take of ninety: the rate over the camera's own frames is perfect.""" + service = await _recorder(tmp_path, own) + result = await record(service, _take(11, seconds=90 * INTERVAL, late=late)) + assert (result.disposition, result.qc_decision) == (Disposition.REJECTED, QcDecision.REJECTED_CAMERA) + camera = _results(result)["camera_min_fps:cam"] + assert camera.measurements["fps"] == pytest.approx(CAMERA.fps) and camera.measurements["frames"] == 11 + assert camera.measurements["take_frames"] == pytest.approx(90.0) + session = service.snapshot().session.session_path + assert not (session / "episode_0.pending").exists() and not (session / "episode_0").exists() + + +async def test_a_camera_that_lost_nothing_and_started_three_intervals_late_is_kept_in_a_take_just_over_the_floor( + tmp_path, own +): + service = await _recorder(tmp_path, own) + result = await record(service, _take(10, seconds=13.1 * INTERVAL, late=3.2)) + assert (result.disposition, result.qc_decision) == (Disposition.KEPT, QcDecision.PASSED) + assert (result.final_path / "cam.mp4").is_file() + assert _results(result)["camera_min_fps:cam"].measurements["frames"] == 10 + + +async def test_a_take_just_over_the_floor_whose_camera_is_healthy_is_kept(tmp_path, own): + """Twelve intervals of take, the camera's ten frames one interval in from each end: all there could be.""" + service = await _recorder(tmp_path, own) + samples = _take(10, seconds=11.5 * INTERVAL) + shifted = [ + sample + if isinstance(sample, NumericSample) + else VideoSample( + "cam", + sample.image, + sample.pixel_format, + sample.capture_time + INTERVAL, + sample.receive_time + INTERVAL, + ) + for sample in samples + ] + result = await record(service, sorted(shifted, key=lambda sample: sample.capture_time)) + assert (result.disposition, result.qc_decision) == (Disposition.KEPT, QcDecision.PASSED) + assert (result.final_path / "cam.mp4").is_file() diff --git a/examples/egocap/tests/recording_service/test_takes_left_behind.py b/examples/egocap/tests/recording_service/test_takes_left_behind.py new file mode 100644 index 0000000000..fc2329dad8 --- /dev/null +++ b/examples/egocap/tests/recording_service/test_takes_left_behind.py @@ -0,0 +1,1056 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Which takes a read of the recording output lists as left behind, and which of them a command may act on. + +The output is shared: other stations record into it, another recorder may have a session open right now (where +its lock can be seen, or on another machine where it cannot), a session directory may have been copied or +renamed by hand, and a folder in it may not be readable at all. Each test builds one of those outputs with real +sessions recorded through the real service, and compares the whole tree file by file around every command that +could delete. + +A session that is open is told by its beat: the recorder rewrites its lock file on a period, and a reader that +looks twice, far enough apart by its own clock, sees the change. The tests shorten the period and give the +reader a clock they move by hand, so nothing here waits for seconds or depends on the time of day. +""" + +import asyncio +import errno +import logging +import os +import shutil +import threading +import time +from pathlib import Path +from types import SimpleNamespace + +import pytest +import zarr +from synthetic import changed, make_config, record, submit_all, take_samples, tree + +import recording_service.output_scan as output_scan +import recording_service.recording_service as impl +from egocap.recording import episode_layout, episode_store, route +from egocap.recording.episode_layout import read_manifest, session_beat +from recording_service import ( + ConfigurationError, + Disposition, + NumericSample, + OutputScan, + RecordingPhase, + RecordingService, + StateError, + storage_problem, +) + +NO_CAMERA = [sample for sample in take_samples() if isinstance(sample, NumericSample)] +STATION = "Bench A" +WATCH = 2.5 + + +def _config(root: Path, station: str | None = STATION, **overrides): + return make_config(root, quarantine=True, station_label=station, **overrides) + + +async def _interrupted_take(service): + """A take cut off while it was being written: pending, and its completeness unknown.""" + episode = await service.start_episode("t", "op") + await submit_all(service, episode.episode_id, take_samples(seconds=1.0)) + result = await service.interrupt_episode(episode.episode_id, "the capture pipeline stopped") + assert result.disposition is Disposition.RECOVERY_REQUIRED + return result + + +async def _left_by_a_recorder_that_is_gone(root: Path, station: str | None = STATION, **overrides): + """A session with one kept take and one take interrupted while writing, its recorder closed.""" + service = RecordingService(_config(root, station, **overrides)) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + interrupted = await _interrupted_take(service) + assert (await service.close()).released + return session, interrupted + + +def _listed(root: Path, station: str | None = STATION, **kwargs): + """One look with no memory: it asks each session's lock and nothing else.""" + return RecordingService(_config(root, station)).pending_under_output_root(**kwargs) + + +class _Reader: + """A reader of the output with a clock of its own that the test moves: its looks are as far apart as said.""" + + def __init__(self, root: Path, stations=(STATION,), watch: float = WATCH): + self.root, self.stations, self.now = root, stations, 1000.0 + self.scan = OutputScan(watch_seconds=watch, clock=lambda: self.now) + + def look(self, later: float = 0.0, **kwargs) -> list[str]: + """Read the output ``later`` seconds after the last look; the ids of the takes listed.""" + self.now += later + return sorted( + f"{item.session_path.name}/{item.manifest.final_path}" + for item in self.scan.read(self.root, self.stations, **kwargs) + ) + + +def _wait_for(condition, seconds: float = 5.0) -> None: + deadline = time.monotonic() + seconds + while not condition(): + assert time.monotonic() < deadline, "the condition never came true" + time.sleep(0.005) + + +def _next_beat(session_path: Path) -> None: + """Wait until the session's holder has written its next beat.""" + before = session_beat(session_path) + _wait_for(lambda: session_beat(session_path) != before) + + +@pytest.fixture +def fast_beat(monkeypatch): + """Recorders beat every 20 ms instead of every second, so a test sees several beats without waiting.""" + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 0.02) + + +@pytest.fixture +def lock_does_not_reach(monkeypatch): + """A shared disk on which a lock taken by one machine is not seen by another: every lock is granted.""" + monkeypatch.setattr(episode_layout.fcntl, "flock", lambda *_: None) + + +# --- a session some recorder has open: its lock, where the lock reaches ----------------------- + + +async def test_a_session_another_recorder_has_open_is_not_listed_until_that_recorder_is_gone(tmp_path, own): + root = tmp_path / "out" + _session, left = await _left_by_a_recorder_that_is_gone(root) + other = own(RecordingService(_config(root))) + other_session = await other.open_session() + episode = await other.start_episode("t", "op") + await submit_all(other, episode.episode_id, take_samples(seconds=1.0)) + # The other recorder is writing its take right now. Its record looks exactly like an interrupted take's. + live = read_manifest(other_session.session_path / ".recording" / "episode_0.json") + assert live.storage_phase == "WRITING" + assert [p.episode_id for p in _listed(root)] == [left.episode_id] + assert (await other.stop_episode(episode.episode_id)).disposition is Disposition.KEPT + interrupted = await _interrupted_take(other) + assert [p.episode_id for p in _listed(root)] == [left.episode_id] + await other.close() + assert sorted(p.episode_id for p in _listed(root)) == sorted([left.episode_id, interrupted.episode_id]) + # A caller leaves out the session it has open itself by name. + skipped = _listed(root, skip_session=other_session.session_id) + assert [p.episode_id for p in skipped] == [left.episode_id] + + +async def test_looking_changes_nothing_under_the_output_and_keeps_no_lock(tmp_path, own): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + before = tree(root) + reader = _Reader(root) + assert reader.look() == [] and reader.look(WATCH) == [left.episode_id] + assert reader.scan.judge(session.session_path) == (True, 0.0) + assert tree(root) == before + reopened = own(RecordingService(_config(root))) + await reopened.open_session(session.session_id) + assert (await reopened.discard_pending(left.episode_id)).disposition is Disposition.DISCARDED + + +# --- a session some recorder has open: its beat, wherever the directory can be seen ----------- + + +async def test_where_the_lock_does_not_reach_a_session_that_is_open_is_told_by_its_beat( + tmp_path, own, fast_beat, lock_does_not_reach +): + root = tmp_path / "out" + _session, left = await _left_by_a_recorder_that_is_gone(root) + other = own(RecordingService(_config(root))) # the same station name, on another machine + other_session = await other.open_session() + episode = await other.start_episode("t", "op") + await submit_all(other, episode.episode_id, take_samples(seconds=1.0)) + live = f"{other_session.session_id}/episode_0" + reader = _Reader(root) + # Nothing is listed on a first look: one look cannot tell an open session from an abandoned one. + assert reader.look() == [] and reader.scan.first_looks() == 2 + for _ in range(4): + _next_beat(other_session.session_path) + # The session nobody holds is listed from the second look on; the one that beats never is. + assert reader.look(WATCH) == [left.episode_id] + # Asked about it before a command: not known yet right after a look that saw a beat, and open as + # soon as the next beat is seen. + quiet, wait = reader.scan.judge(other_session.session_path) + assert quiet is not True and (quiet is False or wait == WATCH) + _next_beat(other_session.session_path) + assert reader.scan.judge(other_session.session_path) == (False, 0.0) + # Its recorder is gone, the take cut off. It is listed once two looks found the beat at rest. + await other.interrupt_episode(episode.episode_id, "the capture pipeline stopped") + await other.close() + assert reader.look() == [left.episode_id] # whatever its last beat was, the watch counts from a look + assert reader.look(1.0) == [left.episode_id] # at rest, and not yet for long enough + assert reader.look(WATCH) == sorted([left.episode_id, live]) + + +async def test_a_take_that_sits_sealed_while_its_checks_run_is_in_an_open_session( + tmp_path, own, fast_beat, lock_does_not_reach, monkeypatch +): + """Nothing is written to the take for as long as its checks run; only the beat says its recorder is there.""" + root = tmp_path / "out" + other = own(RecordingService(_config(root))) + other_session = await other.open_session() + checking, finish = threading.Event(), threading.Event() + real_check = impl.check_capture_quality + + def slow_check(*args): + checking.set() + finish.wait(10.0) + return real_check(*args) + + monkeypatch.setattr(impl, "check_capture_quality", slow_check) + episode = await other.start_episode("t", "op") + await submit_all(other, episode.episode_id, take_samples()) + stopping = asyncio.ensure_future(other.stop_episode(episode.episode_id)) + while not checking.is_set(): + await asyncio.sleep(0.01) + assert read_manifest(other_session.session_path / ".recording" / "episode_0.json").storage_phase == "SEALED" + quiet_files = tree(other_session.session_path / "episode_0.pending") + reader = _Reader(root) + reader.look() + for _ in range(4): + _next_beat(other_session.session_path) + assert reader.look(WATCH) == [] + _next_beat(other_session.session_path) + assert reader.scan.judge(other_session.session_path) == (False, 0.0) + assert tree(other_session.session_path / "episode_0.pending") == quiet_files # the take itself was at rest + finish.set() + assert (await stopping).disposition is Disposition.KEPT + + +async def test_a_session_that_is_open_and_idle_is_never_remembered_as_finished( + tmp_path, own, fast_beat, lock_does_not_reach +): + root = tmp_path / "out" + other = own(RecordingService(_config(root))) + other_session = await other.open_session() + assert (await record(other)).disposition is Disposition.KEPT # nothing waits in it: only a kept take + reader = _Reader(root) + reader.look() + for _ in range(3): + _next_beat(other_session.session_path) + assert reader.look(WATCH) == [] + # The same recorder goes on, leaves a take behind and is gone. A reader that had filed the session as + # finished while it was idle would never list this take. + interrupted = await _interrupted_take(other) + await other.close() + reader.look(WATCH) + assert reader.look(WATCH) == [interrupted.episode_id] + + +async def test_a_take_whose_files_carry_times_in_the_future_is_listed_and_discarded(tmp_path, own): + """The clock was set back after the take was recorded, or the file server's clock runs ahead.""" + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + ahead = time.time() + 3600 + for path in (session.session_path, *session.session_path.rglob("*")): + os.utime(path, (ahead, ahead)) + reader = _Reader(root) + assert reader.look() == [] and reader.look(WATCH) == [left.episode_id] + assert reader.scan.judge(session.session_path) == (True, 0.0) + reopened = own(RecordingService(_config(root))) + await reopened.open_session(session.session_id) + before = tree(root) + assert (await reopened.discard_pending(left.episode_id)).disposition is Disposition.DISCARDED + removed, added, modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session.session_id}/episode_1.pending/") for path in removed) + assert added == set() and modified == {f"{session.session_id}/.recording/episode_1.json"} + + +async def test_a_take_written_a_moment_ago_by_a_recorder_that_is_gone_is_discarded_at_once(tmp_path, own): + """No time on the disk is compared with this machine's clock: what counts is that nobody holds the session.""" + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + reopened = own(RecordingService(_config(root))) + await reopened.open_session(session.session_id) + assert (await reopened.discard_pending(left.episode_id)).disposition is Disposition.DISCARDED + + +async def test_a_look_tells_how_long_until_it_can_judge_a_session_it_has_not_watched(tmp_path, fast_beat): + root = tmp_path / "out" + session, _left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root) + # A reader left to itself watches for the production time; a caller reads it to time its next look. + assert OutputScan().watch_seconds == episode_layout.BEAT_WATCH_SECONDS == reader.scan.watch_seconds == WATCH + assert reader.scan.judge(session.session_path) == (None, WATCH) # a first look + reader.now += 1.0 + assert reader.scan.judge(session.session_path) == (None, WATCH - 1.0) # at rest, not yet for long enough + reader.now += WATCH + assert reader.scan.judge(session.session_path) == (True, 0.0) + # A recorder takes the session: the next look sees its beat, and the watch starts over. + holder = episode_layout.SessionLock(session.session_path) + assert reader.scan.judge(session.session_path) == (False, 0.0) + holder.release() + reader.now += 0.5 + quiet, wait = reader.scan.judge(session.session_path) + assert quiet is None and 0 < wait <= WATCH + + +async def test_a_session_the_reader_itself_just_released_needs_no_second_look(tmp_path, fast_beat): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root) + assert reader.look() == [] + own_use = episode_layout.SessionLock(session.session_path) # the reader's own recorder reopens it + _next_beat(session.session_path) + own_use.release() + reader.scan.note_closed(session.session_path) + assert reader.look() == [left.episode_id] and reader.scan.judge(session.session_path) == (True, 0.0) + + +async def test_one_look_with_no_memory_asks_the_lock_alone(tmp_path, own, fast_beat, lock_does_not_reach): + """What a caller gets that reads once: it cannot see a beat, and the documentation says so.""" + root = tmp_path / "out" + other = own(RecordingService(_config(root))) + await other.open_session() + episode = await other.start_episode("t", "op") + await submit_all(other, episode.episode_id, take_samples(seconds=1.0)) + assert [p.episode_id for p in _listed(root)] == [episode.episode_id] + await other.discard_episode(episode.episode_id) + + +# --- probe before judging: nothing is concluded from a session that is being opened ----------- + + +async def test_a_session_read_while_it_is_being_opened_is_looked_at_again(tmp_path, monkeypatch): + """A new session has its sidecar before its config.yaml: read in between, it names no station yet.""" + root = tmp_path / "out" + reader = _Reader(root, watch=0.0) + seen = {} + real_write = impl.write_yaml_atomic + + def read_in_between(path, data): + if path.name == "config.yaml" and "listed" not in seen: + with monkeypatch.context() as patched: + # The worst case: the opener's lock is not seen either. + patched.setattr(episode_layout.fcntl, "flock", lambda *_: None) + seen["listed"] = reader.look() + seen["config_was_there"] = path.exists() + return real_write(path, data) + + monkeypatch.setattr(impl, "write_yaml_atomic", read_in_between) + service = RecordingService(_config(root)) + await service.open_session() + assert seen == {"listed": [], "config_was_there": False} + interrupted = await _interrupted_take(service) + await service.close() + # Nothing was concluded from the look in between: the take is listed once the session is at rest. + reader.look(1.0) + assert reader.look(1.0) == [interrupted.episode_id] + + +async def test_a_session_whose_config_cannot_be_read_is_listed_and_never_remembered(tmp_path, monkeypatch): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + (session.session_path / "config.yaml").write_text(": :\n - [") + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root, watch=0.0) + assert reader.look() == [left.episode_id] + # Even with nothing left in it, a session that could not be read in full is looked at again. + reopened = RecordingService(_config(root)) + with pytest.raises(ConfigurationError, match="no readable source declarations"): + await reopened.open_session(session.session_id) + shutil.rmtree(session.session_path / "episode_1.pending") + (session.session_path / ".recording" / "episode_1.json").unlink() + opened.clear() + reader.scan.note_closed(session.session_path) + assert reader.look() == [] and reader.look() == [] + assert opened == [session.session_id, session.session_id] + + +async def test_a_directory_replaced_by_another_of_the_same_name_is_read_as_the_new_one(tmp_path): + root, side = tmp_path / "out", tmp_path / "side" + finished = RecordingService(_config(root)) + first = await finished.open_session() + assert (await record(finished)).disposition is Disposition.KEPT + await finished.close() + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and reader.look() == [] # settled: nothing is left in it + # The session is restored from a copy that holds an unresolved take, under the same name. + restored, left = await _left_by_a_recorder_that_is_gone(side) + shutil.rmtree(first.session_path) + shutil.copytree(restored.session_path, first.session_path) + for record_file in (first.session_path / ".recording").glob("episode_*.json"): + record_file.write_text(record_file.read_text().replace(restored.session_id, first.session_id)) + assert reader.look() == [f"{first.session_id}/episode_1"] + assert left.episode_id == f"{restored.session_id}/episode_1" + + +# --- the station: every name it has had, and sessions that carry none ------------------------- + + +async def test_a_take_left_under_an_earlier_name_of_the_station_is_still_listed(tmp_path): + root = tmp_path / "out" + _a, under_old_name = await _left_by_a_recorder_that_is_gone(root, "Bench A") + _b, theirs = await _left_by_a_recorder_that_is_gone(root, "Cart B") + renamed = RecordingService(_config(root, "Bench A2")) + # With only its present name the station would never list what it left before the rename. + assert renamed.pending_under_output_root() == () + listed = renamed.pending_under_output_root(stations=("Bench A2", "Bench A")) + assert [p.episode_id for p in listed] == [under_old_name.episode_id] + assert theirs.episode_id not in {p.episode_id for p in listed} + + +async def test_a_session_that_carries_no_station_name_is_listed_by_a_station_that_has_one(tmp_path): + """Recorded before the station was given its first name: it is nobody else's.""" + root = tmp_path / "out" + _n, unnamed = await _left_by_a_recorder_that_is_gone(root, None) + _a, named = await _left_by_a_recorder_that_is_gone(root, "Bench A") + assert sorted(p.episode_id for p in _listed(root, "Bench A")) == sorted([unnamed.episode_id, named.episode_id]) + assert [p.episode_id for p in _listed(root, "Cart B")] == [unnamed.episode_id] + # A recorder with no name lists the sessions that carry none, never a named station's. + assert [p.episode_id for p in _listed(root, None)] == [unnamed.episode_id] + assert [p.episode_id for p in _listed(root, "")] == [unnamed.episode_id] + + +async def test_another_stations_session_is_remembered_as_such_only_once_its_config_was_read(tmp_path, monkeypatch): + root = tmp_path / "out" + _a, ours = await _left_by_a_recorder_that_is_gone(root, "Bench A") + theirs_session, _theirs = await _left_by_a_recorder_that_is_gone(root, "Cart B") + opened = [] + real_station = output_scan.frozen_station + monkeypatch.setattr(output_scan, "frozen_station", lambda path: opened.append(path.name) or real_station(path)) + reader = _Reader(root, watch=0.0) + assert reader.look() == [ours.episode_id] and theirs_session.session_id in opened + opened.clear() + assert reader.look() == [ours.episode_id] + assert theirs_session.session_id not in opened # its name never changes: it is not opened again + + +async def test_what_was_settled_for_one_set_of_names_is_not_assumed_for_another(tmp_path): + root = tmp_path / "out" + _a, ours = await _left_by_a_recorder_that_is_gone(root, "Bench A") + _b, theirs = await _left_by_a_recorder_that_is_gone(root, "Cart B") + reader = _Reader(root, watch=0.0) + assert reader.look() == [ours.episode_id] + reader.stations = ("Cart B",) + assert reader.look() == [theirs.episode_id] + reader.stations = "Bench A" # one name may be given by itself + assert reader.look() == [ours.episode_id] + + +# --- one unreadable entry breaks nothing ------------------------------------------------------ + + +async def test_an_entry_that_cannot_be_looked_into_is_passed_over_and_logged_once(tmp_path, monkeypatch, caplog): + root = tmp_path / "out" + _session, left = await _left_by_a_recorder_that_is_gone(root) + (root / "lost+found").mkdir() + + def stat(path, *args, **kwargs): + if "lost+found" in Path(path).parts: + raise PermissionError(errno.EACCES, "Permission denied", str(path)) + return os.stat(path, *args, **kwargs) + + # Only the reader's own view of the file system: everything else in the test still sees the folder. + monkeypatch.setattr(output_scan, "os", SimpleNamespace(scandir=os.scandir, stat=stat)) + reader = _Reader(root, watch=0.0) + with caplog.at_level(logging.WARNING, logger="isaaccapture.egocap.output_scan"): + for _ in range(3): + assert reader.look() == [left.episode_id] + logged = [r.getMessage() for r in caplog.records if r.name == "isaaccapture.egocap.output_scan"] + assert logged == [ + "an entry of the recording output cannot be read and is passed over: lost+found (PermissionError)" + ] + assert str(root) not in logged[0] + + +@pytest.mark.skipif(os.geteuid() == 0, reason="the superuser can look into any folder") +async def test_a_folder_this_user_may_not_search_is_passed_over(tmp_path): + root = tmp_path / "out" + _session, left = await _left_by_a_recorder_that_is_gone(root) + closed = root / "lost+found" + closed.mkdir() + closed.chmod(0o000) + try: + assert [p.episode_id for p in _listed(root)] == [left.episode_id] + finally: + closed.chmod(0o700) + + +async def test_a_session_whose_records_cannot_be_listed_is_passed_over_and_tried_again(tmp_path, monkeypatch): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root, watch=0.0) + with monkeypatch.context() as patched: + patched.setattr( + output_scan, + "scan_session", + lambda path: (_ for _ in ()).throw(PermissionError(errno.EACCES, "Permission denied", str(path))), + ) + assert reader.look() == [] + # Nothing was concluded from the failed read: the take is found as soon as the session can be read. + assert reader.look() == [left.episode_id] and left.session_id == session.session_id + + +def test_an_output_that_cannot_be_listed_has_nothing_left_behind(tmp_path): + (tmp_path / "out").write_text("a file where the output should be") + assert _listed(tmp_path / "out") == () + + +# --- a record acts only in the session it was written for ------------------------------------- + + +async def test_a_copied_session_directory_is_listed_as_misplaced_and_no_command_acts_on_it(tmp_path, own): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + copy_name = f"{session.session_id}_copy" + shutil.copytree(session.session_path, root / copy_name) + found = {p.episode_id: p for p in _listed(root)} + # Two rows, each named after the directory its record is in, so that they cannot be mistaken for each other. + assert sorted(found) == sorted([left.episode_id, f"{copy_name}/episode_1"]) + original, copied = found[left.episode_id], found[f"{copy_name}/episode_1"] + assert (original.misplaced, original.session_id, original.written_for) == (False, session.session_id, "") + assert (copied.misplaced, copied.session_id, copied.recoverable) == (True, copy_name, False) + # The row says which session the record was written for: what the folder is a copy of, or was named. + assert copied.written_for == session.session_id + assert copied.pending_path == root / copy_name / "episode_1.pending" + assert copied.issues == ("written for another session; this session directory was copied or renamed",) + # Reopening the copy finds nothing it may act on, under either name, and will not record into it. + before = tree(root) + on_copy = own(RecordingService(_config(root))) + await on_copy.open_session(copy_name) + assert on_copy.pending_episodes() == () and on_copy.retained_rejections() == () + for episode_id in (left.episode_id, f"{copy_name}/episode_1"): + for act in (on_copy.discard_pending, on_copy.recover_episode): + with pytest.raises(StateError, match="no pending episode"): + await act(episode_id) + with pytest.raises(StateError, match="unreadable episode manifests must be resolved first"): + await on_copy.start_episode("t", "op") + await on_copy.close() + assert tree(root) == before + # The original is still the original's to discard, and the copy's files stay where they are. + on_original = own(RecordingService(_config(root))) + await on_original.open_session(session.session_id) + assert (await on_original.discard_pending(left.episode_id)).disposition is Disposition.DISCARDED + removed, _added, _modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session.session_id}/episode_1.pending/") for path in removed) + assert (root / copy_name / "episode_1.pending").is_dir() + + +async def test_a_renamed_session_directory_is_listed_as_misplaced_under_its_new_name(tmp_path): + root = tmp_path / "out" + session, _left = await _left_by_a_recorder_that_is_gone(root) + session.session_path.rename(root / "renamed_by_hand") + (only,) = _listed(root) + assert (only.episode_id, only.session_id, only.misplaced) == ( + "renamed_by_hand/episode_1", + "renamed_by_hand", + True, + ) + assert not only.recoverable and only.storage_phase == "WRITING" and only.written_for == session.session_id + + +async def test_a_resolved_take_of_a_copied_directory_is_not_listed(tmp_path): + root = tmp_path / "out" + service = RecordingService(_config(root)) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + await service.close() + shutil.copytree(session.session_path, root / "a_copy") + assert _listed(root) == () + + +# --- reading again stays cheap ---------------------------------------------------------------- + + +async def test_reading_again_opens_only_the_sessions_that_hold_something_and_the_ones_that_appeared( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + for _ in range(3): # sessions with nothing left to resolve + settled = RecordingService(_config(root)) + await settled.open_session() + assert (await record(settled)).disposition is Disposition.KEPT + await settled.close() + session, left = await _left_by_a_recorder_that_is_gone(root) + (root / "Kitchen" / "2026-10-20-09-30-00").mkdir(parents=True) # a studio folder: not a session + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root) + + def read(later: float = 0.0): + opened.clear() + return reader.look(later), sorted(opened) + + assert read() == ([], []) # a first look opens no session: it only notes each one's beat + listed, second = read(WATCH) + assert listed == [left.episode_id] and len(second) == 4 # the second look reads every session, once + assert read(1.0) == ([left.episode_id], [session.session_id]) # then only the one that holds something + # A session that appears later is watched, then read. + late_session, late = await _left_by_a_recorder_that_is_gone(root) + assert read(1.0) == ([left.episode_id], [session.session_id]) + listed, looked_at = read(WATCH) + assert listed == sorted([left.episode_id, late.episode_id]) + assert looked_at == sorted([session.session_id, late_session.session_id]) + # Once a session holds nothing any more it is read one last time and then left alone. + for held, episode_id in ((session, left.episode_id), (late_session, late.episode_id)): + resolver = own(RecordingService(_config(root))) + await resolver.open_session(held.session_id) + assert (await resolver.discard_pending(episode_id)).disposition is Disposition.DISCARDED + await resolver.close() + reader.scan.note_closed(held.session_path) + assert read() == ([], sorted([session.session_id, late_session.session_id])) + assert read(60.0) == ([], []) + # Without a memory of earlier reads, every session is read every time. + opened.clear() + assert RecordingService(_config(root)).pending_under_output_root() == () + assert len(opened) == 5 + + +async def test_a_take_rejected_for_integrity_in_an_earlier_session_is_no_row_and_lets_the_read_settle( + tmp_path, monkeypatch +): + """Every Record-then-Stop with no camera frame leaves one; it stays on disk and costs later reads nothing.""" + root = tmp_path / "out" + service = RecordingService(_config(root)) + session = await service.open_session() + rejected = await record(service, NO_CAMERA) + assert rejected.disposition is Disposition.REJECTED + await service.close() + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and opened == [session.session_id] + assert reader.look() == [] and reader.look() == [] and opened == [session.session_id] + assert _listed(root) == () + # Its data is where it was left. + assert (session.session_path / "episode_0.pending").is_dir() + + +async def test_a_session_directory_that_is_removed_is_forgotten(tmp_path): + root = tmp_path / "out" + service = RecordingService(_config(root)) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + await service.close() + reader = _Reader(root, watch=0.0) + assert reader.look() == [] + shutil.rmtree(session.session_path) + assert reader.look() == [] and reader.scan._settled == {} and reader.scan._watches == {} + + +def test_a_file_named_like_a_sessions_sidecar_is_not_a_session(tmp_path): + root = tmp_path / "out" + (root / "odd").mkdir(parents=True) + (root / "odd" / ".recording").write_text("a file, not a sidecar directory") + assert _listed(root) == () + + +# --- a take rejected for integrity, in the session that recorded it --------------------------- + + +async def test_a_take_rejected_for_integrity_is_listed_blocks_nothing_and_a_discard_removes_only_its_data( + tmp_path, own +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + rejected = await record(service, NO_CAMERA) + assert rejected.disposition is Disposition.REJECTED and rejected.pending_path.is_dir() + (listed,) = service.retained_rejections() + assert (listed.episode_id, listed.storage_phase, listed.recoverable) == ( + rejected.episode_id, + "REJECTED", + False, + ) + assert listed.issues == ("rejected by the integrity check; its data was kept",) + # It is resolved as far as recording goes: nothing is pending and the next take records. + assert service.pending_episodes() == () and service.snapshot().phase is RecordingPhase.IDLE + assert (await record(service)).disposition is Disposition.KEPT + with pytest.raises(StateError, match="rejected by the integrity check, so it cannot be recovered"): + await service.recover_episode(rejected.episode_id) + before = tree(root) + discarded = await service.discard_pending(rejected.episode_id) + assert discarded.disposition is Disposition.DISCARDED and discarded.pending_path is None + removed, added, modified = changed(before, tree(root)) + assert removed and all(path.startswith(f"{session.session_id}/episode_1.pending/") for path in removed) + assert added == set() and modified == {f"{session.session_id}/.recording/episode_1.json"} + assert service.retained_rejections() == () + manifest = read_manifest(session.session_path / ".recording" / "episode_1.json") + # The record still says why it was rejected, and now that its data is gone. + assert (manifest.storage_phase, manifest.quality["outcome"]) == ("DISCARDED", "FAILED") + + +async def test_a_recorder_that_reopens_the_session_can_still_remove_a_rejected_takes_data(tmp_path, own): + root = tmp_path / "out" + service = RecordingService(_config(root)) + session = await service.open_session() + rejected = await record(service, NO_CAMERA) + await service.close() + reopened = own(RecordingService(_config(root))) + await reopened.open_session(session.session_id) + assert [p.episode_id for p in reopened.retained_rejections()] == [rejected.episode_id] + assert reopened.pending_episodes() == () + assert (await reopened.discard_pending(rejected.episode_id)).disposition is Disposition.DISCARDED + assert not (session.session_path / "episode_0.pending").exists() + + +async def test_a_discard_of_a_rejected_take_that_fails_part_way_keeps_it_listed_and_still_blocks_nothing( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + session = await service.open_session() + rejected = await record(service, NO_CAMERA) + with monkeypatch.context() as patched: + patched.setattr( + episode_layout.shutil, "rmtree", lambda *a, **k: (_ for _ in ()).throw(OSError("device error")) + ) + failed = await service.discard_pending(rejected.episode_id) + assert failed.disposition is Disposition.RECOVERY_REQUIRED + (listed,) = service.retained_rejections() + assert listed.discard_requested and listed.storage_phase == "REJECTED" + assert listed.issues[-1] == "a discard of this take was started and did not finish" + assert service.pending_episodes() == () + assert (await record(service)).disposition is Disposition.KEPT # still blocks nothing + assert (await service.discard_pending(rejected.episode_id)).disposition is Disposition.DISCARDED + assert not (session.session_path / "episode_0.pending").exists() and service.retained_rejections() == () + + +# --- the recorder watches its own beat ---------------------------------------------------------- + + +@pytest.fixture +def short_watch(monkeypatch, fast_beat): + """A beat every 20 ms, and a holder that counts its beat as missing after 300 ms without one.""" + monkeypatch.setattr(episode_layout, "BEAT_WATCH_SECONDS", 0.3) + + +async def _until(condition, seconds: float = 5.0) -> None: + """Wait for ``condition`` without stopping the recorder's event loop.""" + deadline = time.monotonic() + seconds + while not condition(): + assert time.monotonic() < deadline, "the condition never came true" + await asyncio.sleep(0.005) + + +BEAT_ISSUE = "the session's beat has not been written for" + + +async def test_a_beat_made_to_fail_is_kept_trying_and_the_recorder_says_its_session_looks_closed( + tmp_path, own, monkeypatch, short_watch, caplog +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + session = await service.open_session() + assert service.beat_silence() is None and not any(BEAT_ISSUE in issue for issue in service.snapshot().issues) + real_beat, broken = episode_layout.SessionLock.beat, threading.Event() + + def beat(lock): + if broken.is_set(): + raise ValueError("nothing a beat expects") # not an operating-system error + real_beat(lock) + + monkeypatch.setattr(episode_layout.SessionLock, "beat", beat) + broken.set() + with caplog.at_level(logging.ERROR, logger="isaaccapture.egocap.episode_layout"): + await _until(lambda: service.beat_silence() is not None) + assert len([r for r in caplog.records if "beat could not be written" in r.getMessage()]) == 1 + (issue,) = [issue for issue in service.snapshot().issues if BEAT_ISSUE in issue] + assert issue.endswith("another recorder may take this session for one nobody has open") + # What the reviewer showed: with no beat, a reader the lock does not reach takes the session for closed. + stopped_at = session_beat(session.session_path) + await asyncio.sleep(0.1) + assert session_beat(session.session_path) == stopped_at + # A take recorded meanwhile is kept, and its record and result say what happened during it. + result = await record(service) + assert result.disposition is Disposition.KEPT and impl.BEAT_STOPPED_NOTE in result.issues + assert impl.BEAT_STOPPED_NOTE in read_manifest(session.session_path / ".recording" / "episode_0.json").issues + # The thread that beats never ended: once the failure is gone the beat is back, and nothing more is said. + broken.clear() + await _until(lambda: service.beat_silence() is None) + assert session_beat(session.session_path) != stopped_at + assert not any(BEAT_ISSUE in issue for issue in service.snapshot().issues) + # A take that begins after the beat is back has nothing to say about it. + assert (await record(service)).issues == () + + +async def test_a_beat_that_hangs_is_known_while_it_hangs_and_noted_on_the_take_it_spanned( + tmp_path, own, monkeypatch, short_watch +): + """A stalled disk: one beat's write does not return. The recorder records on, and knows.""" + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + session = await service.open_session() + assert (await record(service)).issues == () + real_utime, hanging, let_go = os.utime, threading.Event(), threading.Event() + + def utime(target, *args, **kwargs): + if not let_go.is_set(): + hanging.set() + let_go.wait(5.0) + return real_utime(target, *args, **kwargs) + + episode = await service.start_episode("t", "op") + monkeypatch.setattr(episode_layout.os, "utime", utime) + await _until(hanging.is_set) + await submit_all(service, episode.episode_id, take_samples(seconds=1.0)) + await _until(lambda: service.beat_silence() is not None) + assert any(BEAT_ISSUE in issue for issue in service.snapshot().issues) + # The write returns before Stop: the beat is healthy again, and the take still carries what happened. + let_go.set() + await _until(lambda: service.beat_silence() is None) + result = await service.stop_episode(episode.episode_id) + assert result.disposition is Disposition.KEPT and result.issues == (impl.BEAT_STOPPED_NOTE,) + assert read_manifest(session.session_path / ".recording" / "episode_1.json").issues == [impl.BEAT_STOPPED_NOTE] + assert (await record(service)).issues == () + + +async def test_a_take_that_is_interrupted_while_the_beat_is_missing_carries_both_notes( + tmp_path, own, monkeypatch, short_watch +): + service = own(RecordingService(_config(tmp_path / "out"))) + await service.open_session() + monkeypatch.setattr(episode_layout.SessionLock, "beat", lambda lock: (_ for _ in ()).throw(KeyError("x"))) + episode = await service.start_episode("t", "op") + await _until(lambda: service.beat_silence() is not None) + result = await service.interrupt_episode(episode.episode_id, "the capture pipeline stopped") + assert result.issues[-2:] == (impl.BEAT_STOPPED_NOTE, "the capture pipeline stopped") + + +def test_with_no_session_open_there_is_no_beat_to_miss(tmp_path): + service = RecordingService(_config(tmp_path / "out")) + assert service.beat_silence() is None and service.snapshot().issues == () + + +# --- what the recorder notes about the disk, and about a discard it refused ------------------- + + +@pytest.mark.parametrize( + ("number", "word"), + [ + (errno.ENOSPC, "full"), + (errno.EDQUOT, "quota"), + (errno.EROFS, "read-only"), + (errno.EACCES, "denied"), + (errno.EPERM, "denied"), + ], +) +def test_what_the_disk_refused_is_decided_from_the_error_number_of_a_failure_under_the_output( + tmp_path, number, word +): + root = tmp_path / "out" + inside = str(root / "session_1" / ".recording" / "episode_0.json") + assert storage_problem(OSError(number, "whatever the system says", inside), root) == word + # A rename that fails names two files; either one under the output is the output's failure. + moved = OSError(number, "x", str(tmp_path / "elsewhere"), None, inside) + assert moved.filename2 == inside and storage_problem(moved, root) == word + # Also when another failure was raised from it. + try: + try: + raise OSError(number, "x", inside) + except OSError as cause: + raise RuntimeError("could not finish") from cause + except RuntimeError as wrapped: + assert storage_problem(wrapped, root) == word + # The output itself counts, and it is found through a link to it. + assert storage_problem(OSError(number, "x", str(root)), root) == word + root.mkdir() + (tmp_path / "link").symlink_to(root, target_is_directory=True) + assert storage_problem(OSError(number, "x", str(tmp_path / "link" / "session_1")), root) == word + + +@pytest.mark.parametrize("number", [errno.ENOSPC, errno.EDQUOT, errno.EROFS, errno.EACCES, errno.EPERM]) +def test_a_failure_elsewhere_or_one_that_names_no_file_is_not_put_on_the_recordings_disk(tmp_path, number): + root = tmp_path / "out" + # A calibration file, an encoder program, a temporary directory: full or forbidden, and not the output. + for elsewhere in (tmp_path / "calibration" / "head.json", tmp_path / "bin" / "ffmpeg", tmp_path / "outside"): + assert storage_problem(OSError(number, "x", str(elsewhere)), root) is None + # A name that only begins like the output's is another directory. + assert storage_problem(OSError(number, "x", str(tmp_path / "out_of_it" / "file")), root) is None + # No file name: signalling a process, a socket, anything; nothing says it was the recordings disk. + assert storage_problem(OSError(number, "x"), root) is None + assert storage_problem(OSError(number, "x", 7), root) is None # a descriptor is not a name + # An error that was only being handled when another failure was raised is not that failure's cause. + try: + try: + raise OSError(number, "x", str(root / "session_1")) + except OSError: + raise RuntimeError("the capture source went away") # noqa: B904 - the point: no cause is given + except RuntimeError as unrelated: + assert unrelated.__context__ is not None and storage_problem(unrelated, root) is None + + +def test_a_failure_that_only_says_the_disk_is_full_is_not_taken_for_one(tmp_path): + inside = str(tmp_path / "session_1") + assert storage_problem(OSError(errno.EIO, "No space left on device", inside), tmp_path) is None + assert storage_problem(RuntimeError("[Errno 28] No space left on device"), tmp_path) is None + assert storage_problem(OSError("no number at all"), tmp_path) is None + assert storage_problem(None, tmp_path) is None + + +async def test_a_take_that_cannot_be_finished_because_the_disk_is_full_says_so_in_its_note( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + await service.open_session() + full = OSError(errno.ENOSPC, "No space left on device", str(root / "anywhere")) + with monkeypatch.context() as patched: + patched.setattr(impl, "finalize_episode_dir", lambda *_: (_ for _ in ()).throw(full)) + result = await record(service) + assert result.disposition is Disposition.RECOVERY_REQUIRED + # The recorder's own word comes right after the kind of note, before anything the system said. + assert result.issues[-1].startswith("checked step failed [storage: full]: ") + assert (await service.recover_episode(result.episode_id)).disposition is Disposition.KEPT + + +async def test_a_write_that_fails_during_a_take_is_noted_beside_the_reason_the_take_was_interrupted_for( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + await service.open_session() + + def no_room(*_args, **_kwargs): + # As the system raises it when a write finds the disk full: with no file name. + raise OSError(errno.ENOSPC, "No space left on device") + + # Rows are written every few samples here, so that the write fails while the take is recorded. + monkeypatch.setattr(episode_store, "FLUSH_ROWS", 4) + episode = await service.start_episode("t", "op") + monkeypatch.setattr(zarr.Array, "append", no_room) + for sample in take_samples(seconds=0.5): + try: + service.submit_sample(episode.episode_id, sample) + except StateError: + break # the recorder stopped admitting samples once the write failed + await asyncio.sleep(0) + result = await service.interrupt_episode(episode.episode_id, "recording pipeline failed during recording: x") + assert result.disposition is Disposition.RECOVERY_REQUIRED + manifest = read_manifest(service.snapshot().session.session_path / ".recording" / "episode_0.json") + assert manifest.issues[0].startswith("write failed [storage: full]: ") + assert manifest.issues[-1] == "recording pipeline failed during recording: x" + + +async def test_a_record_that_cannot_be_written_for_lack_of_room_is_put_on_the_recordings_disk( + tmp_path, own, monkeypatch +): + """A full disk as the system reports it at a sync: no file name. The recorder knows which file it wrote.""" + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + await service.open_session() + real_fsync = os.fsync + + def no_room(*_args, **_kwargs): + raise OSError(errno.ENOSPC, "No space left on device") + + with monkeypatch.context() as patched: + patched.setattr(episode_layout.os, "fsync", no_room) + with pytest.raises(OSError) as raised: + await service.start_episode("t", "op") + assert os.fsync is real_fsync + # The take's first record was the file: the failure is the caller's to report, and it says which disk. + assert Path(raised.value.filename).name == "episode_0.json" and storage_problem(raised.value, root) == "full" + # Nothing was left half started, and with room again the session records. + assert service.pending_episodes() == () and (await record(service)).disposition is Disposition.KEPT + + +@pytest.mark.parametrize( + ("number", "where"), + [ + (errno.EACCES, "calibration/head_camera_intrinsics.json"), + (errno.EACCES, "bin/ffmpeg"), + (errno.ENOSPC, "scratch/file"), + (errno.EPERM, None), + ], + ids=["a calibration file", "an encoder program", "a temporary directory", "no file at all"], +) +async def test_a_take_that_fails_on_something_outside_the_output_says_nothing_about_the_recordings_disk( + tmp_path, own, monkeypatch, number, where +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + await service.open_session() + named = () if where is None else (str(tmp_path / where),) + failure = OSError(number, "whatever the system says", *named) + with monkeypatch.context() as patched: + patched.setattr(impl, "finalize_episode_dir", lambda *_: (_ for _ in ()).throw(failure)) + result = await record(service) + assert result.disposition is Disposition.RECOVERY_REQUIRED + assert result.issues[-1].startswith("checked step failed: ") and "[storage" not in " ".join(result.issues) + assert (await service.recover_episode(result.episode_id)).disposition is Disposition.KEPT + + +async def test_a_discard_of_a_take_already_in_its_final_place_is_noted_as_refused_not_as_failed( + tmp_path, own, monkeypatch +): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + await service.open_session() + real_write = impl.write_manifest + + def fail_the_last_checkpoint(session_path, manifest): + if manifest.storage_phase == "FINALIZED": + raise OSError("disk full") + real_write(session_path, manifest) + + monkeypatch.setattr(impl, "write_manifest", fail_the_last_checkpoint) + result = await record(service) + monkeypatch.setattr(impl, "write_manifest", real_write) + refused = await service.discard_pending(result.episode_id) + assert refused.disposition is Disposition.RECOVERY_REQUIRED + assert refused.issues[-1] == "discard refused: the take is already in its final place; recover it to finish" + assert (await service.recover_episode(result.episode_id)).disposition is Disposition.KEPT + + +async def test_a_discard_of_a_directory_that_is_not_the_takes_own_is_noted_as_refused(tmp_path, own): + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + session = await service.open_session() + interrupted = await _interrupted_take(service) + # Its ownership stamp is replaced by another take's: the directory is not this take's to delete. + stamp = session.session_path / "episode_0.pending" / "zarr.json" + stamp.write_text(stamp.read_text().replace(interrupted.episode_id, f"{session.session_id}/episode_9")) + before = tree(root) + refused = await service.discard_pending(interrupted.episode_id) + assert refused.disposition is Disposition.RECOVERY_REQUIRED + assert refused.issues[-1] == "discard refused: the directory under the take's name is not the take's own" + removed, added, _modified = changed(before, tree(root)) + assert removed == set() and added == set() + # Put right by hand, the same take is discarded. + stamp.write_text(stamp.read_text().replace(f"{session.session_id}/episode_9", interrupted.episode_id)) + assert (await service.discard_pending(interrupted.episode_id)).disposition is Disposition.DISCARDED + + +async def test_a_discard_clears_the_claim_an_interrupted_quarantine_left_in_the_sidecar( + tmp_path, own, monkeypatch +): + """Stopped while the quarantine folder was being built, then discarded instead of recovered.""" + root = tmp_path / "out" + service = own(RecordingService(_config(root))) + session = await service.open_session() + real_rename = os.rename + + def stop_before_the_folder_is_put_in_place(source, target, *args, **kwargs): + if Path(source).name == "quarantine_claim": + raise OSError(errno.EIO, "input/output error") + return real_rename(source, target, *args, **kwargs) + + with monkeypatch.context() as patched: + patched.setattr(os, "rename", stop_before_the_folder_is_put_in_place) + # The claim's own tidying does nothing, as if the recorder had died before it. + patched.setattr(route, "shutil", SimpleNamespace(rmtree=lambda *a, **k: None)) + result = await record(service, take_samples(frozen=True)) + assert result.disposition is Disposition.RECOVERY_REQUIRED + staging = session.session_path / ".recording" / "quarantine_claim" + assert (staging / "zarr.json").is_file() + before = tree(root) + assert (await service.discard_pending(result.episode_id)).disposition is Disposition.DISCARDED + assert not staging.exists() + removed, added, modified = changed(before, tree(root)) + own_files = (f"{session.session_id}/episode_0.pending/", f"{session.session_id}/.recording/quarantine_claim/") + assert removed and all(path.startswith(own_files) for path in removed) and added == set() + assert modified == {f"{session.session_id}/.recording/episode_0.json"}