From b757acba1e81db542a0748b5ccd321f18744c7da Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Fri, 27 Nov 2026 13:21:05 -0800 Subject: [PATCH 1/2] egocap: required devices, studio correction in place, calibration provenance and a live check Start of day - A station can require its tracking devices: headset, each controller, each glove. A required device that is not delivering data fails its setup item and holds recording, with the reason. A station that requires nothing behaves as before, and a requirement the software does not know fails closed. While the saved stations file cannot be read, recording is held until it is replaced from the Station tab. - A camera that arrives over LiveKit passes its setup item only while an operator's page reports frames arriving in its preview; otherwise it warns. A page's word never holds a take. End of day - A session's studio can be corrected in place: the label is rewritten in every finalized take, the session's own record and the time-aligned copy, and the files stay where they are. The day's report and counts read the corrected label. - A correction of either label checks every file before its first write and puts back what it wrote if a later write fails. It takes the recorder's own session lock, and is refused while a take whose filing depends on the labels is not settled. Calibration - Each calibration file states what produced it, the grade and rule it was installed under, and what it replaced. Files without these keys read as before; a file in a newer layout is refused by every reader, the time-aligner included, and such a take is aligned once the software can read it. - The headset tool can check the installed head calibration live, without solving or recording: with the board still and the head moving it reports the error in pixels and grades the camera offset and lag the views imply, once the head has turned about two axes. For a camera that arrives over LiveKit the backend joins the video room for the length of the check only. - Before a calibration take, a note says when the camera's picture size differs from the installed lens file's. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/AGENTS.md | 13 + examples/egocap/CALIBRATION_TOOLS.md | 288 +++++- examples/egocap/DESIGN.md | 60 +- examples/egocap/LIVEKIT_PREVIEW.md | 81 +- examples/egocap/backend/README.md | 196 +++- examples/egocap/backend/egocap_web/app.py | 32 +- .../egocap/backend/egocap_web/auto_align.py | 11 +- .../backend/egocap_web/calibration_check.py | 503 ++++++++++ .../egocap_web/calibration_check_pictures.py | 289 ++++++ .../backend/egocap_web/calibration_common.py | 9 +- .../backend/egocap_web/calibration_frames.py | 42 +- .../backend/egocap_web/calibration_routes.py | 47 +- .../backend/egocap_web/calibration_service.py | 90 +- .../backend/egocap_web/capture_status.py | 20 + .../backend/egocap_web/day_report_routes.py | 368 ++++++- .../egocap_web/glove_offset_session.py | 35 +- .../backend/egocap_web/livekit_receiver.py | 41 +- .../backend/egocap_web/livekit_recording.py | 38 +- .../backend/egocap_web/livekit_sightings.py | 92 ++ .../backend/egocap_web/session_locks.py | 31 +- .../egocap/backend/egocap_web/setup_checks.py | 194 +++- .../egocap/backend/egocap_web/setup_routes.py | 29 +- .../backend/egocap_web/setup_service.py | 117 ++- .../backend/egocap_web/station_service.py | 32 +- .../egocap/backend/egocap_web/stations.py | 136 ++- examples/egocap/frontend/README.md | 83 +- examples/egocap/frontend/src/App.tsx | 2 +- .../frontend/src/CalibrationRecorder.test.tsx | 295 +++++- .../frontend/src/CalibrationRecorder.tsx | 233 ++++- .../frontend/src/CameraGrid.livekit.test.tsx | 17 + examples/egocap/frontend/src/CameraGrid.tsx | 8 + .../egocap/frontend/src/DevicesTab.test.tsx | 37 +- examples/egocap/frontend/src/DevicesTab.tsx | 9 +- .../src/HeadsetCalibrationDialog.test.tsx | 99 +- .../frontend/src/HeadsetCalibrationDialog.tsx | 64 +- .../frontend/src/LiveKitCameraTile.test.tsx | 71 +- .../egocap/frontend/src/LiveKitCameraTile.tsx | 34 + .../egocap/frontend/src/StationsCard.test.tsx | 114 ++- examples/egocap/frontend/src/StationsCard.tsx | 112 ++- .../egocap/frontend/src/WrapUpDialog.test.tsx | 234 ++++- examples/egocap/frontend/src/WrapUpDialog.tsx | 151 ++- .../frontend/src/calibrationApi.test.ts | 35 + .../egocap/frontend/src/calibrationApi.ts | 27 + .../frontend/src/calibrationTestDoubles.ts | 69 +- .../egocap/frontend/src/calibrationTypes.ts | 95 ++ .../egocap/frontend/src/dayReportApi.test.ts | 39 +- examples/egocap/frontend/src/dayReportApi.ts | 66 +- .../frontend/src/dayReportTestDoubles.ts | 2 + .../frontend/src/livekitSightings.test.ts | 142 +++ .../egocap/frontend/src/livekitSightings.ts | 79 ++ .../frontend/src/settingsTestDoubles.ts | 8 + .../egocap/frontend/src/setupTestDoubles.ts | 21 +- examples/egocap/frontend/src/stationsApi.ts | 18 + examples/egocap/frontend/src/styles.css | 28 + examples/egocap/recording/README.md | 63 +- .../analytics/count_daily_trajectories.py | 10 +- .../recording/egocap/analytics/day_report.py | 28 +- .../egocap/calibration/camera_pipeline.py | 11 + .../recording/egocap/calibration/files.py | 41 +- .../recording/egocap/calibration/grading.py | 22 +- .../egocap/calibration/live_check.py | 466 +++++++++ .../egocap/calibration/provenance.py | 252 +++++ .../egocap/calibration/station_store.py | 84 +- .../egocap/calibration/wrist_offset.py | 29 +- .../update_episode_task_description.py | 562 +++++++++-- .../egocap/recording/aligned_writer.py | 24 +- .../egocap/recording/episode_layout.py | 54 +- .../recording/egocap/recording/route.py | 22 + .../recording/egocap/studio/session_studio.py | 57 ++ .../recording_service/recording_service.py | 9 +- .../egocap/recording/tools/align_episode.py | 20 +- .../egocap/tests/backend/test_app_stations.py | 28 + .../egocap/tests/backend/test_auto_align.py | 65 ++ .../tests/backend/test_calibration_check.py | 527 ++++++++++ .../backend/test_calibration_check_room.py | 808 +++++++++++++++ .../tests/backend/test_calibration_frames.py | 48 +- .../tests/backend/test_calibration_routes.py | 15 + .../tests/backend/test_calibration_service.py | 224 ++++- .../backend/test_day_report_real_recorder.py | 745 ++++++++++++++ .../tests/backend/test_day_report_routes.py | 613 +++++++++++- .../backend/test_glove_offset_session.py | 39 + .../tests/backend/test_livekit_receiver.py | 19 + .../backend/test_livekit_recording_source.py | 32 + .../tests/backend/test_livekit_sightings.py | 130 +++ .../tests/backend/test_session_locks.py | 68 ++ .../egocap/tests/backend/test_setup_checks.py | 277 +++++- .../egocap/tests/backend/test_setup_routes.py | 280 ++++++ .../tests/backend/test_setup_service.py | 477 ++++++++- .../tests/backend/test_station_routes.py | 50 + .../tests/backend/test_station_service.py | 98 +- .../egocap/tests/backend/test_stations.py | 182 +++- .../recording/unit/test_align_kept_episode.py | 39 + .../recording/unit/test_aligned_camera_lag.py | 36 + .../unit/test_calibration_camera_pipeline.py | 26 +- .../recording/unit/test_calibration_files.py | 74 ++ .../unit/test_calibration_grading.py | 11 + .../unit/test_calibration_live_check.py | 456 +++++++++ .../unit/test_calibration_provenance.py | 319 ++++++ .../unit/test_calibration_station_store.py | 249 ++++- .../unit/test_calibration_wrist_offset.py | 48 + .../unit/test_count_daily_trajectories.py | 15 + .../tests/recording/unit/test_day_report.py | 48 + .../recording/unit/test_episode_store.py | 33 + .../egocap/tests/recording/unit/test_route.py | 52 +- .../recording/unit/test_session_studio.py | 83 ++ .../test_update_episode_task_description.py | 932 +++++++++++++++++- .../tests/tools/test_calibrate_station.py | 29 +- 107 files changed, 13443 insertions(+), 472 deletions(-) create mode 100644 examples/egocap/backend/egocap_web/calibration_check.py create mode 100644 examples/egocap/backend/egocap_web/calibration_check_pictures.py create mode 100644 examples/egocap/backend/egocap_web/livekit_sightings.py create mode 100644 examples/egocap/frontend/src/livekitSightings.test.ts create mode 100644 examples/egocap/frontend/src/livekitSightings.ts create mode 100644 examples/egocap/recording/egocap/calibration/live_check.py create mode 100644 examples/egocap/recording/egocap/calibration/provenance.py create mode 100644 examples/egocap/recording/egocap/studio/session_studio.py create mode 100644 examples/egocap/tests/backend/test_calibration_check.py create mode 100644 examples/egocap/tests/backend/test_calibration_check_room.py create mode 100644 examples/egocap/tests/backend/test_day_report_real_recorder.py create mode 100644 examples/egocap/tests/backend/test_livekit_sightings.py create mode 100644 examples/egocap/tests/backend/test_session_locks.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_live_check.py create mode 100644 examples/egocap/tests/recording/unit/test_calibration_provenance.py create mode 100644 examples/egocap/tests/recording/unit/test_session_studio.py diff --git a/examples/egocap/AGENTS.md b/examples/egocap/AGENTS.md index 59cae280d2..8096f42591 100644 --- a/examples/egocap/AGENTS.md +++ b/examples/egocap/AGENTS.md @@ -86,3 +86,16 @@ before any file is written. An existing derived episode is refused, never replac rewriting `config.yaml`, and never record into a session that has none. - Work that must survive a cancelled caller (notifying the aligner of a kept episode, for one) runs inside the owned operation task, not after the awaited result. +- A label of a recorded session (task, studio) is not corrected while the session holds a take that is still to + be filed by, or into, what is being corrected: an unsettled take with a studio in its manifest and no + assignment yet, or one whose assignment names the group being corrected. The recorder files a kept take by the + labels its manifest froze. Never loosen `assign_output`'s check, and never write a manifest from a correction. + A correction holds the recorder's own session lock for its checks and its writes, and one that really changes + a routed group's studio or whole task drops the session's route to the group. +- A correction of a session's studio or task that answers with a failure leaves the labels as they were, or + names the ones it could not put back, and says so from what the disk holds. +- A required device is judged on whether it delivers its data, from the capture session's own reason for its + state; a degraded reason nobody has read yet holds recording. +- Leaving the video room is guarded on every way out: the room is left in a `finally`, and what the leave raises + is logged and fails neither a take nor a shutdown. +- Read a session's studio through `egocap.studio.session_studio`, not from the name of its folder. diff --git a/examples/egocap/CALIBRATION_TOOLS.md b/examples/egocap/CALIBRATION_TOOLS.md index 94f4baa51a..62d8a2e088 100644 --- a/examples/egocap/CALIBRATION_TOOLS.md +++ b/examples/egocap/CALIBRATION_TOOLS.md @@ -73,6 +73,63 @@ calibrate again* (or the same of `wrist_calibration_offsets.json`): A lens file is not asked for the stamp: a lens is the same whatever tracks the headset. +**What each file states of how it came to be.** Beside the keys above, every file these tools write carries two +more, and no key it had before was renamed, removed or given another value (`wrist_calibration_offsets.json` +included). The files are written with their keys sorted, so the two take their alphabetical places among the +others; a reader finds every key by its name: + +```json +"schema_version": 1, +"provenance": { + "producer": {"software": "egocap", "version": "0.1.0", "tool": "camera_calibration"}, + "grade": "excellent", + "install_rule": "Intrinsics are installed only when excellent.", + "validity": { + "valid_from": "2026-01-02T09:15:07+00:00", + "supersedes": {"sha256": "", "calibrated_at": "2026-01-01T08:00:00+00:00"} + } +} +``` + +- `schema_version` is the layout of the file. It is raised when a key a reader depends on changes its meaning or + goes, never for an added key. A file that states a layout newer than the software reads is refused by every + reader, by name: *head_camera_intrinsics.json is written in layout 2, and this software reads up to layout 1: + update the software, or calibrate again with this one*. A file that states none is read as it always was. A + layout is read however it is written: a whole number, a float with a whole value, either of them as text, + with a sign, leading zeros, a fraction of zero or an exponent (`"2"`, `2.0`, `"2.0"`, `"2e0"`). A number of any + length is refused in the same sentence, as *a layout far newer than any this software knows*, and never + fails a reader. The refusal shows wherever the file is looked at: the start-of-day calibration item and the file's + row in the calibration overview say the sentence, the glove tool shows it in its band of warnings before any + click and starts from zero, and the time aligner refuses the take (see "Camera lag in aligned takes"). +- `producer` is what solved the file: the software, its installed version, and the solver (`camera_calibration` + for a lens or the head camera's position, `wrist_offset_fit` for the wrist offsets). +- `grade` and `install_rule` are the solve's grade and the rule it is held to, in the words the result page uses + (see "Grades"). They are in the review copy of a solve under `runs/` as well, installed or not. The wrist + offsets are not graded, so their `grade` is `null`; their rule is the one the tool enforces, and `evidence` + holds what it was held against: per hand the fit's `rms_px`, `clicks`, `frames` and `at_translation_limit`, + or `null` for a hand that kept the offset the station already had. The block is a closed set whatever calls + the library: a solver or a grade it does not know is refused, the rule is one line of at most 300 characters, + `evidence` keeps only the two hands and these four figures, and a figure that is not a finite number is + written as `null`. +- `validity` is written by the install: `valid_from` is the moment the file became the station's calibration, + the same moment the ledger notes, and one moment for every file of one install (the lens and the position of + a headset calibration say the same time). `supersedes` names the file it replaced by the SHA-256 of its bytes + and, where that file said so in a form that reads as a date and time, when it was made, carried as that date + in ISO form and never as the text was written; any other text there is not carried. It is `null` when the install replaced no file, and holds `null` for both when a file was + there and could not be read. An installed file is never rewritten, since sessions hold its hash; it stands + until the next file installed under its name, which names it here. Installing a record that is the installed + one, apart from its validity, leaves the file as it is, byte for byte, and only notes the ledger: the file + does not supersede itself, and what was prepared against it stays valid. The ledger's note lists such a file + under `unchanged`, Set up says of it *... was already installed, and installing it again changed nothing*, + and a note of nothing but unchanged files is not a calibration done that day. +- A file's history can be followed back from any copy through `history/`, as far as the tools installed each + file. One copied back from `history/` by hand still states the validity it had, so the files that stood + between it and its return are in the archive and in no file's chain. + +Nothing in these keys names the machine: no host, no account and no path. The operator who installed a file is in +the ledger, not in the file, which is copied into every session. A file placed by hand, or made by another tool, +has none of these keys until it is replaced; installed through the tools as it is, it gains `validity` only. + Beside them the tools keep: - `history//`: the archive. Every file installed is copied here as `_` before it goes @@ -224,6 +281,18 @@ loses its position"). The lens model (see "Lens models") is offered whenever intrinsics are solved. For a camera whose video is being corrected in this run the choices that solve its lens are held (see "A camera whose video is being corrected"). + **A changed picture size is said here, before anything is recorded.** When the capture session says the camera + sends another size of picture than its installed lens file was solved at, the step shows *Picture size changed:* + and what that means for the take chosen: for a take that solves the lens, *head_camera_intrinsics.json was + solved on a 640x480 picture, and this camera now sends 1280x960. A solve from this take replaces it with one for + the new size: if the size changed by mistake, set the camera's picture mode back before recording*; for a take + of the position alone, that the position *cannot be solved against it*, with the same two ways out. It tells + and holds nothing: the take can be recorded. Nothing is said when the size is the file's, when the session + states no size for the camera, when the file was solved for another camera (which its row says), or for a + camera whose video is being corrected, whose picture has the size its rectification gave it. The size is the + one the session declares for the camera, which is the size a take records; a frame of another size is refused + by the recorder. + Check the board's numbers against the print. The step lists the installed files, each with when it was calibrated and its headline figure, and under them a line for each kind of calibration the ledger holds, such as *Head camera calibration: last installed by* the operator *on* the day and time. @@ -265,6 +334,162 @@ loses its position"). is shown instead.*, or, when the solve changed while the install was on its way, that the files are from the solve shown now, or that they are from the solve that was shown and nothing is installed from the newer one. +### Checking the installed calibration live + +Set up has a card, *Check the installed calibration*, that answers one question without solving anything: do the +head camera's installed lens file and position still predict where a board appears as the head moves? It reads +`head_camera_intrinsics.json` and `head_camera_extrinsics.json` once, when it starts, and writes nothing: no +take, no file, no ledger entry, no note of the board. The page says so before and while it runs. + +It works for a head camera the capture server delivers and for one that arrives over LiveKit, which is how the +head camera the launcher bridges arrives. The backend has no picture of a LiveKit camera outside a take, so for +the time such a check runs, and only then, the backend joins the video room as a viewer of that one camera's +track; see "A head camera that arrives over LiveKit" below. The card says so before the check is started. + +1. Fix the board where it cannot move, describe it in the Board card, and press *Start check*. Keep the board in + view and hold your head still: the first five good views fix where the board stands in the world, each one + the board's pose in the camera through the installed lens, carried to the world through the installed camera + position and the head pose. The view in the middle of the five is taken. A picture taken while the head moves + (its motion carries the board's place faster than 5 cm a second) is not one of the five, and the card says + *Hold your head still for a moment, with the board in view: the check is fixing where the board stands*: such a + picture would put the place off by the head's speed times any error in the camera's lag. +2. Move your head slowly: turn, nod, tilt, step aside. For each picture the head pose alone now says where the + board's corners should be. The picture shows a dot on each corner seen and a ring where it was predicted, with + a line between the two, and the card shows the distance in pixels for this picture, over the check, and at its + largest. These pixels are shown from the first picture on, whether or not there is a verdict. +3. The card gives a verdict, *Excellent*, *Acceptable* or *Needs repeating*, once the views can carry one: ten + views with the head at least five degrees or five centimeters from where the place was fixed, a turn of at + least fifteen degrees in one of them, and a head that has turned about a second axis as well (the rule a solve + has for its own views). Go on moving to keep watching it, or press *Stop check*. + +**What the verdict grades.** The board never moved, so where it seems to stand from view to view is explained as +far as it can be, and each part is held against the solve's own limit for it (see "Grades"); the worst decides. + +| Figure on the card | What it is | Excellent under | Needs repeating over | +| --- | --- | --- | --- | +| *Board appears to move* | How far the board's place wanders over the counted views. | 5 mm | 10 mm | +| *Board pose fits the picture to* | How well each picture's own board pose fits its corners. | 1 px | 2 px | +| *Camera appears to sit off by* | The camera offset on the headset that explains the wander best: a camera that sits elsewhere than the file says carries the board's place round with the head's turning. Held against the limits of a solved position's uncertainty. | 5 mm | 10 mm | +| *Camera lag appears off by* | The error in the stored camera lag that explains the wander best: pictures older or newer than the file says carry the board's place along with the head's motion. Held against the step a solve searches the lag in. | 10 ms | 20 ms | + +The offset and the lag are found together, by least squares, with how closely the views pin each. A camera +position one centimeter off is therefore never *Excellent*, whichever way it is off, and neither is a lag that is +30 ms off, even with a head that moves slowly; the pixels alone show both, and the wander alone showed neither. +Three things follow from what the views can and cannot show: + +- **One axis is not enough.** A camera's offset along an axis shows only in turns about the other two. Until the + head has turned about a second axis the card says *No verdict yet: your head has turned about one axis only, so + the camera's place along that axis is not tested*, and the lead says *Nod and tilt your head as well as turning + it, keeping the board in view. The board must not move.* There is no verdict then, however large the error. +- **The offset is graded once the views pin it**: to within half its excellent limit, or when it lies beyond that + limit by more than twice what the views leave open. Until then, unless the wander or the fit is already bad, + the card says *No verdict yet: the views so far do not pin the camera's place closely enough to grade it.* +- **A lag shows only while the head moves.** It is graded on the same terms. A verdict from pictures that cannot + tell a lag from their own noise (a head that was still in every picture counted, or very few views) is given + with the line *The camera's lag is not tested yet: it shows only in pictures taken while your head moves. Keep + moving slowly with the board in view to test it.* + +The error in pixels is of everything between the board and the prediction: the lens file, the camera position, the +head tracking and the pairing of each picture with a head pose. A picture's head pose is the one at the picture's +own time, found between the two tracking samples either side of it after the camera's stored lag +(`camera_latency_s`) is taken off; the newest pose is later than the picture, and a turning head is elsewhere by +then. Pictures and tracking arrive on their own schedules, so a picture can be here before the tracking sample +after it: such a picture waits, up to half a second, until the tracking has reached its time, and is judged then. +Only when the tracking stays away for that long does the check say that head tracking is not arriving. + +The check says when it cannot judge, and what to do: + +| It says | When | +| --- | --- | +| *The board is not found in the picture: point the camera at it, and move slowly.* | No board in this picture. | +| *Too little of the board is readable in this picture: show more of it.* | Fewer than eight corners, or corners along one line. | +| *Head tracking is not arriving: check the headset is on and tracked.* | No head pose at the picture's time: none arrived, or the tracking has a hole of more than 0.1 s there. | +| *The headset has lost its position: look around the room until it finds it again. The check starts over from where the board stands then.* | The reader of the head track that the solve uses says the position is lost. The check also starts over when the position leaps, and again when it leaps back: the board's place is held to the stretch of tracking it was fixed in. | +| *Hold your head still for a moment, with the board in view: the check is fixing where the board stands.* | The head was moving in a picture the board's place would have been fixed from. | +| *Nothing to judge: there is no live picture from this camera.* | The camera stopped sending. | +| *Nothing to judge: this camera sends a 1280x720 picture, and the installed calibration is for 640x480, so it cannot be checked on this picture: set the camera's picture mode back, or calibrate again.* | The camera was started in another picture mode than the installed lens file was solved on (the sizes are the ones found). A camera matrix does not fit a picture of another size, and a verdict from it would blame the calibration for the mode. Set up says the same of a take under *Picture size changed*. | + +and it is refused at the start, with the reason, when the calibration cannot be judged at all: + +- a head camera file is missing, unreadable, was solved for another camera, or its position was made with another + tracking source (*calibrate the headset first: ...*); +- a camera the capture server delivers has sent no picture (*there is no live picture from this camera*); +- a take is being recorded, or a recording command is under way (*a take is being recorded, and the check never + runs beside one: finish or discard the take first*). A take that was interrupted and waits to be recovered or + discarded is not being recorded, so a check is allowed beside it: the check writes nothing and holds nothing + a recovery needs; +- the launcher's report of the run could not be read, so it is not known whether the camera's pictures are + corrected and which camera matrix they are pictures of. + +#### A head camera that arrives over LiveKit + +The check gets such a camera's video the way a take does, through the recorder's own code: it joins the room +with a viewer's token, subscribes to that one camera's track, checks the first frame against the size the +session declares, and waits for the clock mapping the publisher's clock-sync replies give. Each picture's time +is the publisher's timestamp placed on this computer's clock through that mapping, exactly as a take records it, +and that clock is the one the head poses are stamped on (which is why the capture server must run on this +computer, as for recording). The camera's stored lag then comes off it, as for any camera. If this run corrects +the camera's video, the corrected camera's matrix is used, as above. Nothing is recorded and no file is written. + +While it joins, the check says what it waits for: + +| It says | When | +| --- | --- | +| *Joining the video room to see this camera.* | The room has not answered yet. | +| *In the video room: waiting for this camera's first picture.* | Joined; the camera's track has sent no frame yet. | +| *Pictures are arriving: waiting for the camera sender's clock to be matched to this computer's, so that each picture's time can be placed among the head poses.* | Frames arrive, and the publisher has not yet answered a clock exchange well enough. No picture is judged by its arrival time meanwhile. | + +A room that cannot be used says so in words, and the backend does not stay in it. The way in has three stages +and one fixed sentence for each; what the video library or the video server itself said can hold anything, so +it goes to the backend's log and never to the page: + +| It says, after *Nothing to judge:* | The stage that ended | +| --- | --- | +| *the video room could not be joined, so the check has no picture of this camera: check that the video server is running and that this computer reaches it, then start the check again* | The join: the room cannot be reached, refuses the token, or does not answer within 15 seconds. | +| *the video room was joined, and this camera's first picture did not come as a take needs it, so the check has no picture of it: check the camera's sender, then start the check again* | The first picture: none within 10 seconds, or one of another size than the session declares. | +| *this camera's pictures arrive, and the camera sender's clock could not be matched to this computer's, so their times cannot be placed among the head poses: check the camera's sender, then start the check again* | The clock mapping: the publisher did not answer clock-sync requests well enough. | +| *the video room was left before this camera's pictures came, so the check has no picture of it: start the check again* | The way in was given up from outside before it ended. | + +Once the pictures flow, video that stops says *Nothing to judge: the check gets this camera's video the way a take +does, and could not: ...*, followed by the recorder's own sentence, composed in this project, since what stops +the one stops the other: the track was lost, went silent for five seconds, or sent a frame without the +publisher's timestamp. A camera whose timestamps are not on the publisher's monotonic clock, whose size or rate +the streams file does not state, or whose tracking comes from another computer is refused before the room is +joined, with the same lead. After any of these the status no longer says the backend is in the room. + +The backend is in the room only between the start of the check and its end. It leaves: + +- when the check is stopped, or the tool moves on from Set up (the page stops it); +- when no page has asked about the check for 20 seconds: the page asks a few times a second, so that long a + silence is a page that was closed or lost its connection. A page that asks again is told *the check ended + because the page that started it stopped asking about it*. A browser that slows the timers of a hidden tab can + cause this; start the check again. The glove calibration's lease is the same length. A check of a camera the + capture server delivers holds nothing between two polls and has no lease; +- when a take starts, from this page or any other: the check ends before the recorder joins the room, and a page + still asking is told *the check ended because a take started: the two never run together*. This holds for a + check of any camera; +- when a check is started again, which leaves the room before it joins it again; +- when the camera's video fails in the room, with the reason; +- when the check has run for ten minutes, its longest, whoever keeps asking: a page that asks again is told *the + check ended after ten minutes, its longest: start it again to go on checking*. This holds for a check of any + camera, so that a tab left open keeps the backend neither in the room nor at work; +- when the backend shuts down. + +Leaving is guarded on every one of these ways. Whatever a step of the leave raises, the room is still left (the +receiver disconnects, and the source is stopped, in a `finally`), the failure goes to the log, and neither a +take, a stop from the page nor a shutdown is failed by it. A take does not wait long either: the check is over +at once, the room is given 1.5 seconds to answer the check's leave and the take at most 2 seconds in all, and a +leave that is slower finishes behind the take, which joins under an identity of its own. While no picture is +judged (the camera stopped, the board is out of view) head poses are kept for four seconds and no longer. + +This is an operator's action for a bounded time. It is not the standing second subscriber the station checklist +does without (see [`LIVEKIT_PREVIEW.md`](LIVEKIT_PREVIEW.md#checked-before-a-take)): between checks and takes the +backend is not in the room. + +For a camera whose video is being corrected in this run the check uses the corrected camera's matrix, as the +Controller–glove offset tool's guide does, and says so: the pictures are the corrected camera's, which the lens +file's numbers do not fit. + ### Live guidance About three times a second the guide looks at the newest live picture and the newest tracking, and says what to do @@ -575,6 +800,12 @@ before it aligns. It reads the copy of the file the take's session carries: - No file, a file that cannot be read, a file not stamped `"pose_source": "openxr"`, or one that states no usable `camera_latency_s`: nothing is taken off, and the take is aligned on its recorded times. +- A file written in a layout newer than this software reads: the take is refused, with nothing written, under + an exit status of its own (3; a refusal for good is 1, an unreadable manifest 2). The background aligner + writes no `.refused` marker for it and tries the take again at every start, so it is aligned once the + software is updated. The lag is stated in that file and a newer layout may state it otherwise: *this session's + head_camera_extrinsics.json is written in layout 2, and this software reads up to layout 1: the take is not + aligned, since the camera's lag is stated in that file; update the software to align it*. - A lag stated without the `tracking_latency_s` it was measured under: the lag is used as stored. - Both stated: the lag is moved by the difference between the tracking latency the take was recorded under and the one the lag was measured under, so a station whose `alignment.tracking_latency_s` changed since the headset @@ -805,7 +1036,9 @@ takes"). - A station with no offsets installed starts from zero: *No offsets are installed on this station, so the fit starts from zero.* So does one whose installed offsets are not stamped with the tracking they were made with, and the band of warnings says so: *wrist_calibration_offsets.json was made with another tracking source or - another tool: calibrate again. The fit starts from zero, and installing replaces that file.* Installed + another tool: calibrate again. The fit starts from zero, and installing replaces that file.* So does one + whose installed offsets are written in a newer layout, with that file's refusal in the same band, before + any click: the install would replace a file a newer version of the software wrote. Installed offsets that cannot be read are not started from either: *The offsets installed on this station could not be started from, so the fit starts from zero.* Otherwise *The fit starts from the offsets installed on this station.* A controller can be strapped on any way round, so a hand @@ -1542,6 +1775,50 @@ start its children with. What that leaves unknown: constant. None has been checked against real cameras. - **A very small corrected picture.** Whether the video encoder can make one is found only when the bridge creates it (see "What the launcher does at start"). +- **What the files state of how they came to be** (`schema_version`, `provenance`) was written and read back on + synthetic solves only. No reader outside this repository was run against a file that carries the added keys, + and no file of a newer layout exists yet: each refusal of one was run on a file a test wrote, and "the software + is updated" was a child process told that it reads layout 2. A station that ran the version before the + aligner's refusal had its own exit status keeps the `.episode_N.refused` markers that version wrote for such + takes; they stay passed over until the marker is deleted by hand. An identical record that holds a + not-a-number is not recognised as identical and supersedes itself. +- **The live check of the installed calibration** was run on rendered boards and written-out head tracks only, + and against the mock capture server, whose pictures hold no board. On hardware it is not known: how many pixels + of error a sound calibration shows with real tracking noise and a real camera delay, and so whether the grade's + limits, chosen for a solve, read a sound calibration as sound; whether the capture time the capture server + stamps on a picture and on a tracking sample are close enough to one clock for the head pose at the picture's + time to be the right one; how often a headset's position leaps in ordinary use, which starts the check over; + and how pictures and tracking samples arrive relative to one another, which decides how often a picture waits + for the tracking to reach its time (on the mock it happened within the first few looks). +- **What the check's verdict rests on that no headset has shown.** The offset and the lag the board's wander + implies were found on rendered scenes, this project's and an independent reviewer's: a right calibration + reads near zero, a centimeter of offset as a centimeter, 30 ms of lag as 30 ms. Not known on hardware: the + noise a real headset's tracking adds to the board's place, which decides how many views pin the offset and + the lag (the check takes it to be no less than half a millimeter); whether the 5 cm a second under which a + head counts as still while the board's place is fixed suits a worn headset; and whether the limits for the + lag, one and two steps of a solve's search, are the right ones. +- **Known, and left as they are.** Turning the head in place with very quiet tracking reads as a lost position: + with the headset under about 11 cm from the axis it turns about and its position steady to a tenth of a + millimeter, most pictures say *The headset has lost its position* and no verdict comes. The threshold is the + head-track reader's, which a solve uses too, and whether a real headset is that quiet is unmeasured; stepping + to the side as well as turning avoids it. Far from the board a right calibration is graded down: at three + meters, with corners read to 0.7 px, the board's wander alone reads *Acceptable* or worse, so check from about + a meter. Each poll costs the backend's event loop about a third of a millisecond per tracking sample that + arrived since the last one, a third of a second after a long pause. A track lost while the check waits for + the sender's clock is noticed only when that wait ends, up to ten seconds later. And a developer's setup that + corrects the camera's video without the launcher's report has pictures of the corrected camera read with the + lens file, so a right calibration reads bad there; takes assume the same report. +- **The live check of a camera that arrives over LiveKit** was never run against a real room or a real + publisher: the room is a scripted frame receiver in the tests, the same stand-in the recorder's LiveKit tests + use, and no LiveKit server ran on the machine this was built on. Not known: whether the join, the first frame + and a usable clock mapping come within the times allowed (15 s, 10 s, 10 s) on a real network; how a LiveKit + picture's mapped time and a tracking sample's time lie relative to one another on a real station, which the + check's error in pixels depends on and which is unmeasured; whether the server forwards the track to a second + viewer beside the operator's page without disturbing the page's preview; and whether 20 seconds is the right + lease for a tablet whose browser throttles a hidden tab. +- **The picture-size note on Set up** was seen against the mock capture server, which declares one size for its + cameras. Whether a real camera started in another sensor mode declares that mode's size to the session, and so + whether the note appears for it, has not been seen. ### What the tools do not do @@ -1582,6 +1859,8 @@ start its children with. What that leaves unknown: 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 one exception is the live check of the installed head calibration, which joins the room for as long as it + runs. - **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 step, only when the head moved enough for a wrong lag to set the board wandering, and only inside the range searched: a lag found at or next to the end of that range is said to be doubtful. A number can be forced from @@ -1603,8 +1882,11 @@ start its children with. What that leaves unknown: projection, a pixel's ray, the board's pose), `intrinsics`, `extrinsics`, `grading` (grades, install policy, advice), `guidance` (the camera take's live guide), `camera_pipeline` (pick, solve and grade one camera), `camera_lag` (how far a take's pictures lag its tracking, from the stored lag and the latencies it and the take - were recorded under), `rectify` (gates, plan, remap table file), `rectification_files` (the files that carry a - rectification from one program to the next: the plan, the launcher's streams state, the record of what was done + were recorded under), `live_check` (the check of an installed head-camera calibration against live pictures: + where the board stands, the prediction's error, the verdict), `provenance` (what a file states of how it came + to be: its layout, producer, grade, rule and validity, and the one refusal of a newer layout), `rectify` (gates, + plan, remap table file), `rectification_files` (the files that carry a rectification from one program to the + next: the plan, the launcher's streams state, the record of what was done to a take's pictures, each with its name, layout and reader), `rectify_take` (the offline copy), `station_store` (install, history, ledger, the operator-name rule), `wrist_offset` (the fit), `hand_view` (frame sampling, overlay, the glove take's live guide), `files` (file names and readers), `frames` (axis conventions). It imports nothing from the diff --git a/examples/egocap/DESIGN.md b/examples/egocap/DESIGN.md index 720d1c1cee..e9d524753a 100644 --- a/examples/egocap/DESIGN.md +++ b/examples/egocap/DESIGN.md @@ -30,8 +30,8 @@ CaptureServer, serves the browser, and writes recorded sessions to local storage A station belongs to one operator working at a time. A site usually has several, so the stations are kept by the backend and chosen from the page: each has a name, a camera type, the camera that -fills each role (the operator's view and each wrist), and the capture host address last given to -its headset. The station in use names every recording and its activity log. A deployment's station +fills each role (the operator's view and each wrist), the tracking devices it requires, and the +capture host address last given to its headset. The station in use names every recording and its activity log. A deployment's station file still supplies the initial task instruction, the default operator name, the recording output location, the cameras requested from CaptureServer, and the station label used while no station has been set up. At startup, the backend reads the station's camera names and @@ -45,9 +45,20 @@ every tracking device and camera, the calibration files of its cameras, and room disk. Nothing is run; the checklist is judged continuously. With a station in use a take is refused, with the reason, while any item fails; a device or check the station does not use is skipped. An item fails for what would stop a take anyway (capture not running, no tracking data, a camera with -no frames) and for a full disk. What goes beyond that only warns: a device reporting another state -than connected, and missing calibration files, which are optional unless the deployment requires -them (an operator setting, off by default). With no stations set up the checklist only advises. +no frames), for a full disk, and for a tracking device the station requires (its headset, a +controller or a glove, chosen per station) that is not connected: switched off, not found, not +started yet, not reported, or switched off in the capture configuration. A required device must be +delivering its data: one that is connected with nothing to send holds recording, and one that still +delivers with a problem of its own, such as a rejected calibration file, only warns. A requirement +fails closed: one the software does not know, as a newer version may have written it, is kept and +holds recording until it is removed, and stations that were saved and cannot be read hold recording +until they are replaced. A calibration take is held only by the devices its tool uses. What goes beyond that only warns: +a device the station does not require reporting another state than connected, and missing +calibration files, which are optional unless the deployment requires them (an operator setting, off +by default). A station requires no device until it is told to. A camera whose video arrives +over LiveKit passes only while an operator's page reports its frames arriving in the preview, since +the backend joins that video only for the length of a take or of a live check of the head calibration +that an operator starts; anything else the page reports of it warns with what to check. With no stations set up the checklist only advises. Before recording, the operator also selects or enters the task being demonstrated, and confirms the live preview — camera video and tracked pose — looks correct. Starting an episode requires every required source to be @@ -74,12 +85,23 @@ The report shows the station's active and down time with its blockers and the op can be saved on the station. A dataset-reporting library function also counts each station's valid versus excluded episodes from the saved session metadata, for offline use. -A misfiled task can be corrected from the report for one take or a range of a session's takes. Only -labels change; recorded video and tracking stay as captured, and a session is never moved from the -page. A correction is refused for the session still open for recording, while a take of that session -is being time-aligned or another correction of it is being written, and for anything that is not a -recorded session inside the recording output. A library function, for offline use, relocates an -older session saved under the wrong studio. +A misfiled task can be corrected from the report for one take or a range of a session's takes, and +the studio a whole session is labelled with can be corrected there too. Only labels change; recorded +video and tracking stay as captured, and a session is never moved: a corrected studio is written into +the recording's own metadata, and a session that lies in a folder named after the studio it was +recorded under stays in that folder. The report and the dataset counts read the studio from the +session's metadata, so they show the corrected one; a file browser shows the folder as it is. A +correction of either label is refused for a session open for recording, in this backend or in any +other recorder on the same output, while a take of that session is being time-aligned or another +correction of it is being written, while the session holds a take that was interrupted and is still +to be filed by, or into, what is being corrected (the recorder files such a take by the labels it +was recorded under), and for anything that is not a recorded session inside the recording output. +Either correction is all or nothing: it is checked whole before its first write, a write that still +fails puts back what was written, and a correction that answers with a failure either left the +session as it was or says, from what the disk holds, which labels it could not put back. A group +whose studio or whole task was really changed stops receiving later takes of its session, which +claim a fresh group. A library function, +for offline use, relocates an older session saved under the wrong studio. ### Timing and calibration requirements @@ -357,6 +379,22 @@ every file need the control token, which the page exchanges once for a same-site request a browser marks as coming from another site is refused. It is independent of the recording page: it never reconnects to CaptureServer and never affects a live session. +### Not yet verified on hardware + +What this document says of the following has been exercised against the mock capture server, scripted stand-ins +and synthetic data only: + +- A station requiring its tracking devices: which path and type a real headset, controller and glove report under, + how quickly each leaves the connected state when it is switched off or loses tracking, and the degraded and + switched-off states, which the mock never reports: which of them still deliver data was read from the capture + session's own code, not seen from a device. +- The live check's verdict: the camera offset and lag it finds were seen on rendered scenes only, and the noise + of a real headset's tracking, which decides how soon the views pin them, is unmeasured. +- A LiveKit camera passing only while its frames are seen in the preview: no LiveKit server or camera sender was + run. +- The corrections and the rules that hold them: run on sessions a real recording service wrote with one numeric + source, never on a session with recorded video, and never with two backends on one output. + ## 4. Assumptions and scope This design serves a single operator working at one station at a time. The browser, backend, and diff --git a/examples/egocap/LIVEKIT_PREVIEW.md b/examples/egocap/LIVEKIT_PREVIEW.md index bc5e5451b3..1b9e3a7c65 100644 --- a/examples/egocap/LIVEKIT_PREVIEW.md +++ b/examples/egocap/LIVEKIT_PREVIEW.md @@ -107,6 +107,65 @@ uv run uvicorn egocap_web.app:app --app-dir backend --port 8000 requests (data messages on topic `isaaccapture.clock-sync`) and reading its replies. The publisher must stay in the room and answer them; without replies the mapping goes stale. +## Checked before a take + +The backend is in the room only while a take records or a live check of the head calibration runs (see "Joined +for a calibration check" below), so at other times it receives nothing from a LiveKit camera. The page is in the +room all the time, to show the picture. A page that holds the control token and is in +view therefore tells the backend, every two seconds, what its preview receives of each stream +(`POST /api/setup/livekit-preview`), and the station checklist goes by the best report under six seconds old: + +| What a page reports | The camera's item | What it says | +| --- | --- | --- | +| frames are arriving | passes | `frames are arriving in the preview` | +| the track is subscribed and no frame has come for three seconds | warns | `no frames in the preview: check the camera and its sender; the recorder checks this camera itself when a take starts` | +| the sender has not published the track | warns | `its sender is not publishing it: start the camera sender; the recorder checks this camera itself when a take starts` | +| the page could not join the room | warns | `the preview cannot join the video room; the recorder checks this camera itself when a take starts` | +| nothing (no page with the token is in view) | warns | `not checked here: keep this page in view with the control token entered; the recorder checks this camera itself when a take starts` | + +A stream that cannot be recorded at all still fails, as before. A report never fails the item and never holds a +take, and the page says so: a warning is listed as "Advisory: does not hold recording.", the Devices step reads +"takes are not held", and each sentence above names the recorder as what checks next. A report is one browser's +observation, and a browser can fail to receive video the recorder would receive (another network path, a codec +the browser lacks). What refuses a take is the recorder itself, which joins the room when the take starts and +gives up, with its reason, when a stream sends no frame within ten seconds. + +A check of the backend's own would need one of two things, and neither is built: + +- The backend staying in the room between takes: the recorder's receiver joined for as long as the session offers + the streams, with a take attaching to that connection. This is a second subscriber to every camera for the whole + day (the server forwards each stream once more, and counting frames without decoding them needs the receiver to + read transport statistics instead of pictures), plus a reconnect policy the take-length connection does not need. +- Asking the LiveKit server, through its room service API, whether the publisher is in the room and publishes the + track. That carries no media, and needs the server's HTTP API reachable from the backend and a token with the + room-administration grant. It says the track is published, not that frames flow. + +## Joined for a calibration check + +The calibration tool's *Check the installed calibration* (see +[`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#checking-the-installed-calibration-live)) needs live pictures of +the head camera on the head poses' clock. When that camera is a LiveKit stream, the backend joins the room for +the length of the check: one more viewer, of that one camera's track, with a viewer's token of its own +(`LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`, as for recording). It is the recorder's own source +(`LiveKitRecordingSource`) told of one stream, so the join, the first-frame and size check, the clock-sync +exchange and the placing of each frame's time are a take's, and so are the conditions: a monotonic +`timestamp_basis`, `width`, `height` and `fps` in the streams file, a publisher that answers clock-sync requests, +and CaptureServer on the same computer. Nothing is recorded. + +The backend leaves the room when the check is stopped, when no page has asked about it for 20 seconds, when a +take starts (the check ends first; a check is refused while a take records), when its video fails, when the +check has run for ten minutes, and at shutdown. This is an operator's explicit action for a bounded time; it is +not the standing connection the checklist does without, and between checks and takes the backend is still not +in the room. + +Leaving is guarded. The frame receiver disconnects from the room whatever an earlier step of its leave raised, +and the recorder's source leaves the room whatever stopping its feed raised; both hold for a take as well. What +a check's leave raises is logged and fails neither the take that is starting, the stop from the page nor the +shutdown. A take waits at most two seconds for the check to be out of the room: the two join under identities +of their own, so a leave the room is slow to answer finishes behind the take. A way into the room that fails is +said to the operator in one fixed sentence per stage; what the video library or the video server answered goes +to the backend's log only, since a server's error body can hold anything. + ## Corrected video A LiveKit stream is recorded as it is published. When the publisher is the camera bridge started by @@ -117,11 +176,29 @@ streams file, and tells the backend what it applied through `EGOCAP_STREAMS_STAT calibration tools refuse to calibrate a lens from that video. See [`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#rectification). -The backend holds no picture of a LiveKit camera outside a take: the page shows the stream itself. While a -calibration take records, the calibration tools' live guide looks at the frames the recorder is fed for the take, +The backend holds no picture of a LiveKit camera outside a take and a calibration check: the page shows the +stream itself. While a calibration take records, the calibration tools' live guide looks at the frames the recorder is fed for the take, so such a camera is guided from the take's first frame on (see [`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#live-guidance)). A backend started by hand, as in step 4, is told nothing about the streams and takes every one for uncorrected: its sessions carry no `rectification.json`. Publish corrected video to it only when that is understood; recording corrected video is what the launcher is for. + +## Not yet verified on hardware + +- The page's reports have been exercised against a scripted room and a scripted video element, and the checklist + against scripted reports. No LiveKit server, camera sender or emulator was run by this work, so a pass has not + been seen for a real stream. +- How long a browser takes to present the first frame of a real stream, against the three seconds after which a + subscribed track is called silent. +- Whether a browser tab that is in view but covered by another window keeps presenting frames; a tab the browser + reports hidden sends no report. +- The room join for a calibration check was run against the recorder's test stand-in for the frame receiver only, + never against a real room or publisher. Whether a second viewer from the backend beside the operator's page + changes what the page receives, and how a LiveKit picture's mapped time and a tracking sample's time lie + relative to one another on a real station, are unmeasured. +- Whether the real LiveKit library's leave returns promptly and never raises is not known: every way out of the + room depends on it, the stand-in's leave is instant and silent, and the guards around it (a `finally` in the + receiver and in the source, a limit of 1.5 seconds on the check's leave) were exercised with injected faults + and a stand-in that stalls, not with a real room. diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index fdca87d3b1..d597ff6c4f 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -31,15 +31,17 @@ or restarts it. | `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, 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/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, the tracking devices it requires (`required_devices`) 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, 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/setup/livekit-preview` | What the caller's preview receives of each LiveKit camera: `{"page": "", "streams": {"": "receiving" \| "silent" \| "no_track" \| "not_connected"}}`. Needs `X-Control-Token`; bodies above 8 KiB are refused with 413, a malformed one with 400 and the reason. Kept in memory per page for six seconds and read by the station checklist, which passes a LiveKit camera only while a report says its frames arrive; it holds no take. See [`../LIVEKIT_PREVIEW.md`](../LIVEKIT_PREVIEW.md#checked-before-a-take). | +| `GET /api/day-report`, `POST /api/day-report/save`, `POST /api/day-report/correct`, `POST /api/day-report/studio` | 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`). `studio` relabels the studio of a whole session where it lies (`session`, `studio`) and answers with the label as stored; nothing is moved. A refused or failed correction is a 400 with the reason in `detail`, and with `left_changed` (a list of names) only when a failed correction of either kind could not put a label back. Each take carries `location`, where its data is under the recording output, `studio`, the label it carries now (null when none was recorded), 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). | +| `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`), with `picture_notes` (`lens` and `position`: what to know before a take when the capture session says the camera sends another size of picture than its installed lens file was solved at, each null when there is nothing to say), 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), whether it reaches the backend through the LiveKit room (`video_room`, which the live check then joins while it runs), 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 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. | +| `POST`/`GET /api/calibration/check`, `POST /api/calibration/check/stop` | The live check of the installed head-camera calibration ([`calibration_check.py`](egocap_web/calibration_check.py)), with `X-Control-Token`. It reads `head_camera_intrinsics.json` and `head_camera_extrinsics.json` once, at the start, and writes nothing: no take, no file, no ledger entry. `POST` (`{"board"}`) starts a check in place of any before it and is refused with 409 and the reason when the calibration cannot be judged at all: no camera in the head role, a head camera file missing, unreadable, solved for another camera or made with another tracking source (`calibrate the headset first: ...`), a launcher report that could not be read, a correction the launcher's record does not describe, a camera the capture server delivers that has sent no picture (`there is no live picture from this camera`), a take being recorded (`a take is being recorded, and the check never runs beside one: finish or discard the take first`), and a LiveKit camera whose video could not be recorded either (`the check gets this camera's video the way a take does, and could not: ...`); 400 for a board that could not exist. **For a head camera that arrives over LiveKit the backend joins the video room for the length of the check** ([`calibration_check_pictures.py`](egocap_web/calibration_check_pictures.py)): the recorder's own `LiveKitRecordingSource`, told of that one stream, joins in the background, and each frame's time is the publisher's timestamp placed on this machine's clock through the clock-sync mapping, as for a take. Nothing is recorded. It leaves the room when the check is stopped, when no page has asked about it for 20 seconds, when a take starts (the recorder's source awaits `yield_to_take()` before its own join), when the check is started again, when the video fails, when the check has run for ten minutes (its longest, for a check of any camera), and at shutdown. Every one of these ways out is guarded: whatever a step of the leave raises the room is still left, the failure is logged, and neither the take, the stop nor the shutdown is failed; a take waits at most two seconds for the check's leave, which otherwise finishes behind it. A way into the room that fails is said in one fixed sentence per stage (the join, the first picture, the clock mapping); what the video library or server said goes to the log only. `GET` (about 3 Hz; 404 when no check runs, with what became of one the backend ended itself: `the check ended because a take started: the two never run together`, `the check ended because the page that started it stopped asking about it` or `the check ended after ten minutes, its longest: start it again to go on checking`) looks at the newest picture CaptureServer delivered, when it is a new one under two seconds old, with every head pose that arrived since the last look; a picture that is here before the tracking sample after it waits, up to half a second, until the tracking has reached its time. A picture of another size than the installed calibration describes is not judged: `available` is false, `unavailable_reason` says so and what to do, and `preview` is the picture as it came. It answers `phase` (`checking`), `camera`, `corrected` (whether the corrected camera's matrix is used, since this run corrects the camera's video), `camera_lag_ms` (the stored lag taken off each picture's time), `elapsed_s`, `available` and `unavailable_reason`, `video_room` (whether the backend is in the room for this check now: false again once its video failed) and `waiting` (what it waits for there, in words: the join, the first picture, or the clock mapping; null otherwise), `check` (the library's record: `phase` `fixing` or `checking`, `judged` and `cannot_judge`, `error_px`, `rms_px`, `worst_px`, `views`, `head_turn_deg`, `board_wander_m`, `pose_fit_px`, `camera_offset_m` and `camera_offset_uncertainty_m` (the camera offset the board's wander implies, and how closely the views pin it), `camera_lag_off_s` (the error in the stored lag it implies; null while no picture counted can show one), their `limits`, `enough`, `verdict`, `no_verdict` (why views that are enough by their count still carry none: the head has turned about one axis only, or the views do not pin the offset), `notes` (what is said beside a verdict), `restarts`, `hints`), `preview` (the picture with each corner seen and each corner predicted drawn on it) and `note`, the sentence that says what it reads and that it writes nothing, and for a check in the room that the backend is in it while the check runs. A look is made only when the page asks; nothing runs between two polls. `stop` ends it. See [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#checking-the-installed-calibration-live). | | `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. | | `POST /api/calibration/glove/session/fit`, `POST /api/calibration/glove/session/reset`, `POST /api/calibration/glove/session/install` | Changes to the labelling session; each answers with the session and is 404 without one, and 409 while another fit or install of it is still running. A change may name the session it means (`session`: its `id`) and is then 409 once a newer session has replaced that one, so clicks placed on one session's frames are never fitted to another's; a change that names none means the current session. `fit` takes the page's whole click list (`clicks`: `sample`, `side`, `finger`, `u`, `v`, at most one per fingertip of a hand in a frame) and fits each hand that has at least three usable clicks; a hand with fewer keeps its offset. 400 for a malformed click, 409 once what the session was prepared from has changed (`stale`). `reset` goes back to the offsets the session started from and forgets its fits. `install` (`operator`) writes `wrist_calibration_offsets.json` into the calibration directory, archived and stamped in the ledger under `wrist`; 400 without an operator name, or with one the station store's rule refuses (longer than 128 characters, a control character, half of a surrogate pair), the same rule as the headset tool's install; 409 with `install.reason` while the offsets may not be installed (a hand that started from zero has no fit, a fitted hand's clicks are too few or on too few frames to pin its offset down, or a fit stopped at the furthest offset the tool fits); and 409 when what the session was prepared from (the head camera's calibration, the installed offsets, the take, the calibration directory) is no longer what it was, in which case the session says so in `stale` and the frames are prepared again. Putting another station of the registry in use is not such a change: the calibration directory is the backend's and stays where it is. Like the headset tool's install, it ends the recording batch for the takes recorded next and says so in `recording_batch`; offsets that went live before the calibration log could be written are installed all the same, and the reply is a 503 with `detail` (`wrist_calibration_offsets.json is installed, but the calibration log was not updated`, then what became of the batch), `installed: true` and `recording_batch`; if that step itself breaks, the reply is a 500 whose sentence says that the offsets were installed and a new batch must be started by hand. Whatever else breaks unexpectedly in a session route is logged and answered with a 500 and a fixed sentence. | @@ -91,6 +93,10 @@ A site usually has several stations, and an operator picks the one they are at. 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. +- **Required tracking devices.** A station may name the tracking devices that must be connected before a take + (see [Start-of-day flow](#start-of-day-flow)). Changing them rotates nothing and relabels nothing; for the + station in use the change is refused during a take like any other, and the checklist is judged again before the + next take is admitted. - **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. @@ -184,13 +190,59 @@ The flow is station, devices, record, wrap-up ([`setup_service.py`](egocap_web/s - **The checklist is live.** There is nothing to run: a background duty judges it every second, and `GET /api/setup` judges it afresh. It reads the calibration directory and the recording disk, so it is judged in a worker thread, one evaluation at a time; a slow mount cannot stall the event loop that carries capture frames. -- **What holds a take** is a failed item, and an item fails only for what recording readiness itself refuses, plus - a full disk: the capture session not running, no recent tracking sample, a station camera that is not offered, - delivers no recent frame or, for a LiveKit camera, cannot be recorded, and less than 10 GB free on the disk - holding the recording output. +- **What holds a take** is a failed item. An item fails for what recording readiness itself refuses, for a full + disk, and for a tracking device the station requires: the capture session not running, no recent tracking + sample, a station camera that is not offered, delivers no recent frame or, for a LiveKit camera, cannot be + recorded, less than 10 GB free on the disk holding the recording output, and a required headset, controller or + glove that is not connected. +- **A station can require its tracking devices.** `required_devices` of a station lists any of `headset`, + `controller_left`, `controller_right`, `glove_left` and `glove_right` (the Station tab's *Required tracking + devices*; `GET /api/stations` lists them as `tracking_devices`). A required device must be delivering its + data when Record is pressed, and the capture session's own reason for a device's state decides it + (`DeviceFact.reason`, `DeviceFact.delivers`). It meets its requirement while connected, or while degraded for + a reason under which it still streams, which today is one: a glove whose calibration file was rejected + (`CALIBRATION_FAILED`), whose row warns with the device's words. It fails, with `this station requires it` + after the session's words, in every other state: degraded with no current data or a device error (a glove + with no usable skeleton; a controller whose aim or grip pose has been lost for a second or more), a degraded + reason nobody has read yet, unavailable, unknown, still starting, disconnected (a controller that is + inactive is this), not reported at all (a glove whose plugin is not running has no entry: `not reported by + the capture session; this station requires it`), and switched off in the capture configuration (`switched + off in the capture configuration; this station requires it`). A reported device is recognised by its path, + `/controller/` or `/hand/`, so any hand-tracking provider counts as the glove of that hand. A + station that names none, and a registry file written before this key existed, require nothing. +- **A requirement fails closed.** The routes refuse a name they do not know, echoing at most five names of at + most 40 characters each (`unknown tracking device(s): 'elbow'; a station can require ...`). The registry file + is read leniently instead: a station whose `required_devices` holds a name this build does not know, written + by a newer build or by hand, is kept with every other field, and that name stays a requirement that cannot be + met. It is a failing row under the name as written (`not a tracking device this software knows; this station + requires it`) and holds recording until the requirement is unticked in the Station tab. `GET /api/stations` + gives each station `unreported_devices`: its requirements that the capture session here does not report now + (empty while the capture session is not connected), which the Station tab shows as a warning. + A stored requirement is written back exactly as the file held it until the requirement itself is edited + from the Station tab, so an unrelated save changes nothing of it; one of more than 32 entries, or of more + than 4096 characters, makes the registry unreadable. +- **A registry that cannot be read holds recording.** While the stored stations file is there and cannot be + read (a field this build does not accept, a damaged file, a file the process may not open) no station is + loaded, and recording is held with the sentence the Station tab shows (`Saved stations are unreadable. Adding + a station replaces them`, or `Saved stations cannot be read. Check the registry file's permissions`) until a + change from the Station tab succeeds; the Station step shows the same. A file that is absent is still "no + stations", which holds nothing. +- **A row is renamed only where the station asks.** The checklist calls a device what the Station tab calls it + (`Headset`, `Left controller`, `Right controller`, `Left glove`, `Right glove`) only when the station requires + that kind. Every other row keeps the capture session's own description, so a station that requires nothing + shows exactly the rows it showed before requirements existed. +- **A calibration take is held only by the devices its tool uses.** The head-camera tool's take uses the headset + and the controllers, the glove tool's all five (`calibration_service.TOOL_DEVICES`); a required device the + tool does not use never holds that take, as the calibration item never does. +- **A LiveKit camera passes only while its frames are seen arriving.** The backend is in the room only during a + take or a live check of the head calibration, so it goes by what an operator's page reports of its preview (`POST /api/setup/livekit-preview`, + [`livekit_sightings.py`](egocap_web/livekit_sightings.py)): frames arriving pass; no frames, an unpublished + track, a page that cannot join the room and no report at all each warn with what to check. None of these holds + a take: the recorder joins the room itself when the take starts and refuses it then. - **What only warns** (`warn`) is shown with its reason and never holds a take; the Devices step stays done and - names it. A tracking device or a camera that reports another state than connected warns: readiness judges the - data that arrives, not the state a device reports, and a station may leave a controller or a glove unused. + names it. A camera, or a tracking device the station does not require, that reports another state than connected + warns: readiness judges the data that arrives, not the state a device reports, and a station may leave a + controller or a glove unused. - **Calibration files are optional unless the deployment requires them.** The files of the roles in use are looked for under `EGOCAP_CALIBRATION_DIR` (head intrinsics and extrinsics, each wrist's intrinsics, and the wrist offsets once a wrist is assigned); calibration is skipped for a mock session. A missing or unreadable @@ -235,8 +287,10 @@ A take belongs to the day in its finalized episode's `recorded_at`, else the day 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; -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. +the line names the record's file, never a directory, and carries nothing the parser or the system said: one +that cannot be opened reads `episode_3.json: the file cannot be read`. 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 sidecar +that cannot be listed is one line of its own (`the take records cannot be listed`), never an empty session. 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 @@ -249,9 +303,87 @@ routed groups; an interrupted take holds only its own session. It is also refuse of that session is being time-aligned, since the copy being built already has the old label, and while another correction of that session is being written. One lock per session ([`session_locks.py`](egocap_web/session_locks.py)) is held by the correction across every file it writes and by the aligner across a whole alignment, so an episode -waiting to be aligned does not start in the middle of a correction. Each metadata file is -replaced whole, both task labels of a take are kept in step, and the session's own task label changes only when -every take was corrected. Nothing is ever moved. +waiting to be aligned does not start in the middle of a correction. The lock is keyed by the directory itself +(device and inode), so two spellings of one directory, as another letter case is on a disk that folds case, are +one lock; a time-aligned copy is refused as a target however its name is cased. + +**The recorder's own lock.** A recorder owns a session by a lock on a file in the session's sidecar +(`egocap.recording.episode_layout.SessionLock`), and this backend's snapshot knows only its own recorder. A +correction therefore takes that lock too, without waiting, from before its checks to its last write, and answers +a held one with `this session is open in a recorder; end its batch there before correcting it`. No recorder can +open the session while a correction writes. The lock is taken only where the lock file already exists, which is +every session a recorder opened; nothing is created for a session that is gone or that no recorder ever locked. +For a routed group the session locked is the one its route stamp names. +A lock file that is not a regular file with one name (a link, a folder, a second name for a file elsewhere) is +refused with `this session's lock is not an ordinary file, so its labels are left as they are`, and is not +opened: taking the lock would write through it. + +**A take still to be filed.** A correction of either label is refused while the session holds a take that is not +settled and whose later filing depends on what is being corrected. That is a take whose manifest carries a +studio and no assignment yet (`an interrupted take of this session must be recovered or discarded first: where +it is filed depends on the labels it was recorded under`): the recording service files it into the group of the +studio and task its manifest froze, and refuses a group whose labels no longer say the same +(`egocap.recording.route.assign_output`), so a correction made first would leave it unrecoverable. And it is a +take that already has its place in the group being corrected (`an interrupted take of this session must be +recovered or discarded first: it is still to be filed in this group`): filed afterwards, it would land in the +corrected group under the labels it was recorded with. An unsettled take recorded with routing off, which is +how this backend records, is filed by no label and holds no correction. While a take record cannot be read, or +the sidecar cannot be listed, both corrections are refused (`a take record of this session cannot be read, so +its labels are left as they are`): nothing shows that no take is waiting. A record that is JSON and no record, +and a session name that cannot be encoded, are refused in sentences like any other. + +**A corrected group stops being a destination.** When a correction will leave a routed group's own studio, or +its own task, different from what it says now, the owning session's route to that group is dropped +(`egocap.recording.route.forget_group`) under the recorder's lock, before the first label is written. A take +recorded later into the reopened session then claims a fresh group instead of being refused the corrected one. A +take's own frozen assignment is not touched. A correction to the label the group already has, and one of some +takes of a group, leave the route; and a correction that fails with nothing left changed puts the route back as +it was. If the session's routes cannot be rewritten the correction is refused with nothing changed (`the +session's record of where its takes are filed cannot be rewritten, so its labels are left as they are`). + +**What a correction writes.** Each metadata file is replaced whole by a file of the same mode, and the file and +its directory are synced, as the recorder does for the same files; `config.yaml` is written as the recorder +writes it, with text outside ASCII escaped, so a reader under any locale still reads it. Both task labels of a +take are kept in step, and the session's own task label changes only when every take was corrected. A +`config.yaml` that cannot be read or does not hold the session's settings refuses the correction before +anything is written (`config.yaml cannot be read, so nothing was changed`), and one that is there and was not +rewritten is a failure, never `config_updated: false` on a success. What a correction that was killed part-way +left behind (the temporary files of an unfinished replacement) is removed under both locks at the start of the +next, once it is older than a minute: a younger one may belong to a writer at work outside these locks. One +that cannot be removed is left, and the check that follows names the take whose folder cannot be written. +Nothing is ever moved. + +**Both corrections are all or nothing.** Before the first write every file the correction will rewrite, of the +session and of the time-aligned copy, is read and checked to be rewritable, and the correction is refused +there with nothing changed and the take named (`episode_1 cannot be rewritten (its folder is read-only), so +nothing was changed`). If a later write still fails, what was written is put back byte for byte and the reply +says so (`the labels could not all be written; those already written were put back, so nothing was changed`). +What the reply says is read from the disk, not taken from which call raised: a label counts as written from the +moment its write begins, and "could not be put back" is said of a file that still differs from what was found +after the put-back, or that cannot be read. Only then does a failed correction leave a change, and the reply +names it: the sentence says which takes say the new studio, or carry the new task, now (`... and episode_0 +could not be put back: it carries the new task now, and the rest what they said before`), and `left_changed` +lists them. + +**A studio correction** (`POST /api/day-report/studio`) is held to every rule above and relabels the whole session +or routed group, never a range: `studio` on each finalized episode, on the root group when there is one, in +`config.yaml` (`meta.studio`) and on the time-aligned copy. The name is stored as one plain word in one Unicode +form, in the task library's spelling when the library knows the studio (`Living room` is stored as +`Living_room`); a name that is empty, hidden, relative or a folder's bookkeeping name (`unmatched`, `unknown`, +however cased or underscored) is refused. It never touches a take's manifest, which keeps the studio the take +was recorded under, and it never moves, renames or creates a directory: a routed group stays at +`/` under the studio it was recorded in. + +The studio's check and undo are `plan_session_studio` and the plan's `apply()` in +[`update_episode_task_description.py`](../recording/egocap/data_processing/update_episode_task_description.py); +the task correction, `update_episode_task_description()`, makes the same check over the same files and puts +back the same way. + +Every reader of a session's studio in this repository takes it from the session's own metadata first +([`egocap.studio.session_studio`](../recording/egocap/studio/session_studio.py)): the day report's `studio` and +`count_daily_trajectories.count_trajectories` both show the corrected label, and fall back to the folder's name +only for a session that states none. What still shows the folder: `location` in the report, the session key of +`count_trajectories`, and the recordings browser, each of which names where the files are. | Variable | Default | Meaning | | --- | --- | --- | @@ -267,6 +399,42 @@ every take was corrected. Nothing is ever moved. | `EGOCAP_TRUSTED_HOSTNAMES` | unset (dev default) | Comma-separated hostnames trusted for the same-origin fallback on `WS /api/session`. Leaving this unset derives the expected origin from the request's own `Host` header, which is fine for local development but not a safe default for a deployment reachable from an untrusted network. | | `EGOCAP_VISER_ENABLED` and related `EGOCAP_VISER_*` | on | The embedded 3D tracking view; see [`frontend/README.md`](../frontend/README.md). | +## Not yet verified on hardware + +No headset, controller, glove, camera or LiveKit server was used for the following; each was run against the mock +capture server, scripted stand-ins or synthetic data: + +- **Required tracking devices.** The device paths and types a real session reports (`/headset`, + `/controller/`, `/hand/` of type `hand_tracker`) were read from the session manager's code. The mock + reports `/head/headset` and type `hand`; both are covered by tests. The mock reports a device only as connected + or unavailable: the degraded, starting, unknown and switched-off states were built in tests from the session's + own status types and have never been seen from a device. Which reason a real glove or controller gives in + each situation was read from the session's status monitor and the glove plugin's source, and driven through + the real monitor with stand-in reports. Whether a glove whose calibration file was rejected really streams + usable data is taken from the plugin's code. A controller that is set down holds a station that requires it + once the session's own one-second delay has passed; how often that happens in real use is unknown. How + quickly a real device leaves `CONNECTED` is unknown too. +- **The LiveKit preview report.** The checklist was fed scripted reports; no room was joined. +- **The corrections.** Run against sessions a real recording service wrote with one numeric source and no camera: + its lock, its manifests, its route stamps and its recovery of a waiting take. A session with recorded video, a + second backend process on the same output, a power cut during a replacement, and a disk that folds letter case + other than the development machine's were not tried. +- **What a correction does not cover, to know.** One backend per recording output is assumed. A correction + that is killed part-way (the process, not a failed write) leaves two studios, or part of a task correction, + with no reply and nothing that records it; no file is truncated, and the next correction of the session + completes it. A time aligner run by hand is not excluded from a correction: only its staging files younger + than a minute are spared. Between the look at a session's lock file and the recorder's own opening of it, + which truncates, the file could be swapped for a link; closing that needs the recorder's lock class to open + without truncating. A take record of an unsupported layout is still reported with the record's full path. +- **Running this suite writes inside the checkout.** `tests/backend/test_recordings.py` builds the recordings + page (`npm ci && npm run build` in `recordings_frontend/`, which reaches the npm registry and rewrites its + git-ignored `node_modules` and `dist`), and `tests/backend/test_preview_routes.py` leaves two sessions under + the git-ignored `recordings/` at each run. No tracked file is touched. +- **The live check of the installed calibration** and the **picture-size note**: see + [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#not-yet-verified-on-hardware). The check's join of the + video room was run against the recorder's test stand-in for the frame receiver, in the service's tests and in + the real application; never against a real room or publisher. + ## Optional LiveKit support Recording LiveKit camera video needs the `livekit` extra (`uv sync --extra livekit`). Without it the backend diff --git a/examples/egocap/backend/egocap_web/app.py b/examples/egocap/backend/egocap_web/app.py index a9cd59bb17..d1d0bf1e48 100644 --- a/examples/egocap/backend/egocap_web/app.py +++ b/examples/egocap/backend/egocap_web/app.py @@ -44,6 +44,8 @@ from . import readiness_text from .auto_align import AutoAligner +from .calibration_check import LiveCheckService +from .calibration_check_pictures import VideoRoom from .calibration_frames import NewestFrames, WatchedLiveKitSource from .calibration_routes import router as calibration_router from .calibration_service import CalibrationService, stored_camera_roles, stored_camera_type @@ -62,6 +64,7 @@ sensor_capture_names, unrecordable_reason, ) +from .livekit_sightings import LiveKitSightings from .operator_settings import OperatorSettingsStore, operator_settings_path from .operator_settings import router as operator_settings_router from .preview_routes import router as preview_router @@ -82,7 +85,7 @@ from .settings_routes import EffectiveSettings from .settings_routes import router as settings_router from .setup_routes import router as setup_router -from .setup_service import CHECKLIST_SECONDS, SetupService, capture_facts +from .setup_service import CHECKLIST_SECONDS, SetupService, capture_facts, reported_tracking_devices from .station_config import ( DEFAULT_VIDEO_ENCODER, ResolvedStation, @@ -717,6 +720,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: _recorder_livekit_token, ), decoded_frames, + # A take and the live check never run together: the check leaves the room before the recorder joins. + before_join=lambda: app.state.calibration_check.yield_to_take(), ) # Shared by the aligner and the end-of-day correction: whichever holds a session's lock has its labels. session_locks = SessionLocks() @@ -788,6 +793,8 @@ def recording_config( session_adapter( offered_cameras=monitor.offered_camera_names, change_blocked=lambda: _station_change_blocked(coordinator), + # The Station tab says when a station requires a device the capture session here does not report. + reported_devices=lambda: reported_tracking_devices(monitor), show_label=monitor.set_station_label, rotate_batch=lambda: _rotate_batch_for_station(coordinator), renamed=station_uptime.rename, @@ -796,9 +803,12 @@ def recording_config( ) app.state.station_service = station_service monitor.set_station_label(station_service.label()) + # What operator pages see of the LiveKit cameras: between takes the backend is not in their room. + livekit_sightings = LiveKitSightings() + app.state.livekit_sightings = livekit_sightings # The start-of-day flow: the live station checklist, which gates a take for a station in use. setup_service = SetupService( - facts=lambda: capture_facts(monitor, config), + facts=lambda: capture_facts(monitor, config, livekit_sightings.seen()), stations=station_service, calibration_dir=calibration_dir, output_root=recording_output_root, @@ -837,6 +847,18 @@ def recording_config( decoded_frames=decoded_frames, ) app.state.calibration = calibration + # The live check of the installed head-camera calibration: it looks at live pictures and writes nothing. + app.state.calibration_check = LiveCheckService( + monitor=monitor, + calibration_dir=calibration_dir, + streams=streams, + camera_for=calibration.camera_for, + # For a head camera that arrives over LiveKit the check joins the room as the recorder does, while it runs. + video_room=VideoRoom( + lambda camera: monitor.livekit_stream(camera), _recorder_livekit_token, config.capture_server_url + ), + take_running=lambda: _station_change_blocked(coordinator) is not None, + ) # The rectification tool saves what the launcher applies at the next start, and shows what this run applies. app.state.rectification = RectificationService( host=calibration, streams=streams, output_root=recording_output_root @@ -905,6 +927,12 @@ async def sample_uptime() -> None: for duty in duties: duty.cancel() await asyncio.gather(*duties, return_exceptions=True) + # A live check may be in the video room; it leaves before the application goes. Whatever its leave + # does, the steps of the shutdown after it still run. + try: + await app.state.calibration_check.aclose() + except Exception: # noqa: BLE001 -- the check's leave must not cut the shutdown short + logger.exception("The live calibration check could not be closed") # A camera solve runs in a worker thread, which would hold the process until it had finished. await calibration.aclose() try: diff --git a/examples/egocap/backend/egocap_web/auto_align.py b/examples/egocap/backend/egocap_web/auto_align.py index 68e91aa1b6..0d54771443 100644 --- a/examples/egocap/backend/egocap_web/auto_align.py +++ b/examples/egocap/backend/egocap_web/auto_align.py @@ -10,8 +10,11 @@ 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, -and how much camera lag was taken off the cameras' times (the lag the session's head-camera extrinsics state). +still have no aligned copy. Only an episode the tool refuses for what it is gets a marker and is passed over +from then on; one the tool cannot read yet (a session file of a newer layout) or could not vouch for (an +unreadable manifest) is tried again at every start. The log line of an aligned episode carries the tool's own +summary: the frames kept, and how much camera lag was taken off the cameras' times (the lag the session's +head-camera extrinsics state). The child copies an episode's labels into the aligned copy, so the worker holds the session's lock (session_locks.py) for the whole alignment: a task correction of that session is refused meanwhile, and an @@ -234,7 +237,9 @@ async def _align(self, job: _Job) -> None: reason = stderr.decode(errors="replace").strip() if process.returncode == 1: # Exit 1 is a refusal, which is the same every time, so remember it instead of retrying at every start; - # any other failure (an unreadable manifest, a killed child) stays retryable. + # any other failure stays retryable: an unreadable manifest, a killed child, and a session file + # written in a layout newer than this software reads (the tool's status 3), which the take is + # aligned from once the software is updated. job.refused_marker.parent.mkdir(parents=True, exist_ok=True) job.refused_marker.write_text(reason + "\n", encoding="utf-8") if process.returncode != 0: diff --git a/examples/egocap/backend/egocap_web/calibration_check.py b/examples/egocap/backend/egocap_web/calibration_check.py new file mode 100644 index 0000000000..a91daf4d84 --- /dev/null +++ b/examples/egocap/backend/egocap_web/calibration_check.py @@ -0,0 +1,503 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A live check of the installed head-camera calibration: no take, no solve, and nothing written. + +The check hands the library's ``LiveCheck`` live pictures of the head camera and every head pose that arrived +since the last look, and reports what it says. It reads the installed head-camera files once, when it starts. +It records no take and writes no file, no ledger entry and no board note. + +The pictures are the capture server's JPEGs for a camera it delivers. A camera that arrives over LiveKit has +no picture in the backend outside a take, so for such a camera the backend joins the video room for the length +of the check, as the recorder does for a take, and leaves when the check ends (calibration_check_pictures.py). + +A look is made when the page asks, as the calibration take's guide is. For a check that is in the video room, +asking is also its lease: one no page has asked about for a while is ended, so a page that was closed cannot +leave the backend in the room. A check and a take never run together: a check is refused while a take records, +and a take that starts ends the check before the recorder joins the room. +""" + +from __future__ import annotations + +import asyncio +import logging +import time +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from egocap.calibration.board import BoardSpec +from egocap.calibration.camera_lag import camera_lag_of_take +from egocap.calibration.files import ( + HEAD_EXTRINSICS, + HEAD_INTRINSICS, + CalibrationFileError, + Intrinsics, + load_headset_extrinsics, + load_intrinsics, + other_camera_problem, + pose_source_problem, + read_json_object, +) +from egocap.calibration.live_check import LiveCheck +from egocap.calibration.rectification_files import StreamsState + +from .calibration_check_pictures import DeliveredPictures, Picture, Pictures, VideoRoom +from .calibration_common import ( + HEAD_ROLE, + ROLE_PHRASES, + CalibrationRefusal, + bounded, + decoded_jpeg, + finite, + jpeg_text, + size_wh, +) +from .calibration_frames import DecodedFrame +from .calibration_service import CALIBRATE_HEADSET_FIRST, NO_LIVE_PICTURE, live_tracking, parse_board +from .rectification_service import RECTIFIED_UNKNOWN +from .streams_state import streams_unknown + +logger = logging.getLogger("isaaccapture.egocap.calibration_check") + +#: Where a check stands, as the page reads it. +CHECKING, STOPPED = "checking", "stopped" +#: What the check tells the operator of itself, whatever it finds. +READS_ONLY = ( + f"The check reads the installed {HEAD_INTRINSICS} and {HEAD_EXTRINSICS}. It records nothing and changes " + "no file." +) +#: Said beside it of a camera that arrives over LiveKit, while the check runs. +JOINS_ROOM = ( + "While it runs the backend is in the video room to see this camera, as it is during a take, and it leaves " + "when the check ends." +) +NO_CHECK = "no check is running" +#: What a page that still asks is told became of a check it did not stop itself. +ENDED_FOR_TAKE = "the check ended because a take started: the two never run together" +ENDED_UNASKED = "the check ended because the page that started it stopped asking about it" +ENDED_LONG = "the check ended after ten minutes, its longest: start it again to go on checking" +#: Why a check is not started beside a take. +TAKE_RUNNING = "a take is being recorded, and the check never runs beside one: finish or discard the take first" +CHECK_FAILED = "the check could not read this picture; see the backend logs" +#: Why a picture of another size than the installed calibration describes is not judged: its camera matrix does +#: not fit the picture, and a verdict from it would say the calibration moved when the picture mode did. +OTHER_SIZE = ( + "this camera sends a {has[0]}x{has[1]} picture, and the installed calibration is for {had[0]}x{had[1]}, so " + "it cannot be checked on this picture: set the camera's picture mode back, or calibrate again" +) +#: How old a picture may be and still be looked at. +_LIVE_SECONDS = 2.0 +#: How long a check stays in the video room with no page asking about it. The page asks a few times a second, +#: so this long a silence is a page that was closed or lost its connection. The glove calibration's lease is +#: the same length. +LEASE_SECONDS = 20.0 +#: The longest a check runs, whoever keeps asking about it: a tab left open must not keep the backend in the +#: video room, or at work on pictures, for the rest of the day. A check is a few minutes of an operator's time. +MAX_CHECK_SECONDS = 600.0 +#: How long a take that starts waits for the check to leave the video room. The two join the room under +#: identities of their own, so a leave that takes longer finishes behind the take. +YIELD_SECONDS = 2.0 +#: How often the lease is looked at. +_WATCH_SECONDS = 1.0 +#: How long a picture newer than the tracking that has arrived waits for the tracking to reach its time. The two +#: arrive on their own schedules, and a picture's head pose lies between the samples either side of it. +_TRACKING_WAIT_S = 0.5 +#: For how long head poses wait for a picture to be judged among them: longer than any picture waits to be +#: looked at, and than the library itself remembers a pose. +_POSES_KEPT_S = 4.0 +#: Seen corners, predicted corners, and the line from one to the other, in the preview (BGR). +_SEEN, _PREDICTED = (0, 255, 0), (255, 0, 255) + + +@dataclass +class _Check: + """One check: the calibration it was started with, and where its looking stands.""" + + camera: str + board: BoardSpec + #: The camera as this run's pictures show it, and its installed position on the headset. + lens: Intrinsics + headset_camera: np.ndarray + #: Whether ``lens`` is the camera a rectification made, since this run corrects the camera's video. + corrected: bool + #: How far a picture's time lies behind the tracking's, in seconds, as the installed position states it. + lag_s: float + started: float + #: Where its pictures come from: the capture server, or the video room for the length of the check. + pictures: Pictures + #: When a page last asked about it, which is its lease. + asked: float + #: Built from the first picture, whose size it needs. + check: LiveCheck | None = None + #: The capture time the check's seconds are counted from, so that they stay small numbers. + origin_ns: int | None = None + #: The picture last taken in, by what tells it from another, and the last tracking sample handed over. + seen: tuple[Any, ...] | None = None + handed: int | None = None + looking: bool = False + #: What the last look found, and the picture it was found in with its overlay. + record: dict[str, Any] | None = None + unavailable: str | None = None + preview: dict[str, Any] | None = None + #: What must come before a first picture can, in words, while the video room is being joined. + waiting_for: str | None = None + #: The head poses that arrived and wait for a look to take them to the library. + poses: list[tuple[float, np.ndarray]] = field(default_factory=list) + #: The time of the newest tracking sample that arrived, on the check's clock. + tracked_until: float | None = None + #: A picture not yet looked at, kept until the tracking reaches its time: the picture, its time on the + #: check's clock, and when it started to wait. + held: tuple[bytes | DecodedFrame, float, float] | None = None + + +def _overlay(frame: np.ndarray, record: Mapping[str, Any]) -> np.ndarray: + """A copy of the picture with each corner seen, each corner predicted, and the line between the two.""" + shown = frame.copy() + width, height = record["image_size_wh"] + scale = np.array([frame.shape[1] / width, frame.shape[0] / height]) + seen = np.asarray(record["corner_points"], dtype=np.float64).reshape(-1, 2) * scale + predicted = np.asarray(record["predicted_points"], dtype=np.float64).reshape(-1, 2) * scale + # A prediction far off the picture has numbers no line can be drawn to; ten pictures away is far enough. + reach = 10.0 * max(frame.shape[:2]) + for corner, point in zip(seen, predicted): + if np.all(np.abs(point) < reach): + u, v = (int(round(value)) for value in point) + cv2.line(shown, (int(round(corner[0])), int(round(corner[1]))), (u, v), _PREDICTED, 1, cv2.LINE_AA) + cv2.circle(shown, (u, v), 4, _PREDICTED, 1, cv2.LINE_AA) + for corner in seen: + cv2.circle(shown, (int(round(corner[0])), int(round(corner[1]))), 2, _SEEN, -1, cv2.LINE_AA) + return shown + + +class LiveCheckService: + """The one live check a backend runs at a time, started, polled and stopped from the calibration tools.""" + + def __init__( + self, + *, + monitor: Any, + calibration_dir: Callable[[], Path], + streams: StreamsState | None, + camera_for: Callable[[str], str | None], + monotonic: Callable[[], float] = time.monotonic, + video_room: VideoRoom | None = None, + take_running: Callable[[], bool] = lambda: False, + watch_seconds: float = _WATCH_SECONDS, + ) -> None: + """``monitor`` is the capture monitor, for the live picture and the tracking. ``calibration_dir`` + is read when a check starts. ``streams`` is what the launcher reported of this run's camera streams, + and ``camera_for`` the camera the station assigns to a role. ``video_room`` reaches the cameras that + arrive over LiveKit; without it none is known to. ``take_running`` says whether a take is being + recorded or a recording command is under way. ``watch_seconds`` is how often the lease is looked at.""" + self._monitor = monitor + self._calibration_dir = calibration_dir + self._streams = streams if streams is not None else StreamsState() + self._camera_for = camera_for + self._monotonic = monotonic + self._room = video_room + self._take_running = take_running + self._watch_seconds = watch_seconds + self._check: _Check | None = None + # What became of the last check when it was not the page that stopped it, for a page that still asks. + self._ended: str | None = None + self._watcher: asyncio.Future[None] | None = None + # One start, stop or other ending at a time: each may wait for the video room to be left. + self._changing = asyncio.Lock() + # Leaves that a take did not wait out, kept until they end. + self._behind: set[asyncio.Future[None]] = set() + + # --- starting and stopping --------------------------------------------------------------------------------- + + async def start(self, body: Mapping[str, Any]) -> dict[str, Any]: + """Start a check of the installed head-camera calibration against the board ``body`` describes, in + place of any check started before; answers with its status. Refused (409) with the reason when the + calibration cannot be judged at all, and while a take records. For a camera that arrives over LiveKit + the video room is joined in the background, and the status says what is waited for.""" + board = parse_board(body.get("board")) + async with self._changing: + camera = self._camera_for(HEAD_ROLE) + if camera is None: + raise CalibrationRefusal(409, f"no camera is assigned to the {ROLE_PHRASES[HEAD_ROLE]} role") + self._refuse_beside_a_take() + # Without the launcher's report it is not known whether this camera's pictures are corrected, and + # so which camera matrix they are pictures of. + if streams_unknown(self._streams): + raise CalibrationRefusal(409, RECTIFIED_UNKNOWN) + stream = None if self._room is None else self._room.stream(camera) + if stream is not None: + # Said before the room is joined: nothing that waiting in it could change. + unusable = self._room.refusal(stream) + if unusable is not None: + raise CalibrationRefusal(409, bounded(unusable)) + elif self._monitor.preview.camera(camera) is None: + raise CalibrationRefusal(409, NO_LIVE_PICTURE) + lens, headset_camera, lag_s, corrected = await asyncio.to_thread(self._installed, camera) + # A take may have started while the files were read. + self._refuse_beside_a_take() + # The check before this one leaves the room before this one joins it. + await self._end(None) + pictures: Pictures = ( + DeliveredPictures(self._monitor.preview, camera) if stream is None else self._room.pictures(stream) + ) + pictures.open() + now = self._monotonic() + check = _Check(camera, board, lens, headset_camera, corrected, lag_s, now, pictures, now) + check.waiting_for = pictures.waiting() + self._check = check + self._watcher = asyncio.ensure_future(self._watch(check)) + return self._status(check) + + def _refuse_beside_a_take(self) -> None: + """Refuse (409) while a take is being recorded or a recording command is under way.""" + if self._take_running(): + raise CalibrationRefusal(409, TAKE_RUNNING) + + def _installed(self, camera: str) -> tuple[Intrinsics, np.ndarray, float, bool]: + """The installed head-camera calibration as the check uses it: the camera this run's pictures show, + its position on the headset, how far its pictures lag the tracking, and whether the camera is a + corrected one. Refused (409) when a file is missing, unreadable, another camera's or made with another + tracking source; file work, for a worker thread. Reads, and writes nothing.""" + directory = Path(self._calibration_dir()) + try: + lens = load_intrinsics(directory / HEAD_INTRINSICS) + headset_camera = load_headset_extrinsics(directory / HEAD_EXTRINSICS) + # Read once more for its stamps and its lag: the loader gives the pose alone. + position = read_json_object(directory / HEAD_EXTRINSICS) + except CalibrationFileError as exc: + raise CalibrationRefusal(409, bounded(f"{CALIBRATE_HEADSET_FIRST}: {exc}")) from None + stamps = ( + other_camera_problem(lens.record, camera, HEAD_INTRINSICS), + other_camera_problem(position, camera, HEAD_EXTRINSICS), + pose_source_problem(position, HEAD_EXTRINSICS), + ) + elsewhere = next(filter(None, stamps), None) + if elsewhere is not None: + raise CalibrationRefusal(409, bounded(f"{CALIBRATE_HEADSET_FIRST}: {elsewhere}")) + try: + # A picture the bridge corrected is one of the corrected camera, which the lens's numbers do not fit. + corrected = self._streams.corrected_camera(camera) + except CalibrationFileError as unusable: + raise CalibrationRefusal( + 409, bounded(f"this camera's video is being corrected, and {unusable}") + ) from None + # Live tracking times are the capture server's own, with no latency taken off them. + lag_s = camera_lag_of_take(position, 0.0).seconds + return (lens if corrected is None else corrected), headset_camera, lag_s, corrected is not None + + async def stop(self) -> dict[str, Any]: + """End the check, if one runs, and leave the video room if it was in it. Nothing was written, so + there is nothing to keep or to undo.""" + async with self._changing: + await self._end(None) + return {"phase": STOPPED, "note": READS_ONLY} + + async def yield_to_take(self) -> None: + """End the check because a take is starting: the two never run together, and the recorder joins the + video room for the take itself. Awaited before the recorder's join, which it never refuses and never + holds for long: the check is over at once, and a leave the room is slow to answer finishes behind + the take, which joins under an identity of its own.""" + async with self._changing: + if self._check is None: + return + logger.info("The live calibration check ended for a take that is starting") + leave = asyncio.ensure_future(self._end(ENDED_FOR_TAKE)) + _ = await asyncio.wait({leave}, timeout=YIELD_SECONDS) + if not leave.done(): + logger.warning("The live calibration check is still leaving the video room as the take starts") + self._behind.add(leave) + leave.add_done_callback(self._behind.discard) + + async def aclose(self) -> None: + """End the check at shutdown, so that the backend is not left in the video room, and give a leave + that a take left behind a moment to finish.""" + async with self._changing: + await self._end(None) + if self._behind: + _ = await asyncio.wait(set(self._behind), timeout=YIELD_SECONDS) + + async def _end(self, reason: str | None) -> None: + """End the check that runs, if one does, and leave the video room if it was in it. ``reason`` is + what a page that still asks is told became of it; None for an end the page itself asked for. Called + under the lock. Never raises: whoever ends a check, a take or a shutdown among them, is not failed + by how the check left.""" + check, watcher = self._check, self._watcher + self._check, self._watcher, self._ended = None, None, reason + # The watcher is this check's; when it is the watcher that ends it, the watcher is the caller. + if watcher is not None and watcher is not asyncio.current_task(): + watcher.cancel() + if check is not None: + try: + await check.pictures.close() + except Exception: # noqa: BLE001 -- the check is over either way; how it left is for the log + logger.exception("The live calibration check did not leave cleanly") + + async def _watch(self, check: _Check) -> None: + """End ``check`` when it has run for its longest length, and, when its pictures hold the backend's + place in the video room, once no page has asked about it for the length of its lease. A page that was + closed or lost its connection cannot stop its check, a tab left open never does, and the backend must + not stay in the room or at work for either. Cancelled when the check ends any other way.""" + reason = None + while reason is None: + await asyncio.sleep(self._watch_seconds) + now = self._monotonic() + if now - check.started > MAX_CHECK_SECONDS: + reason = ENDED_LONG + # The lease is for what a forgotten check would hold: a check of a camera the capture server + # delivers holds nothing between two polls. + elif check.pictures.leased and now - check.asked > LEASE_SECONDS: + reason = ENDED_UNASKED + async with self._changing: + # Another check may have taken this one's place while the lock was waited for. + if self._check is check: + logger.info("The live calibration check ended on its own: %s", reason) + await self._end(reason) + + # --- looking ----------------------------------------------------------------------------------------------- + + async def poll(self) -> dict[str, Any]: + """Where the check stands, after a look at the newest live picture when there is a new one. Refused + (404) when no check runs, with what became of one that ended without the page stopping it.""" + check = self._check + if check is None: + raise CalibrationRefusal(404, self._ended or NO_CHECK) + # Asking is the lease. + check.asked = self._monotonic() + # Polls must not pile up behind a detection: one that finds another at work answers with what is known. + if not check.looking: + await self._look(check) + return self._status(check) + + async def _look(self, check: _Check) -> None: + """Take the head poses that arrived, and look at a picture not yet seen once the tracking has reached + its time.""" + self._collect_poses(check) + pictures, now = check.pictures, self._monotonic() + # A video room that gave up says why; no picture will come from it again. + failure = pictures.failure() + if failure is not None: + check.waiting_for, check.unavailable, check.preview, check.held = None, bounded(failure), None, None + return + # While the room is being joined there is nothing to look at, and nothing wrong either. + check.waiting_for = pictures.waiting() + if check.waiting_for is not None: + return + picture = pictures.newest() + if picture is None or now - picture.received_monotonic > _LIVE_SECONDS: + check.unavailable, check.preview, check.held = NO_LIVE_PICTURE, None, None + return + if picture.key != check.seen: + check.seen = picture.key + if check.origin_ns is None: + check.origin_ns = picture.capture_time_ns + # A picture that already waits keeps its turn: the tracking reaches it before a newer one. + if check.held is None: + check.held = (picture.content, self._seconds(check, picture), now) + if check.held is None: + return + content, seconds, since = check.held + # The later of the two samples a picture's head pose lies between may not have arrived yet. Tracking + # that stays away is the library's to report, so the wait for it is bounded. + reached = check.tracked_until is not None and check.tracked_until >= seconds + if not reached and now - since < _TRACKING_WAIT_S: + return + check.held, check.looking = None, True + track, check.poses = check.poses, [] + try: + looked = await asyncio.to_thread(self._observe, check, content, seconds, track) + except Exception: # noqa: BLE001 -- the check only reports; its failure must not fail the poll + logger.exception("The live calibration check failed on a picture") + looked = None + finally: + check.looking = False + if looked is None: + # What the check found before stands; only this picture said nothing. + check.unavailable, check.preview = CHECK_FAILED, None + return + found, check.preview = looked + if isinstance(found, str): + # The picture is shown as it came: nothing in it is judged, and the sentence says why. + check.unavailable = found + else: + check.unavailable, check.record = None, found + + @staticmethod + def _seconds(check: _Check, picture: Picture) -> float: + """A picture's time on the check's clock, which is the tracking's: the camera's stored lag behind the + tracking comes off it. A capture server picture carries the capture server's time, and a video room + picture the time the recorder's feed placed it at on this machine's clock, where the tracking's times + are too.""" + assert check.origin_ns is not None # set from the first picture or tracking sample, before any look + return (picture.capture_time_ns - check.origin_ns) / 1e9 - check.lag_s + + def _collect_poses(self, check: _Check) -> None: + """Queue the head pose of every tracking sample that arrived since the last look, on the check's + clock. Each is placed by the capture server's own time for it, since arrivals bunch.""" + arrived = self._monitor.preview.tracking_after(check.handed) + if not arrived: + return + check.handed = arrived[-1].sequence + if check.origin_ns is None: + check.origin_ns = arrived[0].capture_time_ns + # Counted whether or not the sample holds a head: tracking that arrives without one is not waited for. + check.tracked_until = (arrived[-1].capture_time_ns - check.origin_ns) / 1e9 + for sample in arrived: + head = live_tracking(sample.payload).head + if head is not None: + check.poses.append(((sample.capture_time_ns - check.origin_ns) / 1e9, head)) + # While no picture is judged nothing takes the poses away. Only those a picture could still be placed + # among are kept: a picture older than this is not looked at. + oldest = check.tracked_until - _POSES_KEPT_S + if check.poses and check.poses[0][0] < oldest: + check.poses = [pose for pose in check.poses if pose[0] >= oldest] + + @staticmethod + def _observe( + check: _Check, content: bytes | DecodedFrame, seconds: float, track: list[tuple[float, np.ndarray]] + ) -> tuple[dict[str, Any] | str, dict[str, Any]] | None: + """One picture through the library's check: its record, and the picture with the corners seen and + the corners predicted drawn on it. For a picture the installed calibration does not describe, the + reason in words and the picture as it came. None for a picture that does not decode. ``content`` is + a JPEG the capture server delivered or a frame the video room's feed decoded. Decoding and detection, + for a worker thread; one call at a time.""" + # A decoded frame is the feed's own array, so the check is given a copy in the order OpenCV takes. + frame = decoded_jpeg(content) if isinstance(content, bytes) else content.bgr() + if frame is None: + return None + # A camera started in another picture mode sends pictures the installed camera matrix was not solved on. + if size_wh(frame) != tuple(check.lens.image_size_wh): + found: dict[str, Any] | str = OTHER_SIZE.format( + has=size_wh(frame), had=tuple(check.lens.image_size_wh) + ) + shown = frame + else: + if check.check is None: + check.check = LiveCheck(check.board, check.lens, check.headset_camera, size_wh(frame)) + found = finite(check.check.observe(frame, seconds, track)) + shown = _overlay(frame, found) + width, height = size_wh(shown) + return found, {"jpeg": jpeg_text(shown), "width": width, "height": height} + + def _status(self, check: _Check) -> dict[str, Any]: + """The check as the page reads it.""" + return { + "phase": CHECKING, + "camera": check.camera, + # Which description of the camera the board is posed and its corners predicted with. + "corrected": check.corrected, + "camera_lag_ms": round(check.lag_s * 1000.0, 3), + "elapsed_s": round(self._monotonic() - check.started, 1), + "available": check.unavailable is None, + "unavailable_reason": check.unavailable, + # Whether the backend is in the video room for this check, and what it waits for there. + "video_room": check.pictures.in_room, + "waiting": check.waiting_for, + "check": check.record, + "preview": check.preview, + "note": f"{READS_ONLY} {JOINS_ROOM}" if check.pictures.in_room else READS_ONLY, + } diff --git a/examples/egocap/backend/egocap_web/calibration_check_pictures.py b/examples/egocap/backend/egocap_web/calibration_check_pictures.py new file mode 100644 index 0000000000..2abd03feb3 --- /dev/null +++ b/examples/egocap/backend/egocap_web/calibration_check_pictures.py @@ -0,0 +1,289 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The live pictures a calibration check looks at, wherever the camera's video reaches the backend. + +A camera the capture server delivers has a JPEG in the backend at all times. A camera that arrives over LiveKit +has none outside a take. For the length of a check, and only then, the backend therefore joins the video room +as a subscriber of that one camera's track, through the recorder's own source (``LiveKitRecordingSource``): the +same join, the same first-frame and size check, the same wait for the publisher's clock mapping, and the same +placing of each frame's time on this machine's clock as for a take. The frames are noted the way a take's are +(``NewestFrames``) by an ingress that offers them no further, so nothing is recorded. + +This is an operator's action for a bounded time. Nothing here keeps the backend in the room between checks. +""" + +from __future__ import annotations + +import asyncio +import logging +import time +from collections.abc import Callable +from dataclasses import dataclass +from types import SimpleNamespace +from typing import Any, Protocol + +from capture_server import protocol as p + +from .calibration_frames import DecodedFrame, NewestFrames, NotingIngress +from .livekit_recording import CLOCK_MAPPING, FIRST_FRAME, JOINING, LiveKitRecordingSource, unrecordable_reason + +logger = logging.getLogger("isaaccapture.egocap.calibration_check_pictures") + +#: What a check says while it is on its way into the video room, by what the recorder's source is waiting for. +WAITING = { + JOINING: "Joining the video room to see this camera.", + FIRST_FRAME: "In the video room: waiting for this camera's first picture.", + CLOCK_MAPPING: ( + "Pictures are arriving: waiting for the camera sender's clock to be matched to this computer's, so that " + "each picture's time can be placed among the head poses." + ), +} +#: How long a check waits for the room to answer its leave before it lets the leave finish on its own: a +#: take may be waiting behind it. +LEAVE_SECONDS = 1.5 +#: Why a check cannot have a camera's video from the room. The reason that follows is the recorder's own +#: sentence, composed in this project: the check gets the video exactly as a take does, so what stops the one +#: stops the other. +AS_A_TAKE = "the check gets this camera's video the way a take does, and could not: {reason}" +#: Why the way into the room ended without pictures, by the stage it ended at. One sentence each, and nothing +#: of what the video library or the video server said: that can hold anything, and goes to the log. +JOIN_FAILED = { + JOINING: ( + "the video room could not be joined, so the check has no picture of this camera: check that the video " + "server is running and that this computer reaches it, then start the check again" + ), + FIRST_FRAME: ( + "the video room was joined, and this camera's first picture did not come as a take needs it, so the " + "check has no picture of it: check the camera's sender, then start the check again" + ), + CLOCK_MAPPING: ( + "this camera's pictures arrive, and the camera sender's clock could not be matched to this computer's, " + "so their times cannot be placed among the head poses: check the camera's sender, then start the check " + "again" + ), +} +#: The same for a way in that was given up from outside before it ended. +LEFT_EARLY = ( + "the video room was left before this camera's pictures came, so the check has no picture of it: start " + "the check again" +) + + +@dataclass(frozen=True) +class Picture: + """One live picture as a check looks at it.""" + + #: What tells it from the picture before. + key: tuple[Any, ...] + #: When it was taken, in nanoseconds on the clock the tracking samples are stamped on. + capture_time_ns: int + #: When it reached the backend, on the monotonic clock live pictures are aged by. + received_monotonic: float + #: The picture itself: a JPEG the capture server delivered, or a frame the video room's feed decoded. + content: bytes | DecodedFrame + + +class Pictures(Protocol): + """Where one check's pictures come from.""" + + #: Whether these pictures hold the backend's place in the video room, so that a check nobody asks about + #: any more must not keep them. + leased: bool + + @property + def in_room(self) -> bool: + """Whether the backend is in the video room for these pictures now, or on its way in.""" + + def open(self) -> None: + """Begin whatever it takes to have pictures. Returns at once.""" + + def newest(self) -> Picture | None: + """The newest picture there is, or None.""" + + def waiting(self) -> str | None: + """What is being waited for before a first picture can come, in words; None when nothing is.""" + + def failure(self) -> str | None: + """Why no further picture will come, in words; None while they may.""" + + async def close(self) -> None: + """Give up the pictures and whatever was held for them.""" + + +class DeliveredPictures: + """The pictures the capture server delivers of a camera: in the backend whenever the camera sends.""" + + leased = False + in_room = False + + def __init__(self, preview: Any, camera: str) -> None: + """``preview`` is the capture monitor's cache of the newest picture of each camera.""" + self._preview = preview + self._camera = camera + + def open(self) -> None: + """Nothing to begin: the capture session already delivers them.""" + + def newest(self) -> Picture | None: + """The newest JPEG delivered, stamped with the capture server's own time for it.""" + slot = self._preview.camera(self._camera) + if slot is None: + return None + return Picture(("delivered", slot.sequence), slot.capture_time_ns, slot.received_monotonic, slot.jpeg) + + def waiting(self) -> str | None: + """Never: nothing is joined for these pictures.""" + return None + + def failure(self) -> str | None: + """Never: a camera that stops sending only has no live picture.""" + return None + + async def close(self) -> None: + """Nothing was held.""" + + +class RoomPictures: + """One LiveKit camera's pictures for the length of a check: the backend is in the video room from + ``open()`` until ``close()``, or until its video fails, and at no other time.""" + + leased = True + + def __init__( + self, + stream: p.LiveKitCameraStream, + make_token: Callable[[str], str], + monotonic: Callable[[], float] = time.monotonic, + ) -> None: + """``stream`` is the camera's stream as the capture session offers it and ``make_token`` signs the + room token, as for the recorder. ``monotonic`` is the clock a picture's age is measured on.""" + self._stream = stream + self._frames = NewestFrames(monotonic) + # The recorder's own source, told of this one stream only: its join, its checks and its clock mapping. + # Its leave is given a short limit: a take may be waiting for the check to be out of its way. + self._source = LiveKitRecordingSource(lambda: (stream,), make_token, leave_timeout_s=LEAVE_SECONDS) + self._joining: asyncio.Future[None] | None = None + self._leaving: asyncio.Future[None] | None = None + self._failure: str | None = None + + @property + def in_room(self) -> bool: + """Whether the backend is in the room for these pictures, or on its way in: not before ``open()``, + not once the video failed, and not after ``close()``.""" + return self._joining is not None and self._failure is None + + def open(self) -> None: + """Begin joining the room. The join, the first picture and the clock mapping are waited for in the + background; ``waiting()`` says which, and ``failure()`` why it did not come to pictures.""" + self._joining = asyncio.ensure_future(self._join()) + + async def _join(self) -> None: + """Join as the recorder does for a take and, once its video is usable, have each frame noted.""" + try: + await self._source.prepare() + except asyncio.CancelledError: + # Given up from outside: the source leaves the room it was entering, and nothing is waited for. + self._failure = LEFT_EARLY + raise + except Exception as exc: # noqa: BLE001 -- whatever stops the join ends it; the operator gets the stage + # The source has already left the room it could not use, and still says how far it had come. What + # was raised may be the video library's or the server's own text: it is logged, never shown. + stage = self._source.stage or JOINING + logger.warning( + "The live check could not get %s from the video room (%s): %s", self._stream.name, stage, exc + ) + self._failure = JOIN_FAILED[stage] + return + self._source.start(NotingIngress(self._frames), self._failed) + + def _failed(self, reason: str) -> None: + """The feed stopped, for the reason it would have ended a take. Called from the feed's own task, so the + room is left from another.""" + logger.warning("The live check lost %s in the video room: %s", self._stream.name, reason) + self._failure = AS_A_TAKE.format(reason=reason) + self._leaving = asyncio.ensure_future(self._left()) + + def newest(self) -> Picture | None: + """The newest frame the feed handed over, at the time the feed placed it on this machine's clock.""" + frame = self._frames.newest(self._stream.name) + if frame is None: + return None + return Picture( + ("decoded", frame.sequence), round(frame.capture_time * 1e9), frame.received_monotonic, frame + ) + + def waiting(self) -> str | None: + """What stands between the check and a first picture: the join's stage while it is under way, and + after it the first frame the feed has yet to hand over.""" + joining = self._joining + if joining is None or self._failure is not None: + return None + if not joining.done(): + # Before the join's first step the source names no stage yet: it is about to join. + return WAITING[self._source.stage or JOINING] + return WAITING[FIRST_FRAME] if self._frames.newest(self._stream.name) is None else None + + def failure(self) -> str | None: + """Why the room gives no pictures: the join's reason, or the feed's.""" + return self._failure + + async def _left(self) -> None: + """Stop the source and leave the room. Never raises: a check that cannot leave cleanly says so in the + log, and neither refuses a take nor fails whoever ended it.""" + try: + await self._source.stop() + except Exception: # noqa: BLE001 -- the source has left the room by now; what it raised is for the log + logger.exception("The live calibration check did not leave cleanly") + + async def close(self) -> None: + """Leave the room, whatever stage the join had reached, and forget the frames noted. Never raises.""" + joining, leaving = self._joining, self._leaving + self._joining = self._leaving = None + try: + if joining is not None: + # A join still under way is abandoned; the source leaves the room it was entering. + joining.cancel() + _ = await asyncio.gather(joining, return_exceptions=True) + if leaving is not None: + # A leave begun when the feed failed is let finish, so the room is not left twice at once. + _ = await asyncio.gather(leaving, return_exceptions=True) + finally: + # Whatever became of the steps before it, the source is stopped: that is what leaves the room. + await self._left() + self._frames.clear() + + +class VideoRoom: + """How a check reaches the cameras that arrive over LiveKit: which they are, whether their video can be + had as a take has it, and their pictures for the length of a check.""" + + def __init__( + self, + stream_named: Callable[[str], p.LiveKitCameraStream | None], + make_token: Callable[[str], str], + capture_server_url: str | None, + monotonic: Callable[[], float] = time.monotonic, + ) -> None: + """``stream_named`` gives the LiveKit stream the capture session offers under a camera's name, or + None. ``make_token`` signs a room token, as for the recorder. ``capture_server_url`` is where the + tracking comes from: frame times can be placed among the head poses only when that is this machine.""" + self._stream_named = stream_named + self._make_token = make_token + self._capture_server_url = capture_server_url + self._monotonic = monotonic + + def stream(self, camera: str) -> p.LiveKitCameraStream | None: + """The LiveKit stream a camera arrives as; None for a camera the capture server delivers.""" + return self._stream_named(camera) + + def refusal(self, stream: p.LiveKitCameraStream) -> str | None: + """Why this stream's video cannot be had as a take has it, in words; None when it can. The rule is the + recorder's, asked of this one stream.""" + reason = unrecordable_reason(SimpleNamespace(streams=(stream,)), self._capture_server_url) + return None if reason is None else AS_A_TAKE.format(reason=reason) + + def pictures(self, stream: p.LiveKitCameraStream) -> RoomPictures: + """The stream's pictures for one check, not yet joined.""" + return RoomPictures(stream, self._make_token, self._monotonic) diff --git a/examples/egocap/backend/egocap_web/calibration_common.py b/examples/egocap/backend/egocap_web/calibration_common.py index b90b7adfa0..ee1d864929 100644 --- a/examples/egocap/backend/egocap_web/calibration_common.py +++ b/examples/egocap/backend/egocap_web/calibration_common.py @@ -26,7 +26,7 @@ from fastapi import Request from fastapi.responses import JSONResponse, Response -from egocap.calibration import files, station_store +from egocap.calibration import files, provenance, station_store from .recording_command import control_token_valid from .request_body import read_authorized_json @@ -149,9 +149,14 @@ def file_holds(path: Path, record: Mapping[str, Any]) -> bool: same; whoever asked for it looks here to tell. A file that cannot be read holds nothing. """ try: + # Without what the store itself states in the file it writes (when it was installed, what it + # replaced), which no caller's record holds. + installed = provenance.without_validity(files.read_json_object(Path(path))) # Compared as JSON text: a tuple in the record is a list once it has been a file, and a number JSON # writes as NaN equals itself there. - return json.dumps(files.read_json_object(Path(path)), sort_keys=True) == json.dumps(record, sort_keys=True) + return json.dumps(installed, sort_keys=True) == json.dumps( + provenance.without_validity(record), sort_keys=True + ) except (files.CalibrationFileError, TypeError, ValueError): return False diff --git a/examples/egocap/backend/egocap_web/calibration_frames.py b/examples/egocap/backend/egocap_web/calibration_frames.py index ffe4de9f57..5e77292d06 100644 --- a/examples/egocap/backend/egocap_web/calibration_frames.py +++ b/examples/egocap/backend/egocap_web/calibration_frames.py @@ -10,13 +10,15 @@ joins the room and is fed decoded frames. This module notes each of those frames on its way into the take, so a calibration take of such a camera is guided by the same pictures it records. -Nothing here changes what is recorded: a frame is noted and then offered on as it came. +Nothing here changes what is recorded: a frame is noted and then offered on as it came. A look at such a camera +that records nothing (the live check of an installed calibration) is fed the same way, through an ingress that +notes each frame and offers it no further. """ from __future__ import annotations import time -from collections.abc import Callable +from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any @@ -33,6 +35,9 @@ class DecodedFrame: #: The picture, height by width by three channels. The take records this array, so nothing may write to it. image: np.ndarray pixel_format: PixelFormat + #: When it was taken, in seconds on this machine's monotonic clock: where the recorder's feed placed the + #: publisher's time for it, which is the time a take records it at. + capture_time: float #: When it was noted, on the monotonic clock the live pictures are aged by. received_monotonic: float #: Counts the frames noted for the camera, so a poll can tell a new picture from the one it looked at. @@ -64,7 +69,7 @@ def note(self, sample: Any) -> None: return self._noted += 1 self._frames[sample.source] = DecodedFrame( - sample.image, sample.pixel_format, self._monotonic(), self._noted + sample.image, sample.pixel_format, sample.capture_time, self._monotonic(), self._noted ) def newest(self, camera: str | None) -> DecodedFrame | None: @@ -90,6 +95,23 @@ def offer(self, sample: Any) -> bool: return self._ingress.offer(sample) +class NotingIngress: + """An ingress that is the end of the line: each frame offered is noted and goes no further. + + It stands where a take's ingress stands for the recorder's LiveKit source, for a look at a camera's video + that records nothing. + """ + + def __init__(self, frames: NewestFrames) -> None: + """``frames`` is where each frame is noted.""" + self._frames = frames + + def offer(self, sample: Any) -> bool: + """Note the frame. Always accepted: nothing behind this ingress can fill or fail.""" + self._frames.note(sample) + return True + + class WatchedLiveKitSource: """The recorder's LiveKit source with the frames it feeds a take noted on the way. @@ -97,13 +119,21 @@ class WatchedLiveKitSource: what it was; the calibration service reads the noted frames. """ - def __init__(self, source: Any, frames: NewestFrames) -> None: - """``source`` is the recorder's LiveKit source and ``frames`` where its frames are noted.""" + def __init__( + self, source: Any, frames: NewestFrames, before_join: Callable[[], Awaitable[None]] | None = None + ) -> None: + """``source`` is the recorder's LiveKit source and ``frames`` where its frames are noted. + ``before_join`` is awaited before each take's join: whatever else is in the room for the same video + (a live check) leaves first.""" self._source = source self._frames = frames + self._before_join = before_join async def prepare(self) -> None: - """Join the room before the take's storage opens, as the source does.""" + """Join the room before the take's storage opens, as the source does, once anything that had to + leave for the take has left.""" + if self._before_join is not None: + await self._before_join() await self._source.prepare() def start(self, ingress: Any, on_failure: Callable[[str], None]) -> None: diff --git a/examples/egocap/backend/egocap_web/calibration_routes.py b/examples/egocap/backend/egocap_web/calibration_routes.py index fb329ca6b1..bc6ed76981 100644 --- a/examples/egocap/backend/egocap_web/calibration_routes.py +++ b/examples/egocap/backend/egocap_web/calibration_routes.py @@ -3,7 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 """HTTP surface of the calibration tools: the overview, the calibration recording shared by the headset and -glove tools, and the camera solve with its cancel, picked frames and install. +glove tools, the camera solve with its cancel, picked frames and install, and the live check of the installed +head-camera calibration, which records and writes nothing. Every route needs the run's control token, reads too: they return camera pictures and who calibrated what. The handlers only admit the request and hand it to the one ``CalibrationService`` (calibration_service.py), which @@ -20,7 +21,7 @@ from fastapi import APIRouter, Request from fastapi.responses import JSONResponse, Response -from .calibration_common import CalibrationRefusal, admitted, admitted_body, jpeg, refused, reply +from .calibration_common import NOT_READY, CalibrationRefusal, admitted, admitted_body, jpeg, refused, reply router = APIRouter(prefix="/api/calibration") @@ -132,3 +133,45 @@ async def install_calibration(request: Request) -> JSONResponse: if body is None: return refusal # type: ignore[return-value] return await _answer(host.install(body)) + + +def _live_check(request: Request) -> Any | None: + """The live check's service (calibration_check.py), or None before the application has set it.""" + return getattr(request.app.state, "calibration_check", None) + + +@router.post("/check") +async def start_check(request: Request) -> JSONResponse: + """Start a live check of the installed head-camera calibration. It reads the installed files and writes + nothing: no take is recorded.""" + host, body, refusal = await admitted_body(request) + if body is None: + return refusal # type: ignore[return-value] + check = _live_check(request) + if check is None: + return reply({"detail": NOT_READY}, 503) + return await _answer(check.start(body)) + + +@router.get("/check") +async def poll_check(request: Request) -> JSONResponse: + """Where the live check stands, after a look at the newest live picture.""" + host, refusal = admitted(request) + if host is None: + return refusal # type: ignore[return-value] + check = _live_check(request) + if check is None: + return reply({"detail": NOT_READY}, 503) + return await _answer(check.poll()) + + +@router.post("/check/stop") +async def stop_check(request: Request) -> JSONResponse: + """End the live check. There is nothing to keep or to undo: it wrote nothing.""" + host, body, refusal = await admitted_body(request) + if body is None: + return refusal # type: ignore[return-value] + check = _live_check(request) + if check is None: + return reply({"detail": NOT_READY}, 503) + return reply(await check.stop()) diff --git a/examples/egocap/backend/egocap_web/calibration_service.py b/examples/egocap/backend/egocap_web/calibration_service.py index a992912680..ad0e2974b0 100644 --- a/examples/egocap/backend/egocap_web/calibration_service.py +++ b/examples/egocap/backend/egocap_web/calibration_service.py @@ -41,7 +41,7 @@ import numpy as np from capture_server import protocol as capture_protocol -from egocap.calibration import station_store +from egocap.calibration import provenance, station_store from egocap.calibration.board import BoardError, BoardSpec, CalibrationError from egocap.calibration.camera_pipeline import ( DEFAULT_LAG_SEARCH_S, @@ -62,6 +62,7 @@ Intrinsics, load_headset_extrinsics, load_intrinsics, + picture_size_note, pose_source_problem, read_json_object, ) @@ -117,6 +118,7 @@ run_notes, streams_reported, ) +from .stations import TRACKING_DEVICES from .streams_state import SessionFiles, streams_unknown logger = logging.getLogger("isaaccapture.egocap.calibration_service") @@ -131,6 +133,13 @@ #: The checklist item a calibration take is not held for: the take is what produces those files. CALIBRATION_ITEMS = frozenset({"calibration"}) +#: The tracking devices each tool's take records with. A station's requirement of any other device does not +#: hold that tool's take: the headset calibration records the headset and both controllers (the recorder keeps +#: tracking only while all three are tracked) and no glove; the controller-glove offset is fitted on all five. +TOOL_DEVICES = { + CAMERA_TOOL: frozenset({"headset", "controller_left", "controller_right"}), + GLOVE_TOOL: frozenset(TRACKING_DEVICES), +} GLOVE_PHRASE = "controller–glove offset" #: The lens models a camera's intrinsics are solved with, and the one each camera type's lens needs when a #: request names none: a wide-angle lens is a fisheye, and a lens of an unknown type is taken for the other. @@ -718,8 +727,9 @@ def _file_row( described: Mapping[str, Any], camera: Any = None, record: Mapping[str, Any] | None = None ) -> dict[str, Any]: """One calibration file as the overview lists it: the store's facts, its headline figure as ``quality``, - the camera its solve stamped it with, when it names one, and, for a file of poses whose content is - ``record``, why it is not built on (``problem``) when it does not say which tracking made it.""" + the camera its solve stamped it with, when it names one, and why a file whose content is ``record`` is + not built on (``problem``): it is written in a newer layout than this software reads, or it is a file of + poses that does not say which tracking made it.""" row = {key: described[key] for key in ("name", "present", "readable", "calibrated_at") if key in described} quality = {key: value for key, value in described.items() if key not in row} # A date written by hand can hold text no reply can be encoded with; the file is then shown without one. @@ -727,10 +737,13 @@ def _file_row( row.pop("calibrated_at", None) if sendable(camera): row["camera"] = camera - # A lens is a lens whoever solved it; only poses are tied to the tracking they were measured against. - problem = ( - pose_source_problem(record, row["name"]) if record is not None and row["name"] in _POSE_FILES else None - ) + problem = None + if record is not None: + # No reader here takes a file of a newer layout, whatever kind of file it is. Then: a lens is a lens + # whoever solved it; only poses are tied to the tracking they were measured against. + problem = provenance.layout_problem(record, row["name"]) + if problem is None and row["name"] in _POSE_FILES: + problem = pose_source_problem(record, row["name"]) if problem is not None: row["problem"] = problem # The same names and units the solve's own result uses, so the page shows one vocabulary. @@ -761,9 +774,22 @@ def _installed_files(directory: Path) -> list[dict[str, Any]]: return rows +def _installed_lenses(directory: Path) -> dict[str, Intrinsics]: + """The lens file installed for each camera role that has a readable one; file work, for a worker thread. + A role whose file is missing or unreadable is left out: the files' own rows say that.""" + lenses = {} + for role, name in ROLE_INTRINSICS.items(): + try: + lenses[role] = load_intrinsics(Path(directory) / name) + except CalibrationFileError: + continue + return lenses + + def _ledger_rows(ledger: Mapping[str, Any]) -> dict[str, Any]: - """The ledger as the page reads it: who last installed each kind of calibration, and when. The file can be - edited by hand, so only what has the expected shape, and can be sent at all, is passed on.""" + """The ledger as the page reads it: who last installed each kind of calibration, when, and which of its + files that install left unchanged. The file can be edited by hand, so only what has the expected shape, + and can be sent at all, is passed on.""" rows = {} for kind, entry in ledger.items(): if not sendable(kind) or not isinstance(entry, dict): @@ -774,6 +800,12 @@ def _ledger_rows(ledger: Mapping[str, Any]) -> dict[str, Any]: # Only the names the station keeps: whatever else a hand wrote there names no file of it. "files": [name for name in files if name in station_store.CALIBRATION_FILES], } + # The entry's files that its last install found already installed and left as they were, so the page + # does not read the note as a calibration that was made. + noted = entry.get("unchanged") if isinstance(entry.get("unchanged"), list) else [] + unchanged = [name for name in rows[kind]["files"] if name in noted] + if unchanged: + rows[kind]["unchanged"] = unchanged return rows @@ -885,6 +917,27 @@ def live_picture(self, camera: str | None) -> Any | None: return None return slot + def _picture_notes(self, role: str, camera: str | None, lens: Intrinsics | None) -> dict[str, str | None]: + """What Set up says before a take when ``camera`` sends another size of picture than its installed + lens file was solved at: ``lens`` for a take that solves the lens, which would replace that file, and + ``position`` for a take of the position alone, which builds on it. Each None when there is nothing to + say: no such file, a file solved for another camera, a size that is not known, or the same size.""" + nothing: dict[str, str | None] = {"lens": None, "position": None} + # The size the capture session says the camera sends, which is the size a take records. + name, size = ROLE_INTRINSICS[role], self._monitor.camera_size(camera) + # A corrected picture has the size its rectification gave it, not the lens's; that case has its own words. + corrected = self._streams.rectified(camera) or streams_unknown(self._streams) + if lens is None or size is None or corrected: + return nothing + # A file solved for another camera is replaced whatever its size; that is said of the file itself. + if other_camera_problem(lens.record, camera, name) is not None: + return nothing + return { + "lens": picture_size_note(lens, size, name, lens_solved=True), + # Only the head camera has a position to solve. + "position": picture_size_note(lens, size, name, lens_solved=False) if role == HEAD_ROLE else None, + } + def _cameras(self) -> list[tuple[str, str | None, bool]]: """Every role with the camera filling it and whether that camera has a live picture.""" cameras = {role: self.camera_for(role) for role in ROLE_INTRINSICS} @@ -971,8 +1024,10 @@ async def _start(self, request: RecordingRequest) -> dict[str, Any]: try: await self.refresh_roles() self._refuse_unless_recorder_free() - # A missing calibration file never holds the take that produces it; everything else holds as usual. - held = self._setup_gate(ignore=CALIBRATION_ITEMS) + # A missing calibration file never holds the take that produces it, and neither does a station's + # requirement of a device this tool does not record with; everything else holds as usual. + unused = frozenset(TRACKING_DEVICES) - TOOL_DEVICES[request.tool] + held = self._setup_gate(ignore=CALIBRATION_ITEMS, unused_devices=unused) if held is not None: raise CalibrationRefusal(409, bounded(held)) camera = self._camera_to_record(request) @@ -1904,12 +1959,15 @@ def _install( ) -> None: """Write each part as the station's file for it, adding its name to ``written``, or to ``unlogged`` when the file went in and the install then failed; file work, for a worker thread.""" + # One install is one moment: each file states it as the time it stands from, and the ledger as when + # the install was made, so the three agree. Local time with its offset, as the store stamps it. + moment = self._wall_clock().astimezone() for part in parts: name = self._part_file(job, part) # The kind the command line installs the role's files under, so the ledger keeps one entry for both. kind = station_store.ROLE_KINDS[job.role] try: - station_store.install(directory, name, job.records[part], kind=kind, operator=operator) + station_store.install(directory, name, job.records[part], kind=kind, operator=operator, now=moment) except (station_store.StationStoreError, OSError): # The store puts the file in place before it writes its log, so a failure after that leaves # the solve's record as the station's file: installed, whatever the request came to. @@ -1932,11 +1990,12 @@ async def overview(self, glove_session: Mapping[str, Any] | None) -> dict[str, A self.settle() directory, cameras = self.calibration_dir(), self._cameras() roles = [(role, camera) for role, camera, _live in cameras] - files, ledger, board = await asyncio.to_thread( + files, ledger, board, lenses = await asyncio.to_thread( lambda: ( _installed_files(directory), station_store.ledger(directory), remembered_board(directory), + _installed_lenses(directory), ) ) # Whether a saved choice waits is the planner's to say, and planning has a worker of its own. @@ -1952,11 +2011,16 @@ async def overview(self, glove_session: Mapping[str, Any] | None) -> dict[str, A "role": role, "camera": camera, "live": live, + # Whether the camera reaches the backend through the LiveKit room, which the live check + # then joins while it runs; said on the page before a check is started. + "video_room": self._monitor.livekit_stream(camera) is not None, "intrinsics_file": ROLE_INTRINSICS[role], "default_model": model, "rectified": None if unknown else self._streams.rectified(camera), # Per camera: a change saved for another camera says nothing of this one's next start. "rectification_waits": waiting[role], + # Said before a take: the camera's picture is not the size its lens file was solved at. + "picture_notes": self._picture_notes(role, camera, lenses.get(role)), } for role, camera, live in cameras ], diff --git a/examples/egocap/backend/egocap_web/capture_status.py b/examples/egocap/backend/egocap_web/capture_status.py index 692ff998c8..f7c41a297a 100644 --- a/examples/egocap/backend/egocap_web/capture_status.py +++ b/examples/egocap/backend/egocap_web/capture_status.py @@ -337,6 +337,26 @@ def offered_camera_names(self) -> frozenset[str] | None: s.name for s in self.native.started.streams if isinstance(s, (p.CameraStream, p.LiveKitCameraStream)) ) + def camera_size(self, name: str | None) -> tuple[int, int] | None: + """The size of the picture the accepted session says the camera ``name`` sends, which is the size + recorded: a CaptureServer camera's or a LiveKit stream's. None before a session has been accepted, + for a camera it does not offer, and for a stream that states no size.""" + started = self.native.started + for stream in started.streams if started is not None else (): + offered = isinstance(stream, (p.CameraStream, p.LiveKitCameraStream)) and stream.name == name + if offered and stream.width is not None and stream.height is not None: + return (stream.width, stream.height) + return None + + def livekit_stream(self, name: str | None) -> p.LiveKitCameraStream | None: + """The LiveKit stream the accepted session offers under the camera name ``name``; None before a + session has been accepted and for a camera that does not arrive over LiveKit.""" + started = self.native.started + for stream in started.streams if started is not None else (): + if isinstance(stream, p.LiveKitCameraStream) and stream.name == name: + return stream + return None + def set_station_label(self, label: str) -> None: """Replaces the station label every status and preview snapshot carries. The revision advances so each viewer is sent the change, the same as any other lifecycle fact.""" diff --git a/examples/egocap/backend/egocap_web/day_report_routes.py b/examples/egocap/backend/egocap_web/day_report_routes.py index 8bb35d2634..8494ee55b9 100644 --- a/examples/egocap/backend/egocap_web/day_report_routes.py +++ b/examples/egocap/backend/egocap_web/day_report_routes.py @@ -3,27 +3,36 @@ # SPDX-License-Identifier: Apache-2.0 """HTTP surface for the end-of-day report: today's takes for the station in use, saving the report, and -correcting a task. +correcting a task or a studio. The report is read from the recording service's manifests (``egocap.analytics.day_report``), so it shows what became of every take, with the station's time from the uptime log. Everything here needs the run's control -token: the report names operators and tasks, and the correction rewrites recorded metadata. +token: the report names operators and tasks, and a correction rewrites recorded metadata. A correction is confined to a recorded session inside the recording output, refused for the session open for -recording, while a take is being written and while that session's take is being time-aligned, and replaces -each metadata file whole. It holds the session's lock (session_locks.py) from its first write to its last, so -neither the aligner nor a second correction can come between them. It changes labels only; recorded video and -tracking stay as captured, and nothing is ever moved. +recording here or in any other recorder, while a take is being written, while that session's take is being +time-aligned and while the session holds a take that is still to be filed by, or into, what is being +corrected, and replaces each metadata file whole. It holds two locks from before its first check to its last +write: this backend's own (session_locks.py), which the aligner and a second correction take, and the +recorder's lock on the session, so that no recorder opens the session meanwhile. It changes labels only; +recorded video and tracking stay as captured, a take's manifest keeps what the take was recorded under, and +nothing is ever moved: a studio correction relabels the session where it lies, whatever its folder is called. +Either correction is all or nothing: it answers with a failure only with the session's labels as they were, +or says which are not. """ from __future__ import annotations import asyncio +import contextlib import datetime import json import logging import re +import stat import time +from collections.abc import Callable, Iterator +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -33,9 +42,22 @@ from egocap.analytics.day_report import build_day_report, recorded_seconds from egocap.data_processing.update_episode_task_description import ( EpisodeRangeError, + RelabelError, + SessionConfigError, + plan_session_studio, + remove_interrupted_writes, + stored_studio_name, update_episode_task_description, ) -from egocap.recording.episode_layout import MANIFEST_DIR, ROUTE_ATTR +from egocap.recording.episode_layout import ( + MANIFEST_DIR, + ROUTE_ATTR, + UNRESOLVED_PHASES, + SessionLock, + scan_manifests, + write_json_atomic, +) +from egocap.recording.route import ROUTES_FILE, forget_group from .recording_command import MAX_TASK_DETAILS_CHARS, control_token_valid, interrupted_take from .request_body import read_authorized_json @@ -53,11 +75,65 @@ #: Room for a range of two long numbers; a longer value is not a take or a range. _MAX_EPISODES_CHARS = 32 _NOT_A_SESSION = "that directory is not a recorded session" -_EPISODE_DIR = re.compile(r"episode_\d+") +# Matched whatever the letter case: on a disk that folds case another spelling names the same directory. +_EPISODE_DIR = re.compile(r"episode_\d+", re.IGNORECASE) +_ALIGNED_SUFFIX = "_aligned" +#: The longest studio name taken; a station's studios are short names. +MAX_STUDIO_CHARS = 64 +#: The studio names that are a folder's bookkeeping and never a studio a take was recorded in, as they compare +#: once letter case and underscores are set aside. +_RESERVED_STUDIOS = ("unmatched", "unknown") +#: Why a correction is refused while one of the session's takes waits to be recovered or discarded. The +#: recording service files such a take by the studio and task its manifest froze, and refuses to file it into a +#: group whose labels no longer say the same, so a correction made first would leave the take unrecoverable. +UNSETTLED_TAKE = ( + "an interrupted take of this session must be recovered or discarded first: " + "where it is filed depends on the labels it was recorded under" +) +#: Why a correction of a routed group is refused while a take that already has its place in that group has not +#: been moved there. Recovered later, the take is filed into the group saying the labels it was recorded +#: under, and the corrected group would hold two. +STILL_TO_BE_FILED = ( + "an interrupted take of this session must be recovered or discarded first: " + "it is still to be filed in this group" +) +#: The same while a take's record cannot be read: nothing shows that no take is still waiting. +UNREADABLE_TAKE = "a take record of this session cannot be read, so its labels are left as they are" +#: The file in a session's sidecar that a recorder locks for as long as it has the session open +#: (``episode_layout.SessionLock``). Looked for, never created: the lock is taken only where it exists. +_RECORDER_LOCK = "session.lock" +#: Why a correction is refused for a session whose lock file is a link, a folder or a file with a second name: +#: taking a recorder's lock opens that file for writing, and it would be written wherever it leads. +LOCK_NOT_A_FILE = "this session's lock is not an ordinary file, so its labels are left as they are" +#: Why a correction is refused while a recorder holds the session: this backend's, or any other on the output. +OPEN_IN_A_RECORDER = "this session is open in a recorder; end its batch there before correcting it" +#: Why a correction of a routed group is refused when the owning session's routes cannot be rewritten: a take +#: recorded later would still be sent to the group, which would no longer say what the take was recorded under. +ROUTES_UNREADABLE = ( + "the session's record of where its takes are filed cannot be rewritten, so its labels are left as they are" +) class DayReportError(ValueError): - """A refused correction, with a public, path-free reason.""" + """A refused correction, with a public, path-free reason. ``left_changed`` names the files that still + carry the new label after a correction that failed and could not put them back; empty otherwise.""" + + def __init__(self, reason: str, left_changed: tuple[str, ...] = ()) -> None: + """``reason`` is the sentence the operator is shown.""" + super().__init__(reason) + self.left_changed = left_changed + + +@dataclass(frozen=True) +class _Kind: + """One kind of correction: what it is called in the log, and how a request's own fields become the write + that rewrites a confined session's labels and says what it changed.""" + + label: str + #: From a request's fields to the write. The write is given the confined session and the route its + #: session sends later takes by, which it drops before it changes the group's own studio or task, and + #: answers with what it changed. + prepare: Callable[[dict[str, Any]], Callable[[Path, _GroupRoute], dict[str, Any]]] def _reply(body: dict[str, Any], status: int = 200) -> JSONResponse: @@ -168,8 +244,9 @@ def _confined_session(root: Path, raw: Any) -> Path: raise DayReportError(_NOT_A_SESSION) try: return _recorded_session(root.resolve(), raw) - except OSError: - # A name the filesystem will not even look up is not a session; the cause is not the caller's to read. + except (OSError, UnicodeError): + # A name the filesystem will not even look up, or that cannot be encoded for it, is not a session; the + # cause is not the caller's to read. raise DayReportError(_NOT_A_SESSION) from None @@ -183,7 +260,7 @@ def _recorded_session(base: Path, raw: str) -> Path: if any(part.startswith(".") for part in parts) or not target.is_dir(): raise DayReportError(_NOT_A_SESSION) # A time-aligned copy and a single episode are corrected with the session they belong to, never alone. - if any(part.endswith("_aligned") for part in parts) or _EPISODE_DIR.fullmatch(target.name): + if any(part.lower().endswith(_ALIGNED_SUFFIX) for part in parts) or _EPISODE_DIR.fullmatch(target.name): raise DayReportError(_NOT_A_SESSION) session = len(parts) == 1 and (target / MANIFEST_DIR).is_dir() # A routed group is known by the recording service's stamp, not by what the directory happens to lack. @@ -228,6 +305,131 @@ def _refuse_while_recording(snapshot: Any, target: Path) -> None: raise DayReportError("this session is still open for recording; start a new batch first") +def _owning_session(root: Path, target: Path) -> Path: + """The recording-service session whose manifests speak for ``target``: the session itself, or for a + routed group the session its stamp names, which need not exist any more.""" + if (target / MANIFEST_DIR).is_dir(): + return target + stamp = _route_stamp(target) or "" + # The stamp is "|"; only its first part names a directory, directly under the output. + return root.resolve() / Path(stamp.split("|", 1)[0]).name + + +def _group_of(target: Path) -> str | None: + """The name a routed group was recorded under, as its session's takes and routes name it: the second part + of its stamp. None for a directory that is no routed group.""" + stamp = _route_stamp(target) + return None if stamp is None or "|" not in stamp else stamp.split("|", 1)[1] + + +def _refuse_with_unsettled_take(owner: Path, target: Path) -> None: + """Refuse a correction of either label of ``target`` while the session ``owner`` holds a take that is not + settled and is still to be filed by, or into, what is being corrected. + + One that was recorded to be routed by its studio and has not been given its destination yet: reproduced + against :func:`egocap.recording.route.assign_output`, once a routed group's studio or task differs from + what such a take's manifest froze, filing the take into the group is refused, so it can no longer be + recovered. The frozen values are the invariant; the labels wait for the take. + + And one whose destination is the group being corrected: recovered later it is moved there saying the + labels it was recorded under, and the corrected group would hold two studios. A take recorded with + routing off is filed where it was recorded, by no label, and holds no correction. + """ + manifests, problems = scan_manifests(owner) + waiting = [manifest for manifest in manifests if manifest.storage_phase in UNRESOLVED_PHASES] + if any(manifest.studio is not None and manifest.assignment is None for manifest in waiting): + raise DayReportError(UNSETTLED_TAKE) + group = _group_of(target) + placed = (manifest.assignment for manifest in waiting if isinstance(manifest.assignment, dict)) + if group is not None and any(assignment.get("group") == group for assignment in placed): + raise DayReportError(STILL_TO_BE_FILED) + # A record that cannot be read, or a sidecar that cannot be listed, may be such a take. + if problems: + raise DayReportError(UNREADABLE_TAKE) + + +@contextlib.contextmanager +def _closed_to_recorders(owner: Path) -> Iterator[None]: + """Hold the recorder's own lock on the session ``owner`` for the guard and the write, so that no recorder + opens it meanwhile, and refuse when one holds it now. Taken without waiting, and only where the file a + recorder locks is there: every session a recorder opened has one. A session that is gone, of a routed + group that outlived it, has no recorder to exclude, and nothing is created for a session no recorder + ever locked. + + Taking the lock opens its file for writing, so a lock file that is a link, a folder, or a file that has + another name somewhere refuses the correction: nothing is written through it.""" + lock: SessionLock | None = None + try: + # Looked at first, and not followed: taking the lock of a session that has no lock file would create + # one, and taking it through a link would empty the file the link leads to. + found = (owner / MANIFEST_DIR / _RECORDER_LOCK).lstat() + if not stat.S_ISREG(found.st_mode) or found.st_nlink != 1: + raise DayReportError(LOCK_NOT_A_FILE) + lock = SessionLock(owner) + except (FileNotFoundError, NotADirectoryError): + # No recorder ever opened this session, or it is gone: there is none to exclude. + pass + except BlockingIOError: + raise DayReportError(OPEN_IN_A_RECORDER) from None + except OSError: + # A sidecar that cannot be looked into cannot say which takes wait in it either. + raise DayReportError(UNREADABLE_TAKE) from None + try: + yield + finally: + if lock is not None: + lock.release() + + +class _GroupRoute: + """The route by which the session ``owner`` sends its later takes to the routed group ``target``, for a + correction that changes the group's studio or the task of every take in it. + + The recorder files a take into the group its session recorded for the take's studio, task and day, and + refuses a group that no longer says the same. A corrected group therefore stops being a destination, and + a later take claims a fresh one. Used under the recorder's lock on ``owner``; a take's own frozen + assignment is not touched. + """ + + def __init__(self, owner: Path, target: Path) -> None: + """Nothing is read or changed until a correction asks.""" + self._owner = owner + self._target = target + # The session's routes as they were before the group was dropped from them; None while it was not. + self._dropped: dict[str, Any] | None = None + + def forget_unless(self, label: str, value: str) -> None: + """Drop the group's route before the correction writes ``value`` as the group's own ``label``, or + refuse the correction when that cannot be done. A group that already says ``value`` keeps its + route: nothing about it will differ from what its session records under.""" + group = _group_of(self._target) + if self._owner == self._target or group is None or not (self._owner / MANIFEST_DIR).is_dir(): + return + try: + said = json.loads((self._target / "zarr.json").read_text()).get("attributes", {}).get(label) + if said == value: + return + routes_file = self._owner / MANIFEST_DIR / ROUTES_FILE + before = json.loads(routes_file.read_text()) if routes_file.is_file() else None + if forget_group(self._owner, group): + self._dropped = before + logger.info("A corrected group is no longer a destination for later takes of its session") + except (OSError, ValueError, AttributeError): + logger.exception("The routes of a corrected group's session could not be rewritten") + raise DayReportError(ROUTES_UNREADABLE) from None + + def put_back(self) -> None: + """Give the group its route back after a correction that failed and left every label as it was: the + group says what it said, so it is still where its session's takes of that studio and task belong.""" + if self._dropped is None: + return + try: + write_json_atomic(self._owner / MANIFEST_DIR / ROUTES_FILE, self._dropped) + except OSError: + # Left dropped: a later take then claims a group of its own, and none is refused. + logger.exception("The route of a group whose correction failed could not be put back") + + #: Why a correction is refused while the session's labels are held, by who holds them. _HELD = { # The aligner copies a take's labels before it publishes the copy; a correction made in between would @@ -238,44 +440,126 @@ def _refuse_while_recording(snapshot: Any, target: Path) -> None: } -def _correct( - state: tuple[Any, Any, Any, Path], snapshot: Any, body: dict[str, Any], locks: SessionLocks +def _corrected( + state: tuple[Any, Any, Any, Path], + snapshot: Any, + body: dict[str, Any], + locks: SessionLocks, + kind: _Kind, ) -> dict[str, Any]: - """Apply one task correction; runs in a worker thread. ``snapshot`` is the recording coordinator's, taken - on the event loop that owns its state, and ``locks`` is shared with the background aligner.""" + """Apply one correction to the session ``body`` names, under every rule a correction is held to; runs in + a worker thread. ``kind`` checks the body's own fields and gives the write, which rewrites the labels of + the confined session and says what it changed. ``snapshot`` is the recording coordinator's, taken on the + event loop that owns its state, and ``locks`` is shared with the background aligner.""" _context, _stations, _uptime, root = state target = _confined_session(root, body.get("session")) _refuse_while_recording(snapshot, target) - task, episodes = body.get("task"), body.get("episodes") - if not isinstance(task, str) or task.strip() == "" or len(task) > MAX_TASK_DETAILS_CHARS: - raise DayReportError(f"task must be text of 1 to {MAX_TASK_DETAILS_CHARS} characters") - if not isinstance(episodes, str) or len(episodes) > _MAX_EPISODES_CHARS: - raise DayReportError("episodes must be a take or a range, such as 3 or 2-7") + write = kind.prepare(body) # Held across every file the correction writes; the aligner takes the same lock before it copies labels. holder = locks.acquire(target, CORRECTION) if holder is not None: raise DayReportError(_HELD[holder]) try: - result = update_episode_task_description(target, episodes, task_description=task.strip()) + owner = _owning_session(root, target) + route = _GroupRoute(owner, target) + with _closed_to_recorders(owner): + # Asked under both locks, immediately before the first write. + _refuse_with_unsettled_take(owner, target) + # What a correction that was killed part-way left behind goes before this one writes. + removed = remove_interrupted_writes(target) + if removed: + logger.info("Removed %d file(s) an interrupted correction left in the session", len(removed)) + try: + changed = write(target, route) + except RelabelError as exc: + # Every label is as it was: the group still says what its session records under. + if not exc.left_changed: + route.put_back() + raise except EpisodeRangeError as exc: raise DayReportError(f"episodes: {exc}") from None + except DayReportError: + raise + except RelabelError as exc: + # The sentence names the session's own files and says what became of its labels. + logger.exception("A %s correction could not be written", kind.label) + raise DayReportError(str(exc), exc.left_changed) from None + except SessionConfigError as exc: + # Found before anything was written. + raise DayReportError(f"{exc}, so nothing was changed") from None except (OSError, ValueError): # The library's messages carry paths; the cause goes to the log and the operator gets the outcome. - logger.exception("A task correction could not be written") + logger.exception("A %s correction could not be written", kind.label) raise DayReportError("the session's metadata could not be updated") from None finally: locks.release(target) - return { - "session": result.zarr_root.relative_to(root.resolve()).as_posix(), - "updated": result.updated_episodes, - "missing": result.missing_episodes, - "config_updated": result.config_yaml_updated, - } + return {"session": target.relative_to(root.resolve()).as_posix(), **changed} -@router.post("/api/day-report/correct") -async def correct_session(request: Request) -> JSONResponse: - """Correct the task of one take or a range of a session's takes.""" +def _task_correction(body: dict[str, Any]) -> Callable[[Path, _GroupRoute], dict[str, Any]]: + """The write of a task correction, once its fields are known to be well formed.""" + task, episodes = body.get("task"), body.get("episodes") + if not isinstance(task, str) or task.strip() == "" or len(task) > MAX_TASK_DETAILS_CHARS: + raise DayReportError(f"task must be text of 1 to {MAX_TASK_DETAILS_CHARS} characters") + if not isinstance(episodes, str) or len(episodes) > _MAX_EPISODES_CHARS: + raise DayReportError("episodes must be a take or a range, such as 3 or 2-7") + + def write(target: Path, route: _GroupRoute) -> dict[str, Any]: + """Relabel the named takes and say which were changed: checked whole first, and put back whole if a + write fails. A correction of every take changes the session's own task as well, and a routed + group that will say another task is dropped from its session's routes first.""" + corrected = task.strip() + result = update_episode_task_description( + target, + episodes, + task_description=corrected, + on_session_task_change=lambda: route.forget_unless("task_description", corrected), + ) + return { + "updated": result.updated_episodes, + "missing": result.missing_episodes, + "config_updated": result.config_yaml_updated, + } + + return write + + +def _studio_correction(body: dict[str, Any]) -> Callable[[Path, _GroupRoute], dict[str, Any]]: + """The write of a studio correction, once the studio is known to be a name.""" + studio = body.get("studio") + usable = isinstance(studio, str) and len(studio) <= MAX_STUDIO_CHARS and studio.isprintable() + stored = stored_studio_name(studio) if usable else "" + # A name that holds nothing, a hidden or relative one, and a folder's bookkeeping name are not studios, + # however the bookkeeping name is cased or underscored. + reserved = stored.replace("_", "").casefold() in _RESERVED_STUDIOS + if stored == "" or stored.startswith(".") or reserved: + raise DayReportError(f"studio must be a name of 1 to {MAX_STUDIO_CHARS} characters, such as Kitchen") + + def write(target: Path, route: _GroupRoute) -> dict[str, Any]: + """Relabel the whole session where it lies and say what was written: checked whole first, and put + back whole if a write fails. A routed group that will say another studio is dropped from its + session's routes first.""" + plan = plan_session_studio(target, stored) + if plan.episodes: + route.forget_unless("studio", stored) + result = plan.apply() + return { + "studio": result.studio_stored, + "updated": result.updated_episodes, + "config_updated": result.config_yaml_updated, + } + + return write + + +#: The corrections the page can make. +_TASK = _Kind("task", _task_correction) +_STUDIO = _Kind("studio", _studio_correction) + + +async def _correction(request: Request, kind: _Kind) -> JSONResponse: + """Authorize one correction request, apply it off the event loop, and answer with what changed or the + reason it was refused.""" state = _state(request) locks = getattr(request.app.state, "session_locks", None) if state is None or locks is None: @@ -287,6 +571,22 @@ async def correct_session(request: Request) -> JSONResponse: # Read here, not in the worker: the coordinator's state changes on this loop, so a thread could see # its fields part-way through a change. snapshot = state[0].coordinator.snapshot() - return _reply(await asyncio.to_thread(_correct, state, snapshot, body, locks)) + return _reply(await asyncio.to_thread(_corrected, state, snapshot, body, locks, kind)) except DayReportError as exc: - return _reply({"detail": str(exc)}, 400) + refusal: dict[str, Any] = {"detail": str(exc)} + # Said only by a correction that failed part-way and could not put every label back. + if exc.left_changed: + refusal["left_changed"] = list(exc.left_changed) + return _reply(refusal, 400) + + +@router.post("/api/day-report/correct") +async def correct_session(request: Request) -> JSONResponse: + """Correct the task of one take or a range of a session's takes.""" + return await _correction(request, _TASK) + + +@router.post("/api/day-report/studio") +async def correct_studio(request: Request) -> JSONResponse: + """Correct the studio a whole session is labelled with, where the session lies: its files are not moved.""" + return await _correction(request, _STUDIO) diff --git a/examples/egocap/backend/egocap_web/glove_offset_session.py b/examples/egocap/backend/egocap_web/glove_offset_session.py index e4df0dd2a8..406e7787c2 100644 --- a/examples/egocap/backend/egocap_web/glove_offset_session.py +++ b/examples/egocap/backend/egocap_web/glove_offset_session.py @@ -31,7 +31,7 @@ import cv2 import numpy as np -from egocap.calibration import station_store +from egocap.calibration import provenance, station_store from egocap.calibration.board import CalibrationError from egocap.calibration.camera_lag import CameraLagError, camera_lag_of_take from egocap.calibration.camera_pipeline import MAX_TRACKING_GAP_S @@ -94,6 +94,12 @@ #: a turn wrong or centimeters off at an RMS near zero, and no hand fitted on at least these was. MIN_FRAMES_TO_TRUST = 3 MIN_CLICKS_TO_TRUST = 8 +#: The rule an install is held to (``_install_blocker``), as the installed file states it. +INSTALL_RULE = ( + f"Wrist offsets are installed once every hand fitted rests on at least {MIN_CLICKS_TO_TRUST} clicks over " + f"at least {MIN_FRAMES_TO_TRUST} frames and its fit did not stop at the translation limit. The fit's error " + "is shown to the operator and not limited." +) #: The RMS above which an offset is taken not to explain its clicks, as a share of the picture's longer side. #: In the same measurements a fit left on a wrong orientation kept more than this, and a sound one less. _POOR_RMS_SHARE = 0.01 @@ -137,6 +143,20 @@ def pinned_down(self) -> bool: return self.result.n_clicks >= MIN_CLICKS_TO_TRUST and self.frames >= MIN_FRAMES_TO_TRUST +def _fit_figures(fit: _HandFit | None) -> dict[str, Any] | None: + """What one hand's install was held against, for the installed file to state; None for a hand whose + offset was not fitted in this session and is the one the station already had.""" + if fit is None: + return None + # Plain numbers: the fit's own may be array scalars, which a JSON file cannot hold. + return { + "rms_px": float(fit.result.rms_px), + "clicks": int(fit.result.n_clicks), + "frames": int(fit.frames), + "at_translation_limit": bool(fit.result.at_translation_limit), + } + + @dataclasses.dataclass(frozen=True) class _Progress: """Where a session's fit stands. Replaced whole, so a reader on another thread never sees half a change.""" @@ -568,7 +588,12 @@ def install(self, operator: Any, calibration_dir: Path) -> dict[str, Any]: raise CalibrationRefusal(409, blocker) # The file states how many frames it was fitted on: the frames whose clicks the fits used. labelled_frames = len({click[0] for click in progress.used}) - record = offsets_record(progress.offsets, n_samples=labelled_frames) + record = offsets_record( + progress.offsets, + n_samples=labelled_frames, + install_rule=INSTALL_RULE, + fits={side: _fit_figures(progress.fits[side]) for side in SIDES}, + ) logged = True try: station_store.install(calibration_dir, WRIST_OFFSETS, record, kind=LEDGER_KIND, operator=name) @@ -660,6 +685,12 @@ def _starting_offsets(directory: Path) -> tuple[str, dict[str, WristOffset], str zero = {side: WristOffset() for side in SIDES} try: record = read_json_object(directory / WRIST_OFFSETS) + # Offsets of a newer layout than this software reads are a calibration the station has, which the + # install here will replace: said before any click, not only in the log. + newer = provenance.layout_problem(record, WRIST_OFFSETS) + if newer is not None: + logger.info("The wrist-offset fit starts from zero: %s", newer) + return START_ZERO, zero, _UNTRUSTED_OFFSETS.format(problem=newer) offsets = offsets_from_record(record) except CalibrationFileError as exc: # A station that was never fitted has no file, and a damaged file is no better a start than none. diff --git a/examples/egocap/backend/egocap_web/livekit_receiver.py b/examples/egocap/backend/egocap_web/livekit_receiver.py index 0b8e1f4424..21825d58a9 100644 --- a/examples/egocap/backend/egocap_web/livekit_receiver.py +++ b/examples/egocap/backend/egocap_web/livekit_receiver.py @@ -16,7 +16,6 @@ from __future__ import annotations import asyncio -import contextlib import logging import time from collections.abc import Sequence @@ -154,21 +153,35 @@ async def start(self) -> None: self._attach(participant, publication.track, publication.name) async def stop(self) -> None: - """Leave the room and stop every reader; frames still queued stay available to the consumer.""" + """Leave the room and stop every reader; frames still queued stay available to the consumer. + + The room is left whatever an earlier step of the leave raises: a caller that was told the receiver + stopped must not have a subscriber still in the room. What a step raised is raised once the room is left. + """ room, self._room = self._room, None - if self.clock_sync is not None: - await self.clock_sync.stop() - self.clock_sync = None - for task in self._readers.values(): - task.cancel() - for task in list(self._readers.values()): - with contextlib.suppress(asyncio.CancelledError): - await task + clock_sync, self.clock_sync = self.clock_sync, None + readers = list(self._readers.values()) self._readers.clear() - if room is not None: - await room.disconnect() - for counters in self.counters.values(): - counters.subscribed = False + try: + if clock_sync is not None: + await clock_sync.stop() + finally: + await self._leave(room, readers) + + async def _leave(self, room: rtc.Room | None, readers: list[asyncio.Task[None]]) -> None: + """Stop the readers and disconnect from the room, the second whatever becomes of the first.""" + try: + for task in readers: + task.cancel() + # A reader that ended in an error of its own keeps neither the others nor the room from being left. + _ = await asyncio.gather(*readers, return_exceptions=True) + finally: + try: + if room is not None: + await room.disconnect() + finally: + for counters in self.counters.values(): + counters.subscribed = False async def next_frame(self, stream_id: int) -> ReceivedFrame: """The oldest queued frame of ``stream_id``, waiting for one if none is queued.""" diff --git a/examples/egocap/backend/egocap_web/livekit_recording.py b/examples/egocap/backend/egocap_web/livekit_recording.py index 30b3e17042..e3680aafa1 100644 --- a/examples/egocap/backend/egocap_web/livekit_recording.py +++ b/examples/egocap/backend/egocap_web/livekit_recording.py @@ -50,6 +50,9 @@ _LEAVE_TIMEOUT_S = 10.0 #: Most mappings recorded as a take's timing evidence, the newest ones; the estimator may have adopted more. _MAX_EVIDENCE_MAPPINGS = 64 +#: What a source's ``prepare()`` is waiting for, for a caller that says so while it waits: the room join, each +#: stream's first frame, or a usable clock mapping from the publisher. +JOINING, FIRST_FRAME, CLOCK_MAPPING = "joining", "first_frame", "clock_mapping" # The bases recorded, and what each one's time means in the saved take. _RECORDABLE_BASES: dict[p.LiveKitTimestampBasis, str] = { @@ -398,6 +401,9 @@ def __init__( self._feed: LiveKitRecordingFeed | None = None # Read from the environment once in prepare(), so the feed and the saved evidence use the same figure. self._budget_ns = int(_DEFAULT_BUDGET_MS * 1e6) + #: What ``prepare()`` is waiting for right now, or was waiting for when it failed; None before it runs + #: and once it has succeeded. + self.stage: str | None = None async def prepare(self) -> None: """Join the room and wait for a usable first frame from every stream; raises if one never arrives. @@ -405,6 +411,7 @@ async def prepare(self) -> None: Runs before the take's storage opens, so a missing camera fails the start instead of a half-written take. Does nothing when the session offers no recordable stream. """ + self.stage = None self._streams = tuple(self._recordable_streams()) if not self._streams: return @@ -413,7 +420,9 @@ async def prepare(self) -> None: receiver = LiveKitFrameReceiver(self._streams, self._make_token(self._streams[0].room), clock_sync=True) self._receiver = receiver try: + self.stage = JOINING await self._join(receiver) + self.stage = FIRST_FRAME for stream in self._streams: frame = await asyncio.wait_for( receiver.next_frame_or_lost(stream.stream_id), self._first_frame_timeout_s @@ -431,7 +440,9 @@ async def prepare(self) -> None: f"{stream.name}: frames are {frame.image.shape[1]}x{frame.image.shape[0]}, " f"expected {stream.width}x{stream.height}" ) + self.stage = CLOCK_MAPPING await self._wait_for_mapping(receiver) + self.stage = None except asyncio.TimeoutError as exc: await self.stop() raise RuntimeError("a LiveKit stream sent no frame before the recording could start") from exc @@ -593,14 +604,19 @@ async def stop(self) -> None: """Stop feeding and leave the room. Safe to call at any point, including after a failed prepare.""" feed, receiver = self._feed, self._receiver self._feed = self._receiver = None - if feed is not None: - await feed.stop() - if receiver is not None: - # A stalled room leave must not block retiring the take's ingress; it is left to finish on its own. - leave = asyncio.ensure_future(receiver.stop()) - self._track(leave, "leaving the LiveKit room") - _ = await asyncio.wait({leave}, timeout=self._leave_timeout_s) - if not leave.done(): - logger.warning( - "leaving the LiveKit room took longer than %g s; continuing teardown", self._leave_timeout_s - ) + try: + if feed is not None: + await feed.stop() + finally: + # The room is left whatever stopping the feed raised: a feed that died must not keep a subscriber + # in the room. + if receiver is not None: + # A stalled room leave must not block retiring the take's ingress; it is left to finish on its own. + leave = asyncio.ensure_future(receiver.stop()) + self._track(leave, "leaving the LiveKit room") + _ = await asyncio.wait({leave}, timeout=self._leave_timeout_s) + if not leave.done(): + logger.warning( + "leaving the LiveKit room took longer than %g s; continuing teardown", + self._leave_timeout_s, + ) diff --git a/examples/egocap/backend/egocap_web/livekit_sightings.py b/examples/egocap/backend/egocap_web/livekit_sightings.py new file mode 100644 index 0000000000..007cf97c70 --- /dev/null +++ b/examples/egocap/backend/egocap_web/livekit_sightings.py @@ -0,0 +1,92 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What operator pages last saw of each LiveKit camera, for the station checklist. + +The backend joins a LiveKit room only for the length of a take, so between takes it receives nothing from a +camera that arrives that way. The page is in the room all the time, to show the picture. A page that holds the +run's control token therefore tells the backend what its preview is receiving of each stream, and the checklist +reads the best report that is still fresh. + +A report is one browser's observation, not the recorder's. It can show that frames are arriving; it cannot show +that the recorder would fail to receive them, so the checklist never holds a take on one (see setup_checks.py). +""" + +from __future__ import annotations + +import time +from collections.abc import Callable +from typing import Any + +#: What a page can say of one stream, best first: frames are being shown; the track is subscribed and no frame +#: arrives; the sender has not published the track; the page is not in the room. +RECEIVING, SILENT, NO_TRACK, NOT_CONNECTED = "receiving", "silent", "no_track", "not_connected" +_BEST_FIRST = (RECEIVING, SILENT, NO_TRACK, NOT_CONNECTED) + +#: How long a report speaks for a camera. The page reports every couple of seconds while it is in view, so a +#: report this old means no page is watching any more. +FRESH_SECONDS = 6.0 +#: Pages remembered at once and streams per report: a station has a few of each, and the bounds keep a caller +#: from growing the table. +MAX_PAGES = 8 +MAX_STREAMS = 16 +_MAX_NAME_CHARS = 128 + + +class SightingError(ValueError): + """A report that was refused, with a public reason.""" + + @property + def public_message(self) -> str: + """The reason, safe to return to the caller.""" + return str(self) + + +def _checked(page: Any, streams: Any) -> tuple[str, dict[str, str]]: + """A report's page id and what it saw per stream, or a refusal naming what is malformed.""" + if not isinstance(page, str) or not 0 < len(page) <= _MAX_NAME_CHARS: + raise SightingError("page must be a short text id") + if not isinstance(streams, dict) or len(streams) > MAX_STREAMS: + raise SightingError(f"streams must be an object of at most {MAX_STREAMS} stream names") + for name, seen in streams.items(): + if len(name) > _MAX_NAME_CHARS: + raise SightingError("a stream name is too long") + if seen not in _BEST_FIRST: + raise SightingError(f"each stream must be one of {', '.join(_BEST_FIRST)}") + return page, dict(streams) + + +class LiveKitSightings: + """The newest report of each operator page. Written and read on the event loop.""" + + def __init__(self, monotonic: Callable[[], float] = time.monotonic) -> None: + """``monotonic`` is the clock reports are aged by; tests pass their own.""" + self._monotonic = monotonic + # Page id to when it reported and what it saw, oldest report first. + self._reports: dict[str, tuple[float, dict[str, str]]] = {} + + def report(self, page: Any, streams: Any) -> None: + """Keep one page's report in place of its previous one; a malformed report raises + :class:`SightingError` and changes nothing.""" + page, seen = _checked(page, streams) + # Removed first so that the page's new report is the newest entry, whatever its previous position. + self._reports.pop(page, None) + self._reports[page] = (self._monotonic(), seen) + # The page that has been silent longest gives way: a reloaded page reports under a new id. + while len(self._reports) > MAX_PAGES: + del self._reports[next(iter(self._reports))] + + def seen(self) -> dict[str, str]: + """What is known of each stream now: the best of the fresh reports that name it. A stream no fresh + report names is absent.""" + now = self._monotonic() + best: dict[str, str] = {} + for at, streams in self._reports.values(): + if now - at > FRESH_SECONDS: + continue + for name, seen in streams.items(): + # One page receiving frames shows they are arriving, whatever another page fails to show. + if name not in best or _BEST_FIRST.index(seen) < _BEST_FIRST.index(best[name]): + best[name] = seen + return best diff --git a/examples/egocap/backend/egocap_web/session_locks.py b/examples/egocap/backend/egocap_web/session_locks.py index 7166048481..bd24d14531 100644 --- a/examples/egocap/backend/egocap_web/session_locks.py +++ b/examples/egocap/backend/egocap_web/session_locks.py @@ -15,6 +15,7 @@ from __future__ import annotations +import os import threading from pathlib import Path @@ -22,6 +23,17 @@ ALIGNER, CORRECTION = "aligner", "correction" +def _identity(directory: Path) -> tuple[int, int] | Path: + """What a directory is locked under: the directory itself, by device and inode, so that two spellings of + one directory (another letter case on a disk that folds case, a link) are one lock. A directory that is + not there is locked under its path.""" + try: + found = os.stat(directory) + except OSError: + return directory + return (found.st_dev, found.st_ino) + + class SessionLocks: """Which sessions' labels are held, and by whom. Safe to use from the event loop and from worker threads.""" @@ -29,21 +41,26 @@ def __init__(self) -> None: """Nothing is held at first.""" self._guard = threading.Lock() # A session is listed only while it is held, so this never grows with the sessions on disk. - self._held: dict[Path, str] = {} + self._held: dict[tuple[int, int] | Path, str] = {} + # What each held path was locked under, so that giving it back finds the lock even when the directory + # was renamed or removed meanwhile. + self._keys: dict[Path, tuple[int, int] | Path] = {} def acquire(self, directory: Path, holder: str) -> str | None: """Take the lock of ``directory`` for ``holder``. Returns None when taken, else who holds it now. - ``directory`` is the resolved session or routed group directory; both callers resolve it the same - way, off the event loop, so one session is never two keys. + ``directory`` is the session or routed group directory. It is locked as the directory it is on the + disk, however the caller spelled its path. """ + key = _identity(directory) with self._guard: - current = self._held.get(directory) + current = self._held.get(key) if current is None: - self._held[directory] = holder + self._held[key] = holder + self._keys[directory] = key return current def release(self, directory: Path) -> None: - """Give the lock of ``directory`` back.""" + """Give the lock of ``directory`` back, under the path it was taken with.""" with self._guard: - self._held.pop(directory, None) + self._held.pop(self._keys.pop(directory, directory), None) diff --git a/examples/egocap/backend/egocap_web/setup_checks.py b/examples/egocap/backend/egocap_web/setup_checks.py index 0ba9e5495a..d7182117c4 100644 --- a/examples/egocap/backend/egocap_web/setup_checks.py +++ b/examples/egocap/backend/egocap_web/setup_checks.py @@ -5,12 +5,14 @@ """The station checklist: what a station must show before it records. A list of items, each passed, failed with the reason, warned about, or skipped. It covers every tracking device -the capture session reports, every camera the station uses, the calibration files of those cameras, and room on -the recording disk. A device or check the station does not use is skipped, never failed. +the capture session reports, every tracking device the station requires, every camera the station uses, the +calibration files of those cameras, and room on the recording disk. A device or check the station does not use +is skipped, never failed. Only a failed item holds a take. An item fails for what recording readiness itself refuses (capture not running, -no recent tracking sample or camera frame, a camera that cannot be recorded) and for a full disk. What goes beyond -that is a warning: a device's reported state, and calibration files unless the deployment requires them. +no recent tracking sample or camera frame, a camera that cannot be recorded), for a full disk, and for a tracking +device the station requires that is not delivering its data. What goes beyond that is a warning: the reported +state of a device the station does not require, and calibration files unless the deployment requires them. This module is pure: it judges a :class:`CaptureFacts` value and never reads the capture session itself. setup_service.py gathers the facts, keeps the checklist fresh and turns it into the recording gate. @@ -18,12 +20,16 @@ from __future__ import annotations -from collections.abc import Callable, Mapping +from collections.abc import Callable, Collection, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any from egocap.calibration.files import CalibrationFileError, pose_source_problem, read_json_object +from egocap.calibration.provenance import layout_problem + +from .livekit_sightings import NO_TRACK, NOT_CONNECTED, RECEIVING, SILENT +from .stations import TRACKING_DEVICES #: ``warn`` is advisory: shown with its reason, and never a reason to hold a take. PASS, FAIL, WARN, SKIP = "pass", "fail", "warn", "skip" @@ -60,6 +66,9 @@ class CheckItem: status: str #: Why it failed, warns or was skipped; None for a pass that needs no comment. detail: str | None = None + #: The tracking device this item is about, by the name a station requires it under; None for any other + #: item. Not sent: it lets a take that does not use the device leave the item out of what holds it. + device: str | None = None def to_json(self) -> dict[str, Any]: """The wire form.""" @@ -72,6 +81,14 @@ def to_json(self) -> dict[str, Any]: } +#: The reasons, by the capture session's names for them, under which a device the session calls degraded still +#: delivers its data. One only: a glove that streams its skeleton although its calibration file was rejected. +#: Every other reason the session gives a degraded device (no current data, a device error) says the opposite: +#: a glove with no usable skeleton, a controller with a pose lost. A reason added to the session later is not +#: here until somebody has read what it means for the data. +DELIVERING_WHILE_DEGRADED = frozenset({"CALIBRATION_FAILED"}) + + @dataclass(frozen=True) class DeviceFact: """One tracking device as the capture status reports it.""" @@ -82,6 +99,20 @@ class DeviceFact: detail: str | None = None #: Whether this is the headset, whose connection is what proves the host address it was given. headset: bool = False + #: Which device a station can require this is, by its ``TRACKING_DEVICES`` name; None for any other. + kind: str | None = None + #: Whether the session calls it degraded: there, with a problem of its own that ``reason`` names. + degraded: bool = False + #: Why the session gives the device its state, by the session's own name for the reason; None when a + #: fact was built without one. It decides whether a degraded device still delivers its data. + reason: str | None = None + + @property + def delivers(self) -> bool: + """Whether the device is delivering its data, as far as the session says: connected, or degraded for + a reason under which it still streams. Anything else, a degraded state this build was told nothing + about included, is not taken to deliver.""" + return self.connected or (self.degraded and self.reason in DELIVERING_WHILE_DEGRADED) @dataclass(frozen=True) @@ -109,6 +140,12 @@ class CaptureFacts: livekit_cameras: frozenset[str] = frozenset() #: Why an offered LiveKit stream cannot be recorded, or None. livekit_blocked: str | None = None + #: What an operator's page last saw of each LiveKit stream, by name (see livekit_sightings.py); a stream no + #: page is watching is absent. + livekit_seen: Mapping[str, str] | None = None + #: The tracking devices switched off in the capture configuration, by their ``TRACKING_DEVICES`` name. They + #: are not among ``devices``: a station that does not require one has no row for it. + disabled: tuple[str, ...] = () @property def headset_connected(self) -> bool: @@ -116,35 +153,103 @@ def headset_connected(self) -> bool: return any(device.headset and device.connected for device in self.devices) -def _tracking_items(facts: CaptureFacts) -> list[CheckItem]: - """One item per tracking device the session reports, and one for whether their data is arriving. +#: What follows the state of a device that fails only because the station in use requires it. +REQUIRED_HERE = "this station requires it" +#: Why a required device the session has no entry for fails, by why it has none. +NOT_REPORTED = "not reported by the capture session" +SWITCHED_OFF = "switched off in the capture configuration" +#: The same for a requirement read from the stations file that names no device this build knows. +NOT_A_DEVICE = "not a tracking device this software knows" - A device that is not connected warns and does not fail. Recording readiness judges the tracking data, not - the state each device reports, and a station may leave a controller or a glove unused. + +def tracking_device_kind(device_type: str, path: str) -> str | None: + """Which device a station can require a reported device is, by its ``TRACKING_DEVICES`` name, or None. + + Read from the path, which names the side: the capture session gives controllers ``/controller/`` + and every hand-tracking device ``/hand/``, whatever type and description its provider states. """ - items = [ - CheckItem( - f"device:{index}", - TRACKING, - device.label, - PASS if device.connected else WARN, - None if device.connected else (device.detail or "not connected"), - ) - for index, device in enumerate(facts.devices) - ] + if device_type == "headset": + return "headset" + family, _, side = path.strip("/").partition("/") + kind = {"controller": "controller", "hand": "glove"}.get(family) + return f"{kind}_{side}" if kind is not None and side in ("left", "right") else None + + +def _tracking_items(facts: CaptureFacts, required: Collection[str]) -> list[CheckItem]: + """One item per tracking device the session reports, one per requirement of the station that no reported + device answers, and one for whether tracking data is arriving. + + A device that is not connected warns: recording readiness judges the tracking data, not the state each + device reports, and a station may leave a controller or a glove unused. A device the station requires + fails instead unless it is delivering its data when Record is pressed: connected, or degraded for a + reason under which it still streams, in which case it keeps its warning. The freshness item below cannot + stand in for this: it is met by any one device's samples. + """ + items = [] + for index, device in enumerate(facts.devices): + state = None if device.connected else (device.detail or "not connected") + needed = device.kind in required + holds = needed and not device.delivers + if holds: + # Said with the reason it holds a take, since the same state only warns at another station. + state = f"{state}; {REQUIRED_HERE}" + status = PASS if device.connected else (FAIL if holds else WARN) + # A device the station requires is called what the Station tab calls it, so the box that was ticked + # and the row that fails name one thing. Every other device keeps the capture session's description. + label = TRACKING_DEVICES[device.kind] if needed and device.kind is not None else device.label + items.append(CheckItem(f"device:{index}", TRACKING, label, status, state, device.kind)) + reported = {device.kind for device in facts.devices} + # Every requirement no reported device answers fails under its own name: the devices in the order they are + # listed to the operator, then whatever else the station names. A glove whose software is not running has + # no entry at all, which must not read as nothing to check. + unknown = [name for name in required if name not in TRACKING_DEVICES] + for name in (*(name for name in TRACKING_DEVICES if name in required), *unknown): + if name in reported: + continue + if name not in TRACKING_DEVICES: + # A name a newer build or a hand wrote into the stations file: kept, and never met here. + why = NOT_A_DEVICE + else: + why = SWITCHED_OFF if name in facts.disabled else NOT_REPORTED + label = TRACKING_DEVICES.get(name, name) + items.append(CheckItem(f"device:required:{name}", TRACKING, label, FAIL, f"{why}; {REQUIRED_HERE}", name)) # Connected devices that deliver nothing would record an empty take. - if items and not facts.tracking_fresh: + if facts.devices and not facts.tracking_fresh: items.append(CheckItem("tracking:samples", TRACKING, "Tracking data", FAIL, "no recent sample")) return items +#: How a LiveKit camera stands by what an operator's page last saw of it. Only arriving frames pass. The rest +#: warns and never fails: the page is not the recorder, which joins the room itself when a take starts and +#: refuses that take, with its own reason, when no frame reaches it. Each warning says what to check and that +#: the recorder is what checks next, so that none reads as this checklist holding a take. +_RECORDER_CHECKS = "the recorder checks this camera itself when a take starts" +_LIVEKIT_SEEN = { + RECEIVING: (PASS, "frames are arriving in the preview"), + SILENT: (WARN, f"no frames in the preview: check the camera and its sender; {_RECORDER_CHECKS}"), + NO_TRACK: (WARN, f"its sender is not publishing it: start the camera sender; {_RECORDER_CHECKS}"), + NOT_CONNECTED: (WARN, f"the preview cannot join the video room; {_RECORDER_CHECKS}"), +} +#: The same for a camera no page is watching: nothing has been received from it, which is not a pass. +LIVEKIT_UNSEEN = f"not checked here: keep this page in view with the control token entered; {_RECORDER_CHECKS}" + + +def _livekit_item(item_id: str, label: str, name: str, facts: CaptureFacts) -> CheckItem: + """How one camera that arrives over LiveKit stands: failed when it cannot be recorded at all, passed only + while an operator's page reports its frames arriving, and otherwise a warning that says what to check.""" + if facts.livekit_blocked: + return CheckItem(item_id, CAMERAS, label, FAIL, facts.livekit_blocked) + seen = (facts.livekit_seen or {}).get(name) + status, detail = _LIVEKIT_SEEN.get(seen, (WARN, LIVEKIT_UNSEEN)) + return CheckItem(item_id, CAMERAS, label, status, detail) + + def _camera_item(item_id: str, label: str, name: str, facts: CaptureFacts) -> CheckItem: - """How one named camera stands: a CaptureServer camera must be delivering frames, a LiveKit camera offered - and recordable (its video is joined when a take starts). A camera that delivers frames while reporting - another state than connected warns: its frames are what recording readiness judges.""" + """How one named camera stands: a CaptureServer camera must be delivering frames, a LiveKit camera must be + recordable and is passed only while its frames are seen arriving. A camera that delivers frames while + reporting another state than connected warns: its frames are what recording readiness judges.""" if name in facts.livekit_cameras: - blocked = facts.livekit_blocked - return CheckItem(item_id, CAMERAS, label, FAIL if blocked else PASS, blocked) + return _livekit_item(item_id, label, name, facts) camera = (facts.cameras or {}).get(name) if camera is None: return CheckItem(item_id, CAMERAS, label, FAIL, f"camera {name!r} is not offered by the capture session") @@ -173,21 +278,24 @@ def _camera_items(facts: CaptureFacts, roles: Mapping[str, str | None] | None) - return items -def _untrusted_poses(calibration_dir: Path, names: list[str]) -> list[str]: - """For each file among ``names`` that holds a transform between tracked poses and does not say it was made - with this project's tracking, the sentence that says so. Reads the files.""" +def _unusable_files(calibration_dir: Path, names: list[str]) -> list[str]: + """Why a file among ``names`` that is there is still no calibration this software uses, one sentence + each: a file written in a newer layout than this software reads, and a transform between tracked poses + that does not say it was made with this project's tracking. Reads the files.""" problems = [] for name in names: - if name not in POSE_CALIBRATION: - continue try: record = read_json_object(calibration_dir / name) except CalibrationFileError as unreadable: - # A file that cannot be read cannot say what it was made with. The library's message names the - # file and what is wrong with it, and no directory. - problems.append(str(unreadable)) + # A file of poses that cannot be read cannot say what it was made with. The library's message + # names the file and what is wrong with it, and no directory. A lens file is not held to that here. + if name in POSE_CALIBRATION: + problems.append(str(unreadable)) continue - problem = pose_source_problem(record, name) + # No reader here takes a file of a newer layout, and nothing else at the start of the day says so. + problem = layout_problem(record, name) + if problem is None and name in POSE_CALIBRATION: + problem = pose_source_problem(record, name) if problem is not None: problems.append(problem) return problems @@ -198,9 +306,10 @@ def _calibration_item( ) -> CheckItem: """The calibration file each camera role in use needs; skipped for a mock session or with no station. - Calibration files are optional unless the deployment requires them: a missing one, and a head-camera - position or wrist offsets made with another tracking source, fails when ``required`` and otherwise warns, - so a station that has not captured its calibration still records. + Calibration files are optional unless the deployment requires them: a missing one, one written in a + newer layout than this software reads, and a head-camera position or wrist offsets made with another + tracking source, fails when ``required`` and otherwise warns, so a station that has not captured its + calibration still records. """ absent = FAIL if required else WARN if facts.mock or roles is None: @@ -217,9 +326,9 @@ def _calibration_item( # A directory that cannot be searched is reported with its cause, never an exception for the caller. detail = f"cannot read the calibration directory: {exc.strerror}" return CheckItem("calibration", SYSTEM, "Camera calibration", absent, detail) - # A file that is there and was made for other poses is no more a calibration of this station than none. - untrusted = _untrusted_poses(calibration_dir, [name for name in needed if name not in missing]) - problems = ([f"missing: {', '.join(missing)}"] if missing else []) + untrusted + # A file that is there and cannot be used here is no more a calibration of this station than none. + unusable = _unusable_files(calibration_dir, [name for name in needed if name not in missing]) + problems = ([f"missing: {', '.join(missing)}"] if missing else []) + unusable detail = "; ".join(problems) if problems else None return CheckItem("calibration", SYSTEM, "Camera calibration", absent if problems else PASS, detail) @@ -250,11 +359,14 @@ def checklist( free_bytes: Callable[[Path], int], min_free_bytes: int = MIN_FREE_BYTES, require_calibration: bool = False, + required_devices: Collection[str] = (), ) -> list[CheckItem]: """Every item of the station checklist, in display order. ``roles`` is the station in use's camera per role, or None when no station is in use. ``require_calibration`` is the deployment's choice of whether missing calibration files hold a take. + ``required_devices`` names the tracking devices the station in use requires; one that is not connected + then fails, where it otherwise warns. Reads the calibration directory and the disk, so it is called from a worker thread. """ system = [ @@ -265,7 +377,7 @@ def checklist( # Nothing can be judged device by device without a running session; say that once. capture = CheckItem("capture", TRACKING, "Capture session", FAIL, facts.error or "capture is not running") return [capture, *system] - return [*_tracking_items(facts), *_camera_items(facts, roles), *system] + return [*_tracking_items(facts, required_devices), *_camera_items(facts, roles), *system] def _first(items: list[CheckItem], status: str) -> str | None: diff --git a/examples/egocap/backend/egocap_web/setup_routes.py b/examples/egocap/backend/egocap_web/setup_routes.py index 005b7ec3c7..2c339f1717 100644 --- a/examples/egocap/backend/egocap_web/setup_routes.py +++ b/examples/egocap/backend/egocap_web/setup_routes.py @@ -6,7 +6,9 @@ Reading the flow is open to any page that can reach the backend, as the capture status is. The capture host address to enter in the headset is a LAN detail, so it is included only when the request carries the run's -control token. Nothing here changes anything: the checklist is observed, not run. +control token. Nothing here changes anything: the checklist is observed, not run. The one thing a page sends is +what its preview is receiving of the LiveKit cameras, which the backend cannot see between takes; that report +needs the control token. """ from __future__ import annotations @@ -18,13 +20,17 @@ from fastapi.responses import JSONResponse from .host_addresses import address_changed, headset_addresses +from .livekit_sightings import SightingError from .recording_command import control_token_valid +from .request_body import read_authorized_json router = APIRouter() _NO_STORE = {"Cache-Control": "no-store"} #: How many times a read starts over because the station in use changed while it was gathering. _ATTEMPTS = 3 +#: A preview report is a page id and a word per stream. +_MAX_REPORT_BYTES = 8 * 1024 def _reply(body: dict[str, Any], status: int = 200) -> JSONResponse: @@ -91,3 +97,24 @@ async def read_setup(request: Request) -> JSONResponse: ) holds_token = control_token_valid(request.headers.get("x-control-token"), context.control_token) return _reply({**body, "headset": headset if holds_token else None}) + + +@router.post("/api/setup/livekit-preview") +async def report_livekit_preview(request: Request) -> JSONResponse: + """What the caller's preview is receiving of each LiveKit camera: ``{"page": id, "streams": {name: state}}``. + + The checklist passes such a camera only while a report says its frames are arriving. The report is kept in + memory, for a few seconds, and holds no take. + """ + state = request.app.state + sightings, context = getattr(state, "livekit_sightings", None), getattr(state, "recording_context", None) + if sightings is None or context is None: + return _reply({"detail": "setup is not available yet"}, 503) + body, refused = await read_authorized_json(request, context.control_token, _MAX_REPORT_BYTES) + if body is None: + return refused # type: ignore[return-value] + try: + sightings.report(body.get("page"), body.get("streams")) + except SightingError as exc: + return _reply({"detail": exc.public_message}, 400) + return _reply({}) diff --git a/examples/egocap/backend/egocap_web/setup_service.py b/examples/egocap/backend/egocap_web/setup_service.py index a26f6d693b..3b8d2ad509 100644 --- a/examples/egocap/backend/egocap_web/setup_service.py +++ b/examples/egocap/backend/egocap_web/setup_service.py @@ -6,8 +6,9 @@ The flow is station, devices, record, wrap-up. The checklist is judged continuously from the capture session, so there is nothing to run. With a station in use it is the recording gate: a take is refused while any item fails; -an item that only warns never holds one. With no stations set up nothing here gates recording, the same -configuration-free default the station registry keeps; the checklist is then advisory. +an item that only warns never holds one. A tracking device holds a take only when the station requires it. With +no stations set up nothing here gates recording, the same configuration-free default the station registry keeps; +the checklist is then advisory. The checklist reads the calibration directory and the recording disk, which can stall on a slow mount, so it is judged in a worker thread (:meth:`SetupService.refresh`, run as a background duty and by the route). The gate and @@ -20,7 +21,7 @@ import logging import shutil import time -from collections.abc import Callable +from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any @@ -41,8 +42,10 @@ first_failure, first_warning, free_bytes_under, + tracking_device_kind, ) from .station_service import StationService +from .stations import Station logger = logging.getLogger("isaaccapture.egocap.setup_service") @@ -59,8 +62,11 @@ CHECKS_PENDING = "the station checks are being evaluated" -def capture_facts(monitor: CaptureStatusMonitor, config: CaptureStatusConfig) -> CaptureFacts: - """The capture session's current state, as the checklist reads it.""" +def capture_facts( + monitor: CaptureStatusMonitor, config: CaptureStatusConfig, livekit_seen: Mapping[str, str] | None = None +) -> CaptureFacts: + """The capture session's current state, as the checklist reads it. ``livekit_seen`` is what operator pages + last saw of each LiveKit stream: the backend itself receives none of their video between takes.""" native = monitor.native now = time.monotonic() status = native.latest_status @@ -76,6 +82,7 @@ def capture_facts(monitor: CaptureStatusMonitor, config: CaptureStatusConfig) -> ) started = native.started livekit = [s for s in started.streams if isinstance(s, p.LiveKitCameraStream)] if started is not None else [] + devices = status.devices if status is not None else () return CaptureFacts( running=running, error=None if running else (monitor.snapshot().error_message or "capture is not running"), @@ -87,14 +94,40 @@ def capture_facts(monitor: CaptureStatusMonitor, config: CaptureStatusConfig) -> connected=device.status is p.DeviceState.CONNECTED, detail=device.error or device.status.name.lower(), headset=device.type == "headset", + kind=tracking_device_kind(device.type, device.path), + degraded=device.status is p.DeviceState.DEGRADED, + # The session's own reason for the state: a degraded device delivers only under some. + reason=device.reason.name, ) - for device in (status.devices if status is not None else ()) - # A device switched off by configuration is not part of this station. + for device in devices + # A device switched off by configuration is not part of this station, unless it requires it. if device.status is not p.DeviceState.DISABLED ), + disabled=tuple( + kind + for device in devices + if device.status is p.DeviceState.DISABLED + and (kind := tracking_device_kind(device.type, device.path)) is not None + ), cameras=cameras, livekit_cameras=frozenset(stream.name for stream in livekit), livekit_blocked=unrecordable_reason(started, config.capture_server_url) if livekit else None, + livekit_seen=dict(livekit_seen or {}), + ) + + +def reported_tracking_devices(monitor: CaptureStatusMonitor) -> frozenset[str] | None: + """The tracking devices the capture session reports, by the names a station requires them under; None + while no status has arrived. A device switched off in the capture configuration is not reported: it + cannot be connected until that configuration changes.""" + status = monitor.native.latest_status + if status is None: + return None + return frozenset( + kind + for device in status.devices + if device.status is not p.DeviceState.DISABLED + and (kind := tracking_device_kind(device.type, device.path)) is not None ) @@ -113,6 +146,20 @@ class Evaluation: items: tuple[CheckItem, ...] #: Monotonic time its facts were sampled, so slow file checks age it. at: float + #: The tracking devices the station judged required. + required: tuple[str, ...] = () + + def judged(self, station: Station | None) -> bool: + """Whether this is a judgement of ``station`` as it stands now: its cameras and what it requires.""" + return (self.key, self.required) == _judged_by(station) + + +def _judged_by(station: Station | None) -> tuple[tuple[tuple[str, str | None], ...] | None, tuple[str, ...]]: + """What the checklist judges a station by, as a comparable value: its camera per role and the tracking + devices it requires. A change to either makes an earlier judgement another station's.""" + if station is None: + return None, () + return tuple(sorted(station.camera_roles.items())), station.required_devices class SetupService: @@ -147,19 +194,9 @@ def __init__( # Evaluations under way, held here because the event loop keeps only weak references to tasks. self._evaluations: set[asyncio.Task[Evaluation]] = set() - def _roles(self) -> dict[str, str | None] | None: - """The camera each role of the station in use is filled by, or None with no station in use.""" - selected = self._stations.registry.selected - return dict(selected.camera_roles) if selected is not None else None - - @staticmethod - def _key_of(roles: dict[str, str | None] | None) -> tuple[tuple[str, str | None], ...] | None: - """The comparable value an evaluation of these roles is kept under.""" - return tuple(sorted(roles.items())) if roles is not None else None - - def _key(self) -> tuple[tuple[str, str | None], ...] | None: - """What an evaluation for the station in use now would be keyed by.""" - return self._key_of(self._roles()) + def _station(self) -> Station | None: + """The station in use, or None.""" + return self._stations.registry.selected async def refresh(self) -> Evaluation: """Judge the checklist now and keep the result for the synchronous readers. @@ -181,15 +218,17 @@ async def _evaluate(self, asked: int) -> Evaluation: """ async with self._refreshing: latest = self._latest - if latest is not None and self._finished > asked and latest.key == self._key(): + if latest is not None and self._finished > asked and latest.judged(self._station()): return latest - roles = self._roles() + # Read once: the station in use can change while the files are being read. + station = self._station() + key, required = _judged_by(station) # Stamped when the facts are sampled, not when the files answer: a stalled disk must age the result. sampled = self._monotonic() try: # The capture facts are plain memory and belong to the event loop; only the files leave it. facts = self._facts() - items = await asyncio.to_thread(self._judged, facts, roles) + items = await asyncio.to_thread(self._judged, facts, station) self._last_failure = None except Exception as exc: # noqa: BLE001 -- the gate must hold with a reason, never raise facts = CaptureFacts() @@ -202,25 +241,26 @@ async def _evaluate(self, asked: int) -> Evaluation: if repr(exc) != self._last_failure: self._last_failure = repr(exc) logger.exception("The station checklist could not be evaluated") - self._latest = Evaluation(self._key_of(roles), facts, tuple(items), sampled) + self._latest = Evaluation(key, facts, tuple(items), sampled, required) self._finished += 1 return self._latest - def _judged(self, facts: CaptureFacts, roles: dict[str, str | None] | None) -> list[CheckItem]: - """The checklist for these facts; blocking file work, run in a worker thread.""" + def _judged(self, facts: CaptureFacts, station: Station | None) -> list[CheckItem]: + """The checklist of ``station`` for these facts; blocking file work, run in a worker thread.""" return checklist( facts, - roles, + dict(station.camera_roles) if station is not None else None, calibration_dir=self._calibration_dir(), output_root=self._output_root, free_bytes=self._free_bytes, require_calibration=self._require_calibration(), + required_devices=station.required_devices if station is not None else (), ) def _current(self) -> Evaluation | None: """The last evaluation while it still speaks for the station in use, else None.""" latest = self._latest - if latest is None or latest.key != self._key(): + if latest is None or not latest.judged(self._station()): return None return latest if self._monotonic() - latest.at <= _STALE_SECONDS else None @@ -230,13 +270,17 @@ def headset_connected(self) -> bool: latest = self._latest return latest is not None and latest.facts.headset_connected - def block_reason(self, ignore: frozenset[str] = frozenset()) -> str | None: + def block_reason( + self, ignore: frozenset[str] = frozenset(), unused_devices: frozenset[str] = frozenset() + ) -> str | None: """Why station setup does not allow a take now, or None when it does. Reads memory only: it is asked on the event loop, by every viewer's sender and by the uptime sample. ``ignore`` names checklist items, by id, whose failure does not hold this take: a calibration take is - what produces the calibration files, so it cannot wait for them. A station problem, a result that is - still pending and every other item hold it as they hold any take. + what produces the calibration files, so it cannot wait for them. ``unused_devices`` names tracking + devices this take does not record with: a station's requirement of one does not hold it, as a camera + calibration is not held for a glove. A station problem, a result that is still pending and every + other item hold it as they hold any take. """ blocked = self._stations.block_reason() if blocked is not None: @@ -248,7 +292,8 @@ def block_reason(self, ignore: frozenset[str] = frozenset()) -> str | None: # Held rather than guessed: a take admitted on no result could fill a disk nobody measured. if current is None: return CHECKS_PENDING - return first_failure([item for item in current.items if item.id not in ignore]) + holding = [item for item in current.items if item.id not in ignore and item.device not in unused_devices] + return first_failure(holding) def status( self, *, took_today: bool, saved_count: int, report_saved: bool, headset_address_changed: bool @@ -281,9 +326,13 @@ def status( def _station_step(self, headset_address_changed: bool) -> dict[str, Any]: """Station: skipped with no stations set up, done once the station in use can record.""" registry = self._stations.registry - if not registry.stations: - return _step("station", "Station", SKIPPED, "no stations set up") blocked = self._stations.block_reason() + if not registry.stations: + # No stations because none were saved is the configuration-free default; no stations because the + # saved ones could not be read holds recording, and the step says so. + if blocked is None: + return _step("station", "Station", SKIPPED, "no stations set up") + return _step("station", "Station", ATTENTION, blocked) if blocked is not None: return _step("station", "Station", TODO if registry.selected is None else ATTENTION, blocked) # Advisory: a headset pointed at an address this host no longer has cannot connect. diff --git a/examples/egocap/backend/egocap_web/station_service.py b/examples/egocap/backend/egocap_web/station_service.py index cf5a612a83..f876a3d63d 100644 --- a/examples/egocap/backend/egocap_web/station_service.py +++ b/examples/egocap/backend/egocap_web/station_service.py @@ -19,7 +19,7 @@ from typing import Any, Protocol from .operator_settings import CAMERA_ROLES, CAMERA_TYPES -from .stations import Station, StationError, StationRegistry, StationStore +from .stations import TRACKING_DEVICES, Station, StationError, StationRegistry, StationStore logger = logging.getLogger("isaaccapture.egocap.station_service") @@ -38,6 +38,10 @@ def offered_cameras(self) -> frozenset[str] | None: def change_blocked(self) -> str | None: """Why the station in use cannot change now, or None when it can.""" + def reported_devices(self) -> frozenset[str] | None: + """The tracking devices the capture session reports, by the names a station requires them under, or + None while it has reported none of its devices yet.""" + def show_label(self, label: str) -> None: """Publish the station label every viewer sees.""" @@ -68,7 +72,8 @@ def __init__(self, store: StationStore, session: StationSession, default_label: def _load(self) -> StationRegistry: """The stored registry; one that is invalid or cannot be read starts empty with a warning the page - shows. Capture preview does not depend on stations, so neither stops the backend from starting.""" + shows, which also holds recording (see :meth:`block_reason`). Capture preview does not depend on + stations, so neither stops the backend from starting. A file that is absent is no stations at all.""" try: return self._store.load() except StationError as exc: @@ -100,9 +105,16 @@ def block_reason(self) -> str | None: An empty registry blocks nothing: that is the configuration-free default. Once stations exist, one must be selected and able to record. While the station in use is being changed nothing may start: the take would open a session under the label, or record against the cameras, on their way out. + + A stored registry that could not be read is not an empty one. It may name a station in use and the + devices that station requires, so recording is held, with the sentence the Station tab shows, until + a change from that tab has replaced or reread the file. """ if self._applying: return STATION_CHANGING + if self._warning is not None: + # A reason is carried without its closing full stop, which each place that prints one adds. + return self._warning.rstrip(".") if not self._registry.stations: return None selected = self._registry.selected @@ -115,6 +127,7 @@ def listing(self, *, private: bool) -> dict[str, Any]: """The wire form of the registry. ``private`` adds each station's headset address, a LAN detail shown only to a caller holding the control token.""" offered = self._session.offered_cameras() + reported = self._session.reported_devices() stations = [] for station in self._registry.stations: record = { @@ -122,6 +135,14 @@ def listing(self, *, private: bool) -> dict[str, Any]: "name": station.name, "camera_type": station.camera_type, "camera_roles": dict(station.camera_roles), + "required_devices": list(station.required_devices), + # What the station requires that the capture session here does not report, and so cannot be + # connected here: the checklist holds recording for it, and the Station tab says so beforehand. + "unreported_devices": [ + device + for device in station.required_devices + if reported is not None and device not in reported + ], "problems": station.problems(offered), } if private: @@ -132,6 +153,8 @@ def listing(self, *, private: bool) -> dict[str, Any]: "selected": self._registry.selected_id, "roles": list(CAMERA_ROLES), "camera_types": list(CAMERA_TYPES), + # The devices a station can require, with the names the page shows for them. + "tracking_devices": [{"id": device, "name": name} for device, name in TRACKING_DEVICES.items()], "label": self._label, "locked_reason": self._session.change_blocked(), } @@ -238,6 +261,7 @@ def session_adapter( show_label: Callable[[str], None], rotate_batch: Callable[[], Awaitable[None]], renamed: Callable[[str, str], None], + reported_devices: Callable[[], frozenset[str] | None] = lambda: None, ) -> StationSession: """A :class:`StationSession` built from plain callables, so the application can bind the real monitor, recording context and uptime log without this module importing any of them.""" @@ -253,6 +277,10 @@ def change_blocked(self) -> str | None: """See :class:`StationSession`.""" return change_blocked() + def reported_devices(self) -> frozenset[str] | None: + """See :class:`StationSession`.""" + return reported_devices() + def show_label(self, label: str) -> None: """See :class:`StationSession`.""" show_label(label) diff --git a/examples/egocap/backend/egocap_web/stations.py b/examples/egocap/backend/egocap_web/stations.py index c98109e6d5..04e3f4bb5c 100644 --- a/examples/egocap/backend/egocap_web/stations.py +++ b/examples/egocap/backend/egocap_web/stations.py @@ -5,10 +5,10 @@ """The station registry: the stations an operator can choose between, and which one is in use. A station is a name plus the hardware that fills its roles: the camera type, which offered camera is the ego view -and which is on each wrist, and the host address last given to the headset. The registry is one JSON file beside -the operator settings, so every browser sees the same stations and they survive a restart. An empty registry is -the configuration-free default: nothing is selected, the deployment's own station label applies, and no station -rule blocks recording. +and which is on each wrist, the tracking devices it requires, and the host address last given to the headset. The +registry is one JSON file beside the operator settings, so every browser sees the same stations and they survive +a restart. An empty registry is the configuration-free default: nothing is selected, the deployment's own station +label applies, and no station rule blocks recording. This module holds the values and their validation only. Applying a selection to the running session lives in station_service.py, and the HTTP surface in station_routes.py. @@ -49,8 +49,19 @@ #: Operator-facing role names for messages; the page keeps its own copy for labels. _ROLE_NAMES = {"ego": "ego (head)", "wrist_left": "left wrist", "wrist_right": "right wrist"} +#: The tracking devices a station may require before it records, by the name a station stores, each with the +#: name the operator reads. A required device must be delivering its data before a take; a station that +#: requires none keeps a device that is not connected a warning. +TRACKING_DEVICES = { + "headset": "Headset", + "controller_left": "Left controller", + "controller_right": "Right controller", + "glove_left": "Left glove", + "glove_right": "Right glove", +} + #: The fields a create or update may carry. ``control_token`` is the legacy body credential, already checked. -_EDITABLE_FIELDS = ("name", "camera_type", "camera_roles", "headset_address") +_EDITABLE_FIELDS = ("name", "camera_type", "camera_roles", "headset_address", "required_devices") _IGNORED_FIELDS = ("control_token",) @@ -103,6 +114,89 @@ def _clean_headset_address(raw: Any) -> str | None: raise StationError(f"headset_address {raw.strip()!r} is not an IP address") from None +#: The longest a name this build does not know is kept and echoed, and how many of them one refusal echoes. +_MAX_ECHOED_CHARS = 40 +_ECHOED_NAMES = 5 + + +def _echoed(names: list[Any]) -> str: + """Names a caller sent that are refused, as the refusal repeats them: a few, each quoted, cut short and + with whatever cannot be printed or encoded escaped, so that no caller's text makes the reply.""" + shown = ", ".join(repr(name)[:_MAX_ECHOED_CHARS] for name in names[:_ECHOED_NAMES]) + more = len(names) - _ECHOED_NAMES + return f"{shown} and {more} more" if more > 0 else shown + + +def _clean_required_devices(raw: Any) -> tuple[str, ...]: + """The tracking devices a request says a station requires, in the order they are listed to the operator; + None for none. Strict: a request that names a device this build does not know is refused.""" + if raw is None: + return () + if not isinstance(raw, list) or not all(isinstance(name, str) for name in raw): + raise StationError("required_devices must be a list of tracking device names") + unknown = sorted(set(raw) - set(TRACKING_DEVICES)) + if unknown: + known = ", ".join(TRACKING_DEVICES) + raise StationError(f"unknown tracking device(s): {_echoed(unknown)}; a station can require {known}") + # One order whatever the request's, so two stations that require the same devices compare and store equal. + return tuple(name for name in TRACKING_DEVICES if name in raw) + + +def _kept_requirement(item: Any) -> str: + """One stored requirement as this build keeps it: a device's name exactly, or the text that was there, + cut short, for a name it does not know. Whatever is no usable text is kept as it would be written out.""" + if isinstance(item, str): + text = item.strip() + if text in TRACKING_DEVICES: + return text + try: + text.encode("utf-8") + except UnicodeEncodeError: + # A name no reply can carry is shown escaped. + text = "" + if text and text.isprintable(): + return text[:_MAX_ECHOED_CHARS] + return repr(item)[:_MAX_ECHOED_CHARS] + + +#: The most a stored requirement may hold: entries, and characters once written out. Far above anything a build +#: writes for its handful of devices, and low enough that what is kept of it, shown and written back stays small. +_MAX_STORED_REQUIREMENTS = 32 +_MAX_STORED_REQUIREMENT_CHARS = 4096 + + +def _stored_requirement_text(raw: Any) -> str | None: + """A stored station's requirement exactly as its file holds it, as JSON text, so that a save which does + not edit the requirement writes it back unchanged; None when the file states none. One that holds more + than a station can require is no station record: the registry is then unreadable, which holds recording. + """ + if raw is None: + return None + too_much = StationError("required_devices holds more than a station can require") + # Counted before it is written out, so a list without end is refused without being copied. + if isinstance(raw, list) and len(raw) > _MAX_STORED_REQUIREMENTS: + raise too_much + text = json.dumps(raw) + if len(text) > _MAX_STORED_REQUIREMENT_CHARS: + raise too_much + return text + + +def _stored_required_devices(raw: Any) -> tuple[str, ...]: + """The tracking devices a stored station requires. Lenient where the wire is strict, and never dropped: + a requirement exists to hold recording, so a file a newer build or a hand wrote must not read as "requires + nothing". The devices this build knows come first, in the order they are listed to the operator; whatever + else is there follows as a requirement that cannot be met, which the checklist shows as failing. + """ + if raw is None: + return () + items = [_kept_requirement(item) for item in (raw if isinstance(raw, list) else [raw])] + known = [name for name in TRACKING_DEVICES if name in items] + # Kept once each, in the order they were written. + unknown = list(dict.fromkeys(name for name in items if name not in TRACKING_DEVICES)) + return (*known, *unknown) + + @dataclass(frozen=True) class Station: """One station: its name and the hardware that fills its roles.""" @@ -114,16 +208,32 @@ class Station: camera_roles: dict[str, str | None] = field(default_factory=lambda: {role: None for role in CAMERA_ROLES}) #: The capture host address last entered in the headset; compared with today's to warn of a change. headset_address: str | None = None + #: The tracking devices, by their :data:`TRACKING_DEVICES` name, that must be delivering before a take. A + #: name read from the file that this build does not know is kept as it was written, cut short: a + #: requirement that cannot be met here. + required_devices: tuple[str, ...] = () + #: The requirement as the registry file held it, as JSON text, for a station read from the file; None for + #: one made or last edited here. Written back as it is, so that a save of anything else never rewrites a + #: requirement this build read leniently. No part of what the station is: two stations compare without it. + stored_requirement: str | None = field(default=None, compare=False, repr=False) def stored(self) -> dict[str, Any]: """The record as written to the registry file.""" - return { + record: dict[str, Any] = { "id": self.station_id, "name": self.name, "camera_type": self.camera_type, "camera_roles": dict(self.camera_roles), "headset_address": self.headset_address, } + if self.stored_requirement is not None: + # Read from the file and not edited since: what a newer build or a hand wrote stays as written. + record["required_devices"] = json.loads(self.stored_requirement) + elif self.required_devices: + # Written only when the station requires something, so a station that says nothing stores what + # it always did and reads the same in a build that does not know the key. + record["required_devices"] = list(self.required_devices) + return record def problems(self, offered_cameras: frozenset[str] | None) -> list[str]: """Why this station cannot record yet, most important first; empty when it can. @@ -157,6 +267,9 @@ def _parse_station(raw: Any) -> Station: camera_type=_clean_camera_type(raw.get("camera_type")), camera_roles=_station_roles(raw.get("camera_roles")), headset_address=_clean_headset_address(raw.get("headset_address")), + # Checked for its size first: what is kept of it below is bounded by that. + stored_requirement=_stored_requirement_text(raw.get("required_devices")), + required_devices=_stored_required_devices(raw.get("required_devices")), ) @@ -174,7 +287,7 @@ def _checked_fields(changes: Any) -> dict[str, Any]: raise StationError("a station change must be an object") unknown = sorted(set(changes) - set(_EDITABLE_FIELDS) - set(_IGNORED_FIELDS)) if unknown: - raise StationError(f"unknown station field(s): {', '.join(unknown)}") + raise StationError(f"unknown station field(s): {_echoed(unknown)}") return {key: changes[key] for key in _EDITABLE_FIELDS if key in changes} @@ -231,6 +344,7 @@ def added( camera_type=_clean_camera_type(checked.get("camera_type")), camera_roles=_station_roles(checked.get("camera_roles")), headset_address=_clean_headset_address(checked.get("headset_address")), + required_devices=_clean_required_devices(checked.get("required_devices")), ) return replace(self, stations=(*self.stations, station)) @@ -252,6 +366,14 @@ def updated(self, station_id: str, changes: Any) -> StationRegistry: merged = replace(merged, camera_roles=_station_roles({**current.camera_roles, **roles})) if "headset_address" in checked: merged = replace(merged, headset_address=_clean_headset_address(checked["headset_address"])) + if "required_devices" in checked: + # The whole list is replaced: unlike a camera role, a device is either named or it is not. From + # here the requirement is this build's own, and no longer what the file held. + merged = replace( + merged, + required_devices=_clean_required_devices(checked["required_devices"]), + stored_requirement=None, + ) return replace( self, stations=tuple(merged if station.station_id == station_id else station for station in self.stations), diff --git a/examples/egocap/frontend/README.md b/examples/egocap/frontend/README.md index 8155f3f4b6..9ddc047965 100644 --- a/examples/egocap/frontend/README.md +++ b/examples/egocap/frontend/README.md @@ -90,6 +90,15 @@ when it isn't. Snapshots arrive about once a second, so a per-frame jitter figur cannot be derived here and is deliberately not shown; measure jitter on the backend or with a direct `/stream{id}` client instead. +A camera that arrives over LiveKit has a tile of its own (`src/LiveKitCameraTile.tsx`), fed by the page's own +connection to the room. The backend is in that room only while a take records or a calibration check of the +head camera runs, so with the control token entered and the page in view, the page tells it every two seconds what each such tile sees: frames arriving, a subscribed +track that sends none, a track its sender has not published, or a room the page could not join +(`src/livekitSightings.ts`, `POST /api/setup/livekit-preview`). The Devices tab's checklist passes a LiveKit camera +only while such a report says its frames arrive. A hidden tab presents no frames, so it reports nothing, nor does +the first interval after it comes back into view. See +[`../LIVEKIT_PREVIEW.md`](../LIVEKIT_PREVIEW.md#checked-before-a-take). + ## Operator layout The page is built for an operator mid-take: the cameras fill it, and everything else is either a glance or one click away. @@ -138,9 +147,17 @@ The page is built for an operator mid-take: the cameras fill it, and everything 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 - the camera per role, saved together; only one editor is open at a time, and a save sends only the fields that - editor changed, so it never undoes a change made in another browser meanwhile. The editor of the station in use + filling each role, the tracking devices it requires, and why it cannot record yet. *Edit* opens the row's inline + editor for its name, camera type, the camera per role and *Required tracking devices* (a box per device the + backend lists), saved together. The help line under the boxes says what a tick asks: recording is held + while a ticked device is not delivering its data (switched off, not found, not started yet, switched off in + the capture configuration, or connected with nothing to send), and one that still delivers with a problem of + its own, such as a rejected calibration file, only warns, as an unticked one does. A requirement the registry holds under a name this build does not know keeps a box of its + own, labelled *(not known to this software)*, so it can be unticked, and the row warns that recording is held + until it is. The row also warns when a ticked device is one the capture session here does not report + (`unreported_devices` of the listing). Only one editor is open + at a time, and a save sends only the fields that editor changed, so it never undoes a change made in another + browser meanwhile. The editor of the station in use ends with the address its headset connects to, and the row warns when this host's address has changed since the headset was given it. While a take is being recorded the station in use cannot be replaced, edited or deleted, and while an interrupted take waits for recovery the backend refuses a change of the station in use; the card shows @@ -152,8 +169,8 @@ The page is built for an operator mid-take: the cameras fill it, and everything shows what the settings hold, not what that station held. - *Devices* is a live checklist (`DevicesTab.tsx`): the tracking devices and cameras the station needs, its calibration files and the free disk space, each passed (`✓`), failed with the reason (`✗`), advisory (`!`, a - finding that does not hold recording) or not needed (`–`), under one line that says whether station setup holds - recording. The backend judges them continuously and the tab reads them again two seconds after each answer while + finding that does not hold recording, which the row says in view: "Advisory: does not hold recording.") or not + needed (`–`), under one line that says whether station setup holds recording. The backend judges them continuously and the tab reads them again two seconds after each answer while it is shown, so there is nothing to run. - Under the checklist, *Require calibration files before recording* is the deployment's choice (`require_calibration` in the operator settings, off by default, changed with the control token). Off, missing @@ -172,7 +189,27 @@ The page is built for an operator mid-take: the cameras fill it, and everything Set up, Record, Solve, Result. Set up chooses the camera, what to solve, the lens model and the board. The lens model is *Fisheye* or *Standard (radial-tangential)*, preselected from the default the backend names for the station's camera type, and is sent with the take and with its solve; no lens model is sent when only the - position on the headset is solved. A camera whose video is being corrected in this run cannot have its lens + position on the headset is solved. When the backend says the camera sends another size of picture than its + installed lens file was solved at (`picture_notes`), Set up shows *Picture size changed:* with the backend's + sentence for the take chosen, before anything is recorded; it holds nothing. Set up also has the card *Check + the installed calibration*: the live check (`CalibrationCheck` in `CalibrationRecorder.tsx`), started and + stopped from one button, followed a few times a second, which shows the picture with each corner seen and + predicted, the prediction's error in pixels, what a verdict still takes and the verdict in the solve's grades, + and says in the backend's words that it reads the installed files and writes nothing. Each graded figure has + the grade's two limits under it: how far the board appears to move, how well its poses fit the picture, and, + once the views can tell, how far the camera appears to sit off and how far its lag appears off. While views + that are enough by their count still carry no verdict, the card says why in the backend's sentence + (`no_verdict`) and goes on showing the error in pixels; what the backend says beside a verdict (`notes`, such + as a lag that was not tested) is shown under it. A verdict that the calibration needs repeating turns the line above the + picture from good news to a warning, and a picture the backend does not judge is shown with its reason and + without the caption of the marks. When the backend says the head camera reaches it through the video room + (`video_room` on the overview's camera), the card says before the start that the backend joins the room + while the check runs, as for a take, and that a take ends the check; while it joins, the line above the + picture is what the backend says it waits for. A check the backend ended itself (a take started, the page + stopped asking, or it ran for its longest) is said in the backend's words, with *Start check* back. Under + *Installed now*, a file that an install found already installed is said to have been changed by nothing + (`unchanged` in the ledger entry). It is ended when the tool + moves on from Set up. A camera whose video is being corrected in this run cannot have its lens calibrated from it: Set up says so, holds the choices that solve the lens, and leaves the head camera's position. Set up leads with the overview's notes on the run as sent (`rectification.notes`); while the launcher's report could not be read (`rectified: null`) the camera is taken neither for corrected nor for @@ -235,8 +272,9 @@ The page is built for an operator mid-take: the cameras fill it, and everything - **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 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. + each session with its takes (outcome, duration, task, studio once any take has one, operator, what was wrong), a + form that corrects the task of one take or a range, and a form that corrects the studio the whole session is + labelled with; *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 @@ -253,6 +291,13 @@ The page is built for an operator mid-take: the cameras fill it, and everything - 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. + - The studio form says what the takes are recorded as and that only the label changes: "the files stay where they + are", and for a routed group "in the folder they were recorded under". A correction the backend refuses, or + could not write, is shown with its sentence after "Not corrected:": that nothing was changed, or which takes say + the new studio, or carry the new task, now. When the reply to either form lists labels a failed correction left + changed (`left_changed`, carried by `CorrectionRefused` in `dayReportApi.ts`) the report is read again, so the + table shows what the recording holds. A form that was sent is empty again, which disables its button: focus + moves from the button to the form's first field, so it does not fall out of the dialog. - 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 @@ -282,6 +327,28 @@ The page is built for an operator mid-take: the cameras fill it, and everything - The 3D view's iframe is never narrower than 640 px: Viser switches to a layout that hides its scene at 576 px and below, and crashes its own page when resized across that breakpoint. +## Not yet verified on hardware + +The following were seen in this page's tests against scripted backends, and in a browser against the mock capture +server only: + +- The *Required tracking devices* boxes, the failing rows they cause and the Station tab's warning for a ticked + device the capture session does not report: no real headset, controller or glove. A row is named as the Station + tab names it only for a device the station requires; what a real session calls its other devices was not seen. + A degraded or switched-off device was never seen from the mock, which reports only connected or unavailable, + so a ticked device that is connected with nothing to send was seen holding recording in tests only. +- The check card's new figures and sentences (the implied camera offset and lag, why there is no verdict yet, + the lag that was not tested): seen with the backend's check run over rendered boards and its answers + replayed. On the mock, whose pictures hold no board, none of them appears. +- The LiveKit preview report: the room and the video element are scripted in the tests, and no LiveKit server was + run, so a camera has not been seen to pass. +- The live check of the installed calibration on Set up: the mock's pictures hold no board, so in a browser only + its "board not found" state and its refusal of a picture of another size were seen against the running backend. + Its other states were seen with the backend's check run over rendered boards and its answers replayed to the + page. No real camera, board or headset was used. For a camera in the video room, the card's sentence and the + lines it shows while the backend joins were seen with the backend's answers replayed: no room was run. +- The *Picture size changed* note, against the mock's one picture size. + ## Status presentation `derivePresentation` (`frontend/src/App.tsx`) is the single source every diff --git a/examples/egocap/frontend/src/App.tsx b/examples/egocap/frontend/src/App.tsx index 03c35c035e..9fd2c3dc14 100644 --- a/examples/egocap/frontend/src/App.tsx +++ b/examples/egocap/frontend/src/App.tsx @@ -646,7 +646,7 @@ export default function App() {
{/* The cameras are the page: they take every pixel the status bar above and the controls below leave. */}
- +
vi.useFakeTimers()); @@ -1194,3 +1205,281 @@ describe("the take's cues", () => { expect(cues()).toBeTruthy(); }); }); + +describe("the live check of the installed head-camera calibration", () => { + /** The check over a fake backend. */ + async function renderCheck(overrides: Partial = {}, backend = fakeCheckBackend()) { + const props: CalibrationCheckProps = { board: BOARD_FIXTURE, controlToken: "tok", backend, ...overrides }; + const utils = render(); + await settle(); + return { ...utils, backend }; + } + /** A check that is running, with what the next polls answer. */ + async function renderChecking(found: Partial | null = {}, status: Partial = {}) { + const backend = fakeCheckBackend(); + const rendered = await renderCheck({}, backend); + fireEvent.click(button("Start check")); + await settle(); + backend.state.status = { ...CHECK_FIXTURE, preview: { jpeg: "AAAA", width: 640, height: 480 }, check: found === null ? null : { ...CHECK_RECORD_FIXTURE, ...found }, ...status }; + await settle(RECORDER_POLL_MS); + return rendered; + } + const lead = () => screen.getByRole("status"); + + it("says before it starts what it does and that nothing is solved or recorded, and starts with the board on the form", async () => { + const { backend } = await renderCheck(); + expect(screen.getByText(/^Checks the installed head camera calibration against the live picture, without solving or recording anything\./)).toBeTruthy(); + expect(screen.queryByRole("status")).toBeNull(); + fireEvent.click(button("Start check")); + await settle(); + expect(backend.start).toHaveBeenCalledWith("tok", { board: BOARD_FIXTURE }); + // From then on it says what the backend says it reads, and that it writes nothing. + expect(screen.getByText("The check reads the installed head_camera_intrinsics.json and head_camera_extrinsics.json. It records nothing and changes no file.")).toBeTruthy(); + expect(lead().textContent).toBe("Waiting for the first picture."); + expect(buttons()).toEqual(["Stop check"]); + }); + + it("reports the error in pixels as it goes, the figures a verdict takes, and the verdict in the solve's grades", async () => { + await renderChecking(); + expect(lead().textContent).toBe("Enough has been seen: the verdict is below. Go on moving to keep watching it, or stop the check."); + expect(lead().className).toContain("calib-lead--ready"); + // The rows of the list that are measures: a graded figure's limits are rows under it. + expect(measures("Error of the prediction").filter(([name]) => name !== undefined)).toEqual([ + ["This picture", "0.62 px", null], + ["Over the check", "0.71 px", null], + ["Largest", "1.34 px", null], + ["Views with the head moved", "24 of 10", 1], + ["Head turned", "41.5 of at least 15°", 1], + ["Board appears to move", "1.2 mm", null], + ["Board pose fits the picture to", "0.21 px", null], + ["Camera appears to sit off by", "0.8 mm", null], + ["Camera lag appears off by", "2 ms", null], + ]); + // Each graded figure has the grade's two limits under it. + const limits = Array.from(within(screen.getByRole("region", { name: "Error of the prediction" })).getAllByRole("list")).flatMap((list) => (list.className === "calib-measure-parts" ? [within(list).getAllByRole("listitem").map((item) => item.textContent)] : [])); + expect(limits).toEqual([ + ["Excellent under 5 mm", "Needs repeating over 10 mm"], + ["Excellent under 1 px", "Needs repeating over 2 px"], + ["Excellent under 5 mm", "Needs repeating over 10 mm"], + ["Excellent under 10 ms", "Needs repeating over 20 ms"], + ]); + expect(screen.getByText("Verdict: Excellent. Graded on how far the board appears to move, the camera place and lag that implies, and how well the board's poses fit, each against a solve's own limit.")).toBeTruthy(); + expect((screen.getByRole("img") as HTMLImageElement).alt).toBe("Live picture, with the board's corners as seen and as predicted from the head pose"); + expect(screen.getByText("Dots are the corners seen. Rings are where the head pose and the installed calibration say they should be.")).toBeTruthy(); + }); + + it("names a calibration that is off as needing repeating, and gives no verdict before the head has moved enough", async () => { + await renderChecking({ verdict: "bad", rms_px: 14.2, board_wander_m: 0.016 }); + expect(screen.getByText("Verdict: Needs repeating. Graded on how far the board appears to move, the camera place and lag that implies, and how well the board's poses fit, each against a solve's own limit.")).toBeTruthy(); + // Having seen enough is not shown as good news when what was seen is a calibration that is off. + expect(lead().className).toContain("calib-lead--warning"); + cleanup(); + await renderChecking({ enough: false, verdict: null, views: 3, head_turn_deg: 6, hints: ["Turn and tilt your head, and step to the side, keeping the board in view. The board must not move."] }); + expect(screen.getByText("No verdict yet: it takes views from a head that has moved.")).toBeTruthy(); + expect(lead().className).toContain("calib-lead--go"); + expect(measures("Error of the prediction").slice(3, 5)).toEqual([ + ["Views with the head moved", "3 of 10", 0.3], + ["Head turned", "6 of at least 15°", 0.4], + ]); + }); + + it("says in the backend's words why enough views still give no verdict, and goes on showing the pixel error", async () => { + const reason = "No verdict yet: your head has turned about one axis only, so the camera's place along that axis is not tested."; + const todo = "Nod and tilt your head as well as turning it, keeping the board in view. The board must not move."; + await renderChecking({ enough: false, verdict: null, no_verdict: reason, hints: [todo], rms_px: 9.8, camera_offset_m: null, camera_lag_off_s: null }); + expect(screen.getByText(reason)).toBeTruthy(); + expect(screen.queryByText(/^Verdict:/)).toBeNull(); + // What to do is the lead, and the error measured so far is still there to be read. + expect(lead().textContent).toBe(todo); + expect(lead().className).toContain("calib-lead--go"); + expect(measures("Error of the prediction")[1]).toEqual(["Over the check", "9.8 px", null]); + // Nothing is implied of the camera's place or lag yet, so neither is shown. + expect(measures("Error of the prediction").map(([name]) => name)).not.toContain("Camera appears to sit off by"); + }); + + it("shows the camera place and lag the board's wander implies, and what the backend says beside a verdict", async () => { + const untested = "The camera's lag is not tested yet: it shows only in pictures taken while your head moves. Keep moving slowly with the board in view to test it."; + await renderChecking({ verdict: "acceptable", camera_offset_m: 0.0098, camera_lag_off_s: null, notes: [untested] }); + expect(measures("Error of the prediction").find(([name]) => name === "Camera appears to sit off by")).toEqual(["Camera appears to sit off by", "9.8 mm", null]); + expect(measures("Error of the prediction").map(([name]) => name)).not.toContain("Camera lag appears off by"); + expect(screen.getByText(untested)).toBeTruthy(); + cleanup(); + // A lag is shown by how far it is off, whichever way. + await renderChecking({ verdict: "bad", camera_lag_off_s: -0.031 }); + expect(measures("Error of the prediction").find(([name]) => name === "Camera lag appears off by")).toEqual(["Camera lag appears off by", "31 ms", null]); + }); + + it("shows how far the board's place is fixed while it is being fixed", async () => { + await renderChecking({ phase: "fixing", fixing: { views: 2, views_needed: 5 }, error_px: null, rms_px: null, worst_px: null, views: 0, camera_offset_m: null, camera_lag_off_s: null, board_wander_m: null, pose_fit_px: null, enough: false, verdict: null, hints: ["Keep the board in view and still while the check fixes where it stands."] }); + expect(lead().textContent).toBe("Keep the board in view and still while the check fixes where it stands."); + expect(measures("Error of the prediction")).toEqual([["Views to fix where the board stands", "2 of 5", 0.4]]); + }); + + it("says why a picture cannot be judged, in the backend's sentence, as the first thing", async () => { + await renderChecking({ judged: false, cannot_judge: "The headset has lost its position: look around the room until it finds it again. The check starts over from where the board stands then.", restarts: 2 }); + expect(lead().textContent).toMatch(/^The headset has lost its position/); + expect(lead().className).toContain("calib-lead--stop"); + expect(screen.getByText("The check started over 2 times: the headset lost or changed its position.")).toBeTruthy(); + cleanup(); + await renderChecking({ judged: false, cannot_judge: "The board is not found in the picture: point the camera at it, and move slowly.", restarts: 1 }); + expect(lead().textContent).toBe("The board is not found in the picture: point the camera at it, and move slowly."); + expect(screen.getByText("The check started over once: the headset lost or changed its position.")).toBeTruthy(); + }); + + it("says there is nothing to judge without a live picture, and which matrix it uses for a corrected camera", async () => { + await renderChecking(null, { available: false, unavailable_reason: "there is no live picture from this camera", preview: null }); + expect(lead().textContent).toBe("Nothing to judge: there is no live picture from this camera."); + expect(lead().className).toContain("calib-lead--warning"); + expect(screen.getByText("No live picture")).toBeTruthy(); + cleanup(); + // A picture of another size than the calibration describes is shown as it came, with no caption of marks that are not drawn. + const otherSize = "this camera sends a 1280x720 picture, and the installed calibration is for 640x480, so it cannot be checked on this picture: set the camera's picture mode back, or calibrate again"; + await renderChecking(null, { available: false, unavailable_reason: otherSize }); + expect(lead().textContent).toBe(`Nothing to judge: ${otherSize}.`); + expect(screen.getByRole("img")).toBeTruthy(); + expect(screen.queryByText(/^Dots are the corners seen/)).toBeNull(); + cleanup(); + await renderChecking({}, { corrected: true }); + expect(screen.getByText(/^Dots are the corners seen/)).toBeTruthy(); + expect(screen.getByText("This camera's video is corrected in this run, so the corrected camera's matrix is used.")).toBeTruthy(); + }); + + it("stops from the same button, keeps keyboard focus on it, and says again what the check did not do", async () => { + const { backend } = await renderChecking(); + const stop = button("Stop check"); + stop.focus(); + fireEvent.click(stop); + await settle(); + expect(backend.stop).toHaveBeenCalledWith("tok"); + expect(document.activeElement).toBe(button("Start check")); + expect(screen.queryByRole("status")).toBeNull(); + expect(screen.getByText(CHECK_FIXTURE.note)).toBeTruthy(); + // Stopped, it is not asked about any more. + const polls = backend.poll.mock.calls.length; + await settle(3 * RECORDER_POLL_MS); + expect(backend.poll).toHaveBeenCalledTimes(polls); + }); + + it("asks again only after each answer, and stops the check when the tool moves on", async () => { + const backend = fakeCheckBackend(); + let answer: (status: LiveCheckStatus) => void = () => {}; + backend.poll = vi.fn(() => new Promise((resolve) => (answer = resolve))); + const { unmount } = await renderCheck({}, backend); + fireEvent.click(button("Start check")); + await settle(RECORDER_POLL_MS); + await settle(5 * RECORDER_POLL_MS); + expect(backend.poll).toHaveBeenCalledTimes(1); + await act(async () => answer(CHECK_FIXTURE)); + await settle(RECORDER_POLL_MS); + expect(backend.poll).toHaveBeenCalledTimes(2); + unmount(); + expect(backend.stop).toHaveBeenCalledWith("tok"); + }); + + it("holds the start, with the reason, while the board cannot exist or the check has nothing to check", async () => { + const { backend } = await renderCheck({ board: null }); + expect(button("Start check").getAttribute("aria-disabled")).toBe("true"); + expect(screen.getByText("Describe the board as printed first.")).toBeTruthy(); + fireEvent.click(button("Start check")); + await settle(); + expect(backend.start).not.toHaveBeenCalled(); + cleanup(); + await renderCheck({ unavailable: "Install the head camera's intrinsics and its position on the headset first." }, backend); + expect(screen.getByText("Install the head camera's intrinsics and its position on the headset first.")).toBeTruthy(); + fireEvent.click(button("Start check")); + await settle(); + expect(backend.start).not.toHaveBeenCalled(); + }); + + it("shows the backend's reason for a refused start and stays ready to start", async () => { + const backend = fakeCheckBackend(); + backend.start = vi.fn(async () => { + throw new SettingsHttpError("the backend holds no live picture of this camera, so its calibration cannot be checked live: a camera that reaches the page over LiveKit is seen by the backend only while a take records", 409); + }); + await renderCheck({}, backend); + fireEvent.click(button("Start check")); + await settle(); + expect(screen.getByRole("alert").textContent).toMatch(/^Not started: the backend holds no live picture of this camera/); + expect(buttons()).toEqual(["Start check"]); + }); + + it("says when a read failed without ending the check, and ends it when the backend no longer has it", async () => { + const backend = fakeCheckBackend(); + backend.poll = vi.fn().mockResolvedValueOnce(CHECK_FIXTURE).mockRejectedValue(new SettingsHttpError("the backend did not answer in time")); + await renderCheck({}, backend); + fireEvent.click(button("Start check")); + await settle(); + await settle(RECORDER_POLL_MS); + expect(screen.queryByRole("alert")).toBeNull(); + await settle(RECORDER_POLL_MS); + await settle(); + expect(screen.getByRole("alert").textContent).toBe("The check is not updating: the backend did not answer in time"); + // The check goes on being asked about: one read that failed ends nothing. + expect(buttons()).toEqual(["Stop check"]); + const polls = backend.poll.mock.calls.length; + await settle(RECORDER_POLL_MS); + expect(backend.poll.mock.calls.length).toBeGreaterThan(polls); + }); + + it("stops following a check the backend no longer has, and says to start it again", async () => { + const backend = fakeCheckBackend(); + backend.poll = vi.fn(async () => { + throw new SettingsHttpError("no check is running", 404); + }); + await renderCheck({}, backend); + fireEvent.click(button("Start check")); + await settle(); + await settle(RECORDER_POLL_MS); + await settle(); + expect(screen.getByRole("alert").textContent).toBe("Not started: the backend no longer has this check. Start it again"); + expect(buttons()).toEqual(["Start check"]); + }); + + it("says in the backend's words what became of a check the backend ended, and takes the words away at the next start", async () => { + const backend = fakeCheckBackend(); + backend.poll = vi.fn(async () => { + throw new SettingsHttpError("the check ended because a take started: the two never run together", 404); + }); + await renderCheck({}, backend); + fireEvent.click(button("Start check")); + await settle(); + await settle(RECORDER_POLL_MS); + await settle(); + expect(screen.getByRole("alert").textContent).toBe("The check ended because a take started: the two never run together."); + expect(buttons()).toEqual(["Start check"]); + fireEvent.click(button("Start check")); + await settle(); + expect(screen.queryByRole("alert")).toBeNull(); + }); + + it("says before the start that a camera in the video room is joined there for the check, and not of any other camera", async () => { + await renderCheck(); + expect(screen.queryByText(CHECK_JOINS_ROOM)).toBeNull(); + cleanup(); + const backend = fakeCheckBackend(CHECK_IN_ROOM_FIXTURE); + await renderCheck({ videoRoom: true }, backend); + expect(CHECK_JOINS_ROOM).toBe( + "This camera reaches the backend through the video room. While the check runs, the backend joins the room to see it, as it does for a take, and leaves when the check ends. A take that starts ends the check.", + ); + expect(screen.getByText(CHECK_JOINS_ROOM)).toBeTruthy(); + fireEvent.click(button("Start check")); + await settle(); + // While it runs the backend's own note says where it is, so the page's sentence gives way to it. + expect(screen.queryByText(CHECK_JOINS_ROOM)).toBeNull(); + expect(screen.getByText(CHECK_IN_ROOM_FIXTURE.note)).toBeTruthy(); + // On its way into the room it says what it waits for, as a step under way and not as a fault. + expect(lead().textContent).toBe("Joining the video room to see this camera."); + expect(lead().className).toContain("calib-lead--go"); + backend.state.status = { ...CHECK_IN_ROOM_FIXTURE, waiting: "Pictures are arriving: waiting for the camera sender's clock to be matched to this computer's, so that each picture's time can be placed among the head poses." }; + await settle(RECORDER_POLL_MS); + expect(lead().textContent).toMatch(/^Pictures are arriving: waiting for the camera sender's clock/); + // In the room and looking: the lead is the check's own again. + backend.state.status = { ...CHECK_IN_ROOM_FIXTURE, waiting: null, check: CHECK_RECORD_FIXTURE }; + await settle(RECORDER_POLL_MS); + expect(lead().textContent).toBe(CHECK_RECORD_FIXTURE.hints[0]); + // Stopped, the sentence is back for the next start. + fireEvent.click(button("Stop check")); + await settle(); + expect(screen.getByText(CHECK_JOINS_ROOM)).toBeTruthy(); + }); +}); diff --git a/examples/egocap/frontend/src/CalibrationRecorder.tsx b/examples/egocap/frontend/src/CalibrationRecorder.tsx index ef2d9981d0..c6b122fa5e 100644 --- a/examples/egocap/frontend/src/CalibrationRecorder.tsx +++ b/examples/egocap/frontend/src/CalibrationRecorder.tsx @@ -20,10 +20,20 @@ * a start is on its way, which the backend finishes whether or not the page waits for it. */ import { useEffect, useReducer, useRef, useState } from "react"; -import { cancelCalibrationRecording, fetchCalibrationRecording, jpegDataUrl, startCalibrationRecording, stopCalibrationRecording } from "./calibrationApi"; +import { + cancelCalibrationRecording, + fetchCalibrationCheck, + fetchCalibrationRecording, + jpegDataUrl, + startCalibrationCheck, + startCalibrationRecording, + stopCalibrationCheck, + stopCalibrationRecording, +} from "./calibrationApi"; import { cuesEnabled, playCue, setCuesEnabled } from "./calibrationCues"; -import type { CalibrationGuide, CalibrationRecording, CalibrationRecordingRequest } from "./calibrationTypes"; +import type { BoardSpec, CalibrationGuide, CalibrationRecording, CalibrationRecordingRequest, LiveCheckRecord, LiveCheckStatus } from "./calibrationTypes"; import { formatElapsed } from "./RecordingPanel"; +import { sentence } from "./sentence"; import { SettingsHttpError } from "./settingsApi"; import { errorMessage } from "./settingsParts"; @@ -921,3 +931,222 @@ export function CalibrationRecorder({ ); } + +/** The calls the live check makes; the real routes unless a test passes fakes. */ +export interface CalibrationCheckBackend { + /** Starts a check against the board described; nothing is recorded. */ + start: (controlToken: string, request: { board: BoardSpec }) => Promise; + /** Reads where the check stands, after a look at the newest live picture. */ + poll: (controlToken: string, signal: AbortSignal) => Promise; + /** Ends the check. */ + stop: (controlToken: string) => Promise; +} + +/** The backend's own routes; the check uses these unless a test passes fakes. */ +export const REAL_CALIBRATION_CHECK_BACKEND: CalibrationCheckBackend = { start: startCalibrationCheck, poll: fetchCalibrationCheck, stop: stopCalibrationCheck }; + +/** What a calibration tool gives the live check it shows. */ +export interface CalibrationCheckProps { + /** The board in view, as the tool's form describes it; null while the form describes none that could exist. */ + board: BoardSpec | null; + /** The run's control token, sent with every call. */ + controlToken: string; + /** Why the check cannot be started at all, in the tool's words; null when it can. */ + unavailable?: string | null; + /** Whether the camera reaches the backend through the LiveKit video room, which the check then joins while it runs. */ + videoRoom?: boolean; + /** The calls the check makes; the real routes unless a test passes fakes. */ + backend?: CalibrationCheckBackend; +} + +/** What the backend answers a read with when no check runs and none ended without being stopped. */ +const NO_CHECK_RUNNING = "no check is running"; +/** Said before a check of a camera that arrives over the video room is started, so that joining the room is no surprise. */ +export const CHECK_JOINS_ROOM = + "This camera reaches the backend through the video room. While the check runs, the backend joins the room to see it, as it does for a take, and leaves when the check ends. A take that starts ends the check."; + +/** What a verdict rests on, said after it. */ +const VERDICT_BASIS = "Graded on how far the board appears to move, the camera place and lag that implies, and how well the board's poses fit, each against a solve's own limit."; +/** Each verdict in the operator's words, as the solve's result page names its grades. */ +const VERDICT_WORDS: Record = { excellent: "Excellent", acceptable: "Acceptable", bad: "Needs repeating" }; + +/** What the check says first: why it cannot judge, what to do now, or that it has seen enough. */ +function checkLead(status: LiveCheckStatus): { words: string; tone: "ready" | "stop" | "go" | "warning" } { + const found = status.check ?? null; + if (status.available === false) return { words: `Nothing to judge: ${bare(status.unavailable_reason ?? "the backend has no live picture of this camera")}.`, tone: "warning" }; + // On its way into the video room: the backend says what it is waiting for there. + if (typeof status.waiting === "string") return { words: status.waiting, tone: "go" }; + if (found === null) return { words: "Waiting for the first picture.", tone: "go" }; + if (!found.judged) return { words: found.cannot_judge ?? "This picture cannot be judged.", tone: "stop" }; + // Enough seen is good news only of the looking: a verdict that the calibration is off is not shown as one. + const done = found.verdict === "bad" ? "warning" : "ready"; + return { words: found.hints[0] ?? "Keep the board in view.", tone: found.enough ? done : "go" }; +} + +/** A figure held under two limits, as a measure with the limits under it: met while it is under the first. */ +function underLimit(name: string, value: number | null, limits: [number, number] | undefined, unit: string, scale = 1): Measure | null { + if (value === null || limits === undefined) return null; + const [excellent, worst] = limits; + // The limits are not states of their own: the figure beside them says on which side of each it stands. + const parts = [ + { words: `Excellent under ${short(excellent * scale, 2)} ${unit}`, met: false }, + { words: `Needs repeating over ${short(worst * scale, 2)} ${unit}`, met: false }, + ]; + return { name, figure: `${short(value * scale, 2)} ${unit}`, share: null, met: value < excellent, parts }; +} + +/** The check's figures: what was seen so far against what a verdict takes, and each graded figure against the grade's limits. */ +function checkMeasures(found: LiveCheckRecord): Measure[] { + const error = (name: string, value: number | null): Measure | null => (value === null ? null : { name, figure: `${short(value, 2)} px`, share: null }); + return [ + found.phase === "fixing" ? counted("Views to fix where the board stands", found.fixing.views, found.fixing.views_needed) : null, + error("This picture", found.error_px), + error("Over the check", found.rms_px), + error("Largest", found.worst_px), + found.phase === "checking" ? counted("Views with the head moved", found.views, found.views_needed) : null, + found.phase === "checking" ? atLeast("Head turned", found.head_turn_deg, found.head_turn_needed_deg, "°") : null, + underLimit("Board appears to move", found.board_wander_m, found.limits?.board_wander_m, "mm", 1000), + underLimit("Board pose fits the picture to", found.pose_fit_px, found.limits?.pose_fit_px, "px"), + // What the board's wander implies of the files, once the views can tell: shown by how far each is off. + underLimit("Camera appears to sit off by", found.camera_offset_m ?? null, found.limits?.camera_offset_m, "mm", 1000), + underLimit("Camera lag appears off by", typeof found.camera_lag_off_s === "number" ? Math.abs(found.camera_lag_off_s) : null, found.limits?.camera_lag_off_s, "ms", 1000), + ].filter((measure): measure is Measure => measure !== null); +} + +/** + * A live check of the installed head-camera calibration, with no solve and nothing recorded: started and stopped + * here, and followed a few times a second while it runs, each time only after the last answer came. The board + * stands still and the operator moves their head; the picture shows each corner seen and where the head pose + * says it should be, and the figures say how far apart the two are. + */ +export function CalibrationCheck({ board, controlToken, unavailable = null, videoRoom = false, backend = REAL_CALIBRATION_CHECK_BACKEND }: CalibrationCheckProps) { + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState(null); + // What became of a check the backend ended without this page stopping it, in the backend's words. + const [ended, setEnded] = useState(null); + const checking = status !== null && status.phase === "checking"; + const { poll, stop } = backend; + + useEffect(() => { + if (!checking) return; + const controller = new AbortController(); + let timer: ReturnType | undefined; + /** Ask where the check stands and, while it runs, again an interval after the answer. */ + const read = () => { + poll(controlToken, controller.signal).then( + (answer) => { + if (controller.signal.aborted) return; + setFailure(null); + setStatus(answer); + timer = setTimeout(read, RECORDER_POLL_MS); + }, + (error: unknown) => { + if (controller.signal.aborted) return; + // The backend no longer has the check: there is nothing left to follow. It says so when it ended the + // check itself, for a take that started or for a page that stopped asking; otherwise it was restarted. + if (saysTakeLost(error)) { + setStatus(null); + if (error.status === 404 && error.message !== NO_CHECK_RUNNING) setEnded(error.message); + else setFailure("the backend no longer has this check. Start it again"); + return; + } + setFailure(errorMessage(error)); + timer = setTimeout(read, RECORDER_POLL_MS); + }, + ); + }; + timer = setTimeout(read, RECORDER_POLL_MS); + return () => { + controller.abort(); + clearTimeout(timer); + }; + }, [checking, controlToken, poll]); + + // A check left running when the tool moves on is ended: nothing reads it any more. It wrote nothing. + const running = useRef(false); + running.current = checking; + useEffect( + () => () => { + if (running.current) void stop(controlToken).catch(() => undefined); + }, + [stop, controlToken], + ); + + /** Start the check, or stop it: one button, so keyboard focus stays where it was. */ + const toggle = () => { + if (busy) return; + if (!checking && (board === null || unavailable !== null)) return; + setBusy(true); + setFailure(null); + setEnded(null); + // The answer to a stop is kept too: it says once more what the check read and that it wrote nothing. + const asked = checking ? backend.stop(controlToken) : backend.start(controlToken, { board: board as BoardSpec }); + asked.then(setStatus, (error: unknown) => setFailure(errorMessage(error))).finally(() => setBusy(false)); + }; + + const found = status?.check ?? null; + const lead = status === null ? null : checkLead(status); + const jpeg = typeof status?.preview?.jpeg === "string" ? status.preview.jpeg : null; + const held = !checking && (board === null || unavailable !== null); + const verdict = found?.verdict ?? null; + return ( +
+

+ {status?.note ?? "Checks the installed head camera calibration against the live picture, without solving or recording anything. Fix the board where it cannot move, keep it in view, and move your head."} +

+ {/* Said while no check runs: once one does, the backend's own note above says that it is in the room. */} + {videoRoom && !checking &&

{CHECK_JOINS_ROOM}

} +
+ {/* Held, never disabled, so the button keeps keyboard focus through the start and the stop. */} + + {held && {unavailable ?? "Describe the board as printed first."}} + {failure !== null && ( + + {checking ? "The check is not updating" : "Not started"}: {failure} + + )} + {ended !== null && ( + + {sentence(ended)}. + + )} +
+ {checking && lead !== null && ( +
+

+ {lead.words} +

+
+
+
+ {jpeg === null ?
No live picture
: Live picture, with the board's corners as seen and as predicted from the head pose} +
+ {/* A picture that is not judged has nothing drawn on it to explain. */} + {jpeg !== null && status?.available !== false &&
Dots are the corners seen. Rings are where the head pose and the installed calibration say they should be.
} +
+
+ {found !== null && } + {found !== null && ( +

+ {/* Why there is none yet is the backend's sentence when it has one: it knows what the views lack. */} + {verdict === null ? (found.no_verdict ?? "No verdict yet: it takes views from a head that has moved.") : `Verdict: ${VERDICT_WORDS[verdict] ?? verdict}. ${VERDICT_BASIS}`} +

+ )} + {found !== null && + (found.notes ?? []).map((note) => ( +

+ {note} +

+ ))} + {found !== null && found.restarts > 0 &&

The check started over {found.restarts === 1 ? "once" : `${found.restarts} times`}: the headset lost or changed its position.

} + {status?.corrected === true &&

This camera's video is corrected in this run, so the corrected camera's matrix is used.

} +
+
+
+ )} +
+ ); +} diff --git a/examples/egocap/frontend/src/CameraGrid.livekit.test.tsx b/examples/egocap/frontend/src/CameraGrid.livekit.test.tsx index e940721371..1d771463a3 100644 --- a/examples/egocap/frontend/src/CameraGrid.livekit.test.tsx +++ b/examples/egocap/frontend/src/CameraGrid.livekit.test.tsx @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { cleanup, render, screen } from "@testing-library/react"; import { CameraGrid } from "./CameraGrid"; import type { LiveKitStreamDescriptor, PreviewSnapshot } from "./captureProtocol"; +import { SIGHT_REPORT_MS } from "./livekitSightings"; import { STREAMS, FakeRoom } from "./livekitTestDoubles"; vi.mock("livekit-client", async () => { @@ -137,6 +138,22 @@ describe("CameraGrid with offered LiveKit streams", () => { expect(primary[0].textContent).toContain("Head left"); }); + it("tells the backend what its LiveKit tiles see once it holds the control token, and nothing without it", async () => { + const fetchFn = stubFetch(200, { token: "tok" }); + const reports = () => fetchFn.mock.calls.filter(([path]) => path === "/api/setup/livekit-preview").map(([, init]) => JSON.parse((init as RequestInit).body as string).streams); + const view = (controlToken: string | null) => ; + const { rerender } = render(view(null)); + await settled(); + await new Promise((r) => setTimeout(r, SIGHT_REPORT_MS + 200)); + expect(reports()).toEqual([]); + rerender(view("control")); + await new Promise((r) => setTimeout(r, SIGHT_REPORT_MS + 200)); + // In the room, and the camera host has published neither track. + expect(reports()).toEqual([{ "Head left": "no_track", "Head right": "no_track" }]); + const sent = fetchFn.mock.calls.find(([path]) => path === "/api/setup/livekit-preview")?.[1] as RequestInit; + expect((sent.headers as Record)["X-Control-Token"]).toBe("control"); + }, 10_000); + it("does not contact the backend and keeps MJPEG behavior when no streams are offered", async () => { const fetchFn = stubFetch(200, { token: "tok" }); const { container, rerender } = render(); diff --git a/examples/egocap/frontend/src/CameraGrid.tsx b/examples/egocap/frontend/src/CameraGrid.tsx index 0d5569adce..c0d1afcdc1 100644 --- a/examples/egocap/frontend/src/CameraGrid.tsx +++ b/examples/egocap/frontend/src/CameraGrid.tsx @@ -17,6 +17,7 @@ import { CameraRateTracker, formatCameraStats } from "./cameraRates"; import { ROLE_LABELS } from "./settingsApi"; import { roleOfCamera } from "./useOperatorSettings"; import { LiveKitCameraTile } from "./LiveKitCameraTile"; +import { useLiveKitSightReports } from "./livekitSightings"; import { useLiveKitPreview } from "./useLiveKitPreview"; const CAMERA_ERROR_RETRY_LIMIT = 3; @@ -157,12 +158,15 @@ export function CameraGrid({ live, receivedAtMonotonic, cameraRoles = null, + controlToken = null, }: { snapshot: PreviewSnapshot | null; live: boolean; receivedAtMonotonic: number | null; /** The assigned ego camera owns the primary tile when it is available. */ cameraRoles?: Record | null; + /** The run's control token; with it the page tells the backend what its preview receives of each LiveKit camera. */ + controlToken?: string | null; }) { const [, forceTick] = useState(0); useEffect(() => { @@ -190,6 +194,9 @@ export function CameraGrid({ // Direct LiveKit tiles sit beside the CaptureServer ones; they have their own connection and readiness. const livekit = useLiveKitPreview(liveKitStreams(snapshot?.started)); + // The backend is in the room only during a take, so the station checklist learns from this page whether each + // LiveKit camera's frames are arriving. + const noteSight = useLiveKitSightReports(controlToken); const cameras = snapshot?.cameras ?? []; const livekitShown = livekit.tiles.length > 0 || livekit.phase === "error"; if (cameras.length === 0 && !livekitShown) { @@ -267,6 +274,7 @@ export function CameraGrid({ phase={livekit.phase} clock={livekit.clock} basis={tile.basis} + onSight={(sight) => noteSight(tile.name, sight)} // A LiveKit tile is a main view only when no CaptureServer camera claims that place: every head // camera when there are several, otherwise the first tile. primary={liveKitOnly && (equalHeads ? isHeadTile(tile.name) : index === 0)} diff --git a/examples/egocap/frontend/src/DevicesTab.test.tsx b/examples/egocap/frontend/src/DevicesTab.test.tsx index d9dcc4bb5f..0d397475e7 100644 --- a/examples/egocap/frontend/src/DevicesTab.test.tsx +++ b/examples/egocap/frontend/src/DevicesTab.test.tsx @@ -6,11 +6,11 @@ import type { ComponentType, ReactNode } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; -import { DEVICES_REFRESH_MS, DevicesTab, type DevicesTabProps } from "./DevicesTab"; +import { ADVISORY_NOTE, DEVICES_REFRESH_MS, DevicesTab, type DevicesTabProps } from "./DevicesTab"; import { SettingsHttpError } from "./settingsApi"; import { OPERATOR_SETTINGS_FIXTURE, TOOLS_FIXTURE } from "./settingsTestDoubles"; import type { SetupStatus } from "./setupApi"; -import { SETUP_ADVISED, SETUP_HELD, SETUP_READY, SETUP_UNCALIBRATED } from "./setupTestDoubles"; +import { SETUP_ADVISED, SETUP_DEVICE_REQUIRED, SETUP_HELD, SETUP_READY, SETUP_UNCALIBRATED } from "./setupTestDoubles"; beforeEach(() => vi.useFakeTimers()); afterEach(() => { @@ -71,6 +71,21 @@ describe("the verdict", () => { }); }); +describe("a tracking device the station requires", () => { + it("fails in the list with why it holds here, beside one that only warns, and is what the verdict names", async () => { + await renderTab(SETUP_DEVICE_REQUIRED); + expect(screen.getByRole("status").textContent).toBe("Recording is held: Left glove: disconnected; this station requires it."); + expect(rowsOf("Tracking")).toEqual([ + "✓Pico headset passed", + "!Left controllerDisconnectedAdvisory: does not hold recording.", + "✗Left glove failedDisconnected; this station requires it", + "✗Right glove failedNot reported by the capture session; this station requires it", + ]); + const rows = within(screen.getByRole("region", { name: "Tracking" })).getAllByRole("listitem"); + expect(rows.map((row) => row.className)).toEqual(["check-row check-row--pass", "check-row check-row--warn", "check-row check-row--fail", "check-row check-row--fail"]); + }); +}); + describe("a check whose outcome this page does not know", () => { it("is shown as unrecognised with its reason, never as passed or not needed", async () => { const [first, ...rest] = SETUP_READY.checks.filter((check) => check.group === "system"); @@ -84,12 +99,24 @@ describe("a check whose outcome this page does not know", () => { }); describe("a check that only warns", () => { - it("has its own mark, colour class and spoken outcome, and its reason", async () => { + it("has its own mark and colour class, its reason, and says in view that it does not hold recording", async () => { await renderTab(SETUP_ADVISED); - expect(rowsOf("System")).toEqual(["!Camera calibration advisoryMissing head_intrinsics.json, head_extrinsics.json", "✓Free disk space passed211.3 GB free"]); + expect(rowsOf("System")).toEqual(["!Camera calibrationMissing head_intrinsics.json, head_extrinsics.jsonAdvisory: does not hold recording.", "✓Free disk space passed211.3 GB free"]); const advised = within(screen.getByRole("region", { name: "System" })).getAllByRole("listitem")[0]; expect(advised.className).toBe("check-row check-row--warn"); - expect(advised.querySelector(".visually-hidden")?.textContent).toBe(" advisory"); + // Said once, in view: an advisory row has no hidden word that would be read out beside it. + expect(within(advised).getByText(ADVISORY_NOTE)).toBeTruthy(); + expect(advised.querySelector(".visually-hidden")).toBeNull(); + // No other outcome carries the note. + expect(screen.getAllByText(ADVISORY_NOTE)).toHaveLength(1); + }); + + it("says the same of a LiveKit camera whose frames no page reports, whose finding names the recorder as what checks next", async () => { + const unseen = "not checked here: keep this page in view with the control token entered; the recorder checks this camera itself when a take starts"; + const checks = SETUP_READY.checks.map((check) => (check.id === "camera:ego" ? { ...check, status: "warn" as const, detail: unseen } : check)); + await renderTab({ ...SETUP_READY, checks }); + expect(rowsOf("Cameras")[0]).toBe(`!Ego (head): cam_head${unseen.charAt(0).toUpperCase()}${unseen.slice(1)}Advisory: does not hold recording.`); + expect(screen.getByRole("status").textContent).toBe("Station setup allows recording."); }); it("leaves the verdict saying recording is allowed", async () => { diff --git a/examples/egocap/frontend/src/DevicesTab.tsx b/examples/egocap/frontend/src/DevicesTab.tsx index 12f9ad1ea1..7de7eb2773 100644 --- a/examples/egocap/frontend/src/DevicesTab.tsx +++ b/examples/egocap/frontend/src/DevicesTab.tsx @@ -40,9 +40,14 @@ const GROUPS: ReadonlyArray<[CheckGroup, string]> = [ ["system", "System"], ]; +/** What an advisory row says in so many words: its finding describes something wrong, and must not be read as + * what holds recording. */ +export const ADVISORY_NOTE = "Advisory: does not hold recording."; + /** One device or check: its outcome, its name, and why when it did not simply pass. */ function CheckRow({ item }: { item: CheckItem }) { const outcome = OUTCOMES[item.status]; + const advisory = item.status === "warn"; return (
  • {item.label} - {outcome.word} + {/* An advisory row says so in view, below; said here as well it would be read out twice. */} + {!advisory && {outcome.word}} {item.detail !== null && {sentence(item.detail)}} + {advisory && {ADVISORY_NOTE}}
  • ); } diff --git a/examples/egocap/frontend/src/HeadsetCalibrationDialog.test.tsx b/examples/egocap/frontend/src/HeadsetCalibrationDialog.test.tsx index c88ff3dcaa..85739cfcbb 100644 --- a/examples/egocap/frontend/src/HeadsetCalibrationDialog.test.tsx +++ b/examples/egocap/frontend/src/HeadsetCalibrationDialog.test.tsx @@ -17,7 +17,9 @@ import { OVERVIEW_FIXTURE, SAVED_TAKE, fakeHeadsetBackend, + CHECK_FIXTURE, } from "./calibrationTestDoubles"; +import { CHECK_JOINS_ROOM } from "./CalibrationRecorder"; import type { CalibrationFile, CalibrationOverview, CalibrationRecording, CalibrationRecordingRequest, CameraJob, CameraJobResult } from "./calibrationTypes"; import { InstallRefusal } from "./calibrationApi"; import { HeadsetCalibrationDialog, SOLVE_POLL_MS, type HeadsetCalibrationDialogProps } from "./HeadsetCalibrationDialog"; @@ -140,7 +142,7 @@ describe("Set up", () => { expect(backend.loadOverview).toHaveBeenCalledWith("tok", expect.any(AbortSignal)); expect(within(screen.getByRole("list", { name: "Steps" })).getAllByRole("listitem").map((item) => item.textContent)).toEqual(["Set up", "Record", "Solve", "Result"]); expect(currentStep()).toBe("Set up"); - expect(Array.from(document.querySelectorAll(".settings-content-body > section")).map((card) => card.getAttribute("aria-label"))).toEqual(["Camera", "Board", "How to move", "Installed now"]); + expect(Array.from(document.querySelectorAll(".settings-content-body > section")).map((card) => card.getAttribute("aria-label"))).toEqual(["Camera", "Board", "How to move", "Installed now", "Check the installed calibration"]); }); it("offers only the roles that have a camera, the first of them chosen", async () => { @@ -292,6 +294,23 @@ describe("Set up", () => { expect(screen.getByRole("list", { name: "Installed calibration files" }).textContent).not.toMatch(/installed by|blake|alex/); }); + it("says of a file an install found already installed that installing it again changed nothing", async () => { + // blake pressed Install on the solve alex had installed the day before: the ledger notes the press, and that + // the file was left as it was. On the left wrist one file of the day's two was really replaced. + const ledger = { + headset: { date: "2026-11-25", at: "2026-11-25T11:00:00-08:00", operator: "blake", files: ["head_camera_intrinsics.json"], unchanged: ["head_camera_intrinsics.json"] }, + wrist: { date: "2026-11-25", operator: "alex", files: ["head_camera_intrinsics.json", "head_camera_extrinsics.json"], unchanged: ["head_camera_intrinsics.json", "head_camera_extrinsics.json"] }, + wrist_left_camera: { date: "2026-11-23", operator: "alex", files: ["left_wrist_camera_intrinsics.json"], unchanged: [] }, + }; + await renderDialog({}, fakeHeadsetBackend({ ledger })); + const card = region("Installed now"); + expect(Array.from(card.querySelectorAll(":scope > p.settings-note")).map((line) => line.textContent)).toEqual([ + "Head camera calibration: last installed by blake on 2026-11-25 11:00. head_camera_intrinsics.json was already installed, and installing it again changed nothing.", + "Controller–glove offset: last installed by alex on 2026-11-25. head_camera_intrinsics.json and head_camera_extrinsics.json were already installed, and installing them again changed nothing.", + "Left wrist camera calibration: last installed by alex on 2026-11-23.", + ]); + }); + it("says nothing of installs on a station that keeps no ledger", async () => { await renderDialog({}, fakeHeadsetBackend({ ledger: undefined })); expect(region("Installed now").querySelectorAll(":scope > p.settings-note")).toHaveLength(0); @@ -563,6 +582,84 @@ describe("a camera whose video is being corrected in this run", () => { }); }); +describe("the live check on Set up", () => { + const card = () => region("Check the installed calibration"); + + it("starts a check of the head camera against the board on the form, with nothing recorded, and stops it on the way to recording", async () => { + const backend = fakeHeadsetBackend(); + const { check } = backend; + await renderDialog({}, backend); + expect(within(card()).getByText(/Nothing is solved, recorded or changed\./)).toBeTruthy(); + fireEvent.change(field("Square size (mm)"), { target: { value: "50" } }); + fireEvent.click(within(card()).getByRole("button", { name: "Start check" })); + await settle(); + expect(check.start).toHaveBeenCalledWith("tok", { board: expect.objectContaining({ square_length_m: 0.05 }) }); + expect(within(card()).getByText(CHECK_FIXTURE.note)).toBeTruthy(); + // Nothing of a take was asked for: the recorder was not touched. + expect(backend.recorder.start).not.toHaveBeenCalled(); + fireEvent.click(button("Continue to recording")); + await settle(); + expect(check.stop).toHaveBeenCalledWith("tok"); + }); + + it("says why there is nothing to check while a head camera file is not installed, and starts nothing", async () => { + const backend = fakeHeadsetBackend(WITHOUT_INTRINSICS); + const { check } = backend; + await renderDialog({}, backend); + expect(within(card()).getByText("Install the head camera's intrinsics and its position on the headset first.")).toBeTruthy(); + fireEvent.click(within(card()).getByRole("button", { name: "Start check" })); + await settle(); + expect(check.start).not.toHaveBeenCalled(); + }); + + it("says that the check joins the video room while it runs when the head camera reaches the backend that way, and only then", async () => { + await renderDialog({}, fakeHeadsetBackend()); + expect(within(card()).queryByText(CHECK_JOINS_ROOM)).toBeNull(); + cleanup(); + // The backend says of the head camera that it arrives over the video room; a wrist camera that does is not what the check looks at. + const inRoom = (role: string) => OVERVIEW_FIXTURE.cameras.map((camera) => ({ ...camera, video_room: camera.role === role })); + await renderDialog({}, fakeHeadsetBackend({ cameras: inRoom("wrist_left") })); + expect(within(card()).queryByText(CHECK_JOINS_ROOM)).toBeNull(); + cleanup(); + await renderDialog({}, fakeHeadsetBackend({ cameras: inRoom("ego") })); + expect(within(card()).getByText(CHECK_JOINS_ROOM)).toBeTruthy(); + }); +}); + +describe("a camera that sends another size of picture than its lens file was solved at", () => { + const LENS = "head_camera_intrinsics.json was solved on a 640x480 picture, and this camera now sends 1280x960. A solve from this take replaces it with one for the new size: if the size changed by mistake, set the camera's picture mode back before recording"; + const POSITION = "head_camera_intrinsics.json is for a 640x480 picture, and this camera now sends 1280x960, so the camera's position cannot be solved against it. Solve the lens as well, or set the camera's picture mode back before recording"; + /** The fixture's cameras with the head camera's picture another size than its lens file's. */ + const resized = OVERVIEW_FIXTURE.cameras.map((camera) => (camera.role === "ego" ? { ...camera, picture_notes: { lens: LENS, position: POSITION } } : { ...camera, picture_notes: { lens: null, position: null } })); + + it("says so on Set up before anything is recorded, in the backend's words for the take chosen, and still lets it start", async () => { + const { backend } = await renderDialog({}, fakeHeadsetBackend({ cameras: resized })); + // A take that solves the lens would replace the file made at the other size. + const said = screen.getByText(`Picture size changed: ${LENS}.`); + expect(said.className).toBe("settings-note tone-warning"); + expect(screen.queryByText(`Picture size changed: ${POSITION}.`)).toBeNull(); + fireEvent.change(select("What to solve"), { target: { value: "intrinsic" } }); + expect(screen.getByText(`Picture size changed: ${LENS}.`)).toBeTruthy(); + // A take of the position alone builds on that file, and is told it cannot. + fireEvent.change(select("What to solve"), { target: { value: "extrinsic" } }); + expect(screen.getByText(`Picture size changed: ${POSITION}.`)).toBeTruthy(); + expect(screen.queryByText(`Picture size changed: ${LENS}.`)).toBeNull(); + // It tells and holds nothing: the start is not a problem, and the take is recorded as chosen. + expect(problem()).toBe(""); + await startRecording(); + expect(backend.recorder.start.mock.calls[0][1]).toMatchObject({ role: "ego", mode: "extrinsic" }); + }); + + it("says nothing for a camera whose picture is the size of its file, and nothing when the backend does not say", async () => { + await renderDialog({}, fakeHeadsetBackend({ cameras: resized })); + fireEvent.change(select("Camera"), { target: { value: "wrist_left" } }); + expect(screen.queryByText(/Picture size changed/)).toBeNull(); + cleanup(); + await renderDialog(); + expect(screen.queryByText(/Picture size changed/)).toBeNull(); + }); +}); + describe("Record", () => { it("starts the take with the role, the mode, the operator and the board in meters", async () => { const { backend } = await renderDialog(); diff --git a/examples/egocap/frontend/src/HeadsetCalibrationDialog.tsx b/examples/egocap/frontend/src/HeadsetCalibrationDialog.tsx index c44f4e2e26..d8c9139778 100644 --- a/examples/egocap/frontend/src/HeadsetCalibrationDialog.tsx +++ b/examples/egocap/frontend/src/HeadsetCalibrationDialog.tsx @@ -23,9 +23,16 @@ * refuses to end the take does it let the operator leave regardless: the take is the recorder's like any * other, and the recording panel can end it too. */ -import { useCallback, useEffect, useId, useReducer, useRef, useState } from "react"; +import { useCallback, useEffect, useId, useReducer, useRef, useState, type ReactNode } from "react"; import { InstallRefusal, fetchCalibrationOverview, fetchCameraJob, fetchPickedFrame, installCameraCalibration, missingCredentials, reasonSentence, startCameraSolve, whenCalibrated } from "./calibrationApi"; -import { CalibrationRecorder, REAL_CALIBRATION_RECORDER_BACKEND, type CalibrationRecorderBackend } from "./CalibrationRecorder"; +import { + CalibrationCheck, + CalibrationRecorder, + REAL_CALIBRATION_CHECK_BACKEND, + REAL_CALIBRATION_RECORDER_BACKEND, + type CalibrationCheckBackend, + type CalibrationRecorderBackend, +} from "./CalibrationRecorder"; import { LENS_MODEL_NAMES, knownLensModel, @@ -55,6 +62,8 @@ export interface HeadsetCalibrationBackend { loadOverview: (controlToken: string, signal: AbortSignal) => Promise; /** The recorder's calls; the dialog itself uses them to end a take it is closed over. */ recorder: CalibrationRecorderBackend; + /** The live check's calls; the real routes when a caller's backend names none. */ + check?: CalibrationCheckBackend; /** Starts solving a take in the background and answers with the job. */ solve: (controlToken: string, request: CameraSolveRequest) => Promise; /** Reads where the solve stands, and its result once done. */ @@ -70,6 +79,7 @@ export interface HeadsetCalibrationBackend { export const REAL_HEADSET_CALIBRATION_BACKEND: HeadsetCalibrationBackend = { loadOverview: fetchCalibrationOverview, recorder: REAL_CALIBRATION_RECORDER_BACKEND, + check: REAL_CALIBRATION_CHECK_BACKEND, solve: startCameraSolve, loadJob: fetchCameraJob, loadPick: fetchPickedFrame, @@ -202,6 +212,14 @@ function headIntrinsicsInstalled(overview: CalibrationOverview): boolean { return head !== undefined && usable(overview.files.find((file) => file.name === head.intrinsics_file)); } +/** Why the head camera's installed calibration cannot be checked live, in a sentence; null when it can. The + * check holds live pictures against both of the head camera's files, so both must be installed and readable. */ +function checkUnavailable(overview: CalibrationOverview): string | null { + const installed = (name: string) => usable(overview.files.find((file) => file.name === name)); + if (overview.cameras.find((camera) => camera.role === "ego")?.camera == null) return "No camera is assigned to the head camera role."; + return headIntrinsicsInstalled(overview) && installed("head_camera_extrinsics.json") ? null : "Install the head camera's intrinsics and its position on the headset first."; +} + /** Whether the overview shows a take being recorded right now. */ function recordingNow(overview: CalibrationOverview): boolean { return overview.recording !== null && (overview.recording.phase === "recording" || overview.recording.phase === "stopping"); @@ -312,15 +330,18 @@ const KIND_NAMES: Record = { wrist: "Controller–glove offset", }; -/** Who last installed each kind of calibration, and when, one sentence a kind. The ledger keeps one operator and - * one time per kind, so nothing here says which of a kind's files that install wrote. */ +/** Who last installed each kind of calibration, and when, one line a kind. The ledger keeps one operator and one + * time per kind, so nothing here says which of a kind's files that install wrote; it does say which of them an + * install found already installed, since such an install changed nothing and must not read as a calibration. */ function lastInstalls(ledger: CalibrationOverview["ledger"]): string[] { return Object.entries(ledger ?? {}).flatMap(([kind, entry]) => { const stamp = typeof entry.at === "string" ? entry.at : entry.date; const facts = [typeof entry.operator === "string" && entry.operator !== "" ? `by ${entry.operator}` : null, typeof stamp === "string" ? `on ${whenCalibrated(stamp)}` : null].filter((fact) => fact !== null); // An entry that names neither says nothing worth a line. if (facts.length === 0) return []; - return [`${Object.hasOwn(KIND_NAMES, kind) ? KIND_NAMES[kind] : sentence(kind.replace(/_/g, " "))}: last installed ${facts.join(" ")}.`]; + const unchanged = Array.isArray(entry.unchanged) ? entry.unchanged.filter((name) => typeof name === "string") : []; + const left = unchanged.length === 0 ? "" : ` ${unchanged.join(" and ")} ${unchanged.length === 1 ? "was already installed, and installing it" : "were already installed, and installing them"} again changed nothing.`; + return [`${Object.hasOwn(KIND_NAMES, kind) ? KIND_NAMES[kind] : sentence(kind.replace(/_/g, " "))}: last installed ${facts.join(" ")}.${left}`]; }); } @@ -363,6 +384,7 @@ function SetupStep({ onContinue, solveLast, onSolveLast, + check, }: { overview: CalibrationOverview; form: SetupForm; @@ -373,6 +395,8 @@ function SetupStep({ /** The action that solves a take without recording again, as its label and which take it is of; null when there is no such take. */ solveLast: { label: string; about: string } | null; onSolveLast: () => void; + /** The live check of the installed head-camera calibration, shown in a card of its own. */ + check: ReactNode; }) { const id = useId(); const assigned = overview.cameras.filter((camera) => camera.camera !== null); @@ -386,6 +410,9 @@ function SetupStep({ // No lens is solved with the position alone, so there is no model to choose for it. const lensSolved = mode !== "extrinsic"; const model = form.model ?? defaultModel; + // Said before the take is recorded: the camera sends another size of picture than its lens file was solved at, + // which most often means it was started in another picture mode. The backend says what that means for this take. + const pictureNote = chosen?.picture_notes?.[lensSolved ? "lens" : "position"] ?? null; const dictionaries = DICTIONARIES.includes(form.dictionary) ? DICTIONARIES : [form.dictionary, ...DICTIONARIES]; /** One board field, typed in the board's own units. */ const boardField = (key: "squaresX" | "squaresY" | "squareMm" | "markerMm", label: string, step: string) => ( @@ -478,6 +505,7 @@ function SetupStep({ {rectifiedWords(form.role, chosen?.rectification_waits === true)}

    )} + {assigned.length > 0 && typeof pictureNote === "string" && pictureNote !== "" &&

    Picture size changed: {pictureNote}.

    }
    @@ -514,6 +542,9 @@ function SetupStep({

    ))} + + {check} +
    {/* Held, never disabled: the overview is read again under the operator, and a problem it turns up must not take keyboard focus from the button it holds. */} @@ -1189,7 +1220,28 @@ export function HeadsetCalibrationDialog({ onClose, controlToken, operatorName, : finished !== null ? { label: "Solve the last take again", take: finished.take ?? null, about: lastSolveOf(finished) } : null; - return solveLast !== null && startSolve(solveLast.take)} />; + // The check looks at the board the form describes, whichever camera the form is set to calibrate next. + const headCheck = ( + camera.role === "ego")?.video_room === true} + backend={backend.check ?? REAL_CALIBRATION_CHECK_BACKEND} + /> + ); + return ( + solveLast !== null && startSolve(solveLast.take)} + check={headCheck} + /> + ); } if (step === "record") { return ( diff --git a/examples/egocap/frontend/src/LiveKitCameraTile.test.tsx b/examples/egocap/frontend/src/LiveKitCameraTile.test.tsx index 46ebc3cf4a..f74f326084 100644 --- a/examples/egocap/frontend/src/LiveKitCameraTile.test.tsx +++ b/examples/egocap/frontend/src/LiveKitCameraTile.test.tsx @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, render, screen } from "@testing-library/react"; -import { LiveKitCameraTile, displayedFps } from "./LiveKitCameraTile"; +import { LiveKitCameraTile, displayedFps, sightOf } from "./LiveKitCameraTile"; import { fakeTrack } from "./livekitTestDoubles"; type FrameMetadata = { presentedFrames: number; [field: string]: number }; @@ -106,6 +106,75 @@ describe("LiveKitCameraTile placeholders", () => { }); }); +describe("what a LiveKitCameraTile reports seeing of its stream", () => { + it("says nothing while the room connects, and that the page is not in the room once that failed", () => { + expect(sightOf("connecting", null, false, false, false)).toBeNull(); + expect(sightOf("reconnecting", fakeTrack(), true, false, false)).toBeNull(); + expect(sightOf("idle", null, false, false, false)).toBeNull(); + expect(sightOf("error", null, false, false, false)).toBe("not_connected"); + }); + + it("follows the tile from no track, through the wait for a first frame, to frames arriving and stopping", () => { + const onSight = vi.fn(); + const track = fakeTrack(); + const { rerender } = render(); + expect(onSight).toHaveBeenLastCalledWith("no_track"); + rerender(); + // Just subscribed: its first frame may still come, so the tile does not call it silent yet. + expect(onSight).toHaveBeenLastCalledWith(null); + presentFrame(); + expect(onSight).toHaveBeenLastCalledWith("receiving"); + act(() => { + vi.advanceTimersByTime(5000); + }); + expect(onSight).toHaveBeenLastCalledWith("silent"); + presentFrame(); + expect(onSight).toHaveBeenLastCalledWith("receiving"); + expect(onSight.mock.calls.map(([sight]) => sight)).toEqual(["no_track", null, "receiving", "silent", "receiving"]); + }); + + it("calls a subscribed track silent once its first frame has not come in the time a frozen picture is given", () => { + const onSight = vi.fn(); + render(); + act(() => { + vi.advanceTimersByTime(3000); + }); + expect(onSight).toHaveBeenLastCalledWith(null); + act(() => { + vi.advanceTimersByTime(2000); + }); + expect(onSight).toHaveBeenLastCalledWith("silent"); + // The picture keeps saying it is waiting; only the report changes. + expect(screen.getByText("Waiting for video")).not.toBeNull(); + presentFrame(); + expect(onSight).toHaveBeenLastCalledWith("receiving"); + }); + + it("gives a replacement track its own wait, and says nothing more once the tile is gone", () => { + const onSight = vi.fn(); + const { rerender, unmount } = render(); + act(() => { + vi.advanceTimersByTime(5000); + }); + expect(onSight).toHaveBeenLastCalledWith("silent"); + rerender(); + expect(onSight).toHaveBeenLastCalledWith(null); + unmount(); + expect(onSight).toHaveBeenLastCalledWith(null); + }); + + it("does not report the same sight again when its parent passes a new callback", () => { + const first = vi.fn(); + const second = vi.fn(); + const { rerender } = render(); + rerender(); + expect(first).toHaveBeenCalledTimes(1); + expect(second).not.toHaveBeenCalled(); + rerender(); + expect(second).toHaveBeenCalledWith("not_connected"); + }); +}); + describe("LiveKitCameraTile track wiring and labels", () => { it("attaches the track to a muted inline video and detaches it on unmount", () => { const track = fakeTrack(); diff --git a/examples/egocap/frontend/src/LiveKitCameraTile.tsx b/examples/egocap/frontend/src/LiveKitCameraTile.tsx index bf3cd2a1e3..169ec810e7 100644 --- a/examples/egocap/frontend/src/LiveKitCameraTile.tsx +++ b/examples/egocap/frontend/src/LiveKitCameraTile.tsx @@ -16,6 +16,7 @@ import { latencySample, summarizeLatency } from "./displayLatency"; import type { LatencySample } from "./displayLatency"; import { MONOTONIC_TIMESTAMP_BASES } from "./captureProtocol"; import type { LiveKitClockSync } from "./liveKitClockSync"; +import type { LiveKitSight } from "./livekitSightings"; import type { LiveKitPhase } from "./useLiveKitPreview"; /** No decoded frame for this long means the picture is frozen. */ @@ -46,6 +47,18 @@ function placeholderFor(phase: LiveKitPhase, track: RemoteTrack | null, hasFrame return stale ? "No video frames" : null; } +/** + * What the tile sees of its stream, for the report to the backend; null while there is nothing to say yet (the + * room is still connecting, or a track has only just been subscribed and its first frame may still come). + */ +export function sightOf(phase: LiveKitPhase, track: RemoteTrack | null, hasFrame: boolean, stale: boolean, waitedOut: boolean): LiveKitSight | null { + if (phase === "error") return "not_connected"; + if (phase !== "connected") return null; + if (track === null) return "no_track"; + if (hasFrame && !stale) return "receiving"; + return stale || waitedOut ? "silent" : null; +} + /** A named live tile. It makes no claim about recording: whether a stream is saved is the recorder's state. */ export function LiveKitCameraTile({ name, @@ -54,6 +67,7 @@ export function LiveKitCameraTile({ primary, clock = null, basis = 0, + onSight, }: { name: string; track: RemoteTrack | null; @@ -63,6 +77,8 @@ export function LiveKitCameraTile({ clock?: LiveKitClockSync | null; /** What the stream's frame timestamp means; only a basis on the publisher's monotonic clock (frame-ready or sensor capture) gives a latency. */ basis?: number; + /** Called with what the tile sees of its stream whenever that changes, and with null when the tile goes away. */ + onSight?: (sight: LiveKitSight | null) => void; }) { const videoRef = useRef(null); // The frame effect runs once per track, but the clock arrives (and the basis can change) after the track does, so @@ -83,6 +99,8 @@ export function LiveKitCameraTile({ const [fpsLabel, setFpsLabel] = useState(null); const [hasFrame, setHasFrame] = useState(false); const [stale, setStale] = useState(false); + // A subscribed track whose first frame did not come within the time a frozen picture is given. + const [waitedOut, setWaitedOut] = useState(false); // Attach the subscribed track to the element, and detach it when the track changes or the tile goes away. useEffect(() => { @@ -96,6 +114,7 @@ export function LiveKitCameraTile({ setFpsLabel(null); setHasFrame(false); setStale(false); + setWaitedOut(false); if (element === null || track === null) return; track.attach(element); return () => { @@ -109,10 +128,12 @@ export function LiveKitCameraTile({ if (element === null || track === null) return; let stopped = false; let callbackId: number | null = null; + const watchedSince = performance.now(); const markFrame = (): void => { lastFrameAtRef.current = performance.now(); setHasFrame(true); setStale(false); + setWaitedOut(false); }; const watchFrames = (): void => { if (stopped) return; @@ -143,6 +164,8 @@ export function LiveKitCameraTile({ const last = lastFrameAtRef.current; const isStale = last !== null && now - last > FRAME_STALE_AFTER_MS; if (isStale) setStale(true); + // A track that never sent a frame is as silent as one that stopped, once it has had the same time. + if (last === null && now - watchedSince > FRAME_STALE_AFTER_MS) setWaitedOut(true); // Displayed rate: the change in the browser's own presented-frame count over the window, not a callback tally. const latest = presentedRef.current; // The window's latency samples are summarized once and cleared; only those made under the clock mapping's @@ -194,6 +217,17 @@ export function LiveKitCameraTile({ }; }, [track]); + // What the tile sees is handed up when it changes. The callback is read through a ref, so a parent that passes + // a new function on every render does not have the same sight reported again. + const onSightRef = useRef(onSight); + onSightRef.current = onSight; + const sight = sightOf(phase, track, hasFrame, stale, waitedOut); + useEffect(() => { + onSightRef.current?.(sight); + }, [sight]); + // A tile that goes away sees nothing any more. + useEffect(() => () => onSightRef.current?.(null), []); + const placeholder = placeholderFor(phase, track, hasFrame, stale); return (
    diff --git a/examples/egocap/frontend/src/StationsCard.test.tsx b/examples/egocap/frontend/src/StationsCard.test.tsx index 52cde9712e..176f3596f9 100644 --- a/examples/egocap/frontend/src/StationsCard.test.tsx +++ b/examples/egocap/frontend/src/StationsCard.test.tsx @@ -9,7 +9,7 @@ import { useState } from "react"; import { SettingsHttpError } from "./settingsApi"; import { STATIONS_FIXTURE, fakeStationRegistry } from "./settingsTestDoubles"; import type { HeadsetLink } from "./setupApi"; -import { StationsCard, type StationsBackend } from "./StationsCard"; +import { REQUIRED_HELP, requirementWarnings, StationsCard, type StationsBackend } from "./StationsCard"; import type { StationListing, StationRecord } from "./stationsApi"; afterEach(cleanup); @@ -513,6 +513,118 @@ describe("a station's inline editor", () => { }); }); +describe("the tracking devices a station requires", () => { + const GLOVED: StationRecord = { ...BENCH, required_devices: ["headset", "glove_left"] }; + const box = (station: string, device: string) => within(within(editor(station)).getByRole("group", { name: "Required tracking devices" })).getByLabelText(device) as HTMLInputElement; + + it("says in the row what a station requires, and nothing for one that requires none", () => { + renderCard({ ...TWO_STATIONS, stations: [GLOVED, CART] }); + expect(within(rows()[0]).getByText("Requires: Headset · Left glove")).toBeTruthy(); + expect(within(rows()[1]).queryByText(/Requires/)).toBeNull(); + }); + + it("offers every device the backend lists, ticked as saved, and says what a tick does", () => { + renderCard({ ...TWO_STATIONS, stations: [GLOVED, CART] }); + edit(0); + const group = within(editor("Bench A")).getByRole("group", { name: "Required tracking devices" }); + expect(within(group).getAllByRole("checkbox").map((input) => [input.parentElement?.textContent, (input as HTMLInputElement).checked])).toEqual([ + ["Headset", true], + ["Left controller", false], + ["Right controller", false], + ["Left glove", true], + ["Right glove", false], + ]); + expect(REQUIRED_HELP).toBe( + "Recording is held while a ticked device is not delivering its data: switched off, not found, not started yet, switched off in the capture configuration, or connected with nothing to send. One that still delivers with a problem of its own, such as a rejected calibration file, only shows a warning, as a device that is not ticked does.", + ); + expect(group.getAttribute("aria-describedby")).toBe(screen.getByText(REQUIRED_HELP).id); + expect(button("Save").disabled).toBe(true); // nothing changed yet + }); + + it("says in the row when a required device is one the capture session here does not report", () => { + const unreported: StationRecord = { ...GLOVED, unreported_devices: ["glove_left"] }; + renderCard({ ...TWO_STATIONS, stations: [unreported, CART] }); + const said = within(rows()[0]).getByText("Left glove is not reported by the capture session here: recording is held until it is, or until the requirement is unticked."); + expect(said.className).toBe("settings-note tone-warning"); + expect(within(rows()[1]).queryByText(/not reported/)).toBeNull(); + cleanup(); + // Several are named together, and a station whose devices are all reported says nothing. + renderCard({ ...TWO_STATIONS, stations: [{ ...GLOVED, required_devices: ["headset", "glove_left", "glove_right"], unreported_devices: ["glove_left", "glove_right"] }, GLOVED] }); + expect(within(rows()[0]).getByText("Left glove and Right glove are not reported by the capture session here: recording is held until they are, or until the requirement is unticked.")).toBeTruthy(); + expect(within(rows()[1]).queryByText(/not reported/)).toBeNull(); + expect(requirementWarnings({ ...GLOVED, required_devices: ["headset", "controller_left", "glove_left"], unreported_devices: ["headset", "controller_left", "glove_left"] }, TWO_STATIONS.tracking_devices ?? [])).toEqual([ + "Headset, Left controller and Left glove are not reported by the capture session here: recording is held until they are, or until the requirement is unticked.", + ]); + }); + + it("shows a requirement the backend read from its file and does not know, says it holds recording, and lets it be unticked", async () => { + const newer: StationRecord = { ...GLOVED, required_devices: ["headset", "tracker_waist"], unreported_devices: ["tracker_waist"] }; + const { backend } = renderCard({ ...TWO_STATIONS, stations: [newer, CART] }); + expect(within(rows()[0]).getByText("Requires: Headset · tracker_waist")).toBeTruthy(); + expect(within(rows()[0]).getByText("tracker_waist is not a tracking device this software knows: recording is held until the requirement is unticked.")).toBeTruthy(); + edit(0); + const unknown = box("Bench A", "tracker_waist (not known to this software)"); + expect(unknown.checked).toBe(true); + expect(button("Save").disabled).toBe(true); + fireEvent.click(unknown); + // Unticked, its box is gone: nothing this software knows could be ticked in its place. + expect(within(editor("Bench A")).queryByLabelText("tracker_waist (not known to this software)")).toBeNull(); + fireEvent.click(button("Save")); + await waitFor(() => expect(backend.updateStation).toHaveBeenCalledWith("tok", "st_1", { required_devices: ["headset"] })); + }); + + it("saves the whole list alone when only it changed, and the row then says what is required", async () => { + const { backend } = renderCard(TWO_STATIONS); + edit(0); + fireEvent.click(box("Bench A", "Right glove")); + fireEvent.click(box("Bench A", "Headset")); + fireEvent.click(button("Save")); + await waitFor(() => expect(screen.queryByRole("group", { name: "Edit Bench A" })).toBeNull()); + expect(backend.updateStation).toHaveBeenCalledWith("tok", "st_1", { required_devices: ["glove_right", "headset"] }); + expect(within(rows()[0]).getByText("Requires: Headset · Right glove")).toBeTruthy(); + }); + + it("clears a requirement with an empty list, and a tick put back is no change", async () => { + const { backend } = renderCard({ ...TWO_STATIONS, stations: [GLOVED, CART] }); + edit(0); + fireEvent.click(box("Bench A", "Headset")); + fireEvent.click(box("Bench A", "Headset")); + expect(button("Save").disabled).toBe(true); // the same devices, ticked in another order + fireEvent.click(box("Bench A", "Headset")); + fireEvent.click(box("Bench A", "Left glove")); + fireEvent.click(button("Save")); + await waitFor(() => expect(backend.updateStation).toHaveBeenCalledWith("tok", "st_1", { required_devices: [] })); + }); + + it("does not send the list when another field is all that changed", async () => { + const { backend } = renderCard({ ...TWO_STATIONS, stations: [GLOVED, CART] }); + edit(0); + fireEvent.change(field("Bench A", "Name"), { target: { value: "Bench Z" } }); + fireEvent.click(button("Save")); + await waitFor(() => expect(backend.updateStation).toHaveBeenCalledWith("tok", "st_1", { name: "Bench Z" })); + }); + + it("holds the boxes while the save is on its way", async () => { + let finish: (listing: StationListing) => void = () => undefined; + const updateStation = vi.fn(() => new Promise((resolve) => (finish = resolve))); + renderCard(TWO_STATIONS, { backend: { updateStation } }); + edit(0); + fireEvent.click(box("Bench A", "Headset")); + fireEvent.click(button("Save")); + await waitFor(() => expect(box("Bench A", "Headset").disabled).toBe(true)); + await act(async () => finish(TWO_STATIONS)); + }); + + it("shows no such control for a backend that lists no device to require", () => { + const { tracking_devices: _none, ...older } = TWO_STATIONS; + renderCard({ ...older, stations: [GLOVED, CART] }); + expect(within(rows()[0]).queryByText(/Requires/)).toBeNull(); + edit(0); + expect(within(editor("Bench A")).queryByRole("group")).toBeNull(); + expect(within(editor("Bench A")).queryAllByRole("checkbox")).toEqual([]); + }); +}); + describe("the headset address in the Stations card", () => { it("is the last line of the editor of the station in use, and of no other station", () => { renderCard(TWO_STATIONS, { headset: HEADSET }); diff --git a/examples/egocap/frontend/src/StationsCard.tsx b/examples/egocap/frontend/src/StationsCard.tsx index 9cea05b004..0df02e1c8b 100644 --- a/examples/egocap/frontend/src/StationsCard.tsx +++ b/examples/egocap/frontend/src/StationsCard.tsx @@ -4,7 +4,7 @@ /** * The Stations card of the Settings dialog: the stations this site records at, the one in use, and each - * station's name, camera type and cameras, edited in place. + * station's name, camera type, cameras and required tracking devices, edited in place. * * The station in use names every recording and its activity log. It cannot change while a take is being * recorded; the backend says so in `locked_reason` and refuses the change either way. A station that is not in @@ -15,7 +15,7 @@ import { Card, TokenHint, useAction } from "./settingsParts"; import { CAMERA_TYPE_LABELS, ROLE_LABELS } from "./settingsApi"; import { sentence } from "./sentence"; import type { HeadsetLink } from "./setupApi"; -import type { StationChange, StationListing, StationRecord } from "./stationsApi"; +import type { StationChange, StationListing, StationRecord, TrackingDevice } from "./stationsApi"; /** The registry calls the card makes; the dialog passes the real ones and tests pass fakes. */ export interface StationsBackend { @@ -37,6 +37,51 @@ function roleSummary(station: StationRecord, roles: readonly string[]): string { return roles.map((role) => `${ROLE_LABELS[role] ?? role}: ${station.camera_roles[role] ?? "—"}`).join(" · "); } +/** A required device by the name the operator reads; one the backend does not know keeps the name it was written with. */ +function deviceName(id: string, devices: readonly TrackingDevice[]): string { + return devices.find((device) => device.id === id)?.name ?? id; +} + +/** The requirements among `required` that name no device the backend lists: read from its file, and never met here. + * A backend that lists no device at all says nothing of requirements, so none is called unknown. */ +function unknownRequirements(required: readonly string[], devices: readonly TrackingDevice[]): string[] { + return devices.length === 0 ? [] : required.filter((id) => !devices.some((device) => device.id === id)); +} + +/** The tracking devices a station requires, by the names the operator reads, in the order they are listed; null when it requires none. */ +function requiredSummary(station: StationRecord, devices: readonly TrackingDevice[]): string | null { + const required = station.required_devices ?? []; + const named = [...devices.filter((device) => required.includes(device.id)).map((device) => device.name), ...unknownRequirements(required, devices)]; + return named.length === 0 ? null : `Requires: ${named.join(" · ")}`; +} + +/** Several names as they are read in a sentence: "A", "A and B", "A, B and C". */ +function listed(names: readonly string[]): string { + return names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`; +} + +/** + * Why a station that requires its devices cannot record here whatever is switched on, said on the Station tab before + * anybody presses Record: a required device the capture session here does not report, and a requirement that names + * no device this software knows. Null when there is nothing of the kind to say. + */ +export function requirementWarnings(station: StationRecord, devices: readonly TrackingDevice[]): string[] { + const unknown = unknownRequirements(station.required_devices ?? [], devices); + const unreported = (station.unreported_devices ?? []).filter((id) => !unknown.includes(id)).map((id) => deviceName(id, devices)); + const warnings: string[] = []; + if (unreported.length > 0) { + warnings.push(`${listed(unreported)} ${unreported.length === 1 ? "is" : "are"} not reported by the capture session here: recording is held until ${unreported.length === 1 ? "it is" : "they are"}, or until the requirement is unticked.`); + } + if (unknown.length > 0) { + warnings.push(`${listed(unknown)} ${unknown.length === 1 ? "is" : "are"} not a tracking device this software knows: recording is held until the requirement is unticked.`); + } + return warnings; +} + +/** What a tick under *Required tracking devices* does: the device must be delivering its data, and what that excludes. */ +export const REQUIRED_HELP = + "Recording is held while a ticked device is not delivering its data: switched off, not found, not started yet, switched off in the capture configuration, or connected with nothing to send. One that still delivers with a problem of its own, such as a rejected calibration file, only shows a warning, as a device that is not ticked does."; + /** What to tell the operator when the headset still holds an address this host no longer has; null otherwise. */ function headsetWarning(headset: HeadsetLink | null): string | null { if (headset === null || !headset.changed || headset.address === null || headset.saved === null) return null; @@ -202,6 +247,7 @@ function StationRow({ const frozen = inUse && locked; const editable = canChange && !frozen; const warning = headsetWarning(headset); + const required = requiredSummary(station, listing.tracking_devices ?? []); // The row's actions give way to the editor or the delete confirmation and come back as new elements. When // that leaves keyboard focus on nothing, it returns to Edit; focus that already moved elsewhere is left alone. const editButton = useRef(null); @@ -220,6 +266,12 @@ function StationRow({ {inUse && in use} {roleSummary(station, listing.roles)} + {required !== null && {required}} + {requirementWarnings(station, listing.tracking_devices ?? []).map((warning) => ( + + {warning} + + ))} {station.problems.length > 0 && Cannot record yet: {station.problems.join("; ")}.} {/* The open editor says the same beside the address, so it is not repeated here. */} {warning !== null && !editing && {warning}} @@ -273,6 +325,8 @@ export interface CameraDraft { /** The editor's working copy of a station. */ interface StationDraft extends CameraDraft { name: string; + /** The tracking devices the station requires, by id. */ + required: string[]; } /** A working copy of a saved camera setup. */ @@ -294,6 +348,9 @@ export function cameraChangesOf(original: CameraSetup, roles: readonly string[], function changesOf(original: StationRecord, roles: readonly string[], draft: StationDraft): StationChange { const changes: StationChange = cameraChangesOf(original, roles, draft); if (draft.name.trim() !== original.name) changes.name = draft.name.trim(); + // Compared as sets: the backend keeps its own order, so the order the boxes were ticked in is no change. + const before = original.required_devices ?? []; + if (draft.required.length !== before.length || draft.required.some((device) => !before.includes(device))) changes.required_devices = draft.required; return changes; } @@ -398,7 +455,7 @@ function StationEditor({ // The station as the editor opened on it. The listing can bring another browser's change while the editor is // open; what this editor changed is judged against what the operator started from, never against that. const [original] = useState(station); - const [draft, setDraft] = useState({ name: station.name, ...cameraDraftOf(station) }); + const [draft, setDraft] = useState({ name: station.name, required: station.required_devices ?? [], ...cameraDraftOf(station) }); const [{ busy, failure }, run] = useAction(); const { roles } = listing; const changes = changesOf(original, roles, draft); @@ -443,6 +500,12 @@ function StationEditor({
    {selectableCameras(cameraSources, station.camera_roles).length === 0 &&

    {NO_CAMERAS_NOTE}

    } + setDraft((current) => ({ ...current, required: on ? [...current.required, device] : current.required.filter((other) => other !== device) }))} + />
    {/* Not disabled while saving, for the same reason as the name field; `save` ignores a second press. */}
    )} - {holders.length > 0 && } + {holders.length > 0 && } + {holders.length > 0 && } ); } +/** + * Move focus to `field` when it is on `button`. A form that was just sent is empty again, which disables its + * button, and a disabled button drops the focus it held out of the dialog. + */ +function focusFieldFrom(button: HTMLButtonElement | null, field: HTMLInputElement | null): void { + if (button !== null && document.activeElement === button) field?.focus(); +} + /** Correct the task of one take or a range of takes of a session. */ function CorrectionForm({ holders, @@ -620,6 +653,8 @@ function CorrectionForm({ const [{ busy, failure }, run] = useAction(); const ready = episodes.trim() !== "" && task.trim() !== "" && !busy; const typed = episodes !== "" || task !== ""; + const range = useRef(null); + const send = useRef(null); useEffect(() => { onTyped(typed); // A form that leaves the report has nothing left to lose. @@ -629,13 +664,18 @@ function CorrectionForm({ const apply = () => run(async () => { setDone(null); - const reply = await correct(controlToken, { session: holder, episodes: episodes.trim(), task: task.trim() }); + const reply = await correct(controlToken, { session: holder, episodes: episodes.trim(), task: task.trim() }).catch((error: unknown) => { + // A correction that failed and could not put every take back changed what the table should show. + if (error instanceof CorrectionRefused && error.leftChanged.length > 0) onCorrected(); + throw error; + }); const skipped = reply.missing.length === 0 ? "" : ` Not found: ${reply.missing.join(", ")}.`; // With more than one group the take numbers repeat, so the confirmation says which group was changed. const where = holders.length > 1 ? ` in ${holder}` : ""; setDone(`Corrected ${reply.updated.length === 0 ? "nothing" : reply.updated.join(", ")}${where}.${skipped}`); setEpisodes(""); setTask(""); + focusFieldFrom(send.current, range.current); onCorrected(); }); return ( @@ -652,9 +692,9 @@ function CorrectionForm({ )}
    - setEpisodes(e.target.value)} /> + setEpisodes(e.target.value)} /> setTask(e.target.value)} /> -
    @@ -664,6 +704,93 @@ function CorrectionForm({ ); } +/** The studios the finalized takes held in `holder` are labelled with, in the order they first appear. */ +function studiosOf(session: ReportSession, holder: string): string[] { + const named = session.episodes.filter((episode) => holderOf(episode) === holder).map((episode) => episode.studio ?? null); + return [...new Set(named.filter((studio): studio is string => studio !== null))]; +} + +/** Correct the studio every take of a session, or of one routed group of it, is labelled with. The label + * changes in the recording's own metadata; its files stay where they are. */ +function StudioForm({ + session, + holders, + controlToken, + correctStudio, + onCorrected, + onTyped, +}: { + /** The session, for the studio its takes are labelled with now. */ + session: ReportSession; + /** Where the session's finalized takes are: the session itself, or each routed group it filled. */ + holders: string[]; + controlToken: string; + correctStudio: WrapUpBackend["correctStudio"]; + onCorrected: () => void; + /** Told whether the form holds typed input, which closing the dialog would drop. */ + onTyped: (typed: boolean) => void; +}) { + const [holder, setHolder] = useState(holders[0]); + const [studio, setStudio] = useState(""); + const [done, setDone] = useState(null); + const [{ busy, failure }, run] = useAction(); + const ready = studio.trim() !== "" && !busy; + const typed = studio !== ""; + const field = useRef(null); + const send = useRef(null); + useEffect(() => { + onTyped(typed); + // A form that leaves the report has nothing left to lose. + return () => onTyped(false); + }, [typed, onTyped]); + const recorded = studiosOf(session, holder); + /** Apply the correction, say what was written and that nothing moved, and have the report read again. */ + const apply = () => + run(async () => { + setDone(null); + const reply = await correctStudio(controlToken, { session: holder, studio: studio.trim() }).catch((error: unknown) => { + // A correction that failed and could not put every label back changed what the table should show. + if (error instanceof CorrectionRefused && error.leftChanged.length > 0) onCorrected(); + throw error; + }); + // With more than one group the confirmation says which group was relabelled. + const where = holders.length > 1 ? ` in ${holder}` : ""; + const takes = `${reply.updated.length} ${reply.updated.length === 1 ? "take" : "takes"}`; + setDone(reply.updated.length === 0 ? `Nothing to relabel${where}: no recorded take.` : `Studio set to ${reply.studio} for ${takes}${where}. The files were not moved.`); + setStudio(""); + focusFieldFrom(send.current, field.current); + onCorrected(); + }); + return ( +
    + Correct the studio +

    + {recorded.length === 0 ? "No studio is recorded for these takes." : `Recorded as ${recorded.join(" and ")}.`} Only the label in the recording changes: the files stay where they are + {/* A routed group lies in a folder named after the studio it was recorded under, and stays in it. */} + {holder === session.session_id ? "." : ", in the folder they were recorded under."} +

    + {holders.length > 1 && ( + // Held, not disabled, while a correction is sent: disabling the focused field would drop focus out of the dialog. + + )} +
    + setStudio(e.target.value)} /> + +
    + {failure !== null &&

    Not corrected: {failure}

    } + {done !== null && failure === null &&

    {done}

    } +
    + ); +} + /** Save the report as a file on the station and say what was written. */ function SaveReport({ controlToken, save }: { controlToken: string; save: WrapUpBackend["save"] }) { const [saved, setSaved] = useState(null); diff --git a/examples/egocap/frontend/src/calibrationApi.test.ts b/examples/egocap/frontend/src/calibrationApi.test.ts index 43a383834c..be23d82f37 100644 --- a/examples/egocap/frontend/src/calibrationApi.test.ts +++ b/examples/egocap/frontend/src/calibrationApi.test.ts @@ -21,8 +21,12 @@ import { previewRectification, reasonSentence, saveRectificationPlans, + fetchCalibrationCheck, + parseLiveCheck, + startCalibrationCheck, startCalibrationRecording, startCameraSolve, + stopCalibrationCheck, stopCalibrationRecording, whenCalibrated, } from "./calibrationApi"; @@ -30,6 +34,8 @@ import { BOARD_FIXTURE, BORDER_REFUSAL, CAMERA_RECORDING_FIXTURE, + CHECK_FIXTURE, + CHECK_RECORD_FIXTURE, FISHEYE_INTRINSICS_FIXTURE, GLOVE_RECORDING_FIXTURE, HEAD_APPLIED_FIXTURE, @@ -612,3 +618,32 @@ describe("what the page makes of a calibration reply", () => { expect(reasonSentence("")).toBe(""); }); }); + +describe("the live check of the installed head-camera calibration", () => { + it("is started with the board alone, polled with the control token, and stopped with an empty body", async () => { + const fn = stubFetch(200, CHECK_FIXTURE); + await expect(startCalibrationCheck("tok", { board: BOARD_FIXTURE })).resolves.toEqual(CHECK_FIXTURE); + expect(fn).toHaveBeenLastCalledWith("/api/calibration/check", change({ board: BOARD_FIXTURE })); + const found = { ...CHECK_FIXTURE, check: CHECK_RECORD_FIXTURE, preview: { jpeg: "AAAA", width: 640, height: 480 } }; + const polled = stubFetch(200, found); + await expect(fetchCalibrationCheck("tok", new AbortController().signal)).resolves.toEqual(found); + expect(polled).toHaveBeenLastCalledWith("/api/calibration/check", READ); + const stopped = stubFetch(200, { phase: "stopped", note: CHECK_FIXTURE.note }); + await expect(stopCalibrationCheck("tok")).resolves.toEqual({ phase: "stopped", note: CHECK_FIXTURE.note }); + expect(stopped).toHaveBeenLastCalledWith("/api/calibration/check/stop", change({})); + }); + + it("surfaces the backend's reason with its status, so a check the backend lost can be told from a refusal", async () => { + stubFetch(404, { detail: "no check is running" }); + await expect(fetchCalibrationCheck("tok")).rejects.toMatchObject({ message: "no check is running", status: 404 }); + stubFetch(409, { detail: "calibrate the headset first: head_camera_extrinsics.json could not be read" }); + await expect(startCalibrationCheck("tok", { board: BOARD_FIXTURE })).rejects.toMatchObject({ status: 409 }); + }); + + it("rejects a reply that says neither where the check stands nor what it reads, or whose hints are no list", () => { + for (const body of [null, {}, { phase: "checking" }, { phase: "recording", note: "x" }, { ...CHECK_FIXTURE, check: { hints: "move" } }]) { + expect(() => parseLiveCheck(body)).toThrow("calibration check is malformed"); + } + expect(parseLiveCheck({ ...CHECK_FIXTURE, check: undefined })).toMatchObject({ phase: "checking" }); + }); +}); diff --git a/examples/egocap/frontend/src/calibrationApi.ts b/examples/egocap/frontend/src/calibrationApi.ts index 69513bf4b0..bc9a51f20e 100644 --- a/examples/egocap/frontend/src/calibrationApi.ts +++ b/examples/egocap/frontend/src/calibrationApi.ts @@ -12,6 +12,7 @@ * change's bound: it plans a correction and may decode a frame of a recorded take first. */ import type { + BoardSpec, CalibrationFile, CalibrationOverview, CalibrationPart, @@ -20,6 +21,7 @@ import type { CameraJob, CameraSolveRequest, InstallBatchOutcome, + LiveCheckStatus, RectificationCamera, RectificationListing, RectificationPlanChange, @@ -267,6 +269,31 @@ export function cancelCalibrationRecording(controlToken: string): Promise { + return change("/check", controlToken, request, parseLiveCheck); +} + +/** Read where the live check stands, after a look at the newest live picture; rejects with a 404 + * `SettingsHttpError` when no check runs. */ +export function fetchCalibrationCheck(controlToken: string, signal?: AbortSignal): Promise { + return read("/check", controlToken, signal, async (response) => parseLiveCheck(await response.json())); +} + +/** End the live check. It wrote nothing, so there is nothing to keep. */ +export function stopCalibrationCheck(controlToken: string): Promise { + return change("/check/stop", controlToken, {}, parseLiveCheck); +} + /** Start solving a take in the background; the reply is the job to poll. */ export function startCameraSolve(controlToken: string, request: CameraSolveRequest): Promise { return change("/camera/solve", controlToken, request, parseJob); diff --git a/examples/egocap/frontend/src/calibrationTestDoubles.ts b/examples/egocap/frontend/src/calibrationTestDoubles.ts index 7952430af5..423e721298 100644 --- a/examples/egocap/frontend/src/calibrationTestDoubles.ts +++ b/examples/egocap/frontend/src/calibrationTestDoubles.ts @@ -8,7 +8,7 @@ * plans that are previewed and saved. */ import { vi } from "vitest"; -import type { CalibrationRecorderBackend } from "./CalibrationRecorder"; +import type { CalibrationCheckBackend, CalibrationRecorderBackend } from "./CalibrationRecorder"; import type { BoardSpec, CalibrationGuide, @@ -19,6 +19,8 @@ import type { CameraJob, CameraSolveRequest, KeptCameraTake, + LiveCheckRecord, + LiveCheckStatus, RectificationApplied, RectificationCamera, RectificationListing, @@ -441,6 +443,8 @@ export function fakeHeadsetBackend(overview: Partial = {}, }; return { recorder, + /** The live check, which a test starts from Set up. */ + check: fakeCheckBackend(), /** The solve as the next read answers it. */ get job() { return job; @@ -578,3 +582,66 @@ export function fakeRectificationBackend(initial: RectificationListing = RECTIFI }), } satisfies RectificationBackend & { listing: RectificationListing }; } + +/** What the live check knows once it has seen enough of a true calibration: every figure inside the grade's limits. */ +export const CHECK_RECORD_FIXTURE: LiveCheckRecord = { + phase: "checking", + fixing: { views: 0, views_needed: 5 }, + judged: true, + cannot_judge: null, + error_px: 0.62, + rms_px: 0.71, + worst_px: 1.34, + views: 24, + views_needed: 10, + head_turn_deg: 41.5, + head_turn_needed_deg: 15, + board_wander_m: 0.0012, + pose_fit_px: 0.21, + camera_offset_m: 0.0008, + camera_offset_uncertainty_m: 0.0011, + camera_lag_off_s: 0.002, + limits: { board_wander_m: [0.005, 0.01], pose_fit_px: [1, 2], camera_offset_m: [0.005, 0.01], camera_lag_off_s: [0.01, 0.02] }, + enough: true, + verdict: "excellent", + no_verdict: null, + notes: [], + restarts: 0, + hints: ["Enough has been seen: the verdict is below. Go on moving to keep watching it, or stop the check."], +}; + +/** A check that has just been started: nothing looked at yet. */ +export const CHECK_FIXTURE: LiveCheckStatus = { + phase: "checking", + camera: "head_cam", + corrected: false, + elapsed_s: 0, + available: true, + unavailable_reason: null, + video_room: false, + waiting: null, + check: null, + preview: null, + note: "The check reads the installed head_camera_intrinsics.json and head_camera_extrinsics.json. It records nothing and changes no file.", +}; + +/** The same check of a camera that arrives over the video room, as the backend answers while it joins the room. */ +export const CHECK_IN_ROOM_FIXTURE: LiveCheckStatus = { + ...CHECK_FIXTURE, + video_room: true, + waiting: "Joining the video room to see this camera.", + note: `${CHECK_FIXTURE.note} While it runs the backend is in the video room to see this camera, as it is during a take, and it leaves when the check ends.`, +}; + +/** A live check that answers like the real one: started, then polled with whatever `status` holds, then stopped. */ +export function fakeCheckBackend(first: LiveCheckStatus = CHECK_FIXTURE) { + const state = { status: first }; + const backend = { + /** What the next poll answers; a test replaces it to move the check on. */ + state, + start: vi.fn(async (_token: string, _request: { board: BoardSpec }) => state.status), + poll: vi.fn(async (_token: string, _signal: AbortSignal) => state.status), + stop: vi.fn(async (_token: string): Promise => ({ phase: "stopped", note: first.note })), + }; + return backend satisfies CalibrationCheckBackend; +} diff --git a/examples/egocap/frontend/src/calibrationTypes.ts b/examples/egocap/frontend/src/calibrationTypes.ts index f5b16a1ac6..66e1721db5 100644 --- a/examples/egocap/frontend/src/calibrationTypes.ts +++ b/examples/egocap/frontend/src/calibrationTypes.ts @@ -131,6 +131,82 @@ export interface CalibrationRecording { problem: string | null; } +/** What the live check of the installed head-camera calibration knows after one picture. */ +export interface LiveCheckRecord { + /** `fixing` while the board's place is being fixed from the first good views, `checking` once it is. */ + phase: "fixing" | "checking"; + /** How many views the place has been fixed from so far, and how many it takes. */ + fixing: { views: number; views_needed: number }; + /** Whether this picture could be held against the calibration. */ + judged: boolean; + /** Why it could not, as a sentence that says what to do; null when it could. */ + cannot_judge: string | null; + /** This picture's error: how far the corners seen are from the corners the head pose predicts, in pixels. */ + error_px: number | null; + /** The error over every view that tested the calibration, as a root mean square, and the largest of them. */ + rms_px: number | null; + /** The largest error of a view that tested the calibration. */ + worst_px: number | null; + /** Views that tested the calibration (the head had moved from where the place was fixed), and how many a verdict takes. */ + views: number; + /** How many such views a verdict takes. */ + views_needed: number; + /** The furthest the head has turned in one of them, in degrees, and how far a verdict takes. */ + head_turn_deg: number; + /** How far the head must have turned in one of them for a verdict. */ + head_turn_needed_deg: number; + /** How far the board, which never moved, seems to stand from view to view, in meters. */ + board_wander_m: number | null; + /** How well the board's poses fit the picture, in pixels. */ + pose_fit_px: number | null; + /** How far the camera sits from where its file has it, as the board's wander implies, in meters; null until the head has turned about two axes. */ + camera_offset_m?: number | null; + /** How closely the views pin that offset, in meters. */ + camera_offset_uncertainty_m?: number | null; + /** How far the camera's stored lag is off, as the wander implies, in seconds (positive: the pictures are older than the file says); null while no picture counted could show it. */ + camera_lag_off_s?: number | null; + /** The grade's own limits for each graded figure: under the first it is excellent, over the second it needs repeating. */ + limits: { board_wander_m: [number, number]; pose_fit_px: [number, number]; camera_offset_m?: [number, number]; camera_lag_off_s?: [number, number] }; + /** Whether enough has been seen for a verdict. */ + enough: boolean; + /** The verdict, in the solve's grades (`excellent`, `acceptable`, `bad`); null until the views can carry one. */ + verdict: string | null; + /** Why views that are enough by their count still carry no verdict, as the backend's sentence; null otherwise. */ + no_verdict?: string | null; + /** What the backend says beside a verdict, such as what it could not test. */ + notes?: string[]; + /** How often the check started over because the headset lost or leapt its position. */ + restarts: number; + /** What to do next. */ + hints: string[]; +} + +/** `GET /api/calibration/check`, and the reply to starting or stopping the check. */ +export interface LiveCheckStatus { + /** `checking` while a check runs, `stopped` in the reply to stopping it. */ + phase: "checking" | "stopped"; + /** The camera being checked. */ + camera?: string; + /** Whether the camera's video is corrected in this run, so the corrected camera's matrix is what is checked with. */ + corrected?: boolean; + /** Seconds since the check started. */ + elapsed_s?: number; + /** False while the check has no picture it can read. */ + available?: boolean; + /** Why it has none. */ + unavailable_reason?: string | null; + /** Whether the backend is in the LiveKit video room for this check: the camera reaches it no other way. */ + video_room?: boolean; + /** What the check waits for before its first picture, in the backend's words, while the room is being joined; null when nothing is. */ + waiting?: string | null; + /** What the last picture looked at found; null before the first. */ + check?: LiveCheckRecord | null; + /** That picture, with the corners seen and the corners predicted drawn on it. */ + preview?: { jpeg: string; width: number; height: number } | null; + /** What the check reads and that it writes nothing, in the backend's words. */ + note: string; +} + /** What a tool dialog is given by the page. */ export interface CalibrationDialogProps { /** Asked for when the operator closes the tool; the page returns to Settings. */ @@ -171,6 +247,11 @@ export interface CalibrationLedgerEntry { * so the page states them for the kind and reads no file's installer or time from this list. */ files?: string[]; + /** + * The files of `files` that the last install found already installed and left as they were; absent when every + * install noted here wrote its file. The page says of these that installing them again changed nothing. + */ + unchanged?: string[]; } /** One camera role as the station in use fills it. */ @@ -182,6 +263,9 @@ export interface CalibrationCamera { /** Whether the backend holds a live picture of the camera now. A camera that reaches the page over LiveKit has * none until a take feeds the backend its picture, so this says nothing of the guidance during a take. */ live: boolean; + /** Whether the camera reaches the backend through the LiveKit video room, which a live check of it joins while it + * runs; absent from a backend that does not say. */ + video_room?: boolean; /** The file the role's intrinsics are installed as. */ intrinsics_file: string; /** The lens model a solve of this camera uses when the page names none; absent from a backend that does not say. */ @@ -192,6 +276,17 @@ export interface CalibrationCamera { /** Whether a rectification choice saved for this camera differs from what this run applies to it, and starting * the capture stack again would apply it; absent from a backend that does not say. */ rectification_waits?: boolean; + /** What to know before a take when the camera sends another size of picture than its installed lens file was + * solved at, in the backend's words; absent from a backend that does not say. */ + picture_notes?: PictureNotes; +} + +/** What a camera's changed picture size means for each kind of take; null where there is nothing to say. */ +export interface PictureNotes { + /** For a take that solves the lens: its solve would replace a file made at another size. */ + lens: string | null; + /** For a take that solves the position alone: it builds on a file made at another size, and cannot. */ + position: string | null; } /** The camera take the backend kept last, whatever was recorded after it, with what it was recorded for. */ diff --git a/examples/egocap/frontend/src/dayReportApi.test.ts b/examples/egocap/frontend/src/dayReportApi.test.ts index f465bdf236..e5a88a515c 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, parseReply, saveDayReport, tallyRows } from "./dayReportApi"; +import { CorrectionRefused, correctSession, correctStudio, fetchDayReport, parseReply, saveDayReport, tallyRows } from "./dayReportApi"; import { DAY_REPORT_FIXTURE } from "./dayReportTestDoubles"; import { SettingsHttpError, SettingsParseError } from "./settingsApi"; @@ -41,9 +41,44 @@ describe("the day report", () => { expect(fn).toHaveBeenCalledWith("/api/day-report/correct", { signal: expect.any(AbortSignal), method: "POST", headers: JSON_AUTH, body: JSON.stringify(correction) }); }); + it("sends a studio correction as the session and the studio alone, and answers with the label as stored", async () => { + const reply = { session: "session_a", studio: "Living_room", updated: ["episode_0", "episode_1"], config_updated: true }; + const fn = stubFetch(200, reply); + const correction = { session: "session_a", studio: "Living room" }; + await expect(correctStudio("tok", correction)).resolves.toEqual(reply); + expect(fn).toHaveBeenCalledWith("/api/day-report/studio", { signal: expect.any(AbortSignal), method: "POST", headers: JSON_AUTH, body: JSON.stringify(correction) }); + }); + + it("surfaces the backend's reason for a refused studio correction, and rejects a reply of the wrong shape", async () => { + const waiting = "an interrupted take of this session must be recovered or discarded first: where it is filed depends on the labels it was recorded under"; + stubFetch(400, { detail: waiting }); + await expect(correctStudio("tok", { session: "s", studio: "Pantry" })).rejects.toThrow(new CorrectionRefused(waiting, [])); + for (const body of [{ updated: [] }, { studio: "Pantry", updated: "episode_0" }, {}]) { + stubFetch(200, body); + await expect(correctStudio("tok", { session: "s", studio: "Pantry" })).rejects.toThrow(SettingsParseError); + } + }); + + it("carries the labels a failed studio correction left changed, and none for any other refusal", async () => { + const stuck = "the labels could not all be written, and episode_0 could not be put back: it says Pantry now, and the rest what they said before"; + stubFetch(400, { detail: stuck, left_changed: ["episode_0"] }); + const failed = await correctStudio("tok", { session: "s", studio: "Pantry" }).catch((error: unknown) => error); + expect(failed).toBeInstanceOf(CorrectionRefused); + expect([(failed as CorrectionRefused).message, (failed as CorrectionRefused).leftChanged]).toEqual([stuck, ["episode_0"]]); + // A refusal that changed nothing says so by carrying none; a field of the wrong shape is none too. + for (const body of [{ detail: "x" }, { detail: "x", left_changed: "episode_0" }, { detail: "x", left_changed: [7] }]) { + stubFetch(400, body); + const refused = await correctStudio("tok", { session: "s", studio: "Pantry" }).catch((error: unknown) => error); + expect((refused as CorrectionRefused).leftChanged).toEqual([]); + } + stubFetch(400, { detail: "x" }); + const task = await correctSession("tok", { session: "s", episodes: "0", task: "x" }).catch((error: unknown) => error); + expect((task as CorrectionRefused).leftChanged).toEqual([]); + }); + it("surfaces the backend's reason, or the status when it gave none", async () => { stubFetch(400, { detail: "the session is outside the recording output" }); - await expect(correctSession("tok", { session: "../x", episodes: "0", task: "x" })).rejects.toThrow(new SettingsHttpError("the session is outside the recording output")); + await expect(correctSession("tok", { session: "../x", episodes: "0", task: "x" })).rejects.toThrow(new CorrectionRefused("the session is outside the recording output", [])); stubFetch(403, { detail: "control token rejected" }); await expect(fetchDayReport("wrong")).rejects.toThrow(new SettingsHttpError("control token rejected")); vi.stubGlobal("fetch", vi.fn(async () => new Response("gateway down", { status: 502 }))); diff --git a/examples/egocap/frontend/src/dayReportApi.ts b/examples/egocap/frontend/src/dayReportApi.ts index 14eb5202fb..8240b0d372 100644 --- a/examples/egocap/frontend/src/dayReportApi.ts +++ b/examples/egocap/frontend/src/dayReportApi.ts @@ -4,8 +4,8 @@ /** * The end-of-day report (`/api/day-report`): today's takes for the station in use, by session, with what - * became of each; the station's uptime; saving the report on the station; and correcting a task after - * recording. Every call carries the run's control token: the report names operators and tasks, and a + * became of each; the station's uptime; saving the report on the station; and correcting a task or a studio + * after recording. Every call carries the run's control token: the report names operators and tasks, and a * correction rewrites recorded labels. */ import { CHANGE_TIMEOUT_MS, withTimeout } from "./requestTimeout"; @@ -72,6 +72,8 @@ export interface ReportEpisode { duration_seconds: number; /** The task it shows: the corrected one when its task was corrected after recording. */ task: string; + /** The studio the take is labelled with, as corrected if it was; null or absent when none is recorded. */ + studio?: string | null; /** The free-text details recorded with the task; "" when none. */ task_details: string; /** The operator who recorded it. */ @@ -142,6 +144,53 @@ export interface CorrectionReply { config_updated: boolean; } +/** A studio correction for every take of one session or routed group. */ +export interface StudioCorrection { + /** The session or routed group to relabel, relative to the recording output. */ + session: string; + /** The studio it was recorded in. */ + studio: string; +} + +/** `POST /api/day-report/studio`. */ +export interface StudioCorrectionReply { + session: string; + /** The label as stored: the name given, as one plain word in the task library's spelling. */ + studio: string; + /** The episodes relabelled; empty when the session holds no recorded take. */ + updated: string[]; + config_updated: boolean; +} + +/** A correction the backend refused, or could not write. */ +export class CorrectionRefused extends SettingsHttpError { + /** The takes and files that still carry the new label after a correction of the studio or of a task failed + * part-way and could not put them back, as the backend names them; empty for every refusal that changed + * nothing. */ + readonly leftChanged: string[]; + + /** Keep the backend's sentence and what it says was left changed. */ + constructor(message: string, leftChanged: string[]) { + super(message); + this.leftChanged = leftChanged; + } +} + +/** The backend's reason for refusing a correction, with the labels it says a failed one left changed. */ +async function correctionRefused(response: Response): Promise { + let detail = `HTTP ${response.status}`; + let leftChanged: string[] = []; + try { + const body = (await response.json()) as { detail?: unknown; left_changed?: unknown }; + if (typeof body.detail === "string") detail = body.detail; + // Anything but a list of names says nothing was left changed. + if (Array.isArray(body.left_changed) && body.left_changed.every((name) => typeof name === "string")) leftChanged = body.left_changed; + } catch { + // A non-JSON error body keeps the status-code message. + } + return new CorrectionRefused(detail, leftChanged); +} + /** The backend's public reason for a refusal, or the HTTP status when it gave none. */ async function failureOf(response: Response): Promise { let detail = `HTTP ${response.status}`; @@ -224,9 +273,20 @@ export function saveDayReport(controlToken: string): Promise { export function correctSession(controlToken: string, correction: Correction): Promise { return withTimeout(undefined, CHANGE_TIMEOUT_MS, async (signal) => { const response = await fetch("/api/day-report/correct", { method: "POST", signal, headers: jsonHeaders(controlToken), body: JSON.stringify(correction) }); - if (!response.ok) throw await failureOf(response); + if (!response.ok) throw await correctionRefused(response); const body = (await response.json()) as Partial; if (!Array.isArray(body.updated) || !Array.isArray(body.missing)) throw new SettingsParseError("correction reply is malformed"); return body as CorrectionReply; }); } + +/** Correct the studio a whole session is labelled with. The label changes where the session lies; nothing is moved. */ +export function correctStudio(controlToken: string, correction: StudioCorrection): Promise { + return withTimeout(undefined, CHANGE_TIMEOUT_MS, async (signal) => { + const response = await fetch("/api/day-report/studio", { method: "POST", signal, headers: jsonHeaders(controlToken), body: JSON.stringify(correction) }); + if (!response.ok) throw await correctionRefused(response); + const body = (await response.json()) as Partial; + if (typeof body.studio !== "string" || !Array.isArray(body.updated)) throw new SettingsParseError("studio correction reply is malformed"); + return body as StudioCorrectionReply; + }); +} diff --git a/examples/egocap/frontend/src/dayReportTestDoubles.ts b/examples/egocap/frontend/src/dayReportTestDoubles.ts index 2606bd269c..b477f1c21f 100644 --- a/examples/egocap/frontend/src/dayReportTestDoubles.ts +++ b/examples/egocap/frontend/src/dayReportTestDoubles.ts @@ -15,6 +15,8 @@ function take(index: number, disposition: TakeDisposition, seconds: number, extr disposition, duration_seconds: seconds, task: "Pour water.", + // A recording that was never given a studio reports none. + studio: null, task_details: "", operator: "alex", issues: [], diff --git a/examples/egocap/frontend/src/livekitSightings.test.ts b/examples/egocap/frontend/src/livekitSightings.test.ts new file mode 100644 index 0000000000..ac346312b2 --- /dev/null +++ b/examples/egocap/frontend/src/livekitSightings.test.ts @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** What the page tells the backend of its LiveKit preview: the request, and when it is and is not sent. */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { renderHook } from "@testing-library/react"; +import { SIGHT_REPORT_MS, reportLiveKitPreview, useLiveKitSightReports, type LiveKitSight } from "./livekitSightings"; + +beforeEach(() => vi.useFakeTimers()); +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + Object.defineProperty(document, "hidden", { configurable: true, value: false }); +}); + +/** Put the tab out of view or back in it, as the browser reports it. */ +function hide(hidden: boolean): void { + Object.defineProperty(document, "hidden", { configurable: true, value: hidden }); +} + +/** The hook over a recorded sender; `finish` ends the report that is on its way. */ +function reporter(controlToken: string | null) { + const sent: Array<{ token: string; streams: Record }> = []; + const pending: Array<() => void> = []; + const report = vi.fn((token: string, streams: Record) => { + sent.push({ token, streams }); + return new Promise((resolve) => pending.push(resolve)); + }); + const hook = renderHook(({ token }) => useLiveKitSightReports(token, report), { initialProps: { token: controlToken } }); + /** Let the report on its way be answered. */ + const finish = async () => { + pending.splice(0).forEach((resolve) => resolve()); + await vi.advanceTimersByTimeAsync(0); + }; + return { sent, finish, note: (name: string, sight: LiveKitSight | null) => hook.result.current(name, sight), rerender: (token: string | null) => hook.rerender({ token }), unmount: hook.unmount }; +} + +describe("reportLiveKitPreview", () => { + it("posts this page's id and what it sees of each stream, with the control token", async () => { + const fetchFn = vi.fn(async (_path: string, _init: RequestInit) => ({ ok: true, status: 200, json: async () => ({}) })); + vi.stubGlobal("fetch", fetchFn); + await reportLiveKitPreview("tok", { "Head left": "receiving", "Left wrist": "silent" }); + await reportLiveKitPreview("tok", { "Head left": "no_track" }); + const [path, init] = fetchFn.mock.calls[0]; + expect(path).toBe("/api/setup/livekit-preview"); + expect(init.method).toBe("POST"); + expect(init.headers).toEqual({ "content-type": "application/json", "X-Control-Token": "tok" }); + const first = JSON.parse(init.body as string); + expect(first.streams).toEqual({ "Head left": "receiving", "Left wrist": "silent" }); + // One page keeps one id, so its newer report replaces its older one at the backend. + expect(first.page).toMatch(/^page-[a-z0-9]+$/); + expect(JSON.parse(fetchFn.mock.calls[1][1].body as string).page).toBe(first.page); + }); + + it("resolves when the backend cannot be reached: the next report follows anyway", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async () => { + throw new TypeError("Failed to fetch"); + }), + ); + await expect(reportLiveKitPreview("tok", { "Head left": "receiving" })).resolves.toBeUndefined(); + }); +}); + +describe("useLiveKitSightReports", () => { + it("reports what the tiles last said, every interval, and drops a tile that has nothing to say", async () => { + const { sent, finish, note } = reporter("tok"); + note("Head left", "receiving"); + note("Left wrist", "no_track"); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toEqual([{ token: "tok", streams: { "Head left": "receiving", "Left wrist": "no_track" } }]); + await finish(); + note("Left wrist", null); + note("Head left", "silent"); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent[1].streams).toEqual({ "Head left": "silent" }); + }); + + it("sends nothing without the control token, and starts once it is entered", async () => { + const { sent, note, rerender } = reporter(null); + note("Head left", "receiving"); + await vi.advanceTimersByTimeAsync(3 * SIGHT_REPORT_MS); + expect(sent).toEqual([]); + rerender("tok"); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toHaveLength(1); + }); + + it("sends nothing while no LiveKit tile has anything to say", async () => { + const { sent } = reporter("tok"); + await vi.advanceTimersByTimeAsync(3 * SIGHT_REPORT_MS); + expect(sent).toEqual([]); + }); + + it("keeps one report on its way at a time", async () => { + const { sent, finish, note } = reporter("tok"); + note("Head left", "receiving"); + await vi.advanceTimersByTimeAsync(3 * SIGHT_REPORT_MS); + expect(sent).toHaveLength(1); + await finish(); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toHaveLength(2); + }); + + it("is silent while the tab is hidden, and for one interval after it returns", async () => { + const { sent, finish, note } = reporter("tok"); + note("Head left", "receiving"); + hide(true); + // A hidden tab presents no frames, so its tile would call a live camera silent. + note("Head left", "silent"); + await vi.advanceTimersByTimeAsync(3 * SIGHT_REPORT_MS); + expect(sent).toEqual([]); + hide(false); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toEqual([]); + note("Head left", "receiving"); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toEqual([{ token: "tok", streams: { "Head left": "receiving" } }]); + await finish(); + }); + + it("starts silent for one interval when the page was opened out of view", async () => { + hide(true); + const { sent, note } = reporter("tok"); + note("Head left", "silent"); + hide(false); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toEqual([]); + await vi.advanceTimersByTimeAsync(SIGHT_REPORT_MS); + expect(sent).toHaveLength(1); + }); + + it("stops when the component goes away", async () => { + const { sent, note, unmount } = reporter("tok"); + note("Head left", "receiving"); + unmount(); + await vi.advanceTimersByTimeAsync(3 * SIGHT_REPORT_MS); + expect(sent).toEqual([]); + }); +}); diff --git a/examples/egocap/frontend/src/livekitSightings.ts b/examples/egocap/frontend/src/livekitSightings.ts new file mode 100644 index 0000000000..b1d2983067 --- /dev/null +++ b/examples/egocap/frontend/src/livekitSightings.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** + * Tells the backend what this page's preview is receiving of each LiveKit camera + * (`POST /api/setup/livekit-preview`). + * + * The backend joins a LiveKit room only while a take records, so between takes this page is what is in the room. + * The station checklist passes such a camera only while a page reports its frames arriving. The report is an + * observation, never a verdict: the backend judges, and never holds a take on it. + */ +import { useCallback, useEffect, useRef } from "react"; + +/** What the preview shows of one stream: frames arriving, a subscribed track that sends none, a track its sender + * has not published, or a room this page is not in. */ +export type LiveKitSight = "receiving" | "silent" | "no_track" | "not_connected"; + +/** How often the page reports while it is in view; the backend forgets a report three intervals old. */ +export const SIGHT_REPORT_MS = 2_000; + +/** This page load's name in its reports, so that a second operator page is counted beside it, not over it. */ +const PAGE_ID = `page-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`; + +/** Send one report. Resolves whether or not the backend took it: the next one follows shortly either way. */ +export async function reportLiveKitPreview(controlToken: string, streams: Record, signal?: AbortSignal): Promise { + try { + await fetch("/api/setup/livekit-preview", { + method: "POST", + signal, + headers: { "content-type": "application/json", "X-Control-Token": controlToken }, + body: JSON.stringify({ page: PAGE_ID, streams }), + }); + } catch { + // An unreachable backend shows elsewhere on the page; a lost report only leaves the camera unchecked. + } +} + +/** + * Reports what the tiles see, every couple of seconds while the page is in view and holds the control token. + * Returns the callback a tile calls with its stream's name and what it sees now, or null when it has nothing to + * say (still connecting, or gone). + */ +export function useLiveKitSightReports(controlToken: string | null, report: typeof reportLiveKitPreview = reportLiveKitPreview): (name: string, sight: LiveKitSight | null) => void { + const sights = useRef(new Map()); + const note = useCallback((name: string, sight: LiveKitSight | null) => { + if (sight === null) sights.current.delete(name); + else sights.current.set(name, sight); + }, []); + useEffect(() => { + if (controlToken === null) return; + const controller = new AbortController(); + let sending = false; + // A hidden tab presents no frames, so its tiles look silent. Nothing is reported while it is hidden, nor on + // the first tick after it returns, by when a camera that is sending has shown a frame again. + let settled = !document.hidden; + const timer = setInterval(() => { + if (document.hidden) { + settled = false; + return; + } + if (!settled) { + settled = true; + return; + } + // One report at a time: a slow backend must not collect a queue of stale ones. + if (sending || sights.current.size === 0) return; + sending = true; + void report(controlToken, Object.fromEntries(sights.current), controller.signal).finally(() => { + sending = false; + }); + }, SIGHT_REPORT_MS); + return () => { + clearInterval(timer); + controller.abort(); + }; + }, [controlToken, report]); + return note; +} diff --git a/examples/egocap/frontend/src/settingsTestDoubles.ts b/examples/egocap/frontend/src/settingsTestDoubles.ts index 8c77c0938a..2fa28e00d8 100644 --- a/examples/egocap/frontend/src/settingsTestDoubles.ts +++ b/examples/egocap/frontend/src/settingsTestDoubles.ts @@ -24,6 +24,13 @@ export const STATIONS_FIXTURE: StationListing = { selected: null, roles: ["ego", "wrist_left", "wrist_right"], camera_types: ["sensing_gmsl", "oak_d"], + tracking_devices: [ + { id: "headset", name: "Headset" }, + { id: "controller_left", name: "Left controller" }, + { id: "controller_right", name: "Right controller" }, + { id: "glove_left", name: "Left glove" }, + { id: "glove_right", name: "Right glove" }, + ], label: "Station 01", locked_reason: null, }; @@ -162,6 +169,7 @@ export function fakeStationRegistry(initial: StationListing = STATIONS_FIXTURE) return listing; }, updateStation: async (_token: string, id: string, changes: StationChange): Promise => { + // As the backend does: roles are merged, and a list of required devices replaces the saved one. replace(id, (station) => ({ ...station, ...changes, camera_roles: { ...station.camera_roles, ...changes.camera_roles } })); return relabel(); }, diff --git a/examples/egocap/frontend/src/setupTestDoubles.ts b/examples/egocap/frontend/src/setupTestDoubles.ts index a6b2bd3bc2..a369d214d8 100644 --- a/examples/egocap/frontend/src/setupTestDoubles.ts +++ b/examples/egocap/frontend/src/setupTestDoubles.ts @@ -3,7 +3,8 @@ // SPDX-License-Identifier: Apache-2.0 /** Start-of-day flow bodies for tests: a station in use held by a camera that stopped, the same station ready, - * and the same station ready on real cameras whose calibration files are missing but not required. */ + * the same station ready on real cameras whose calibration files are missing but not required, and the same + * station held by a glove it requires. */ import type { CheckItem, SetupStatus } from "./setupApi"; const SYSTEM: CheckItem[] = [ @@ -57,3 +58,21 @@ export const SETUP_UNCALIBRATED: SetupStatus = { checks: SETUP_READY.checks.map((check) => (check.id === "calibration" ? { ...check, status: "fail", detail: MISSING_CALIBRATION } : check)), blocked_reason: `Camera calibration: ${MISSING_CALIBRATION}`, }; + +const UNREPORTED = "not reported by the capture session; this station requires it"; + +/** The ready station once it requires both gloves: the left one is reported and not connected, the right one is + * not reported at all, and each holds recording. The controller it does not require still only warns. A required + * device's row carries the Station tab's name for it; every other row the capture session's own description. */ +export const SETUP_DEVICE_REQUIRED: SetupStatus = { + ...SETUP_READY, + steps: SETUP_READY.steps.map((step) => (step.id === "devices" ? { ...step, status: "attention", detail: "Left glove: disconnected; this station requires it" } : step)), + checks: [ + { id: "device:0", group: "tracking", label: "Pico headset", status: "pass", detail: null }, + { id: "device:1", group: "tracking", label: "Left controller", status: "warn", detail: "disconnected" }, + { id: "device:2", group: "tracking", label: "Left glove", status: "fail", detail: "disconnected; this station requires it" }, + { id: "device:required:glove_right", group: "tracking", label: "Right glove", status: "fail", detail: UNREPORTED }, + ...SETUP_READY.checks.filter((check) => check.group !== "tracking"), + ], + blocked_reason: "Left glove: disconnected; this station requires it", +}; diff --git a/examples/egocap/frontend/src/stationsApi.ts b/examples/egocap/frontend/src/stationsApi.ts index 707acfb0fd..9374e1a57e 100644 --- a/examples/egocap/frontend/src/stationsApi.ts +++ b/examples/egocap/frontend/src/stationsApi.ts @@ -20,6 +20,20 @@ export interface StationRecord { camera_roles: Record; /** Why this station cannot record yet, most important first; empty when it can. */ problems: string[]; + /** The tracking devices that must be connected before a take, by id; absent or empty when it requires none. A + * name the backend read from its file and does not know is listed as it was written. */ + required_devices?: string[]; + /** The required devices the capture session here does not report, and so cannot be connected here; absent from a + * backend that does not say, empty while the capture session has reported no devices yet. */ + unreported_devices?: string[]; +} + +/** A tracking device a station can require. */ +export interface TrackingDevice { + /** The name a station stores for it. */ + id: string; + /** The name the operator reads. */ + name: string; } /** `GET /api/stations`, and the reply to every registry change. */ @@ -29,6 +43,8 @@ export interface StationListing { selected: string | null; roles: string[]; camera_types: string[]; + /** The tracking devices a station can require, in the order they are listed; absent from a backend that holds a take for none. */ + tracking_devices?: TrackingDevice[]; /** The station label recordings carry right now. */ label: string; /** Why the station in use cannot change now (a take is being recorded), or null. */ @@ -42,6 +58,8 @@ export interface StationChange { name?: string; camera_type?: string | null; camera_roles?: Record; + /** Every tracking device the station requires, by id: the list replaces the saved one, and an empty list requires none. */ + required_devices?: string[]; } /** The backend's public reason for a refusal, or the HTTP status when it gave none. */ diff --git a/examples/egocap/frontend/src/styles.css b/examples/egocap/frontend/src/styles.css index 341196b156..dddeb8b3dc 100644 --- a/examples/egocap/frontend/src/styles.css +++ b/examples/egocap/frontend/src/styles.css @@ -386,6 +386,27 @@ width, so a long line wraps inside it instead of pushing the row's buttons onto border-top: 1px solid var(--border); } +/* The tracking devices a station requires: a group of boxes under the editor's fields, named by its legend. */ +.station-required { + margin: var(--space-3) 0 0; + padding: 0; + border: 0; + min-width: 0; +} + +.station-required legend { + padding: 0; + font-size: 13px; + color: var(--text-secondary); +} + +.station-required-boxes { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + margin-top: var(--space-2); +} + /* A destructive action: a delete, a discard or a reset. */ .settings-danger { height: 32px; @@ -3407,6 +3428,13 @@ below for the narrow/stacked layout). */ font-size: 15px; } +/* The live check's verdict: the one line under its figures, as weighty as a measure's name. */ +.calib-verdict { + margin: var(--space-3) 0 0; + font-size: 15px; + font-weight: 600; +} + /* The live picture carries the take's clock and what was covered, so neither is looked for elsewhere. */ .calib-preview { margin: 0; diff --git a/examples/egocap/recording/README.md b/examples/egocap/recording/README.md index df07010a6a..1499a13d22 100644 --- a/examples/egocap/recording/README.md +++ b/examples/egocap/recording/README.md @@ -106,7 +106,13 @@ such file, or one that states no usable lag or was not made with this project's episode whose session states a lag for a stated tracking latency, while the take does not say which latency it was recorded under, is refused. The session's calibration files, the lens files and `rectification.json` among them, are carried into the aligned session as they are. See -[`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#camera-lag-in-aligned-takes). +[`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#camera-lag-in-aligned-takes). A session file written in a +layout newer than this software reads raises `NewerLayoutError`, and the aligner tool +(`tools/align_episode.py`) exits with a status of its own for it: 0 aligned, 1 refused for good, 2 the +manifest could not be read, 3 a newer build is needed. The background aligner marks a take refused only for +1, so a take refused under 3 is aligned once the software is updated. `calibration.provenance.newer_layout()` +names a layout this build cannot read, however the number is written, and one beyond `LAYOUT_CEILING` as +far newer than any it knows. `episode_layout.py` owns the on-disk layout: pending/final directory naming, studio/timestamp routing (`assign_output`/`finalize_episode_dir` route each finalized episode to @@ -165,13 +171,18 @@ module does, the limits it applies and how an operator uses the tools are in `///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 midnight-crossing episode). A standalone library function for offline reporting — the backend - and recording service do not call it. + and recording service do not call it. A session's `studio` is the label the session states, which a + correction can change without moving the folder; the session's key stays its folder. +- `egocap/studio/session_studio.py`'s `session_studio()` is the one reader of a session's studio: its + root group's `studio`, else `meta.studio` of its `config.yaml`, else the fallback the caller gives + (the name of the studio folder, for a session that states none). ## EOD session tooling — `egocap/eod/`, `egocap/data_processing/` Library functions for session/episode metadata maintenance after the fact. The recording service calls none of them; the backend's end-of-day correction (`POST /api/day-report/correct`) calls -`update_episode_task_description()` with a task only, and the rest is for offline callers: +`update_episode_task_description()` with a task only, its studio correction (`POST /api/day-report/studio`) +calls `update_session_studio()`, and the rest is for offline callers: - `eod_studio_session_move.py`'s `relocate_session_to_canonical_studio()` moves a session folder from `_unmatched/` (or a mis-filed studio) to its canonical `///` @@ -184,6 +195,52 @@ none of them; the backend's end-of-day correction (`POST /api/day-report/correct (Zarr attrs and `config.yaml`'s `meta`) changes only when the range covers every finalized episode, so correcting some takes does not relabel the rest; `config.yaml` is replaced atomically. A range covers at most 10,000 episodes; a longer one is refused before anything is read. +- `update_session_studio()` relabels the studio of a whole session where it lies: on every finalized + episode, on the root group when the session has one, in `config.yaml` and on the time-aligned copy. + It moves, renames and creates nothing, touches no task and no manifest, and leaves a session with no + finalized episode as it was. It is `plan_session_studio()` followed by the plan's `apply()`. The plan + reads every file that carries the label and checks each can be rewritten, and raises `RelabelError` + there with nothing changed and the take named. `apply()` writes the episodes, then the session's own + label, then `config.yaml`, then the same of the copy; a write that fails puts back what was written, + byte for byte, and `RelabelError.left_changed` names any that could not be put back. What was written + and what was put back are read from the files: a label counts as written from the moment its write + begins, and one counts as put back only when the file holds what was found. The stored name is one + plain word in one Unicode form (`stored_studio_name()`). +- `update_episode_task_description()` is checked whole and put back in the same way, over the same + files, before it calls `on_session_task_change`; it raises `RelabelError` or `SessionConfigError`. +- Both corrections replace each metadata file by a file of the same mode and sync the file and its + directory, and write `config.yaml` as the recorder writes it, with text outside ASCII escaped. A + `config.yaml` that cannot be read or is not a mapping raises `SessionConfigError` before anything is + written, and one that is there and is not rewritten raises instead of being passed over. + `remove_interrupted_writes(zarr_root, now=None)` removes the temporary files a correction that was + killed part-way left in the session, its episodes and its copy, once they are older than a minute + (`STRAY_MIN_AGE_S`): a younger one may belong to a writer at work. One it cannot remove is left and + logged. The caller holds the session's lock. +- A caller must not run either correction on a session that holds a take still to be filed by, or into, + what is being corrected (unsettled, with a studio in its manifest and no assignment yet, or with an + assignment that names the group being corrected): the recording service files a kept take by the + studio and task its manifest froze, and refuses a group whose labels differ. A caller that really + changes a routed group's studio or whole task also calls `egocap.recording.route.forget_group()` + under the session's lock, so a later take of that session claims a fresh group. + `episode_layout.scan_manifests()` reports a sidecar it cannot list, a record that is JSON and no + record, and a record that cannot be opened (by its name and the reason, with no path) as problems, + never as no take. + +## Not yet verified on hardware + +Run on synthetic sessions and rendered pictures only, with no recorded episode and no device: + +- `update_session_studio()` and `session_studio()`, on sessions built in the tests and, through the backend's + routes, on sessions a recording service wrote with one numeric source. Never on a session with recorded video, + and the syncing of a replaced file was counted, not tried against a power cut. A correction killed + part-way leaves two studios, or part of a task correction, until the next correction of the session + completes it; no file is truncated. +- The live check's implied camera offset and lag (`calibration/live_check.py`), on rendered scenes only: the + noise of a real headset's tracking, which decides how soon the views pin them, is unmeasured. +- What the calibration files state of how they came to be (`calibration/provenance.py`), on synthetic solves; no + reader outside this repository was run against a file that carries the added keys. +- The live check of an installed head-camera calibration (`calibration/live_check.py`), on rendered boards and + written-out head tracks. ## Data layout and format diff --git a/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py b/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py index 08d0493511..aa25764158 100644 --- a/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py +++ b/examples/egocap/recording/egocap/analytics/count_daily_trajectories.py @@ -10,7 +10,9 @@ ///episode_*/zarr.json Each ``/`` folder is one session. Its own ``zarr.json`` -carries ``discarded_episode_indices`` (indices that were discarded). Each +carries ``discarded_episode_indices`` (indices that were discarded) and the +``studio`` the session is labelled with, which a correction can change without +moving the folder (see :mod:`egocap.studio.session_studio`). Each episode's ``zarr.json`` carries ``episode_duration`` (seconds) and ``task_description`` (the instruction string used for that episode). @@ -28,6 +30,8 @@ from datetime import datetime from pathlib import Path +from egocap.studio.session_studio import session_studio + def make_session_stats() -> dict: """Create a new session stats dict.""" @@ -266,7 +270,9 @@ def count_trajectories( continue stats = sessions[session_key] - stats["studio"] = studio_dir.name + # The label the session states, which a correction changes; the folder's name is only what a + # session that states none is known by. The key above stays the folder: it is where the data is. + stats["studio"] = session_studio(session_dir, fallback=studio_dir.name, attributes=session_attrs) stats["timestamp"] = session_dir.name duration = float(ep_attrs.get("episode_duration") or 0.0) diff --git a/examples/egocap/recording/egocap/analytics/day_report.py b/examples/egocap/recording/egocap/analytics/day_report.py index 352c1ce11d..a074a3dd00 100644 --- a/examples/egocap/recording/egocap/analytics/day_report.py +++ b/examples/egocap/recording/egocap/analytics/day_report.py @@ -31,6 +31,7 @@ quarantine_destination, scan_manifests, ) +from egocap.studio.session_studio import session_studio #: What became of a take, in the order the page lists them. ``recording`` is the take being written right now. #: A flagged take and a quarantined one were both marked bad by the capture checks; the first stayed with its @@ -131,11 +132,29 @@ def take_reasons(manifest: EpisodeManifest) -> tuple[list[str], list[str]]: return [issue for result in decided for issue in result.issues], list(report.warnings) +def _studio(session_path: Path, manifest: EpisodeManifest, attributes: dict[str, Any]) -> str | None: + """The studio a take is labelled with: its finalized episode's own label, else the label of the session + or routed group that holds it, else the studio it was recorded under. None for a take with none of these, + which is every take of a recording that was never given a studio.""" + own = attributes.get("studio") + if isinstance(own, str) and own.strip(): + return own + group = manifest.assignment.get("group") if manifest.assignment is not None else None + # A group's name comes from the manifest; one of another shape names no directory to read a label from. + holder = session_path.parent / group if isinstance(group, str) and group else session_path + return session_studio(holder, fallback=manifest.studio) + + def _episode_record( - manifest: EpisodeManifest, disposition: str, attributes: dict[str, Any], describe: Describe | None + session_path: Path, + 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.""" + """One take as the report lists it. The task and the studio are the finalized episode's own when it has + them: a label 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 { @@ -144,6 +163,7 @@ def _episode_record( "disposition": disposition, "duration_seconds": float(manifest.duration_seconds), "task": corrected if isinstance(corrected, str) and corrected else manifest.task, + "studio": _studio(session_path, manifest, attributes), "task_details": manifest.task_details, "operator": manifest.operator, "issues": list(manifest.issues), @@ -167,7 +187,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, describe) + record = _episode_record(session_path, manifest, disposition, attributes, describe) except OSError: # The manifest vanished between the scan and here (a discard finishing); the next read is correct. continue diff --git a/examples/egocap/recording/egocap/calibration/camera_pipeline.py b/examples/egocap/recording/egocap/calibration/camera_pipeline.py index a6b7f37e43..190ef8686d 100644 --- a/examples/egocap/recording/egocap/calibration/camera_pipeline.py +++ b/examples/egocap/recording/egocap/calibration/camera_pipeline.py @@ -24,6 +24,7 @@ import cv2 import numpy as np +from . import provenance from .board import BoardDetector, BoardSpec, BoardView, CalibrationError, as_gray, draw_corners from .extrinsics import ( TRACK_FROZEN_M_PER_DEG, @@ -853,6 +854,16 @@ def run_camera_calibration( for record in filter(None, (intrinsics, extrinsics)): record.update(stamp) grade = grade_calibration(intrinsics, extrinsics) + # Each record states what made it, how it was graded and the rule it is held to, so the file an install + # writes carries them wherever it is copied. + for part, record in (("intrinsics", intrinsics), ("extrinsics", extrinsics)): + if record is not None: + provenance.stamp( + record, + tool=provenance.CAMERA_CALIBRATION, + grade=grade[part]["grade"], + install_rule=grade[part]["install_rule"], + ) for line in _result_lines(intrinsics, extrinsics, grade, problem): _say(log, line) if review is not None: diff --git a/examples/egocap/recording/egocap/calibration/files.py b/examples/egocap/recording/egocap/calibration/files.py index fd59915233..4acc511d21 100644 --- a/examples/egocap/recording/egocap/calibration/files.py +++ b/examples/egocap/recording/egocap/calibration/files.py @@ -27,6 +27,8 @@ from egocap.recording.episode_layout import fsync_dir +from .provenance import layout_problem + HEAD_INTRINSICS = "head_camera_intrinsics.json" HEAD_EXTRINSICS = "head_camera_extrinsics.json" LEFT_WRIST_INTRINSICS = "left_wrist_camera_intrinsics.json" @@ -166,8 +168,17 @@ def _matrix(record: dict[str, Any], key: str, shape: tuple[int, int], name: str) return matrix +def refuse_newer_layout(record: Mapping[str, Any], name: str) -> None: + """Refuse a calibration file written in a layout newer than this build reads, before any of its keys is + taken for what it means here. A file that states no layout is read as it always was.""" + problem = layout_problem(record, name) + if problem is not None: + raise CalibrationFileError(problem) + + def intrinsics_from_record(record: dict[str, Any], name: str) -> Intrinsics: """The intrinsics an intrinsics file's record describes; ``name`` is the file named in an error.""" + refuse_newer_layout(record, name) K = _matrix(record, "K", (3, 3), name) # OpenCV's lens models read four numbers of this matrix. One that states a skew or another last row (from # another solver, or a hand edit) would be used as if it did not, and recorded as if it had been. @@ -259,6 +270,32 @@ def camera_stamp_note(record: Mapping[str, Any], name: str) -> str | None: return f"{name} is not stamped for a camera, so it cannot be checked against the camera in this role" +def picture_size_note( + installed: Intrinsics, picture_wh: tuple[int, int], name: str, *, lens_solved: bool +) -> str | None: + """What an operator should know before a take of a camera whose picture is not the size the installed + lens file ``name`` was solved at; None when it is that size. + + ``picture_wh`` is the size the camera's picture has now. ``lens_solved`` says what the take is for: a + take that solves the lens replaces the file with one for the new size, and a take that solves the + position alone builds on the file, which cannot be done across sizes. A changed size is most often a + camera started in another picture mode, so both sentences say to look at that first. + """ + had, has = tuple(installed.image_size_wh), tuple(picture_wh) + if had == has: + return None + sizes = f"a {had[0]}x{had[1]} picture, and this camera now sends {has[0]}x{has[1]}" + if lens_solved: + return ( + f"{name} was solved on {sizes}. A solve from this take replaces it with one for the new size: " + "if the size changed by mistake, set the camera's picture mode back before recording" + ) + return ( + f"{name} is for {sizes}, so the camera's position cannot be solved against it. Solve the lens as " + "well, or set the camera's picture mode back before recording" + ) + + def pose_source_problem(record: Mapping[str, Any], name: str) -> str | None: """Why the head-camera position or the wrist offsets in the file ``name`` must not be built on; None when they may. @@ -310,4 +347,6 @@ def load_intrinsics_with_sha256(path: Path) -> tuple[Intrinsics, str]: def load_headset_extrinsics(path: Path) -> np.ndarray: """Read ``T_headset_camera`` from a head-camera extrinsics file: the camera's optical frame expressed in the headset frame whose axes are X forward, Y left, Z up, in meters.""" - return _matrix(read_json_object(path), "T_headset_camera", (4, 4), path.name) + record = read_json_object(path) + refuse_newer_layout(record, path.name) + return _matrix(record, "T_headset_camera", (4, 4), path.name) diff --git a/examples/egocap/recording/egocap/calibration/grading.py b/examples/egocap/recording/egocap/calibration/grading.py index 660c751876..f40e7d33f6 100644 --- a/examples/egocap/recording/egocap/calibration/grading.py +++ b/examples/egocap/recording/egocap/calibration/grading.py @@ -82,6 +82,14 @@ _Shortfall = tuple[str, str] +#: The rule extrinsics are installed under, as a file states it: alone, and solved in one run with intrinsics. +EXTRINSICS_RULE = f"Extrinsics are installed unless graded {BAD}." +EXTRINSICS_RULE_PAIRED = ( + f"Extrinsics are installed unless graded {BAD}, and only with the intrinsics they were solved with when " + "those may be installed." +) + + def _grade_low(value: float, limits: tuple[float, float]) -> str: """The grade of a number that should be small; one that is not a number is bad.""" if value < limits[0]: @@ -96,6 +104,11 @@ def _grade_high(value: float, limits: tuple[float, float]) -> str: return ACCEPTABLE if value >= limits[1] else BAD +def grade_under(value: float, limits: tuple[float, float]) -> str: + """The grade of a number that should be small, against one (excellent, acceptable) pair of limits.""" + return _grade_low(value, limits) + + def grade_intrinsics(rms_px: float) -> str: """The grade of an intrinsics solve's fit, from its reprojection RMS in pixels.""" return _grade_low(rms_px, INTRINSICS_RMS_PX) @@ -354,6 +367,8 @@ def _grade_intrinsics_record(record: dict[str, Any], feedback: list[str]) -> dic "field_of_view": _field_of_view(record), "installable": installable, "not_installable_reason": None if installable else f"{rule}, and this solve is {grade}{at}{why}.", + # The rule by itself, for the file to state whether or not this solve met it. + "install_rule": f"{rule}.", } @@ -496,6 +511,7 @@ def _grade_extrinsics_record(record: dict[str, Any], feedback: list[str]) -> dic "not_installable_reason": None if installable else f"Extrinsics graded {BAD} are not installed: {refused}.", + "install_rule": EXTRINSICS_RULE, } @@ -503,8 +519,9 @@ def grade_calibration(intrinsics: dict[str, Any] | None, extrinsics: dict[str, A """Grade what a calibration run solved; either record may be None when that part was not solved. Returns ``overall`` (the worse of the parts, None when nothing was solved), a part for ``intrinsics`` and - for ``extrinsics`` (None when not solved) with its grade, its numbers, ``installable`` and - ``not_installable_reason``, and ``feedback``: one sentence of advice per number that is not excellent. + for ``extrinsics`` (None when not solved) with its grade, its numbers, ``installable``, + ``not_installable_reason`` and ``install_rule`` (the rule it is held to, in words), and ``feedback``: one + sentence of advice per number that is not excellent. A part's grade is the worst of its residuals and of the evidence its record carries (see the module). Extrinsics solved in the same run as intrinsics are installed with them or not at all (``with_intrinsics``). """ @@ -528,6 +545,7 @@ def _pair(intrinsics: dict[str, Any], extrinsics: dict[str, Any]) -> None: intrinsics may not be installed the extrinsics may not be either. """ extrinsics["with_intrinsics"] = True + extrinsics["install_rule"] = EXTRINSICS_RULE_PAIRED if extrinsics["installable"] and not intrinsics["installable"]: extrinsics["installable"] = False extrinsics["not_installable_reason"] = ( diff --git a/examples/egocap/recording/egocap/calibration/live_check.py b/examples/egocap/recording/egocap/calibration/live_check.py new file mode 100644 index 0000000000..58730c4803 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/live_check.py @@ -0,0 +1,466 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A live check of the installed head-camera calibration, with no solve. + +A board that stands still is watched by a head that moves. The first good views fix where the board stands in +the world: its pose in the camera through the installed lens, carried to the world through the installed camera +position and the head pose. From then on the head pose of each picture alone says where the board's corners +should appear, and how far that is from where they do appear is the error, in pixels, of the installed +calibration together with the tracking and its timing. + +The verdict grades what the views can show, each figure against the solve's own limit for it. The board +never moved, so where it seems to stand from view to view is explained as far as it can be: a camera that +sits elsewhere on the headset than the file says carries the board's place round with the head's turning, and +a camera whose pictures are older or newer than its stored lag says carries it along with the head's motion. +The offset and the lag that explain the wander best are graded, beside the wander itself and how well the +board's poses fit the picture (``grading.grade_extrinsics``). An offset along an axis shows only in turns +about the other two, so there is no verdict until the head has turned about a second axis, as for a solve; +and a lag shows only while the head moves, so a verdict from pictures of a still head says the lag was not +tested. + +A picture's head pose is the one at the picture's own time, found between the tracking samples either side +of it: the newest sample is later than the picture by the camera's delay, and a turning head is elsewhere by +then. + +Nothing is solved, read from disk or written here: the caller hands in the calibration to check. +""" + +from __future__ import annotations + +from collections import deque +from collections.abc import Sequence +from typing import Any + +import numpy as np +from scipy.spatial.transform import Rotation, Slerp + +from .board import BoardDetector, BoardSpec, BoardView, as_gray +from .camera_model import board_pose, project, reprojection_rms +from .extrinsics import LATENCY_STEP_S, TRACK_FROZEN_M_PER_DEG, HeadTrackReader, head_turn_problem +from .files import Intrinsics +from .frames import invert_pose, openxr_poses_to_flu +from .grading import ( + BAD, + EXTRINSICS_PNP_RMS_PX, + EXTRINSICS_SPREAD_M, + EXTRINSICS_UNCERTAINTY_M, + grade_extrinsics, + grade_under, + worst_grade, +) + +#: How many good views the board's place is fixed from. The middle one of them is taken, so one view of a +#: board that was still settling does not set the place. +ANCHOR_VIEWS = 5 +#: The fewest corners a view must show to be used: fewer fix the board's pose too loosely to hold a +#: prediction against. +MIN_CORNERS = 8 +#: How far the head must have turned or moved from where the board's place was fixed for a view to test the +#: calibration: seen from the same head pose, the board is predicted where it was seen whatever the files say. +MOVED_TURN_DEG = 5.0 +MOVED_SHIFT_M = 0.05 +#: What a verdict needs: this many such views, and a head that turned this far in one of them. +VIEWS_NEEDED = 10 +TURN_NEEDED_DEG = 15.0 +#: How fast the head's motion may carry the board's place, in meters a second, in a picture the place is fixed +#: from: a picture taken while the head moves puts the place off by that speed times any error in the lag. +STILL_M_PER_S = 0.05 +#: Over how long either side of a picture the head's motion at the picture's time is read from the track. +_RATE_SPAN_S = 0.02 +#: The camera's lag as the wander implies it, against the step a solve searches the lag in: within one step +#: it is as right as a solve makes it, and beyond two it is plainly wrong. +CAMERA_LAG_OFF_S = (LATENCY_STEP_S, 2 * LATENCY_STEP_S) +#: No picture places the board more closely than this, however well a fit explains the views: the least +#: noise the offset and the lag are taken to be known against. +_PLACE_NOISE_M = 0.0005 + +#: How far apart the two tracking samples either side of a picture may lie for its head pose to be found +#: between them, and for how long samples are kept to find it: a picture is never older than this. +MAX_POSE_GAP_S = 0.1 +_POSE_MEMORY_S = 3.0 + +#: Where the check stands. +FIXING, CHECKING = "fixing", "checking" +#: Why a picture could not be judged, each with what to do; None for one that was. +NO_HEAD_POSE = "Head tracking is not arriving: check the headset is on and tracked." +HEAD_LOST = ( + "The headset has lost its position: look around the room until it finds it again. The check starts over " + "from where the board stands then." +) +NOT_FOUND = "The board is not found in the picture: point the camera at it, and move slowly." +TOO_LITTLE = "Too little of the board is readable in this picture: show more of it." +HEAD_MOVING = ( + "Hold your head still for a moment, with the board in view: the check is fixing where the board stands." +) +MOVE_HEAD = "Turn and tilt your head, and step to the side, keeping the board in view. The board must not move." +HOLD_STILL = "Keep the board in view, and the board and your head still, while the check fixes where it stands." +ENOUGH = "Enough has been seen: the verdict is below. Go on moving to keep watching it, or stop the check." +#: Why enough views by the count still give no verdict, and what to do about either. +SECOND_AXIS = ( + "No verdict yet: your head has turned about one axis only, so the camera's place along that axis is not " + "tested." +) +NOT_PINNED = "No verdict yet: the views so far do not pin the camera's place closely enough to grade it." +TILT_TOO = "Nod and tilt your head as well as turning it, keeping the board in view. The board must not move." +#: Said beside a verdict that rests on pictures none of which could show a wrong lag. +LAG_UNTESTED = ( + "The camera's lag is not tested yet: it shows only in pictures taken while your head moves. Keep moving " + "slowly with the board in view to test it." +) + + +def _least_squares(columns: np.ndarray, values: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """The unknowns that best explain ``values`` as ``columns`` times them, and how closely the views pin + them: their covariance, from what the fit leaves unexplained and never from less than a picture's own + noise in placing a board.""" + answer = np.linalg.lstsq(columns, values, rcond=None)[0] + left = values - columns @ answer + variance = max(float(left @ left) / max(len(values) - columns.shape[1], 1), _PLACE_NOISE_M**2) + return answer, variance * np.linalg.pinv(columns.T @ columns) + + +def _told(value: float, deviation: float, limit: float) -> bool: + """Whether a figure found to within ``deviation`` can be graded against ``limit``: the views pin it to + within half the limit, so that noise alone does not carry a sound one over it, or it lies beyond the + limit by more than twice what they leave open.""" + return deviation < limit / 2 or value - 2 * deviation > limit + + +def _turn_deg(pose: np.ndarray, reference: np.ndarray) -> float: + """The angle between two poses' orientations, in degrees.""" + return float(np.degrees(Rotation.from_matrix(reference[:3, :3].T @ pose[:3, :3]).magnitude())) + + +def _usable(pose: Any) -> np.ndarray | None: + """A head pose as a 4x4 array, or None for what is no pose: one with holes in it, or no rotation.""" + pose = np.asarray(pose, dtype=np.float64).reshape(4, 4) + return pose if np.all(np.isfinite(pose)) and np.linalg.det(pose[:3, :3]) > 0.0 else None + + +def _between(earlier: tuple[float, np.ndarray], later: tuple[float, np.ndarray], seconds: float) -> np.ndarray: + """The pose at ``seconds`` between two timed poses: the position along the line between them, the + orientation along the shortest turn, as the time aligner places a pose between two samples.""" + (start, first), (end, second) = earlier, later + share = (seconds - start) / (end - start) + pose = np.eye(4) + pose[:3, 3] = (1.0 - share) * first[:3, 3] + share * second[:3, 3] + turns = Rotation.from_matrix(np.stack([first[:3, :3], second[:3, :3]])) + pose[:3, :3] = Slerp([0.0, 1.0], turns)([share]).as_matrix()[0] + return pose + + +class LiveCheck: + """Checks one camera's installed calibration against live pictures of a board that stands still. + + ``camera`` is the camera as the pictures show it: the installed lens file, or for a camera whose video is + corrected the camera its rectification made. ``headset_camera`` is the installed camera position + (``T_headset_camera``, in the headset's forward-left-up frame). One instance follows one check; a + position that leaps or is lost starts it over, since the board's place was fixed in the frame it left. + """ + + def __init__( + self, spec: BoardSpec, camera: Intrinsics, headset_camera: np.ndarray, image_size_wh: Any + ) -> None: + """Start a check of ``camera`` and ``headset_camera`` on pictures of ``image_size_wh``.""" + self._detector = BoardDetector(spec) + self._camera = camera + self._headset_camera = np.asarray(headset_camera, dtype=np.float64) + self._size = (int(image_size_wh[0]), int(image_size_wh[1])) + self._reader = HeadTrackReader() + # The head poses of the last few seconds, oldest first, to find a picture's own between. + self._track: deque[tuple[float, np.ndarray]] = deque() + # The stretch of sound tracking the last picture lay in: what is fixed was fixed in that one. + self._stretch = 0 + self._restarts = 0 + self._start_over() + + def _start_over(self) -> None: + """Forget where the board stands and everything measured against it.""" + # The views the place is being fixed from: the board in the world, the head pose it was seen from, + # how well the board's pose fitted the picture, and how fast the head carried the board's place. + self._fixing: list[tuple[np.ndarray, np.ndarray, float, np.ndarray]] = [] + self._anchor: np.ndarray | None = None + self._anchor_head: np.ndarray | None = None + # Of the view the place was fixed from and of every view that tested it: where the board stood, the + # head pose it was seen from, how fast the head carried its place, how well its pose fitted the + # picture, and (of the tested ones) the error of the prediction. + self._positions: list[np.ndarray] = [] + self._heads: list[np.ndarray] = [] + self._rates: list[np.ndarray] = [] + self._fits: list[float] = [] + self._errors: list[float] = [] + self._largest_turn = 0.0 + + def _take_in(self, head_track: Sequence[tuple[float, Any]]) -> None: + """Keep the head poses that arrived, for the reader of the head track and to find a picture's between.""" + arrived = [(float(seconds), _usable(pose)) for seconds, pose in head_track] + latest = self._track[-1][0] if self._track else -np.inf + for seconds, pose in arrived: + # A pose that is none, or not later than the last, places nothing. + if pose is not None and seconds > latest: + self._track.append((seconds, pose)) + latest = seconds + if self._track: + while self._track[0][0] < latest - _POSE_MEMORY_S: + self._track.popleft() + usable = [(seconds, pose) for seconds, pose in arrived if pose is not None] + if usable: + self._reader.add([seconds for seconds, _ in usable], [pose for _, pose in usable]) + + def _pose_at(self, seconds: float) -> np.ndarray | None: + """The head pose at a picture's time, from the two samples either side of it; None when the track + does not reach that time, or has a hole there.""" + earlier = later = None + for sample in self._track: + if sample[0] <= seconds: + earlier = sample + elif later is None: + later = sample + if earlier is None or later is None or later[0] - earlier[0] > MAX_POSE_GAP_S: + return None + return _between(earlier, later, seconds) + + def _carried(self, picture_seconds: float, head_board: np.ndarray) -> np.ndarray: + """How fast the head's own motion carries the board's place at a picture's time, in meters a second + along the world's axes: the place moves that far, per second of error in the picture's time. + ``head_board`` is the board in the head's forward-left-up frame. Zero where the track holds no pose + either side of the picture to read the motion from.""" + sides = [] + for seconds in (picture_seconds - _RATE_SPAN_S, picture_seconds, picture_seconds + _RATE_SPAN_S): + pose = self._pose_at(seconds) + if pose is not None: + sides.append((seconds, (openxr_poses_to_flu(pose) @ head_board)[:3, 3])) + if len(sides) < 2: + return np.zeros(3) + (start, first), (end, last) = sides[0], sides[-1] + return (last - first) / (end - start) + + def _head_state( + self, picture_seconds: float, head_track: Sequence[tuple[float, Any]] + ) -> tuple[np.ndarray | None, str | None]: + """The head pose at the picture's time in the world's forward-left-up axes, or why there is none to + use. A leap starts the check over, and so does a lost position: the headset's world is then another.""" + self._take_in(head_track) + per_degree = self._reader.reading() + unusable = self._reader.unusable_spans + lost = (per_degree is not None and per_degree < TRACK_FROZEN_M_PER_DEG) or bool( + unusable and picture_seconds <= unusable[-1][1] + ) + # The stretch this picture lies in, not how many there have been: a position that leaps away and back + # returns to its first stretch and adds none, and what was fixed while it was away is in the other. + stretch = int(self._reader.stretches([picture_seconds])[0]) + leapt = stretch >= 0 and stretch != self._stretch + if stretch >= 0: + self._stretch = stretch + if (lost or leapt) and (self._anchor is not None or self._fixing): + self._restarts += 1 + self._start_over() + if lost: + return None, HEAD_LOST + pose = self._pose_at(picture_seconds) + if pose is None: + return None, NO_HEAD_POSE + return openxr_poses_to_flu(pose), None + + def _board_view(self, frame: np.ndarray) -> tuple[BoardView | None, str | None]: + """The board as one picture shows it, in the full picture's pixels, or why it cannot be used.""" + gray = as_gray(frame) + detection = self._detector.detect(gray) + if detection is None: + return None, NOT_FOUND + # Corners are placed in the picture's own pixels, whatever size the frame was handed in at. + scale = (self._size[0] / gray.shape[1], self._size[1] / gray.shape[0]) + points = (detection.corners.astype(np.float64) * scale).astype(np.float32) + view = BoardView(0, detection.ids, points, self._detector.object_points(detection)) + if view.corners < MIN_CORNERS: + return view, TOO_LITTLE + return view, None + + def _fix(self, world_board: np.ndarray, world_head: np.ndarray, fit: float, rate: np.ndarray) -> bool: + """Take one more view towards the board's place, and fix it once there are enough. False, with the + view left out, for one taken while the head was moving: its place is off by any error in the lag.""" + if float(np.linalg.norm(rate)) > STILL_M_PER_S: + return False + self._fixing.append((world_board, world_head, fit, rate)) + if len(self._fixing) < ANCHOR_VIEWS: + return True + places = np.asarray([board[:3, 3] for board, _, _, _ in self._fixing]) + # The view nearest the middle of them all: a pose that was really seen, not an average of turns. + middle = int(np.argmin(np.linalg.norm(places - np.median(places, axis=0), axis=1))) + self._anchor, self._anchor_head, fitted, carried = self._fixing[middle] + self._positions, self._heads, self._rates = [self._anchor[:3, 3]], [self._anchor_head], [carried] + self._fits = [fitted] + self._fixing = [] + return True + + def _test( + self, + view: BoardView, + world_camera: np.ndarray, + camera_board: np.ndarray, + world_head: np.ndarray, + fit: float, + rate: np.ndarray, + ) -> tuple[float | None, list[list[float]]]: + """Hold one view against the board's fixed place: the error in pixels between the corners seen and + the corners the head pose predicts, and where those are predicted. Counted towards the verdict only + when the head has moved from where the place was fixed: seen from there, any files predict it right.""" + predicted_pose = invert_pose(world_camera) @ self._anchor + error = reprojection_rms(view, predicted_pose, self._camera) + board = view.object_points.astype(np.float64) + points = project(board @ predicted_pose[:3, :3].T + predicted_pose[:3, 3], self._camera) + # A board predicted behind the camera, or past what the lens model reaches, has no pixels to draw. + if not np.isfinite(error) or not np.all(np.isfinite(points)): + return None, [] + turn = _turn_deg(world_head, self._anchor_head) + shift = float(np.linalg.norm(world_head[:3, 3] - self._anchor_head[:3, 3])) + if turn >= MOVED_TURN_DEG or shift >= MOVED_SHIFT_M: + self._errors.append(error) + self._positions.append((world_camera @ camera_board)[:3, 3]) + self._heads.append(world_head) + self._rates.append(rate) + self._fits.append(fit) + self._largest_turn = max(self._largest_turn, turn) + return error, points.tolist() + + def _implied(self) -> tuple[float, float, float | None]: + """What the board's wander implies of the files, over the view the place was fixed from and those + that tested it: how far the camera sits from where the file has it, how closely the views pin that, + and how far the camera's lag is off (None when the views cannot tell a lag from their own noise). + + The board stood still at ``c``. A camera that sits ``d`` from its file, in the headset's axes, puts + the board at ``c + R d`` in a view whose head is turned by ``R``; pictures that are ``t`` seconds + older than their stored lag says put it ``t`` times the speed the head carried its place at further + on. ``c``, ``d`` and ``t`` are found together by least squares, each with how closely the views pin + it. A positive lag means the pictures are older than the file says. + """ + heads, rates = np.asarray(self._heads), np.asarray(self._rates) + places = np.asarray(self._positions).reshape(-1) + turned = np.concatenate([np.hstack([np.eye(3), head[:3, :3]]) for head in heads]) + lag = None + # A lag shows only in pictures taken while the head moved; with none, there is no column to fit. + if np.any(rates): + answer, pinned = _least_squares(np.hstack([turned, rates.reshape(-1, 1)]), places) + if _told(abs(float(answer[6])), float(np.sqrt(pinned[6, 6])), CAMERA_LAG_OFF_S[0]): + lag = float(answer[6]) + if lag is None: + answer, pinned = _least_squares(turned, places) + # Along the direction the views pin least. + loosest = float(np.sqrt(np.linalg.eigvalsh(pinned[3:6, 3:6]).max())) + return float(np.linalg.norm(answer[3:6])), loosest, lag + + def _judged(self, spread: float, pnp: float) -> dict[str, Any]: + """The verdict on views that are enough by their count, or why there is none yet, with the offset + and the lag the wander implies and what is to be said beside the verdict.""" + nothing = {"verdict": None, "camera_offset_m": None, "camera_offset_uncertainty_m": None} + nothing = {**nothing, "camera_lag_off_s": None, "notes": []} + # A camera's offset along an axis shows only in turns about the other two, as in a solve: until the + # head has turned about a second axis there is an offset no view tests, and no fit to find it by. + if head_turn_problem(np.asarray(self._heads)) is not None: + return {**nothing, "no_verdict": SECOND_AXIS} + offset, uncertainty, lag = self._implied() + implied = {"camera_offset_m": offset, "camera_offset_uncertainty_m": uncertainty, "camera_lag_off_s": lag} + fit = grade_extrinsics(spread, pnp) + # A wander or a fit that is bad stays bad whatever the offset turns out to be. Short of that, an + # offset the views leave open cannot be told from a sound one. + if fit != BAD and not _told(offset, uncertainty, EXTRINSICS_UNCERTAINTY_M[0]): + return {**nothing, **implied, "no_verdict": NOT_PINNED} + grades = [fit, grade_under(offset, EXTRINSICS_UNCERTAINTY_M)] + if lag is not None: + grades.append(grade_under(abs(lag), CAMERA_LAG_OFF_S)) + notes = [] if lag is not None else [LAG_UNTESTED] + return {**implied, "verdict": worst_grade(grades), "no_verdict": None, "notes": notes} + + def _figures(self) -> dict[str, Any]: + """What the tested views amount to, and the verdict once they can carry one.""" + errors = np.asarray(self._errors) + views = len(errors) + spread = pnp = None + if views: + # The solve's own two figures, over the view the place was fixed from and those that tested it: + # how far the board, which never moved, seems to stand from view to view, and how well its poses + # fit the picture. + spread = float(np.linalg.norm(np.asarray(self._positions).std(axis=0))) + pnp = float(np.mean(self._fits)) + judged = {"verdict": None, "no_verdict": None, "camera_offset_m": None, "notes": []} + judged = {**judged, "camera_offset_uncertainty_m": None, "camera_lag_off_s": None} + if views >= VIEWS_NEEDED and self._largest_turn >= TURN_NEEDED_DEG: + judged = self._judged(spread, pnp) + return { + "views": views, + "views_needed": VIEWS_NEEDED, + "head_turn_deg": self._largest_turn, + "head_turn_needed_deg": TURN_NEEDED_DEG, + "rms_px": float(np.sqrt(np.mean(errors**2))) if views else None, + "worst_px": float(errors.max()) if views else None, + "board_wander_m": spread, + "pose_fit_px": pnp, + "limits": { + "board_wander_m": list(EXTRINSICS_SPREAD_M), + "pose_fit_px": list(EXTRINSICS_PNP_RMS_PX), + "camera_offset_m": list(EXTRINSICS_UNCERTAINTY_M), + "camera_lag_off_s": list(CAMERA_LAG_OFF_S), + }, + # Enough has been seen once there is a verdict: views that cannot carry one are not enough yet. + "enough": judged["verdict"] is not None, + **judged, + } + + def observe( + self, frame: np.ndarray, picture_seconds: float, head_track: Sequence[tuple[float, Any]] = () + ) -> dict[str, Any]: + """Take in one picture (grayscale or BGR), the time it was taken at, and every head pose that arrived + since the last picture as ``(seconds, pose)`` pairs on the same clock, oldest first; poses are 4x4 + world-from-head in OpenXR axes. Returns what the check knows now, as plain JSON data. + + ``picture_seconds`` is the picture's time on the tracking's clock, the camera's lag behind the + tracking taken off. ``judged`` says whether this picture could be held against the calibration and + ``cannot_judge`` why not. ``error_px`` is this picture's error; ``corner_points`` and + ``predicted_points`` are where its corners are and where they were predicted, for an overlay. + ``verdict`` is the grade once the views can carry one and ``no_verdict`` why they cannot yet; + ``camera_offset_m`` and ``camera_lag_off_s`` are what the board's wander implies of the camera's + place and lag, and ``notes`` what is to be said beside the verdict. + """ + world_head, problem = self._head_state(picture_seconds, head_track) + view, unseen = self._board_view(frame) + seen = [] if view is None else view.image_points.astype(np.float64).tolist() + error, predicted = None, [] + problem = problem or unseen + posed = board_pose(view, self._camera) if problem is None else None + if problem is None and posed is None: + problem = TOO_LITTLE + if posed is not None: + camera_board, fit = posed + world_camera = world_head @ self._headset_camera + rate = self._carried(picture_seconds, self._headset_camera @ camera_board) + if self._anchor is not None: + error, predicted = self._test(view, world_camera, camera_board, world_head, fit, rate) + elif not self._fix(world_camera @ camera_board, world_head, fit, rate): + problem = HEAD_MOVING + figures = self._figures() + phase = FIXING if self._anchor is None else CHECKING + if problem is not None: + hint = problem + elif phase == FIXING: + hint = HOLD_STILL + elif figures["no_verdict"] is not None: + hint = TILT_TOO + else: + hint = ENOUGH if figures["enough"] else MOVE_HEAD + return { + "image_size_wh": list(self._size), + "phase": phase, + "fixing": {"views": len(self._fixing), "views_needed": ANCHOR_VIEWS}, + "judged": problem is None, + "cannot_judge": problem, + "board_visible": view is not None, + "corners": len(seen), + "corner_points": seen, + "predicted_points": predicted, + "error_px": error, + "restarts": self._restarts, + "hints": [hint], + **figures, + } diff --git a/examples/egocap/recording/egocap/calibration/provenance.py b/examples/egocap/recording/egocap/calibration/provenance.py new file mode 100644 index 0000000000..95ac493428 --- /dev/null +++ b/examples/egocap/recording/egocap/calibration/provenance.py @@ -0,0 +1,252 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What a calibration file says of how it came to be. + +Every calibration file this project's tools write states the layout it is written in, what made it, how its +solve was graded and the rule under which it may be installed, and, once installed, from when it is the +station's calibration and which file it replaced. All of it is added beside the keys a file already had: a +file from before these keys existed, or from another tool, reads as it always did, and a reader that knows +none of them loses nothing. + +Nothing here names the machine: no host, no account and no path. The operator who installed a file is in the +station's ledger, not in the file, which is copied into every session. +""" + +from __future__ import annotations + +import math +import re +from collections.abc import Mapping +from decimal import Decimal, InvalidOperation +from importlib import metadata +from typing import Any + +#: The layout of the calibration files this build writes, stated by each file under ``schema_version``. Raised +#: when a key a reader depends on changes its meaning or goes; adding a key does not raise it. +SCHEMA_VERSION = 1 +SCHEMA_VERSION_KEY = "schema_version" +#: The largest layout number read as itself. A file can state a number of any length; one beyond this is read +#: as this, which is newer than any layout this software will have, and is never printed. +LAYOUT_CEILING = 1_000_000 +#: A number written as text in plain digits: a sign, a fraction part and an exponent are taken, as another +#: tool's writer may put them, and nothing a number parser would also accept (names, underscores, other scripts). +_NUMBER_TEXT = re.compile(r"\+?(?P\d+\.?\d*|\.\d+)(?:[eE](?P[+-]?\d+))?", re.ASCII) +#: The key every other statement here is kept under, so that a file's own keys stay as they were. +PROVENANCE_KEY = "provenance" +#: The distribution the tools ship in; its version is the version of whatever solved a file. +SOFTWARE = "egocap" + +#: The solvers that make calibration files, as a file names them. +CAMERA_CALIBRATION = "camera_calibration" +WRIST_OFFSET_FIT = "wrist_offset_fit" +_TOOLS = (CAMERA_CALIBRATION, WRIST_OFFSET_FIT) +#: The grades a solve is given (grading.py); a kind of calibration that is not graded states a null. +_GRADES = ("excellent", "acceptable", "bad") +#: What a statement's ``evidence`` may hold: per hand, the figures an install rule was held against. A closed +#: set, so that nothing a caller happens to pass is written into a file every session copies. +EVIDENCE_HANDS = ("left", "right") +EVIDENCE_FIGURES = ("rms_px", "clicks", "frames", "at_translation_limit") +#: The longest install rule written; the rules are a sentence or two. +_MAX_RULE_CHARS = 300 + + +def software_version() -> str: + """The installed version of this software, or ``unknown`` where it runs without being installed.""" + try: + return metadata.version(SOFTWARE) + except metadata.PackageNotFoundError: + return "unknown" + + +def _figure(value: Any) -> tuple[bool, Any]: + """Whether ``value`` is a figure, and the figure as a strict JSON reader takes it: a number that is not + finite becomes a null.""" + if isinstance(value, (bool, int)): + return True, value + if isinstance(value, float): + return True, value if math.isfinite(value) else None + return False, None + + +def _closed_evidence(evidence: Mapping[str, Any]) -> dict[str, Any]: + """``evidence`` as a statement holds it: per hand a null or its known figures, and nothing else.""" + stated: dict[str, Any] = {} + for hand in EVIDENCE_HANDS: + if hand not in evidence: + continue + given = evidence[hand] + if given is None: + # A hand whose offset was not fitted this time says so with a null. + stated[hand] = None + elif isinstance(given, Mapping): + figures = ((key, _figure(given[key])) for key in EVIDENCE_FIGURES if key in given) + stated[hand] = {key: figure for key, (usable, figure) in figures if usable} + return stated + + +def stamp( + record: dict[str, Any], + *, + tool: str, + grade: str | None = None, + install_rule: str | None = None, + evidence: Mapping[str, Any] | None = None, +) -> None: + """State in ``record`` its layout, what made it, how it was graded and the rule it may be installed + under. In place, beside the record's own keys, which are left as they are. + + ``tool`` is the solver. ``grade`` is the solve's grade, None for a kind of calibration that has none. + ``install_rule`` is the rule in words. ``evidence`` is what the rule was held against, when the record's + own keys do not already say it. + + What is written is a closed set whatever is passed: the solver and the grade are ones this module knows + (``ValueError`` otherwise, with ``record`` unchanged), the rule is one bounded line, and of ``evidence`` + only each hand's known figures are kept. + """ + if tool not in _TOOLS: + raise ValueError(f"a calibration file is made by one of {', '.join(_TOOLS)}") + if grade is not None and grade not in _GRADES: + raise ValueError(f"a grade is one of {', '.join(_GRADES)}, or none") + if install_rule is not None and not isinstance(install_rule, str): + raise ValueError("an install rule is a sentence, or none") + statement: dict[str, Any] = { + "producer": {"software": SOFTWARE, "version": software_version(), "tool": tool}, + "grade": grade, + # One line: the rule is shown as a sentence, and a file is no place for a caller's paragraphs. + "install_rule": None if install_rule is None else " ".join(install_rule.split())[:_MAX_RULE_CHARS], + } + if evidence is not None: + statement["evidence"] = _closed_evidence(evidence) + record[SCHEMA_VERSION_KEY] = SCHEMA_VERSION + record[PROVENANCE_KEY] = statement + + +def with_validity( + record: Mapping[str, Any], *, valid_from: str, supersedes: Mapping[str, Any] | None +) -> dict[str, Any]: + """``record`` as an install writes it: stating from when it is the station's calibration and which file + it replaced. A copy; the caller's record is left as it was. + + A file is never rewritten once installed, since sessions hold its hash. It is superseded by the next file + installed under its name, which names it here by the hash of its bytes; None when it replaced nothing. + A record with no statement yet (one another tool made) gains one that holds only this. + """ + statement = record.get(PROVENANCE_KEY) + # What another tool left under the key and is no object cannot hold the stamp; an install states its own. + statement = dict(statement) if isinstance(statement, dict) else {} + statement["validity"] = { + "valid_from": valid_from, + "supersedes": None if supersedes is None else dict(supersedes), + } + return {**record, PROVENANCE_KEY: statement} + + +def without_validity(record: Mapping[str, Any]) -> dict[str, Any]: + """``record`` without what only an install states, for holding an installed file against the record it + was installed from. A statement that held nothing else goes with it.""" + statement = record.get(PROVENANCE_KEY) + if not isinstance(statement, dict) or "validity" not in statement: + return dict(record) + rest = {key: value for key, value in statement.items() if key != "validity"} + bare = {key: value for key, value in record.items() if key != PROVENANCE_KEY} + return {**bare, PROVENANCE_KEY: rest} if rest else bare + + +def _text(value: Any) -> str | None: + """``value`` when it is text, else None: a file edited by hand can hold anything under any key.""" + return value if isinstance(value, str) else None + + +def _whole(text: str) -> int | None: + """The whole number ``text`` writes out, of any length, held to :data:`LAYOUT_CEILING`; None when the text + is no number or the number is not whole.""" + written = _NUMBER_TEXT.fullmatch(text.strip()) + if written is None: + return None + try: + # Exact at any length: a float would round, and a whole number of thousands of digits has no int(). + number = Decimal(written.group(0)) + except InvalidOperation: + # Only an exponent beyond what any number type holds is left to fail. Such a number is past the + # ceiling when it is not zero and its exponent is not negative, and is no layout otherwise. + grows = not (written.group("exponent") or "-").startswith("-") + return LAYOUT_CEILING if grows and written.group("digits").strip("0.") else None + if number != number.to_integral_value(): + return None + return int(min(number, LAYOUT_CEILING)) + + +def _layout(value: Any) -> int | None: + """The layout number a file states under ``schema_version``, however it wrote the number: a whole number, + a float with a whole value, or either of them as text. None for anything else, which states no layout. + + Another tool, or a hand, writes a number its own way; a newer layout read as "none stated" would be read + as the layout before the key existed. A number beyond :data:`LAYOUT_CEILING` is read as the ceiling: it + is newer than this build reads whatever it is, and a file must not be able to make a reader fail, or a + sentence endless, by the length of a number. + """ + # A bool is a whole number to Python, and no layout is version True. + if type(value) is int: + return min(value, LAYOUT_CEILING) + if isinstance(value, float) and math.isfinite(value) and value == int(value): + return min(int(value), LAYOUT_CEILING) + if isinstance(value, str): + return _whole(value) + return None + + +def read(record: Mapping[str, Any]) -> dict[str, Any]: + """What a calibration file's record states of how it came to be, whatever it holds. + + Every field is present: the schema version (a whole number or None, read from however the file wrote the + number and held to :data:`LAYOUT_CEILING`), the producer's software, version and tool, the grade, the + install rule, and the time it stands + from, each text or None. A file from before these keys existed gives None throughout. The text is as the + file holds it; a caller that shows it makes it fit to show. + """ + statement = record.get(PROVENANCE_KEY) + statement = statement if isinstance(statement, dict) else {} + producer = statement.get("producer") + producer = producer if isinstance(producer, dict) else {} + validity = statement.get("validity") + validity = validity if isinstance(validity, dict) else {} + return { + SCHEMA_VERSION_KEY: _layout(record.get(SCHEMA_VERSION_KEY)), + "software": _text(producer.get("software")), + "version": _text(producer.get("version")), + "tool": _text(producer.get("tool")), + "grade": _text(statement.get("grade")), + "install_rule": _text(statement.get("install_rule")), + "valid_from": _text(validity.get("valid_from")), + } + + +def newer_layout(record: Mapping[str, Any]) -> str | None: + """How the layout a calibration file's ``record`` states is named in a sentence, when it is newer than + this build reads: ``layout 2``. None when this build reads the file. + + A file that states no layout, or anything that is not a layout number, is read as the files written + before the key existed are. A number at the ceiling is named without being printed. + """ + version = read(record)[SCHEMA_VERSION_KEY] + if version is None or version <= SCHEMA_VERSION: + return None + return f"layout {version}" if version < LAYOUT_CEILING else "a layout far newer than any this software knows" + + +def layout_problem(record: Mapping[str, Any], name: str) -> str | None: + """Why the calibration file ``name``, whose content is ``record``, cannot be read by this build; None + when it can. + + Only a file that states a layout newer than this build writes (:func:`newer_layout`): its keys may no + longer mean what a reader here takes them to mean. The sentence is written for an operator. + """ + newer = newer_layout(record) + if newer is None: + return None + return ( + f"{name} is written in {newer}, and this software reads up to layout {SCHEMA_VERSION}: " + "update the software, or calibrate again with this one" + ) diff --git a/examples/egocap/recording/egocap/calibration/station_store.py b/examples/egocap/recording/egocap/calibration/station_store.py index 31909a16fe..55c4edf3b6 100644 --- a/examples/egocap/recording/egocap/calibration/station_store.py +++ b/examples/egocap/recording/egocap/calibration/station_store.py @@ -12,6 +12,8 @@ from __future__ import annotations import fcntl +import hashlib +import json import logging import math import os @@ -24,6 +26,7 @@ from pathlib import Path from typing import Any +from . import provenance from .files import ( HEAD_EXTRINSICS, HEAD_INTRINSICS, @@ -155,6 +158,10 @@ def _shown_entry(entry: dict[str, Any]) -> dict[str, Any]: if isinstance(entry.get("operator"), str): shown["operator"] = _one_line(entry["operator"], MAX_OPERATOR_LENGTH) shown["files"] = _known_files(entry.get("files")) + # Said only where it says something: the entry's own files that its last install left as they were. + unchanged = [name for name in _known_files(entry.get("unchanged")) if name in shown["files"]] + if unchanged: + shown["unchanged"] = unchanged return shown @@ -202,10 +209,15 @@ def _exclusive(directory: Path) -> Iterator[None]: os.close(handle) -def _note(directory: Path, kind: str, name: str, operator: Any, moment: datetime) -> dict[str, Any]: +def _note( + directory: Path, kind: str, name: str, operator: Any, moment: datetime, changed: bool = True +) -> dict[str, Any]: """Record in the ledger that ``name`` was installed under ``kind`` at ``moment``; returns the entry. - The ledger is read, changed and written back whole, so the caller holds the directory (``_exclusive``). + With ``changed`` false the install found the record already installed and left the file as it was: the + entry then lists the file under ``unchanged`` as well, so that nothing reads the note as a calibration + that was made. The ledger is read, changed and written back whole, so the caller holds the directory + (``_exclusive``). """ # Bounded as the name itself is, so the ledger holds every accepted name whole, as the takes carry it. day, who = moment.strftime("%Y-%m-%d"), _one_line(operator, MAX_OPERATOR_LENGTH) @@ -219,6 +231,13 @@ def _note(directory: Path, kind: str, name: str, operator: Any, moment: datetime # Installed again, a file moves to the end and is not listed twice. files = [*(listed for listed in earlier if listed != name), name] entry = {"date": day, "at": moment.isoformat(timespec="seconds"), "operator": who, "files": files} + # What the same operator's earlier installs of the day left unchanged still is, until that file is really + # replaced. The key is written only when it names a file, so an entry of real installs reads as it always did. + noted = _known_files(previous.get("unchanged")) if same else [] + left = [listed for listed in noted if listed in earlier and listed != name] + unchanged = left if changed else [*left, name] + if unchanged: + entry["unchanged"] = unchanged entries[kind] = entry try: write_json(directory / LEDGER_NAME, entries) @@ -286,6 +305,46 @@ def _keep_replaced(directory: Path, name: str, destination: Path) -> None: os.fsync(handle.fileno()) +def _made_at(content: bytes) -> str | None: + """When a calibration file says it was made, carried on only when it is a date and time, and then in the + one form this store writes dates in. The key may hold anything in a file placed by hand, and what is + carried is copied into every later file and session: the date as read, never the text as written, which + may be a date followed by any length of digits.""" + try: + return datetime.fromisoformat(json.loads(content).get("calibrated_at")).isoformat() + except (ValueError, TypeError, AttributeError, RecursionError): + # No JSON object, no such key, or nothing that reads as a time. + return None + + +def _superseded(directory: Path, name: str) -> dict[str, Any] | None: + """The installed ``name`` as the file that replaces it names it: the hash of its bytes and, where it + says, when it was made. None when nothing is installed. A file that is there and cannot be read is + replaced all the same, and is named with no hash: that something was replaced is still said.""" + path = directory / name + if not os.path.lexists(path): + return None + try: + current = path.read_bytes() + except OSError: + return {"sha256": None, "calibrated_at": None} + return {"sha256": hashlib.sha256(current).hexdigest(), "calibrated_at": _made_at(current)} + + +def _is_installed(directory: Path, name: str, record: dict[str, Any]) -> bool: + """Whether the installed ``name`` is an install of ``record``: the same content with only what an + install adds beside it. A copy placed by hand without that is not one.""" + try: + current = json.loads((directory / name).read_bytes()) + except (OSError, ValueError, RecursionError): + return False + if not isinstance(current, dict): + return False + statement = current.get(provenance.PROVENANCE_KEY) + installed = isinstance(statement, dict) and "validity" in statement + return installed and provenance.without_validity(current) == record + + def install( directory: Path, name: str, @@ -301,6 +360,11 @@ def install( ``kind`` groups the files of one calibration in the ledger. With ``archive`` a dated copy is kept under ``history`` so an earlier calibration can be recovered, and so is the file being replaced when the archive does not already hold it. ``StationStoreError`` for a name, kind or record that is not acceptable. + + The file written is ``record`` with what only an install knows added (``provenance.with_validity``): the + moment it became the station's calibration and the file it replaced. ``record`` itself is not changed; + ``provenance.without_validity`` of the file's content is the record again. Installing the record that is + already installed writes no file and only notes the ledger, where the entry names the file as unchanged. """ # Reachable from a web route: only the station's own file names are ever joined to the directory, and # what was sent is not echoed back. @@ -321,6 +385,15 @@ def install( # own day. Read once the directory is held: an install that waited its turn must not be archived # as earlier than the one that went in ahead of it. moment = now or datetime.now().astimezone() + # The record that is already installed stays as it is: sessions hold the file's hash, and a file that + # superseded its own earlier install would say the calibration changed when it did not. Who installed + # it again, and when, is the ledger's to say. + if _is_installed(directory, name, record): + return _note(directory, kind, name, operator, moment, changed=False) + # Stated before either copy is written, so the archive and the live file say the same. + record = provenance.with_validity( + record, valid_from=moment.isoformat(timespec="seconds"), supersedes=_superseded(directory, name) + ) if archive: day = directory / HISTORY_DIR / moment.strftime("%Y-%m-%d") day.mkdir(parents=True, exist_ok=True) @@ -382,7 +455,10 @@ def installed(directory: Path) -> list[dict[str, Any]]: def done_today(directory: Path, kind: str, today: date) -> bool: - """Whether the ledger says a calibration of ``kind`` was installed on the day ``today``.""" + """Whether the ledger says a calibration of ``kind`` was installed on the day ``today``. A note of + installs that all found their record already installed is not one: nothing was calibrated.""" # Only a well-formed entry counts: the ledger may have been edited by hand. entry = ledger(directory).get(kind) - return isinstance(entry, dict) and entry.get("date") == today.strftime("%Y-%m-%d") + if not isinstance(entry, dict) or entry.get("date") != today.strftime("%Y-%m-%d"): + return False + return not entry["files"] or set(entry.get("unchanged", ())) != set(entry["files"]) diff --git a/examples/egocap/recording/egocap/calibration/wrist_offset.py b/examples/egocap/recording/egocap/calibration/wrist_offset.py index d7f534b03f..02bdeed811 100644 --- a/examples/egocap/recording/egocap/calibration/wrist_offset.py +++ b/examples/egocap/recording/egocap/calibration/wrist_offset.py @@ -22,8 +22,16 @@ from scipy.optimize import least_squares from scipy.spatial.transform import Rotation +from egocap.calibration import provenance from egocap.calibration.camera_model import project -from egocap.calibration.files import OPENXR_POSES, POSE_SOURCE_KEY, WRIST_OFFSETS, CalibrationFileError, Intrinsics +from egocap.calibration.files import ( + OPENXR_POSES, + POSE_SOURCE_KEY, + WRIST_OFFSETS, + CalibrationFileError, + Intrinsics, + refuse_newer_layout, +) from egocap.calibration.frames import R_FLU_FROM_OPENXR, euler_pose, homogeneous, invert_pose _LOG = logging.getLogger("isaaccapture.egocap.wrist_offset") @@ -391,11 +399,20 @@ def optimize( def offsets_record( - offsets: Mapping[str, WristOffset], *, n_samples: int, now: datetime | None = None + offsets: Mapping[str, WristOffset], + *, + n_samples: int, + now: datetime | None = None, + install_rule: str | None = None, + fits: Mapping[str, Mapping[str, Any] | None] | None = None, ) -> dict[str, Any]: """The saved file's content for both hands' offsets, fitted on ``n_samples`` frames. ``now`` is the calibration time and defaults to the present; it is written with its offset from UTC. + ``install_rule`` is the rule the caller holds an install to, in words, and ``fits`` what it held it + against: per hand, the fit's figures, or None for a hand whose offset was not fitted this time. Both are + stated under the file's ``provenance``, beside what made it; the keys readers of the offsets use are as + they were. A wrist-offset fit has no grade, and the file says so with a null. """ # A time without a zone is taken as local, so the stamp always says how far it is from UTC. moment = (datetime.now() if now is None else now).astimezone() @@ -417,6 +434,13 @@ def offsets_record( f"hand_{side}_pico_rotation": rotation.tolist(), f"hand_{side}_pico_translation": translation.tolist(), } + # A hand the caller names no fit for kept the offset it had: said as a null, never left out. + evidence = None + if fits is not None: + evidence = {side: None if fits.get(side) is None else dict(fits[side]) for side in SIDES} + provenance.stamp( + record, tool=provenance.WRIST_OFFSET_FIT, grade=None, install_rule=install_rule, evidence=evidence + ) return record @@ -446,6 +470,7 @@ def offsets_from_record(record: Mapping[str, Any], name: str = WRIST_OFFSETS) -> record's ``pose_source`` stamp to say, and ``files.pose_source_problem`` reads it: a caller that builds on the offsets asks that first, since another tracking source's offsets have this very shape. """ + refuse_newer_layout(record, name) offsets = {} for side in SIDES: entry = record.get(side) diff --git a/examples/egocap/recording/egocap/data_processing/update_episode_task_description.py b/examples/egocap/recording/egocap/data_processing/update_episode_task_description.py index 84d3ce0a16..63a56e50f9 100644 --- a/examples/egocap/recording/egocap/data_processing/update_episode_task_description.py +++ b/examples/egocap/recording/egocap/data_processing/update_episode_task_description.py @@ -10,16 +10,33 @@ ``total_data_time_hours``, plus seed-style ``discarded_*`` fields). The backend's end-of-day correction route (``POST /api/day-report/correct``) calls this with a -task only. Studio and relocation are for offline callers: one that also sets "Studio (metadata)" +task only, and its studio correction (``POST /api/day-report/studio``) calls +:func:`plan_session_studio`, which relabels a whole session where it lies and can move nothing. +Relocation is for offline callers of legacy sessions: one that also sets "Studio (metadata)" should call :func:`relocate_session_to_canonical_studio` first, so the whole session tree moves like a **properly routed** record under ``…/EOD///``. + +Both corrections are all or nothing as far as files allow: every file one will rewrite is opened and +checked before the first write, and when a write still fails the files already written are put +back, so a correction that answers with a failure leaves the session saying what it said. What a +failed correction says of the session is read from the disk, not taken from which calls raised. +Each file is replaced whole through a temporary file beside it, keeps the permissions it had, and +is synced with its directory, as the recorder writes the same files. """ from __future__ import annotations +import contextlib +import fnmatch +import json +import logging import os import re +import stat import tempfile +import time +import unicodedata +from collections.abc import Callable, Iterator from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -39,6 +56,8 @@ ) from egocap.studio.task_library_data import TASK_LIBRARY +logger = logging.getLogger("isaaccapture.egocap.update_episode_task_description") + _EPISODE_RE = re.compile(r"^(\d+)(?:-(\d+))?$") #: No session holds this many takes; a longer range is a slip of the hand, refused before it is walked. MAX_EPISODE_SPAN = 10_000 @@ -71,53 +90,180 @@ def _parse_episode_arg(spec: str) -> range: return range(a, b + 1) +class SessionConfigError(ValueError): + """A session's ``config.yaml`` that a correction will not rewrite, in a sentence that names no directory.""" + + +#: What goes before the name of a file of the time-aligned copy, to tell it from the session's own. +_OF_THE_COPY = "the time-aligned copy's " + + +def _session_config(zarr_root: Path, name: str = "config.yaml") -> dict[str, Any] | None: + """A session's ``config.yaml`` as a correction rewrites it: the mapping it holds, or None when the session + has none. :class:`SessionConfigError` for one that cannot be read or is not a mapping: rewriting it would + replace whatever it holds with the label alone. ``name`` is what the file is called in that sentence.""" + path = zarr_root / "config.yaml" + if not path.is_file(): + return None + try: + data = yaml.safe_load(path.read_bytes()) + except (OSError, ValueError, yaml.YAMLError) as exc: + raise SessionConfigError(f"{name} cannot be read") from exc + # An empty file holds nothing to lose, and is given a meta of its own. + data = {} if data is None else data + if not isinstance(data, dict) or not isinstance(data.get("meta", {}), dict): + raise SessionConfigError(f"{name} does not hold the session's settings") + return data + + def _update_session_config_yaml( zarr_root: Path, *, task_description: str | None, task_name: str, studio: str, + data: dict[str, Any] | None = None, ) -> bool: - """Returns True if ``config.yaml``'s ``meta`` was updated and written, - False if it was absent or the write failed -- the caller surfaces this - on the result rather than letting a failure pass silently. A ``task_description`` - of None leaves the session's task as it is.""" - cfg_p = zarr_root / "config.yaml" - if not cfg_p.is_file(): + """Write the labels into ``config.yaml``'s ``meta``. True when it was written; False only when the session + has no ``config.yaml``. A file that is there and is not rewritten is a failure and raises, never a False: + with no root group it is the one place the session's own label lives. + + A ``task_description`` of None leaves the session's task as it is. ``data`` is the file's content when the + caller has already read it. + """ + data = _session_config(zarr_root) if data is None else data + if data is None: return False + meta = dict(data.get("meta", {})) + if task_description is not None: + meta["task_description"] = task_description + if task_name: + meta["task_name"] = task_name + if studio: + meta["studio"] = studio + _replace_yaml(zarr_root / "config.yaml", {**data, "meta": meta}) + return True + + +def _mode_of(path: Path) -> int | None: + """A file's permission bits, or None when there is no such file yet.""" try: - with open(cfg_p, encoding="utf-8") as f: - data: Any = yaml.safe_load(f) or {} - if not isinstance(data, dict): - data = {} - meta: dict = data.get("meta") # type: ignore[assignment] - if not isinstance(meta, dict): - meta = {} - if task_description is not None: - meta["task_description"] = task_description - if task_name: - meta["task_name"] = task_name - if studio: - meta["studio"] = studio - data["meta"] = meta - _replace_yaml(cfg_p, data) - return True - except (OSError, TypeError, yaml.YAMLError): - return False + return stat.S_IMODE(os.stat(path).st_mode) + except FileNotFoundError: + return None -def _replace_yaml(path: Path, data: Any) -> None: - """Replace a YAML file through a temporary file beside it, so a crash never leaves half of one.""" +def _sync_directory(directory: Path) -> None: + """Flush a directory's entries to stable storage, so a replaced file outlives a power cut.""" + fd = os.open(directory, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def _replace_file(path: Path, content: bytes) -> None: + """Replace ``path`` whole with ``content`` through a temporary file beside it, so a crash never leaves half + of one. The new file keeps the permissions of the one it replaces, and it and its directory are synced, + as the recorder writes the same files.""" + mode = _mode_of(path) fd, staged = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - yaml.dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False) - f.flush() - os.fsync(f.fileno()) + with os.fdopen(fd, "wb") as handle: + handle.write(content) + handle.flush() + # A temporary file is made owner-only; the file it replaces may have been opened to others. + if mode is not None: + os.fchmod(handle.fileno(), mode) + os.fsync(handle.fileno()) os.replace(staged, path) except BaseException: Path(staged).unlink(missing_ok=True) raise + _sync_directory(path.parent) + + +def _replace_yaml(path: Path, data: Any) -> None: + """Replace a YAML file whole (see :func:`_replace_file`), written as the recorder writes it: text outside + ASCII is escaped, so a reader that opens the file in its locale's encoding reads what was recorded.""" + text = yaml.safe_dump(data, default_flow_style=False, sort_keys=False) + _replace_file(path, text.encode("utf-8")) + + +def _replace_json(path: Path, document: Any) -> None: + """Replace a group's metadata file whole (see :func:`_replace_file`), in the layout Zarr and the recorder + write it in, so a rewritten file differs from the one it replaces in the label alone.""" + _replace_file(path, json.dumps(document, indent=2).encode("utf-8")) + + +#: The staging files an interrupted correction can leave beside the file it was replacing: Zarr's own (the +#: task correction writes group metadata through Zarr), this module's for a group's metadata in either Zarr +#: format, and for ``config.yaml``. +STRAY_PATTERNS = ("zarr.*.partial", ".zarr.json.*.tmp", "..zattrs.*.tmp", ".config.yaml.*.tmp") +#: How old a staging file is before it is taken for a stray. A writer renames its staging file within +#: moments of making it, and one that the caller's locks do not cover (a time-aligner run by hand) must not +#: lose the file it is about to rename. +STRAY_MIN_AGE_S = 60.0 + + +def _is_stray(entry: Path, now: float) -> bool: + """Whether a directory entry is a staging file an interrupted correction left: a regular file, named as + one of :data:`STRAY_PATTERNS`, and no younger than :data:`STRAY_MIN_AGE_S`.""" + if not any(fnmatch.fnmatchcase(entry.name, pattern) for pattern in STRAY_PATTERNS): + return False + found = entry.lstat() + return stat.S_ISREG(found.st_mode) and now - found.st_mtime >= STRAY_MIN_AGE_S + + +def remove_interrupted_writes(zarr_root: Path, now: float | None = None) -> list[str]: + """Remove the staging files a correction that was killed part-way left in a session: in the session, in + each of its episodes, and the same in its time-aligned copy. Returns what was removed, relative to the + session's parent. ``now`` is the time staging files are aged against; the clock's when not given. + + Only regular files whose names are one of :data:`STRAY_PATTERNS`, directly in those directories: nothing a + recording holds is named so. A staging file younger than a minute is left, since a writer outside the + caller's locks may be about to rename it. One that cannot be removed, or a folder that cannot be listed, + is left too and not raised: the correction's own check then names the folder that cannot be rewritten. + """ + zarr_root = zarr_root.expanduser().resolve() + now = time.time() if now is None else now + removed = [] + for holder in (zarr_root, zarr_root.with_name(f"{zarr_root.name}_aligned")): + if not holder.is_dir() or holder.is_symlink(): + continue + episodes = [holder / key for key in _finalized_keys(_episode_keys(holder, None))] + for directory in (holder, *episodes): + try: + for entry in sorted(directory.iterdir()): + if _is_stray(entry, now): + entry.unlink() + removed.append(entry.relative_to(zarr_root.parent).as_posix()) + except OSError as failure: + logger.warning("Staging files of an interrupted correction were left in place: %s", failure) + return removed + + +@contextlib.contextmanager +def _metadata_kept(directory: Path) -> Iterator[None]: + """Around a write of a group's attributes through Zarr, which replaces the group's metadata file: give + the new file the permissions of the one it replaced, and sync it and its directory.""" + path = _metadata_file(directory) + mode = _mode_of(path) + yield + if mode is not None: + os.chmod(path, mode) + fd = os.open(path, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + _sync_directory(directory) + + +def _metadata_file(directory: Path) -> Path: + """The file a Zarr group keeps its attributes in: ``zarr.json`` in format 3, ``.zattrs`` in format 2.""" + current = directory / "zarr.json" + return current if current.is_file() else directory / ".zattrs" @dataclass @@ -130,6 +276,8 @@ class EpisodeTaskUpdateResult: missing_episodes: list[str] = field(default_factory=list) aggregates_refreshed: bool = False config_yaml_updated: bool = False + #: Whether the correction covered every finalized episode, so that the session's own task was changed too. + session_task_updated: bool = False def _relabel_episode(group: Any, task_description: str, task_name: str, studio: str) -> None: @@ -158,26 +306,37 @@ def _episode_keys(zarr_root: Path, store: Any | None) -> list[str]: def _update_aligned_copy( - aligned_root: Path, indices: range, task_description: str, task_name: str, studio: str, whole: bool + aligned_root: Path, + indices: range, + task_description: str, + task_name: str, + studio: str, + whole: bool, + config: dict[str, Any] | None, ) -> None: """Apply the same task, name and studio metadata to an aligned copy's episodes and, when the correction - covers the ``whole`` session, to its root and ``config.yaml``.""" + covers the ``whole`` session, to its root and ``config.yaml``, whose content is ``config``.""" # Opened, never created: a directory that is not an aligned copy must not become one. store = zarr.open(str(aligned_root), mode="r+") - if whole: - store.attrs["task_description"] = task_description - if task_name: - store.attrs["task_name"] = task_name - if studio: - store.attrs["studio"] = studio + # The copy's own labels change only with a correction of the whole session, or of its studio. + if whole or studio: + with _metadata_kept(aligned_root): + if whole: + store.attrs["task_description"] = task_description + if task_name: + store.attrs["task_name"] = task_name + if studio: + store.attrs["studio"] = studio for n in indices: if f"episode_{n}" in store: - _relabel_episode(store[f"episode_{n}"], task_description, task_name, studio) + with _metadata_kept(aligned_root / f"episode_{n}"): + _relabel_episode(store[f"episode_{n}"], task_description, task_name, studio) _update_session_config_yaml( aligned_root, task_description=task_description if whole else None, task_name=task_name if whole else "", studio=studio, + data=config, ) @@ -189,12 +348,23 @@ def update_episode_task_description( task_name: str = "", studio: str = "", relocate: bool = False, + on_session_task_change: Callable[[], None] | None = None, ) -> EpisodeTaskUpdateResult: """Backfill task/studio metadata for the episodes of a recorded session that ``episodes`` names, on the session and on its time-aligned copy; episodes it names that do not exist are reported, not created. Nothing is created: a session whose episodes are groups of their own keeps having no root group, and a session that holds none of the named episodes is left exactly as it was. + + All or nothing as far as files allow, as the studio relabel is. Before the first write every file the + correction will rewrite, of the session and of its time-aligned copy, is read and checked to be + rewritable: a ``config.yaml`` that cannot be read or is not a mapping is refused + (:class:`SessionConfigError`), and so is a take whose metadata cannot be read or whose folder is + read-only (:class:`RelabelError`, naming the take), with nothing changed. When a write still fails, the + files already written are put back and :class:`RelabelError` says what the session holds now. + + ``on_session_task_change`` is called once, after those checks and before the first write, when the + correction covers every finalized episode and so changes the session's own task as well. """ zarr_root = zarr_root.expanduser().resolve() if relocate and not (studio or "").strip(): @@ -216,7 +386,7 @@ def update_episode_task_description( if studio: # Falls back to the already-truthy `studio` when canonicalization # yields nothing, so studio_stored is always truthy here. - studio_stored = canonicalize_studio_dir_name(sanitize_studio_dir_name(studio), known) or studio + studio_stored = stored_studio_name(studio) or studio result = EpisodeTaskUpdateResult(zarr_root=zarr_root, studio_stored=studio_stored) named = [f"episode_{n}" for n in indices] result.missing_episodes = [key for key in named if key not in keys] @@ -229,18 +399,70 @@ def update_episode_task_description( # covers all of them; correcting some takes of a session must not relabel the rest. finalized = {index for index in map(_episode_index_from_key, keys) if index is not None} whole = all(index in indices for index in finalized) + # The time-aligned copy beside the session carries the same metadata, so it is updated with it. + aligned_root = zarr_root.with_name(f"{zarr_root.name}_aligned") + aligned = _is_zarr_root(aligned_root) + # Read before the first write: a config.yaml that will not be rewritten refuses the correction whole. + config = _session_config(zarr_root) + aligned_config = _session_config(aligned_root, f"{_OF_THE_COPY}config.yaml") if aligned else None + # And so does a take, or the session's own label, that cannot be read or rewritten: a correction that + # stopped at it would leave the takes before it relabelled, on every repeat. What each file holds now + # is kept, to be put back if a write fails all the same. + found = _holder_labels(zarr_root, present, "") + if aligned: + found += _holder_labels(aligned_root, present, _OF_THE_COPY) + if whole and on_session_task_change is not None: + on_session_task_change() + result.session_task_updated = whole + try: + _write_task(zarr_root, store, present, task_description, task_name, studio_stored, whole, config, result) + if aligned: + _update_aligned_copy( + aligned_root, indices, task_description, task_name, studio_stored, whole, aligned_config + ) + except Exception as failure: # noqa: BLE001 -- whatever stops a write, the files written go back + logger.warning("A task correction stopped at a file it could not write: %s", failure) + raise _put_back_all(found, "it carries the new task now", "they carry the new task now") from failure + + # The aggregates live on the root group, so a session without one has none to refresh. + if store is not None: + try: + with _metadata_kept(zarr_root): + refresh_session_egocap_zarr_aggregates(zarr_root) + result.aggregates_refreshed = True + except Exception: # noqa: BLE001 + result.aggregates_refreshed = False + + return result + + +def _write_task( + zarr_root: Path, + store: Any | None, + present: list[str], + task_description: str, + task_name: str, + studio_stored: str, + whole: bool, + config: dict[str, Any] | None, + result: EpisodeTaskUpdateResult, +) -> None: + """Write a checked task correction onto a session: its root group when it has one, the episodes in + ``present``, then ``config.yaml``, whose content is ``config``. ``result`` is told what was written.""" if store is not None: - ensure_dataset_level_seed_fields(store) - if whole: - store.attrs["task_description"] = task_description - if task_name: - store.attrs["task_name"] = task_name - if studio_stored: - store.attrs["studio"] = studio_stored + with _metadata_kept(zarr_root): + ensure_dataset_level_seed_fields(store) + if whole: + store.attrs["task_description"] = task_description + if task_name: + store.attrs["task_name"] = task_name + if studio_stored: + store.attrs["studio"] = studio_stored for key in present: - group = store[key] if store is not None else zarr.open_group(str(zarr_root / key), mode="r+") - _relabel_episode(group, task_description, task_name, studio_stored) + with _metadata_kept(zarr_root / key): + group = store[key] if store is not None else zarr.open_group(str(zarr_root / key), mode="r+") + _relabel_episode(group, task_description, task_name, studio_stored) result.updated_episodes.append(key) result.config_yaml_updated = _update_session_config_yaml( @@ -248,18 +470,238 @@ def update_episode_task_description( task_description=task_description if whole else None, task_name=task_name if whole else "", studio=studio_stored, + data=config, ) - # The time-aligned copy beside the session carries the same metadata, so it is updated with it. + + +@dataclass +class SessionStudioUpdateResult: + """Outcome of :func:`update_session_studio`.""" + + zarr_root: Path + #: The label as written: the name given, made a plain segment and spelled as the task library spells it. + studio_stored: str + updated_episodes: list[str] = field(default_factory=list) + config_yaml_updated: bool = False + + +def stored_studio_name(studio: str) -> str: + """The label a studio name is stored as: one plain segment, in the task library's spelling when the + library knows the studio, and in one Unicode form, so that a name typed with a combining accent and the + same name typed precomposed are one studio. Empty for a name that holds nothing.""" + composed = unicodedata.normalize("NFC", studio) + return canonicalize_studio_dir_name(sanitize_studio_dir_name(composed), frozenset(TASK_LIBRARY.keys())) + + +def _finalized_keys(keys: list[str]) -> list[str]: + """The entries that are finalized episodes, in take order; a pending take is not one.""" + indexed = [(index, key) for key in keys if (index := _episode_index_from_key(key)) is not None] + return [key for _index, key in sorted(indexed)] + + +class RelabelError(RuntimeError): + """A correction of a session's studio or task that was refused or that failed, in a sentence fit for an + operator: it names files of the session, never a directory. ``left_changed`` names what still carries + the new label after a failed correction that could not put everything back; it is empty when the + session says what it said before.""" + + def __init__(self, message: str, left_changed: tuple[str, ...] = ()) -> None: + """``message`` is the sentence, ``left_changed`` the files that could not be put back.""" + super().__init__(message) + self.left_changed = left_changed + + +@dataclass +class _Label: + """One file of a session that carries its labels, as a correction found it.""" + + #: What an operator can be told it is: ``episode_3``, ``the session's own label``, ``config.yaml``, each + #: of the time-aligned copy said to be so. + name: str + path: Path + #: The file's bytes as the relabel found them, which a failed relabel puts back; None for a file that was + #: not there (a format 2 group that had no attributes yet). + original: bytes | None + #: The file's content, and the mapping inside it that holds the label under ``studio``. + document: dict[str, Any] + holder: dict[str, Any] + yaml: bool = False + + def write(self, studio: str) -> None: + """Replace the file with its content under the new label.""" + self.holder["studio"] = studio + (_replace_yaml if self.yaml else _replace_json)(self.path, self.document) + + def restore(self) -> None: + """Put the file back as it was found, byte for byte.""" + if self.original is None: + self.path.unlink(missing_ok=True) + _sync_directory(self.path.parent) + else: + _replace_file(self.path, self.original) + + def as_found(self) -> bool: + """Whether the file holds now what it held when the correction found it, read from the disk. A file + that cannot be read is not known to: it counts as changed.""" + try: + return self.path.read_bytes() == self.original + except FileNotFoundError: + return self.original is None + except OSError: + return False + + +def _unwritable(directory: Path) -> bool: + """Whether a file in ``directory`` cannot be replaced: replacing one creates and renames an entry there.""" + return not os.access(directory, os.W_OK | os.X_OK) + + +def _group_label(directory: Path, name: str) -> _Label: + """The label file of the Zarr group in ``directory``, read and checked to be rewritable; + :class:`RelabelError` naming ``name`` otherwise.""" + path = _metadata_file(directory) + current = path.name == "zarr.json" + try: + # A format 2 group with no attributes has no such file yet, and holds none. + original = path.read_bytes() if current or path.is_file() else None + document = {} if original is None else json.loads(original) + except (OSError, ValueError, RecursionError) as exc: + raise RelabelError(f"{name} cannot be read, so nothing was changed") from exc + # Format 3 keeps a group's attributes under one key of its metadata; format 2 keeps them as the file, beside + # the file that marks the directory a group. + holder = document.setdefault("attributes", {}) if current and isinstance(document, dict) else document + marked = (directory / ".zgroup").is_file() if not current else None + group = isinstance(document, dict) and (document.get("node_type") == "group" if current else marked) + if not group or not isinstance(holder, dict): + raise RelabelError(f"{name} is not a recorded take's metadata, so nothing was changed") + if _unwritable(directory): + raise RelabelError(f"{name} cannot be rewritten (its folder is read-only), so nothing was changed") + return _Label(name, path, original, document, holder) + + +def _config_label(holder_dir: Path, name: str) -> _Label | None: + """The label in a session's ``config.yaml``, read and checked to be rewritable; None when the session has + no such file. :class:`RelabelError` naming ``name`` otherwise.""" + path = holder_dir / "config.yaml" + try: + data = _session_config(holder_dir, name) + original = None if data is None else path.read_bytes() + except (SessionConfigError, OSError) as exc: + said = str(exc) if isinstance(exc, SessionConfigError) else f"{name} cannot be read" + raise RelabelError(f"{said}, so nothing was changed") from exc + if data is None: + return None + if _unwritable(holder_dir): + raise RelabelError(f"{name} cannot be rewritten (its folder is read-only), so nothing was changed") + return _Label(name, path, original, data, data.setdefault("meta", {}), yaml=True) + + +def _holder_labels(holder: Path, present: list[str], said: str) -> list[_Label]: + """Every file of one holder (the session, or its time-aligned copy) that carries the studio, in the order + a relabel writes them: the episodes, then the holder's own label, then its ``config.yaml``. ``said`` goes + before each name, to tell the copy's files from the session's.""" + # A linked episode would lead the write outside the session; the copy may also hold fewer takes. + episodes = [key for key in present if (holder / key).is_dir() and not (holder / key).is_symlink()] + labels = [_group_label(holder / key, f"{said}{key}") for key in episodes] + if _is_zarr_root(holder): + labels.append(_group_label(holder, f"{said}own label" if said else "the session's own label")) + config = _config_label(holder, f"{said}config.yaml") + return labels if config is None else [*labels, config] + + +@dataclass +class SessionStudioPlan: + """A studio relabel that has been checked and not yet written: every file it will rewrite was opened, + read and found rewritable. :meth:`apply` writes it.""" + + zarr_root: Path + #: The label as it will be written. + studio_stored: str + #: The finalized episodes it relabels; empty for a session with no recorded take, which it leaves alone. + episodes: list[str] = field(default_factory=list) + _labels: list[_Label] = field(default_factory=list) + + def apply(self) -> SessionStudioUpdateResult: + """Write the label into every file. When a write fails, the files already written are put back and + :class:`RelabelError` says what was and was not changed: a relabel that fails leaves the session + with one studio, the one it had.""" + try: + for label in self._labels: + label.write(self.studio_stored) + except Exception as failure: # noqa: BLE001 -- whatever stops a write, the labels written go back + logger.warning("A studio relabel stopped at a file it could not write: %s", failure) + now = self.studio_stored + raise _put_back_all(self._labels, f"it says {now} now", f"they say {now} now") from failure + config = any(label.yaml and label.path.parent == self.zarr_root for label in self._labels) + return SessionStudioUpdateResult(self.zarr_root, self.studio_stored, list(self.episodes), config) + + +def _put_back_all(labels: list[_Label], one_says: str, several_say: str) -> RelabelError: + """After a correction failed: put back every file that no longer holds what it held, from the last one + written to the first, and return the failure that says what the session holds now. + + Both questions are answered by reading the files. A write can raise after its file was replaced, so a + file counts as written from the moment its write began, whether or not it returned; and a put-back can + raise after the file is back, so "could not be put back" is said only of a file that still differs. + ``one_says`` and ``several_say`` are what such files hold now, for one of them and for more. + """ + stuck = [] + for label in reversed(labels): + if label.as_found(): + continue + try: + label.restore() + except Exception as failure: # noqa: BLE001 -- said below, of the file it left changed + logger.warning("A label could not be put back after a failed correction: %s", failure) + if not label.as_found(): + stuck.append(label.name) + if not stuck: + return RelabelError( + "the labels could not all be written; those already written were put back, so nothing was changed" + ) + return RelabelError( + f"the labels could not all be written, and {', '.join(stuck)} could not be put back: " + f"{one_says if len(stuck) == 1 else several_say}, and the rest what they said before", + tuple(stuck), + ) + + +def plan_session_studio(zarr_root: Path, studio: str) -> SessionStudioPlan: + """Check a relabel of the studio of a whole recorded session where it lies: on every finalized episode, + on its root group when it has one, in ``config.yaml``, and the same on the time-aligned copy beside it. + + Nothing is written here. Every file the relabel will rewrite is opened, read and checked to be + rewritable, and :class:`RelabelError` says which one is not, with nothing changed. A session with no + finalized episode gives a plan that changes nothing. + """ + zarr_root = zarr_root.expanduser().resolve() + stored = stored_studio_name(studio) + if not stored: + raise ValueError("a studio correction needs a non-empty studio") + if not zarr_root.is_dir(): + raise FileNotFoundError(f"not a directory: {zarr_root}") + present = _finalized_keys(_episode_keys(zarr_root, None)) + plan = SessionStudioPlan(zarr_root, stored) + # A session that holds no recorded take has no studio to correct, and must not gain metadata from this. + if not present: + return plan + plan.episodes = present + # The session's own label is written after its episodes', and the copy after the session. + plan._labels = _holder_labels(zarr_root, present, "") aligned_root = zarr_root.with_name(f"{zarr_root.name}_aligned") + # Opened, never created: a directory that is not an aligned copy must not become one. if _is_zarr_root(aligned_root): - _update_aligned_copy(aligned_root, indices, task_description, task_name, studio_stored, whole) + plan._labels += _holder_labels(aligned_root, present, _OF_THE_COPY) + return plan - # The aggregates live on the root group, so a session without one has none to refresh. - if store is not None: - try: - refresh_session_egocap_zarr_aggregates(zarr_root) - result.aggregates_refreshed = True - except Exception: # noqa: BLE001 - result.aggregates_refreshed = False - return result +def update_session_studio(zarr_root: Path, studio: str) -> SessionStudioUpdateResult: + """Relabel the studio of a whole recorded session where it lies: on its root group when it has one, on + every finalized episode, in ``config.yaml`` and on the time-aligned copy beside it. + + Nothing is moved, renamed or created, and no task is touched: the session's folder keeps its name, and + its episode manifests keep the studio each take was recorded under. A session with no finalized episode + is left exactly as it was. All or nothing as far as files allow (see :func:`plan_session_studio` and + :meth:`SessionStudioPlan.apply`). + """ + return plan_session_studio(zarr_root, studio).apply() diff --git a/examples/egocap/recording/egocap/recording/aligned_writer.py b/examples/egocap/recording/egocap/recording/aligned_writer.py index 2eb631079c..587f9ae8b1 100644 --- a/examples/egocap/recording/egocap/recording/aligned_writer.py +++ b/examples/egocap/recording/egocap/recording/aligned_writer.py @@ -37,6 +37,7 @@ import yaml import zarr +from egocap.calibration import provenance from egocap.calibration.board import CalibrationError from egocap.calibration.camera_lag import CAMERA_LAG_KEY, TRACKING_LATENCY_KEY, CameraLag, camera_lag_of_take from egocap.calibration.files import ( @@ -98,6 +99,12 @@ class AlignedWriteError(RuntimeError): """The aligned episode could not be written or did not validate.""" +class NewerLayoutError(AlignedWriteError): + """The take was not aligned because its session carries a file written in a layout newer than this build + reads. Nothing is wrong with the take: a build that reads the layout aligns it, so the refusal is not one + to remember against the take.""" + + def _copy_attrs(source: Any, target: Any) -> None: """Carry every attribute of a zarr group over to the aligned group.""" for key, value in source.attrs.items(): @@ -156,9 +163,10 @@ def _session_camera_lag(raw_session: Path, episode_dir: Path) -> CameraLag | Non None when the session states no lag that can be used, and the take then aligns on its recorded times. A session states none when it has no such file, or one that cannot be read, was not made with this - project's tracking, or holds no lag. Raises ``AlignedWriteError`` when the lag was stored for a stated - tracking latency and the take does not say which it was recorded under: pairing its pictures on a guess - would be wrong without a sign of it. + project's tracking, or holds no lag. Raises ``NewerLayoutError`` when the file is of a newer layout than + this build reads, and ``AlignedWriteError`` when the lag was stored for a stated tracking latency and the + take does not say which it was recorded under: pairing its pictures on a guess would be wrong without a + sign of it. """ path = raw_session / HEAD_EXTRINSICS # A session recorded before the station's headset was calibrated carries no such file. @@ -171,6 +179,16 @@ def _session_camera_lag(raw_session: Path, episode_dir: Path) -> CameraLag | Non # it states no lag, and the log says why nothing was taken off. logger.warning("%s; pictures are paired with tracking unshifted", exc) return None + # A file of a newer layout than this build reads may mean something else by its keys, the lag among them. + # Aligning without the lag would pair every picture off by it with nothing in the result to show it, so + # the take is refused; the build that wrote the file aligns it. + newer = provenance.newer_layout(record) + if newer is not None: + raise NewerLayoutError( + f"this session's {HEAD_EXTRINSICS} is written in {newer}, and this software reads up to " + f"layout {provenance.SCHEMA_VERSION}: the take is not aligned, since the camera's lag is stated in " + "that file; update the software to align it" + ) # A lag measured against another tracking source's times is no lag against this take's tracking, and no # tool of this project builds on such a file. untrusted = pose_source_problem(record, HEAD_EXTRINSICS) diff --git a/examples/egocap/recording/egocap/recording/episode_layout.py b/examples/egocap/recording/egocap/recording/episode_layout.py index 1468cb9ff9..191eee0058 100644 --- a/examples/egocap/recording/egocap/recording/episode_layout.py +++ b/examples/egocap/recording/egocap/recording/episode_layout.py @@ -299,6 +299,11 @@ def read_manifest(path: Path) -> EpisodeManifest: #: 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" +#: The diagnostic for a sidecar directory that cannot be listed. It stands alone, with no file's name in front: +#: nothing says which records the directory holds. +RECORDS_UNLISTABLE = "the take records cannot be listed" + +_MANIFEST_NAME = re.compile(r"episode_.*\.json") @dataclass(frozen=True) @@ -308,7 +313,8 @@ class SessionScan: ``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. + or misplaced, naming the file and never a directory, or the one diagnostic of a sidecar directory that + cannot be listed. """ manifests: tuple[EpisodeManifest, ...] @@ -317,30 +323,42 @@ class SessionScan: def scan_session(session_path: Path) -> SessionScan: - """Read every record of a session directory, sorting out the ones nothing may act on.""" + """Read every record of a session directory, sorting out the ones nothing may act on. + + A sidecar directory that cannot be listed is a diagnostic too, never an empty session: a take waiting in + it to be recovered would otherwise read as no take at all. + """ manifests, misplaced, problems = [], [], [] directory = session_path / MANIFEST_DIR - if directory.is_dir(): - for path in sorted(directory.glob("episode_*.json")): - try: - manifest = read_manifest(path) - except ManifestError as exc: - problems.append(f"{path.name}: {exc}") - 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}") + if not directory.is_dir(): + return SessionScan((), (), ()) + try: + # Listed directly: a glob swallows the error of a directory it may not read and lists nothing. + with os.scandir(directory) as entries: + names = sorted(entry.name for entry in entries if _MANIFEST_NAME.fullmatch(entry.name)) + except OSError: + return SessionScan((), (), (RECORDS_UNLISTABLE,)) + for name in names: + try: + manifest = read_manifest(directory / name) + except ManifestError as exc: + problems.append(f"{name}: {exc}") + except OSError: + problems.append(f"{name}: {RECORD_UNREADABLE}") + except Exception: # noqa: BLE001 - damaged JSON, a list for an object, a field nobody declared + problems.append(f"{name}: {NOT_A_RECORD}") + else: + if manifest.session_id == session_path.name: + manifests.append(manifest) else: - if manifest.session_id == session_path.name: - manifests.append(manifest) - else: - misplaced.append(manifest) - problems.append(f"{path.name}: {MISPLACED_RECORD}") + misplaced.append(manifest) + problems.append(f"{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.""" + """Return every manifest of a session plus a diagnostic for each record that is unreadable or misplaced, + or the one diagnostic of a sidecar directory that cannot be listed.""" scan = scan_session(session_path) return list(scan.manifests), list(scan.problems) diff --git a/examples/egocap/recording/egocap/recording/route.py b/examples/egocap/recording/egocap/recording/route.py index 6badac11df..aa332b6bc8 100644 --- a/examples/egocap/recording/egocap/recording/route.py +++ b/examples/egocap/recording/egocap/recording/route.py @@ -54,6 +54,7 @@ "assign_output", "claim_quarantine_group", "discard_quarantine_claim", + "forget_group", "refresh_group_totals", "resolve_studio", ] @@ -298,6 +299,27 @@ def discard_quarantine_claim(session_path: Path) -> None: fsync_dir(staging.parent) +def forget_group(session_path: Path, group: str) -> bool: + """Stop sending a session's later takes to ``group``; whether the session had a route to it. + + For a group whose studio or whole-group task was corrected after its takes were filed: it no longer says + what a later take of the same studio, task and day was recorded under, and :func:`assign_output` refuses to + file a take into a group that says otherwise. With its route dropped, such a take claims a fresh group. + + Only the session's ``routes.json`` is rewritten, and only when it holds a route to the group; nothing is + created for a session that never routed. The group, its stamp and its episodes are not touched, and neither + is any take's own destination, which is the assignment frozen in its manifest. Damaged routes fail clearly + and are left as they are. The caller holds the session's lock. + """ + routes_file = session_path / MANIFEST_DIR / ROUTES_FILE + routes = _load_routes(routes_file) + kept = {key: recorded for key, recorded in routes.items() if recorded != group} + if len(kept) == len(routes): + return False + write_json_atomic(routes_file, kept) + return True + + 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/studio/session_studio.py b/examples/egocap/recording/egocap/studio/session_studio.py new file mode 100644 index 0000000000..576adccc20 --- /dev/null +++ b/examples/egocap/recording/egocap/studio/session_studio.py @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The studio a recorded session is labelled with, read from the session's own metadata. + +A session may lie in a folder named after a studio (``//``), and a correction of +its label never moves it. A reader therefore takes the studio from the session itself wherever the session +states one, and from the folder's name only for a session that states none. Every reader of a session's +studio goes through :func:`session_studio`, so a corrected label is what each of them shows. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import yaml + + +def _named(value: Any) -> str | None: + """A studio label when ``value`` is one: non-empty text. Anything else is no label.""" + return value if isinstance(value, str) and value.strip() else None + + +def _root_attributes(session_dir: Path) -> Mapping[str, Any]: + """The attributes of a session's root group; empty when it has none or it cannot be read.""" + try: + attributes = json.loads((session_dir / "zarr.json").read_text()).get("attributes") + except (OSError, ValueError, AttributeError): + return {} + return attributes if isinstance(attributes, dict) else {} + + +def _config_studio(session_dir: Path) -> str | None: + """``meta.studio`` of a session's ``config.yaml``, or None when the file or the field is not there.""" + try: + config = yaml.safe_load((session_dir / "config.yaml").read_text()) + except (OSError, UnicodeError, yaml.YAMLError): + return None + meta = config.get("meta") if isinstance(config, dict) else None + return _named(meta.get("studio")) if isinstance(meta, dict) else None + + +def session_studio( + session_dir: Path, *, fallback: str | None = None, attributes: Mapping[str, Any] | None = None +) -> str | None: + """The studio of the session (or routed group) at ``session_dir``. + + Its root group's ``studio`` attribute, else ``meta.studio`` of its ``config.yaml``, else ``fallback``: + what the caller knows the session by when the session itself says nothing, such as the name of the + studio folder it lies in. ``attributes`` are the root group's, for a caller that has read them already. + """ + root = _root_attributes(session_dir) if attributes is None else attributes + return _named(root.get("studio")) or _config_studio(session_dir) or _named(fallback) diff --git a/examples/egocap/recording/recording_service/recording_service.py b/examples/egocap/recording/recording_service/recording_service.py index 2671928803..1e9203146c 100644 --- a/examples/egocap/recording/recording_service/recording_service.py +++ b/examples/egocap/recording/recording_service/recording_service.py @@ -992,10 +992,13 @@ def _seed_group_assets(self, session_path: Path, group: str) -> None: Idempotent: a later take routed into the same group re-checks every file but copies nothing new. A group's existing config.yaml must come from the same station as this session, or this assignment is refused outright rather than finalizing under conflicting station metadata. - Compares only the station key, not the whole structure: the EOD Episode Rename backfill + Compares only the station key, not the whole structure: a correction (``update_episode_task_description.py``) legitimately rewrites a group's config.yaml meta - after the fact (task description, studio), so a later take routed into that same group must - not be refused over a difference the rename itself introduced. + after the fact (task description, studio), and that difference alone must not refuse this + copy. It says nothing of whether a later take may be filed into such a group: ``assign_output`` + refuses a group whose studio or task no longer says what the take was recorded under, and a + correction that changes either drops the group from the session's routes + (``route.forget_group``), so a later take claims a fresh group instead. """ group_dir = session_path.parent / group session_config = session_path / SESSION_CONFIG_FILE diff --git a/examples/egocap/recording/tools/align_episode.py b/examples/egocap/recording/tools/align_episode.py index eed5741a26..449cc4ec9c 100755 --- a/examples/egocap/recording/tools/align_episode.py +++ b/examples/egocap/recording/tools/align_episode.py @@ -22,17 +22,24 @@ differs from ``--episode`` (a routed episode sits under its slot). The manifest is used only if it describes exactly this finalized, kept episode. Exit status 0 means the aligned episode was published; 1 means it was refused (the same input is refused every time); 2 means the manifest could not be read -(retry later). The reason is on stderr. +(retry later); 3 means the session carries a file written in a layout newer than this software reads (the take +is aligned once the software is updated). The reason is on stderr. """ import argparse import sys from pathlib import Path -from egocap.recording.aligned_writer import AlignedWriteError, align_kept_episode +from egocap.recording.aligned_writer import AlignedWriteError, NewerLayoutError, align_kept_episode from egocap.recording.alignment import AlignmentError from egocap.recording.episode_layout import manifest_path, read_manifest +#: The exit statuses a caller acts on. A refusal is the same for the same input under any build; the other two +#: are not the take's fault and are worth trying again: later, or once the software is updated. +REFUSED = 1 +MANIFEST_UNREADABLE = 2 +NEWER_SOFTWARE_NEEDED = 3 + def main(argv: list[str] | None = None) -> int: """Align the named episode and report the result; returns the process exit status.""" @@ -56,7 +63,7 @@ def main(argv: list[str] | None = None) -> int: manifest = read_manifest(manifest_path(args.manifest_session or args.session, manifest_episode)) except (OSError, ValueError) as exc: print(f"cannot read the episode's manifest: {exc}", file=sys.stderr) - return 2 + return MANIFEST_UNREADABLE try: aligned = align_kept_episode( args.session, @@ -66,9 +73,14 @@ def main(argv: list[str] | None = None) -> int: aligned_session=args.aligned_session, downsample=args.downsample, ) + except NewerLayoutError as exc: + # Said in the same words as a refusal, under a status of its own: whoever runs this must not put the + # take aside for good, since the build the sentence asks for aligns it. + print(f"not aligned: {exc}", file=sys.stderr) + return NEWER_SOFTWARE_NEEDED except (AlignedWriteError, AlignmentError) as exc: print(f"not aligned: {exc}", file=sys.stderr) - return 1 + return REFUSED kept, total = int(aligned.valid_indices.sum()), len(aligned.valid_indices) # Said either way: a take aligned without the lag looks the same in every other respect. lag = f"{aligned.camera_lag_s * 1000.0:.1f} ms of" if aligned.camera_lag_s else "no" diff --git a/examples/egocap/tests/backend/test_app_stations.py b/examples/egocap/tests/backend/test_app_stations.py index 7359feedf8..deb128fd6a 100644 --- a/examples/egocap/tests/backend/test_app_stations.py +++ b/examples/egocap/tests/backend/test_app_stations.py @@ -135,6 +135,34 @@ def test_the_monitor_offers_every_camera_of_the_accepted_session_by_name(): assert monitor.offered_camera_names() == frozenset({"cam_head", "cam_wrist"}) +def test_the_monitor_says_the_size_of_the_picture_each_offered_camera_sends(): + import dataclasses + + monitor = CaptureStatusMonitor(CaptureStatusConfig(), backend_instance_id="b1") + assert monitor.camera_size("cam_head") is None # nothing accepted yet + tracking = SimpleNamespace(name="cam_head") + unsized = dataclasses.replace(_livekit("cam_preview"), width=None, height=None) + streams = (tracking, _camera("cam_head"), dataclasses.replace(_livekit("cam_wrist"), width=16), unsized) + monitor.native = SimpleNamespace(started=SimpleNamespace(streams=streams)) + # A CaptureServer camera and a LiveKit stream alike, by name; a stream of another kind is no camera. + assert monitor.camera_size("cam_head") == (8, 4) + assert monitor.camera_size("cam_wrist") == (16, 4) + # A stream that states no size, a camera the session does not offer, and no camera at all. + assert monitor.camera_size("cam_preview") is None + assert monitor.camera_size("cam_gone") is None and monitor.camera_size(None) is None + + +def test_the_monitor_names_the_livekit_stream_a_camera_arrives_as(): + monitor = CaptureStatusMonitor(CaptureStatusConfig(), backend_instance_id="b1") + assert monitor.livekit_stream("cam_wrist") is None # nothing accepted yet + wrist = _livekit("cam_wrist") + monitor.native = SimpleNamespace(started=SimpleNamespace(streams=(_camera("cam_head"), wrist))) + assert monitor.livekit_stream("cam_wrist") is wrist + # A camera the capture server delivers, one the session does not offer, and no camera at all. + assert monitor.livekit_stream("cam_head") is None + assert monitor.livekit_stream("cam_gone") is None and monitor.livekit_stream(None) is None + + def test_a_changed_station_label_is_announced_to_every_viewer_once(): monitor = CaptureStatusMonitor(CaptureStatusConfig(station_label="Deployment"), backend_instance_id="b1") revision = monitor.revision diff --git a/examples/egocap/tests/backend/test_auto_align.py b/examples/egocap/tests/backend/test_auto_align.py index f3a47129b5..d1356c8c38 100644 --- a/examples/egocap/tests/backend/test_auto_align.py +++ b/examples/egocap/tests/backend/test_auto_align.py @@ -15,6 +15,7 @@ import yaml import zarr +from egocap.calibration.files import HEAD_EXTRINSICS from egocap.recording.episode_layout import ( FINALIZATION_KEEP, FINALIZATION_QUARANTINE, @@ -591,6 +592,70 @@ async def test_an_episode_the_tool_refuses_is_marked_with_its_reason_and_left_un assert marker.read_text().strip() and not (tmp_path / "out" / "s1_aligned" / "episode_0").exists() +#: What the child runs first when "the software has been updated": a build that reads the next layout. +UPDATED_BUILD = "from egocap.calibration import provenance\n\nprovenance.SCHEMA_VERSION = 2\n" + + +async def _one_start(out: Path, done) -> list[str]: + """One start of the backend's aligner on the output ``out``: what its start-up scan finds, the worker left + to run until ``done`` holds, then stopped as a shutdown stops it.""" + aligner = AutoAligner(out, INDEX) + found = [f"{job.session_id}/episode_{job.episode_index}" for job in aligner.scan()] + task = asyncio.create_task(aligner.run()) + # The child is a whole interpreter with its imports to load. + for _ in range(1200): + if done(): + break + await asyncio.sleep(0.1) + await aligner.close(task, 120) + assert done() + return found + + +async def test_a_take_refused_over_a_newer_session_file_is_not_marked_and_is_aligned_once_the_software_is_updated( + tmp_path, monkeypatch, caplog +): + out = tmp_path / "out" + session = out / "s1" + build_raw(session, timing=timing_under(0.02)) + state_a_lag(session) + stated = json.loads((session / HEAD_EXTRINSICS).read_text()) + (session / HEAD_EXTRINSICS).write_text(json.dumps({**stated, "schema_version": 2})) + write_manifest(session, make_manifest(session, session_id="s1")) + marker = out / "s1_aligned" / ".episode_0.refused" + aligned = out / "s1_aligned" / "episode_0" + caplog.set_level(logging.WARNING, logger=auto_align.logger.name) + + def recorded() -> dict[str, bytes]: + return {str(path.relative_to(session)): path.read_bytes() for path in session.rglob("*") if path.is_file()} + + before = recorded() + + # This build reads layout 1: the take is not aligned, the log says what to do, and nothing marks the take + # as refused, so every later start finds it again. + for _ in range(2): + caplog.clear() + assert await _one_start(out, lambda: len(caplog.records) > 0) == ["s1/episode_0"] + assert [record.getMessage() for record in caplog.records] == [ + "s1 episode 0 was not time-aligned: not aligned: this session's head_camera_extrinsics.json is " + "written in layout 2, and this software reads up to layout 1: the take is not aligned, since the " + "camera's lag is stated in that file; update the software to align it" + ] + assert not marker.exists() and not aligned.exists() + + # The software is updated, as the sentence asks: the next start aligns the take, with its lag taken off. + newer = tmp_path / "newer_build" + newer.mkdir() + (newer / "sitecustomize.py").write_text(UPDATED_BUILD) + monkeypatch.setenv("PYTHONPATH", f"{newer}{os.pathsep}{os.environ.get('PYTHONPATH', '')}") + assert await _one_start(out, aligned.is_dir) == ["s1/episode_0"] + assert not marker.exists() + assert zarr.open_group(str(aligned), mode="r").attrs["camera_lag"]["taken_off_s"] == 0.05 + 0.02 + assert AutoAligner(out, INDEX).scan() == [] + # Refused or aligned, the recording itself is only read. + assert recorded() == before + + async def test_an_unreadable_manifest_leaves_no_marker_and_a_later_scan_queues_the_episode_again(tmp_path): session = tmp_path / "out" / "s1" build_raw(session) diff --git a/examples/egocap/tests/backend/test_calibration_check.py b/examples/egocap/tests/backend/test_calibration_check.py new file mode 100644 index 0000000000..baae076273 --- /dev/null +++ b/examples/egocap/tests/backend/test_calibration_check.py @@ -0,0 +1,527 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The live check of the installed head-camera calibration: what it is refused for, how it is fed pictures +and head poses, what it reports, and that it writes nothing. The pictures are rendered boards and the head +poses are written out to match them.""" + +from __future__ import annotations + +import asyncio +import base64 +import json +from pathlib import Path +from types import SimpleNamespace + +import cv2 +import numpy as np +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from scipy.spatial.transform import Rotation + +from egocap.calibration.files import HEAD_EXTRINSICS, HEAD_INTRINSICS, OPENXR_POSES, POSE_SOURCE_KEY +from egocap.calibration.rectification_files import CameraStream, StreamsState +from egocap_web import calibration_check, calibration_routes +from egocap_web.calibration_check import ( + ENDED_LONG, + MAX_CHECK_SECONDS, + NO_CHECK, + READS_ONLY, + LiveCheckService, +) +from egocap_web.calibration_common import CalibrationRefusal +from egocap_web.calibration_service import NO_LIVE_PICTURE, capture_protocol +from egocap_web.capture_preview import LatestPreviewCache +from egocap_web.streams_state import UnreadStreams +from tests.backend.test_recording_adapter import default_tracking_values +from tests.recording.unit import calibration_synthetic as synthetic + +HEAD = synthetic.CAMERA +BOARD = synthetic.SPEC.to_record() +TOKEN = "t" * 43 +AUTH = {"X-Control-Token": TOKEN} +#: How fast the synthetic head goes along its sweep, and how often it is looked at and tracked. +PACE, LOOK_S, POSE_S = 0.02, 0.25, 0.01 +#: How long the synthetic head holds still before it sets off, as the check asks while it fixes the board's place. +HOLD_S = 2.0 + + +def board_at(seconds: float) -> np.ndarray: + """The board in the camera at a moment: held at the sweep's start, then along the sweep.""" + return synthetic.sweep_pose(PACE * max(seconds - HOLD_S, 0.0)) + + +#: The installed lens file of the synthetic camera, and its position on the headset as the tools write it. +LENS = { + "model": "pinhole", + "K": synthetic.K_TRUE.tolist(), + "dist_coeffs": [0.0, 0.0, 0.0, 0.0, 0.0], + "image_size_wh": list(synthetic.SIZE), + "camera": HEAD, +} +POSITION = {POSE_SOURCE_KEY: OPENXR_POSES, "T_headset_camera": synthetic.T_HEADSET_CAMERA.tolist(), "camera": HEAD} + + +def tree(root: Path) -> dict[str, bytes]: + return {str(path.relative_to(root)): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} + + +class World: + """One station as the check sees it: the capture monitor's cache, the calibration directory, the run.""" + + def __init__(self, tmp_path: Path, streams: StreamsState | None = None, lag_s: float = 0.0): + self.now = 1_000.0 + self.directory = tmp_path / "calibration" + self.directory.mkdir(parents=True) + self.install(HEAD_INTRINSICS, LENS) + self.install(HEAD_EXTRINSICS, {**POSITION, "camera_latency_s": lag_s}) + self.preview = LatestPreviewCache(lambda: self.now) + self.camera: str | None = HEAD + self.pictures = self.samples = 0 + self.fed = 0.0 + self.lag_s = lag_s + self.service = LiveCheckService( + monitor=SimpleNamespace(preview=self.preview), + calibration_dir=lambda: self.directory, + streams=streams, + camera_for=lambda role: self.camera if role == "ego" else None, + monotonic=lambda: self.now, + ) + + def install(self, name: str, record: object) -> None: + (self.directory / name).write_text(record if isinstance(record, str) else json.dumps(record)) + + def head(self, seconds: float) -> np.ndarray: + return synthetic.head_pose_for(board_at(seconds)) + + def track(self, seconds: float, pose: np.ndarray | None = None, valid: bool = True) -> None: + """Deliver the tracking sample of a moment: the head where the sweep has it, unless told otherwise.""" + pose = self.head(seconds) if pose is None else pose + values = { + **default_tracking_values(), + "head.position": tuple(pose[:3, 3]), + "head.orientation": tuple(Rotation.from_matrix(pose[:3, :3]).as_quat()), + "head.is_valid": int(valid), + } + self.samples += 1 + self.preview.set_tracking( + sequence=self.samples, + capture_time_ns=round(seconds * 1e9), + receive_time_ns=round(seconds * 1e9), + payload=capture_protocol.encode_tracking_frame(values), + ) + + def show(self, seconds: float, image: np.ndarray | None = None, raw: bytes | None = None) -> None: + """Deliver the picture of a moment, stamped later by the camera's lag, with the tracking up to it.""" + # Tracking runs ahead of the pictures: by the time a picture arrives, the poses up to its stamp have. + for moment in np.arange(self.fed, seconds + self.lag_s + 3 * POSE_S, POSE_S): + self.track(float(moment)) + self.fed = seconds + self.lag_s + 3 * POSE_S + picture = synthetic.render(board_at(seconds)) if image is None else image + self.pictures += 1 + self.preview.set_camera( + HEAD, + sequence=self.pictures, + capture_time_ns=round((seconds + self.lag_s) * 1e9), + receive_time_ns=round(seconds * 1e9), + jpeg=cv2.imencode(".jpg", picture, [cv2.IMWRITE_JPEG_QUALITY, 95])[1].tobytes() + if raw is None + else raw, + ) + + async def sweep(self, looks: int, start: float = 0.5) -> dict: + """Show the board from a moving head ``looks`` times, polling after each; the last status.""" + status = {} + for index in range(looks): + self.show(start + index * LOOK_S) + status = await self.service.poll() + return status + + +async def refused(work, status: int) -> str: + with pytest.raises(CalibrationRefusal) as caught: + await work + assert caught.value.status == status, caught.value.detail + return caught.value.detail + + +@pytest.fixture +def world(tmp_path) -> World: + made = World(tmp_path) + made.show(0.25) + return made + + +async def test_a_true_calibration_is_followed_live_in_pixels_to_a_verdict_and_nothing_is_written(world, tmp_path): + before = tree(tmp_path) + started = await world.service.start({"board": BOARD}) + assert started == { + "phase": "checking", + "camera": HEAD, + "corrected": False, + "camera_lag_ms": 0.0, + "elapsed_s": 0.0, + "available": True, + "unavailable_reason": None, + # A camera the capture server delivers: no video room is joined for it, and nothing is waited for. + "video_room": False, + "waiting": None, + "check": None, + "preview": None, + "note": "The check reads the installed head_camera_intrinsics.json and head_camera_extrinsics.json. " + "It records nothing and changes no file.", + } + world.now += 2.5 + done = await world.sweep(44) + check = done["check"] + assert (done["elapsed_s"], done["available"], check["phase"], check["judged"]) == (2.5, True, "checking", True) + assert check["verdict"] == "excellent" and check["rms_px"] < 1.5 and check["error_px"] < 1.5 + assert check["views"] >= 10 and check["board_wander_m"] < 0.003 + # The picture is sent with the corners seen and the corners predicted drawn on it. + preview = done["preview"] + assert (preview["width"], preview["height"]) == synthetic.SIZE + shown = cv2.imdecode(np.frombuffer(base64.b64decode(preview["jpeg"]), dtype=np.uint8), cv2.IMREAD_COLOR) + assert shown.shape[:2] == (synthetic.SIZE[1], synthetic.SIZE[0]) + plain = synthetic.render(board_at(0.5 + 43 * LOOK_S)) + assert np.abs(shown.astype(int) - plain.astype(int)).max() > 80 + # A poll with no new picture answers with what is known and looks at nothing. + again = await world.service.poll() + assert again["check"] == check and again["preview"] == preview + assert await world.service.stop() == {"phase": "stopped", "note": READS_ONLY} + assert await refused(world.service.poll(), 404) == NO_CHECK + # Not a file was added, changed or removed: no take, no ledger entry, no note of the board. + assert tree(tmp_path) == before + + +async def test_a_camera_position_that_is_off_is_graded_bad(tmp_path): + world = World(tmp_path) + # Three centimeters off and turned two degrees: enough to move the board by more than the grade allows. + turned = np.eye(4) + turned[:3, :3] = Rotation.from_euler("y", 2, degrees=True).as_matrix() + turned[:3, 3] = [0.03, 0.0, 0.0] + off = synthetic.T_HEADSET_CAMERA @ turned + world.install(HEAD_EXTRINSICS, {**POSITION, "T_headset_camera": off.tolist()}) + world.show(0.25) + await world.service.start({"board": BOARD}) + check = (await world.sweep(44))["check"] + assert check["verdict"] == "bad" and check["rms_px"] > 5.0 and check["board_wander_m"] > 0.010 + + +async def test_the_cameras_stored_lag_is_taken_off_a_pictures_time_before_its_head_pose_is_looked_up(tmp_path): + # Pictures stamped 80 ms after the head poses they were taken at, as the installed position says they are. + world = World(tmp_path, lag_s=0.08) + world.show(0.25) + started = await world.service.start({"board": BOARD}) + assert started["camera_lag_ms"] == 80.0 + assert (await world.sweep(40))["check"]["rms_px"] < 1.5 + # Checked without the lag being stated, the same pictures are paired with the wrong poses. + unstated = World(tmp_path / "unstated") + unstated.lag_s = 0.08 + unstated.show(0.25) + await unstated.service.start({"board": BOARD}) + wrong = (await unstated.sweep(40))["check"] + # The pixels show it, and the check names it: the pictures are some 80 ms older than the file says. + assert wrong["rms_px"] > 1.0 and wrong["verdict"] == "bad" + assert wrong["camera_lag_off_s"] == pytest.approx(0.08, abs=0.02) + + +async def test_a_check_is_refused_with_the_reason_when_the_calibration_cannot_be_judged_at_all(world, tmp_path): + def after(change) -> World: + made = World(tmp_path / f"case{len(list(tmp_path.iterdir()))}") + made.show(0.25) + change(made) + return made + + start = {"board": BOARD} + nobody = after(lambda made: setattr(made, "camera", None)) + assert await refused(nobody.service.start(start), 409) == "no camera is assigned to the head camera role" + # A camera the capture server should deliver and has sent no picture of. + unseen = World(tmp_path / "unseen") + assert await refused(unseen.service.start(start), 409) == "there is no live picture from this camera" + missing = after(lambda made: (made.directory / HEAD_EXTRINSICS).unlink()) + assert await refused(missing.service.start(start), 409) == ( + "calibrate the headset first: head_camera_extrinsics.json could not be read" + ) + other = after(lambda made: made.install(HEAD_INTRINSICS, {**LENS, "camera": "cam_a"})) + assert (await refused(other.service.start(start), 409)).startswith( + "calibrate the headset first: head_camera_intrinsics.json was solved for camera 'cam_a'" + ) + foreign = after(lambda made: made.install(HEAD_EXTRINSICS, {"T_headset_camera": POSITION["T_headset_camera"]})) + assert await refused(foreign.service.start(start), 409) == ( + "calibrate the headset first: head_camera_extrinsics.json was made with another tracking source or " + "another tool: calibrate again" + ) + assert (await refused(world.service.start({"board": {"squares": [1, 1]}}), 400)) != "" + # Nothing was started by any of them. + assert await refused(world.service.poll(), 404) == NO_CHECK + + +async def test_a_camera_whose_video_is_corrected_is_checked_with_the_corrected_cameras_matrix(tmp_path): + corrected = { + "model": "pinhole", + "K": synthetic.K_TRUE.tolist(), + "dist_coeffs": [0.0, 0.0, 0.0, 0.0, 0.0], + "image_size_wh": list(synthetic.SIZE), + } + stream = CameraStream(HEAD, "head", "ego", synthetic.SIZE, 1, synthetic.SIZE, corrected) + world = World(tmp_path, streams=StreamsState(cameras={HEAD: stream})) + # The installed lens is another camera altogether: the pictures are the corrected camera's, not its. + world.install(HEAD_INTRINSICS, {**LENS, "K": (synthetic.K_TRUE * [[1.3], [1.3], [1.0]]).tolist()}) + world.show(0.25) + started = await world.service.start({"board": BOARD}) + assert started["corrected"] is True + assert (await world.sweep(40))["check"]["verdict"] == "excellent" + + # A correction the launcher's record does not describe, and a report of the run that could not be read, + # leave it unknown which camera the pictures are of. + broken = CameraStream(HEAD, "head", "ego", synthetic.SIZE, 1, synthetic.SIZE, {"K": "not a matrix"}) + undescribed = World(tmp_path / "broken", streams=StreamsState(cameras={HEAD: broken})) + undescribed.show(0.25) + assert (await refused(undescribed.service.start({"board": BOARD}), 409)).startswith( + "this camera's video is being corrected, and " + ) + unread = World(tmp_path / "unread", streams=UnreadStreams(problem="not valid JSON")) + unread.show(0.25) + assert "report of the camera streams could not be read" in await refused( + unread.service.start({"board": BOARD}), 409 + ) + + +async def test_a_look_without_a_live_picture_or_with_one_that_cannot_be_read_says_so_and_keeps_what_was_found( + world, monkeypatch, caplog +): + await world.service.start({"board": BOARD}) + found = (await world.sweep(8))["check"] + assert found["phase"] == "checking" + # The camera stops sending: its last picture grows too old to call live. + world.now += 5.0 + stale = await world.service.poll() + assert (stale["available"], stale["unavailable_reason"], stale["preview"]) == ( + False, + "there is no live picture from this camera", + None, + ) + assert stale["check"] == found + # A picture that does not decode, and one the check fails on, say so without ending the check. + world.show(3.0, raw=b"not a jpeg") + undecoded = await world.service.poll() + assert (undecoded["available"], undecoded["unavailable_reason"]) == ( + False, + "the check could not read this picture; see the backend logs", + ) + assert undecoded["check"] == found + + def failing(*arguments): + raise RuntimeError("detector fault") + + monkeypatch.setattr(LiveCheckService, "_observe", staticmethod(failing)) + world.show(3.25) + failed = await world.service.poll() + assert failed["available"] is False and failed["check"] == found + assert "The live calibration check failed on a picture" in caplog.text + monkeypatch.undo() + world.show(3.5) + assert (await world.service.poll())["available"] is True + + +async def test_a_picture_of_another_size_than_the_installed_calibration_is_not_judged_and_the_check_says_why( + world, tmp_path +): + before = tree(tmp_path) + await world.service.start({"board": BOARD}) + width, height = synthetic.SIZE + # The camera was started in another picture mode: the board is in view at half the size the lens was solved on. + half = cv2.resize(synthetic.render(board_at(0.5)), (width // 2, height // 2)) + world.show(0.5, image=half) + other = await world.service.poll() + assert (other["available"], other["check"]) == (False, None) + # The picture is shown as it came, with nothing drawn on it. + assert (other["preview"]["width"], other["preview"]["height"]) == (width // 2, height // 2) + assert other["unavailable_reason"] == ( + f"this camera sends a {width // 2}x{height // 2} picture, and the installed calibration is for " + f"{width}x{height}, so it cannot be checked on this picture: set the camera's picture mode back, or " + "calibrate again" + ) + # Set back, the same check judges the pictures that follow. + judged = await world.sweep(8, start=0.75) + assert judged["available"] is True and judged["check"]["corners"] > 0 + assert tree(tmp_path) == before + + +async def test_head_poses_that_are_not_valid_are_not_handed_over_and_a_picture_without_one_is_not_judged(tmp_path): + world = World(tmp_path) + world.show(0.25) + await world.service.start({"board": BOARD}) + # From here the headset reports no valid pose. + for moment in np.arange(world.fed, 1.0, POSE_S): + world.track(float(moment), valid=False) + world.fed = 10.0 + world.show(0.9) + status = await world.service.poll() + assert status["check"]["judged"] is False + assert status["check"]["cannot_judge"] == "Head tracking is not arriving: check the headset is on and tracked." + + +def picture_alone(world: World, seconds: float) -> None: + """Deliver the picture of a moment and no tracking with it.""" + world.pictures += 1 + world.preview.set_camera( + HEAD, + sequence=world.pictures, + capture_time_ns=round(seconds * 1e9), + receive_time_ns=round(seconds * 1e9), + jpeg=cv2.imencode(".jpg", synthetic.render(board_at(seconds)))[1].tobytes(), + ) + + +async def test_a_picture_newer_than_the_tracking_that_has_arrived_waits_for_it_and_is_judged_with_its_own_pose( + world, +): + await world.service.start({"board": BOARD}) + first = (await world.service.poll())["check"] + assert (first["judged"], first["fixing"]["views"]) == (True, 1) + # The next picture is here before the tracking sample after it: nothing is said of it yet. + picture_alone(world, 0.5) + waiting = await world.service.poll() + assert waiting["available"] is True and waiting["check"] == first + # A newer picture does not take its turn: the tracking reaches the one that waits first. + picture_alone(world, 0.75) + assert (await world.service.poll())["check"] == first + # The tracking reaches the first of the two, and not the second: a judged picture is the one that waited. + for moment in np.arange(world.fed, 0.6, POSE_S): + world.track(float(moment)) + reached = (await world.service.poll())["check"] + assert (reached["judged"], reached["fixing"]["views"]) == (True, 2) + + +async def test_a_picture_the_tracking_never_reaches_is_looked_at_after_a_wait_and_not_judged(tmp_path): + world = World(tmp_path) + picture = cv2.imencode(".jpg", synthetic.render(synthetic.sweep_pose(0.0)))[1].tobytes() + world.preview.set_camera(HEAD, sequence=1, capture_time_ns=5_000_000_000, receive_time_ns=1, jpeg=picture) + await world.service.start({"board": BOARD}) + held = await world.service.poll() + assert (held["available"], held["check"]) == (True, None) + world.now += 0.4 + assert (await world.service.poll())["check"] is None + world.now += 0.1 + status = await world.service.poll() + assert status["available"] is True and status["check"]["board_visible"] is True + assert ( + status["check"]["judged"] is False and "Head tracking is not arriving" in status["check"]["cannot_judge"] + ) + + +async def test_polls_that_arrive_while_a_picture_is_looked_at_do_not_pile_up_behind_it(world, monkeypatch): + import asyncio + + await world.service.start({"board": BOARD}) + world.show(0.5) + entered, release = asyncio.Event(), asyncio.Event() + loop = asyncio.get_running_loop() + observe = LiveCheckService._observe + + def slow(*arguments): + loop.call_soon_threadsafe(entered.set) + asyncio.run_coroutine_threadsafe(release.wait(), loop).result(5) + return observe(*arguments) + + monkeypatch.setattr(LiveCheckService, "_observe", staticmethod(slow)) + first = asyncio.create_task(world.service.poll()) + await entered.wait() + # Answered at once, from what is known, while the first is still at the picture. + meanwhile = await world.service.poll() + assert meanwhile["check"] is None + release.set() + assert (await first)["check"]["phase"] == "fixing" + + +async def test_a_check_started_again_replaces_the_one_before(world): + await world.service.start({"board": BOARD}) + assert (await world.sweep(8))["check"]["phase"] == "checking" + again = await world.service.start({"board": BOARD}) + assert again["check"] is None and again["elapsed_s"] == 0.0 + + +def test_the_overlay_draws_nothing_for_a_prediction_no_line_can_reach(): + frame = np.zeros((48, 64, 3), dtype=np.uint8) + record = {"image_size_wh": [64, 48], "corner_points": [[10.0, 10.0]], "predicted_points": [[1e9, -1e9]]} + shown = calibration_check._overlay(frame, record) + # Only the corner seen is drawn. + assert shown[10, 10].tolist() == [0, 255, 0] and int(shown.sum()) < 255 * 3 * 30 + record["predicted_points"] = [[30.0, 10.0]] + assert int(calibration_check._overlay(frame, record).sum()) > int(shown.sum()) + + +# --- the routes ------------------------------------------------------------------------------------------------ + + +def _client(world: World | None, ready: bool = True) -> TestClient: + app = FastAPI() + app.include_router(calibration_routes.router) + if ready: + app.state.calibration = SimpleNamespace() + app.state.recording_context = SimpleNamespace(control_token=TOKEN) + if world is not None: + app.state.calibration_check = world.service + return TestClient(app) + + +def test_the_check_is_started_polled_and_stopped_over_http_with_the_control_token(world): + client = _client(world) + for call in ( + lambda headers: client.post("/api/calibration/check", json={"board": BOARD}, headers=headers), + lambda headers: client.get("/api/calibration/check", headers=headers), + lambda headers: client.post("/api/calibration/check/stop", json={}, headers=headers), + ): + assert call({}).status_code == 403 and call({"X-Control-Token": "wrong"}).status_code == 403 + none = client.get("/api/calibration/check", headers=AUTH) + assert (none.status_code, none.json()) == (404, {"detail": "no check is running"}) + started = client.post("/api/calibration/check", json={"board": BOARD}, headers=AUTH) + assert started.status_code == 200 and started.json()["phase"] == "checking" + assert started.headers["cache-control"] == "no-store" + world.show(0.5) + polled = client.get("/api/calibration/check", headers=AUTH).json() + assert polled["check"]["phase"] == "fixing" and polled["preview"]["width"] == synthetic.SIZE[0] + stopped = client.post("/api/calibration/check/stop", json={}, headers=AUTH) + assert (stopped.status_code, stopped.json()) == (200, {"phase": "stopped", "note": READS_ONLY}) + refused_start = client.post("/api/calibration/check", json={"board": {"squares": [1, 1]}}, headers=AUTH) + assert refused_start.status_code == 400 and isinstance(refused_start.json()["detail"], str) + + +def test_the_check_routes_answer_503_until_the_application_has_set_the_service(world): + for client in (_client(None), _client(world, ready=False)): + assert client.post("/api/calibration/check", json={}, headers=AUTH).status_code == 503 + assert client.get("/api/calibration/check", headers=AUTH).status_code == 503 + assert client.post("/api/calibration/check/stop", json={}, headers=AUTH).status_code == 503 + + +async def test_head_poses_are_not_kept_while_no_picture_is_judged(tmp_path): + world = World(tmp_path) + world.show(0.25) + await world.service.start({"board": BOARD}) + await world.service.poll() + # The camera stops sending; the tracking goes on for two minutes, and the page keeps asking. + status = {} + for second in range(120): + for moment in np.arange(1.0 + second, 2.0 + second, POSE_S): + world.track(float(moment)) + world.now += 1.0 + status = await world.service.poll() + assert status["unavailable_reason"] == NO_LIVE_PICTURE + # Only what a picture could still be placed among is held: a few seconds of poses, not two minutes. + assert len(world.service._check.poses) <= 5 / POSE_S + + +async def test_a_check_of_a_camera_the_capture_server_delivers_has_the_same_longest_length(tmp_path): + world = World(tmp_path) + world.service._watch_seconds = 0.01 + world.show(0.25) + await world.service.start({"board": BOARD}) + world.now += MAX_CHECK_SECONDS - 1.0 + await asyncio.sleep(0.05) + assert (await world.service.poll())["phase"] == "checking" + world.now += 2.0 + await asyncio.sleep(0.05) + assert await refused(world.service.poll(), 404) == ENDED_LONG diff --git a/examples/egocap/tests/backend/test_calibration_check_room.py b/examples/egocap/tests/backend/test_calibration_check_room.py new file mode 100644 index 0000000000..92610ce3d3 --- /dev/null +++ b/examples/egocap/tests/backend/test_calibration_check_room.py @@ -0,0 +1,808 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The live check of a head camera that arrives over LiveKit: the video room is joined only while a check runs +and left on every way out, each picture is placed on the head poses' clock as the recorder places it, a check +and a take never run together, and a room that cannot be used says so in words. The room is the frame receiver +stand-in of the recorder's own LiveKit tests; the pictures are rendered boards.""" + +from __future__ import annotations + +import asyncio +import dataclasses +import functools +import json +import time +from types import SimpleNamespace + +import cv2 +import numpy as np +import pytest +from fastapi.testclient import TestClient + +from capture_server import protocol as p +from egocap.calibration.files import HEAD_EXTRINSICS, HEAD_INTRINSICS, OPENXR_POSES, POSE_SOURCE_KEY +from egocap_web import calibration_check as check_module +from egocap_web import calibration_check_pictures as pictures_module +from egocap_web import livekit_recording as lrec +from egocap_web.calibration_check import ( + ENDED_FOR_TAKE, + ENDED_LONG, + ENDED_UNASKED, + JOINS_ROOM, + LEASE_SECONDS, + MAX_CHECK_SECONDS, + NO_CHECK, + READS_ONLY, + TAKE_RUNNING, + LiveCheckService, +) +from egocap_web.calibration_check_pictures import WAITING, DeliveredPictures, RoomPictures, VideoRoom +from egocap_web.calibration_frames import NewestFrames, WatchedLiveKitSource +from egocap_web.clock_exchange import ClockMapping +from egocap_web.livekit_receiver import ReceivedFrame +from egocap_web.livekit_recording import CLOCK_MAPPING, FIRST_FRAME, JOINING, LiveKitRecordingSource +from tests.backend.test_calibration_check import BOARD, LOOK_S, POSE_S, World, board_at, refused, tree +from tests.backend.test_calibration_service import CAMERA_TAKE +from tests.backend.test_livekit_recording_source import FakeReceiver, livekit_stream +from tests.backend.test_livekit_recording_source import frame as room_frame +from tests.backend.test_preview_routes import _poll_until_sync, _ServerThread +from tests.recording.unit import calibration_synthetic as synthetic + +HEAD = synthetic.CAMERA +WIDTH, HEIGHT = synthetic.SIZE +STREAM_ID = 16 +#: The head camera as the capture session offers it over LiveKit, at the size the synthetic camera sends. +STREAM = dataclasses.replace(livekit_stream(STREAM_ID, width=WIDTH, height=HEIGHT), name=HEAD) +LOCAL_CAPTURE = "ws://127.0.0.1:8765" +AS_A_TAKE = "the check gets this camera's video the way a take does, and could not: " + + +@pytest.fixture(autouse=True) +def room(monkeypatch): + """The recorder's frame receiver replaced by its tests' stand-in, as for the recorder's own tests.""" + FakeReceiver.instances = [] + FakeReceiver.start_error = None + FakeReceiver.start_gate = FakeReceiver.stop_gate = None + FakeReceiver.mapping_ready = True + monkeypatch.setattr(lrec, "LiveKitFrameReceiver", FakeReceiver) + monkeypatch.setattr(lrec, "livekit_available", lambda: True) + # The recorder's source as it is, waiting only a moment where it would wait ten seconds. + monkeypatch.setattr( + pictures_module, + "LiveKitRecordingSource", + functools.partial(LiveKitRecordingSource, first_frame_timeout_s=0.2), + ) + + +async def settled(turns: int = 8) -> None: + """Let the join and the feed, which run as tasks, take what was put before them.""" + for _ in range(turns): + await asyncio.sleep(0) + + +def receiver() -> FakeReceiver: + return FakeReceiver.instances[-1] + + +class RoomWorld(World): + """A station whose head camera arrives over LiveKit: the capture server delivers no picture of it.""" + + def __init__(self, tmp_path, *, stream=STREAM, capture_server_url=LOCAL_CAPTURE, lag_s: float = 0.0): + super().__init__(tmp_path, lag_s=lag_s) + self.taking = False + self.tokens: list[str] = [] + #: How far the publisher's clock runs ahead of this machine's, in seconds. + self.publisher_ahead_s = 0.0 + self.sent = 0 + self.service = LiveCheckService( + monitor=SimpleNamespace(preview=self.preview), + calibration_dir=lambda: self.directory, + streams=None, + camera_for=lambda role: self.camera if role == "ego" else None, + monotonic=lambda: self.now, + video_room=VideoRoom( + lambda camera: stream if camera == HEAD else None, + lambda room_name: self.tokens.append(room_name) or f"token-{room_name}", + capture_server_url, + lambda: self.now, + ), + take_running=lambda: self.taking, + watch_seconds=0.01, + ) + + def frame(self, seconds: float, image: np.ndarray | None = None, stamped: bool = True) -> ReceivedFrame: + """The room's frame of a moment, stamped on the publisher's clock later by the camera's lag.""" + picture = synthetic.render(board_at(seconds)) if image is None else image + taken = seconds + self.lag_s + self.sent += 1 + return ReceivedFrame( + stream_id=STREAM_ID, + # The room delivers RGB; the renderer draws in the order OpenCV takes. + image=cv2.cvtColor(picture, cv2.COLOR_BGR2RGB), + # It arrives ten milliseconds after it was taken, on this machine's clock. + receive_time_ns=round((taken + 0.010) * 1e9), + transport_timestamp_us=self.sent, + user_timestamp_us=round((taken + self.publisher_ahead_s) * 1e6) if stamped else None, + frame_id=None, + user_data=None, + ) + + def send(self, seconds: float, **frame) -> None: + """Put the room's frame of a moment before the feed, with the tracking up to it delivered.""" + for moment in np.arange(self.fed, seconds + self.lag_s + 3 * POSE_S, POSE_S): + self.track(float(moment)) + self.fed = seconds + self.lag_s + 3 * POSE_S + receiver().queues[STREAM_ID].put_nowait(self.frame(seconds, **frame)) + + async def joined(self) -> dict: + """Start a check and bring it into the room: the join answered and the first frame taken.""" + started = await self.service.start({"board": BOARD}) + await settled() + self.send(0.25) + await settled() + return started + + async def sweep(self, looks: int, start: float = 0.5) -> dict: + """Send the board from a moving head ``looks`` times, polling after each; the last status.""" + status = {} + for index in range(looks): + self.send(start + index * LOOK_S) + await settled() + status = await self.service.poll() + return status + + +@pytest.fixture +async def world(tmp_path): + made = RoomWorld(tmp_path) + yield made + await made.service.aclose() + + +# --- joined only while a check runs, and for one camera's track ----------------------------------------------- + + +async def test_the_room_is_joined_when_a_check_starts_and_at_no_other_time_and_the_check_says_so(world, tmp_path): + before = tree(tmp_path) + # Nothing is joined for looking at what is installed, or for a check that is refused. + assert FakeReceiver.instances == [] + world.camera = None + assert ( + await refused(world.service.start({"board": BOARD}), 409) + == "no camera is assigned to the head camera role" + ) + world.camera = HEAD + assert FakeReceiver.instances == [] + started = await world.service.start({"board": BOARD}) + assert (started["video_room"], started["waiting"], started["check"]) == (True, WAITING[JOINING], None) + assert started["note"] == f"{READS_ONLY} {JOINS_ROOM}" + assert JOINS_ROOM == ( + "While it runs the backend is in the video room to see this camera, as it is during a take, and it leaves " + "when the check ends." + ) + await settled() + # One receiver, of this one camera's track, joined as the recorder joins: its token, its clock sync. + assert len(FakeReceiver.instances) == 1 + joined = receiver() + assert [stream.name for stream in joined.streams] == [HEAD] and joined.clock_sync_requested + assert (world.tokens, joined.token) == ([STREAM.room], f"token-{STREAM.room}") + assert joined.events == ["start"] and joined.stops == 0 + assert await world.service.stop() == {"phase": "stopped", "note": READS_ONLY} + assert joined.stops == 1 + # No take, no file, no ledger entry: the check in the room writes as little as the one outside it. + assert tree(tmp_path) == before + + +async def test_a_check_in_the_room_follows_the_error_to_a_verdict_on_pictures_the_room_decoded(world, tmp_path): + before = tree(tmp_path) + await world.joined() + done = await world.sweep(44) + check = done["check"] + assert (done["available"], done["waiting"], done["video_room"]) == (True, None, True) + assert check["verdict"] == "excellent" and check["rms_px"] < 1.5 and check["views"] >= 10 + assert (done["preview"]["width"], done["preview"]["height"]) == synthetic.SIZE + assert tree(tmp_path) == before + + +async def test_each_picture_is_placed_on_the_head_poses_clock_through_the_publishers_clock_mapping(tmp_path): + # The publisher's clock runs five seconds ahead of this machine's, and the camera lags the tracking by 80 ms. + world = RoomWorld(tmp_path, lag_s=0.08) + world.publisher_ahead_s = 5.0 + await world.service.start({"board": BOARD}) + await settled() + receiver().clock_sync.mapping = lambda: ClockMapping( + epoch=1, offset_ns=5_000_000_000, rtt_ns=2_000, uncertainty_ns=1_000, accepted_at_ns=0 + ) + world.send(0.25) + await settled() + mapped = await world.sweep(40) + assert mapped["camera_lag_ms"] == 80.0 and mapped["check"]["rms_px"] < 1.5 + await world.service.aclose() + # Paired by any other time the same pictures meet the wrong head poses: here the stored lag is not stated. + unstated = RoomWorld(tmp_path / "unstated") + unstated.lag_s = 0.08 + await unstated.joined() + wrong = (await unstated.sweep(40))["check"] + # The pixels show it, and the check names it: the pictures are some 80 ms older than the file says. + assert wrong["rms_px"] > 1.0 and wrong["verdict"] == "bad" + assert wrong["camera_lag_off_s"] == pytest.approx(0.08, abs=0.02) + await unstated.service.aclose() + + +async def test_the_check_says_what_it_waits_for_while_the_room_the_first_picture_and_the_clock_come(world): + FakeReceiver.start_gate = asyncio.Event() + FakeReceiver.mapping_ready = False + await world.service.start({"board": BOARD}) + await settled() + waiting = await world.service.poll() + assert (waiting["available"], waiting["waiting"], waiting["check"]) == (True, WAITING[JOINING], None) + assert WAITING[JOINING] == "Joining the video room to see this camera." + # The room answers: the camera's first picture is waited for. + FakeReceiver.start_gate.set() + await settled() + assert (await world.service.poll())["waiting"] == WAITING[FIRST_FRAME] + assert WAITING[FIRST_FRAME] == "In the video room: waiting for this camera's first picture." + # Pictures arrive before the publisher has answered a clock exchange: the check waits, and says for what. + receiver().queues[STREAM_ID].put_nowait(world.frame(0.25)) + await settled() + clockless = await world.service.poll() + assert (clockless["available"], clockless["check"]) == (True, None) + assert clockless["waiting"] == WAITING[CLOCK_MAPPING] + assert WAITING[CLOCK_MAPPING] == ( + "Pictures are arriving: waiting for the camera sender's clock to be matched to this computer's, so " + "that each picture's time can be placed among the head poses." + ) + # The mapping comes: from then on pictures are looked at. + receiver().clock_sync.ready = True + await asyncio.sleep(0.1) + await settled() + assert (await world.service.poll())["waiting"] == WAITING[FIRST_FRAME] + looked = await world.sweep(2) + assert looked["waiting"] is None and looked["check"]["board_visible"] is True + + +# --- a room that cannot be used says so in words -------------------------------------------------------------- + + +async def test_a_room_that_cannot_be_joined_says_so_in_a_sentence_of_its_own_and_is_not_stayed_in(world, caplog): + # What a video server answers a refused join with can hold anything, its own configuration included. + said = "signal failure: 401 Unauthorized - body of the server's answer, host=media.example path=/srv/config" + FakeReceiver.start_error = RuntimeError(said) + await world.service.start({"board": BOARD}) + await settled() + unjoined = await world.service.poll() + assert (unjoined["available"], unjoined["waiting"], unjoined["check"], unjoined["preview"]) == ( + False, + None, + None, + None, + ) + assert unjoined["unavailable_reason"] == ( + "the video room could not be joined, so the check has no picture of this camera: check that the video " + "server is running and that this computer reaches it, then start the check again" + ) + # The library's own words are for the log, and none of them reaches the page. + assert said in caplog.text and "Unauthorized" not in json.dumps(unjoined) + # Out of the room, the status no longer says the backend is in it. + assert (unjoined["video_room"], unjoined["note"]) == (False, READS_ONLY) + # The source left the room it could not use, and stopping the check leaves nothing to leave. + assert receiver().stops == 1 + await world.service.stop() + assert receiver().stops == 1 + + +async def test_a_clock_that_is_never_matched_and_a_camera_that_never_sends_end_the_wait_with_the_reason(world): + FakeReceiver.mapping_ready = False + await world.service.start({"board": BOARD}) + await settled() + receiver().queues[STREAM_ID].put_nowait(world.frame(0.25)) + await asyncio.sleep(0.4) + assert (await world.service.poll())["unavailable_reason"] == ( + "this camera's pictures arrive, and the camera sender's clock could not be matched to this computer's, " + "so their times cannot be placed among the head poses: check the camera's sender, then start the check " + "again" + ) + assert receiver().stops == 1 + # A camera whose track sends nothing: the second check's room is left the same way. + FakeReceiver.mapping_ready = True + await world.service.start({"board": BOARD}) + await asyncio.sleep(0.4) + silent = await world.service.poll() + assert silent["unavailable_reason"] == ( + "the video room was joined, and this camera's first picture did not come as a take needs it, so the " + "check has no picture of it: check the camera's sender, then start the check again" + ) + assert len(FakeReceiver.instances) == 2 and receiver().stops == 1 + + +async def test_a_room_token_that_cannot_be_signed_says_so(tmp_path): + world = RoomWorld(tmp_path) + + def unsigned(room_name: str) -> str: + raise RuntimeError("the room's key pair is not set") + + world.service._room = VideoRoom(lambda camera: STREAM, unsigned, LOCAL_CAPTURE, lambda: world.now) + await world.service.start({"board": BOARD}) + await settled() + assert (await world.service.poll())["unavailable_reason"].startswith( + "the video room could not be joined, so the check has no picture of this camera: check that the video " + ) + assert FakeReceiver.instances == [] + await world.service.aclose() + + +async def test_video_that_could_not_be_placed_among_the_head_poses_is_refused_before_the_room_is_joined( + tmp_path, monkeypatch +): + start = {"board": BOARD} + # Stamped on a clock that cannot be mapped onto this machine's: nothing that waiting in the room could change. + unmappable = dataclasses.replace(STREAM, timestamp_basis=p.LiveKitTimestampBasis.PUBLISHER_PROCESSING_UNIX_US) + assert await refused(RoomWorld(tmp_path / "a", stream=unmappable).service.start(start), 409) == ( + AS_A_TAKE + f"LiveKit stream {HEAD!r}: its timestamps are not on the publisher's monotonic clock, so it " + "cannot be recorded" + ) + # Tracking that comes from another machine is on another clock than the one frames are placed on. + elsewhere = RoomWorld(tmp_path / "b", capture_server_url="ws://capture.example:8765") + assert (await refused(elsewhere.service.start(start), 409)).startswith( + AS_A_TAKE + f"LiveKit stream {HEAD!r}: recording needs CaptureServer on this machine" + ) + monkeypatch.setattr(lrec, "livekit_available", lambda: False) + assert (await refused(RoomWorld(tmp_path / "c").service.start(start), 409)).startswith( + AS_A_TAKE + f"LiveKit stream {HEAD!r}: receiving LiveKit video needs the livekit package" + ) + assert FakeReceiver.instances == [] + + +async def test_video_that_stops_in_the_room_ends_the_looking_with_the_reason_and_the_room_is_left(world): + await world.joined() + assert (await world.sweep(8))["check"]["phase"] == "checking" + # The camera's track is lost, which would end a take. + receiver().queues[STREAM_ID].put_nowait(None) + await settled() + lost = await world.service.poll() + assert (lost["available"], lost["preview"]) == (False, None) + assert lost["unavailable_reason"] == AS_A_TAKE + f"{HEAD}: the LiveKit track was lost" + # The backend has left the room, and the status says so. + assert (lost["video_room"], lost["note"]) == (False, READS_ONLY) + # What was found before stands, and the backend is no longer in the room. + assert lost["check"]["phase"] == "checking" and receiver().stops == 1 + await world.service.stop() + assert receiver().stops == 1 + + +async def test_a_picture_without_the_publishers_time_is_not_placed_by_when_it_arrived(world): + await world.joined() + world.send(0.5, stamped=False) + await settled() + unstamped = await world.service.poll() + assert unstamped["unavailable_reason"] == ( + AS_A_TAKE + f"{HEAD}: a frame arrived without the publisher's frame timestamp" + ) + assert unstamped["check"] is None + + +async def test_a_picture_of_another_size_than_the_session_declares_is_refused_as_a_take_would_refuse_it(world): + await world.service.start({"board": BOARD}) + await settled() + half = cv2.resize(synthetic.render(synthetic.sweep_pose(0.0)), (WIDTH // 2, HEIGHT // 2)) + receiver().queues[STREAM_ID].put_nowait(world.frame(0.25, image=half)) + await settled() + assert (await world.service.poll())["unavailable_reason"].startswith( + "the video room was joined, and this camera's first picture did not come as a take needs it" + ) + assert receiver().stops == 1 + + +# --- the ways out of the room --------------------------------------------------------------------------------- + + +async def test_stopping_the_check_leaves_the_room_also_while_it_is_still_being_joined(world): + await world.joined() + assert receiver().stops == 0 + await world.service.stop() + assert receiver().stops == 1 and await refused(world.service.poll(), 404) == NO_CHECK + # Stopped before the room answered: the join is abandoned, and the room is left as soon as it does answer. + FakeReceiver.start_gate = asyncio.Event() + await world.service.start({"board": BOARD}) + await settled() + await world.service.stop() + assert receiver().stops == 0 + FakeReceiver.start_gate.set() + await settled() + assert len(FakeReceiver.instances) == 2 and receiver().stops == 1 + + +async def test_a_check_no_page_asks_about_any_more_leaves_the_room_when_its_lease_runs_out(world): + await world.joined() + # A page that keeps asking keeps the check: each poll is the lease. + for _ in range(3): + world.now += LEASE_SECONDS - 5.0 + await asyncio.sleep(0.03) + world.send(world.fed) + await settled() + assert (await world.service.poll())["phase"] == "checking" + assert receiver().stops == 0 + # The page is closed without stopping the check. + world.now += LEASE_SECONDS + 1.0 + await asyncio.sleep(0.05) + assert receiver().stops == 1 + assert await refused(world.service.poll(), 404) == ENDED_UNASKED + assert ENDED_UNASKED == "the check ended because the page that started it stopped asking about it" + assert LEASE_SECONDS == 20.0 + + +async def test_a_take_that_starts_ends_the_check_and_the_room_is_left_before_the_recorder_joins_it(world): + await world.joined() + order: list[str] = [] + check_receiver = receiver() + + class Recorder: + async def prepare(self) -> None: + order.append(f"the recorder joins with the check's receiver stopped {check_receiver.stops} time(s)") + + # As the application wires it: the recorder's source lets the check leave before its own join. + recorder = WatchedLiveKitSource(Recorder(), NewestFrames(), before_join=world.service.yield_to_take) + await recorder.prepare() + assert order == ["the recorder joins with the check's receiver stopped 1 time(s)"] + assert await refused(world.service.poll(), 404) == ENDED_FOR_TAKE + assert ENDED_FOR_TAKE == "the check ended because a take started: the two never run together" + # A take that starts with no check running ends nothing and is told nothing. + await world.service.stop() + await world.service.yield_to_take() + assert await refused(world.service.poll(), 404) == NO_CHECK + + +async def test_a_check_is_refused_while_a_take_records_and_joins_no_room(world, tmp_path): + world.taking = True + assert await refused(world.service.start({"board": BOARD}), 409) == TAKE_RUNNING + assert TAKE_RUNNING == ( + "a take is being recorded, and the check never runs beside one: finish or discard the take first" + ) + assert FakeReceiver.instances == [] + # A take that starts while the installed files are being read is seen before the room is joined. + answers = iter([False, True]) + racing = RoomWorld(tmp_path / "racing") + racing.service._take_running = lambda: next(answers) + assert await refused(racing.service.start({"board": BOARD}), 409) == TAKE_RUNNING + assert FakeReceiver.instances == [] + # The take over, the check starts. + world.taking = False + assert (await world.service.start({"board": BOARD}))["video_room"] is True + + +async def _in_the_room_with_a_feed_whose_stop_raises(world) -> FakeReceiver: + """A check in the room whose feed has died of something the feed does not expect: stopping it raises.""" + await world.joined() + + async def dead() -> None: + raise KeyError("an exception the feed does not expect") + + world.service._check.pictures._source._feed.stop = dead + return receiver() + + +async def test_a_leave_that_raises_refuses_no_take_and_the_room_is_still_left(world, caplog): + joined = await _in_the_room_with_a_feed_whose_stop_raises(world) + # The take's own hook: it must not raise into the recorder's join. + await world.service.yield_to_take() + assert joined.stops == 1 + assert await refused(world.service.poll(), 404) == ENDED_FOR_TAKE + assert "The live calibration check did not leave cleanly" in caplog.text + + +async def test_a_leave_that_raises_answers_the_stop_and_does_not_cut_a_shutdown_short(world): + joined = await _in_the_room_with_a_feed_whose_stop_raises(world) + assert await world.service.stop() == {"phase": "stopped", "note": READS_ONLY} + assert joined.stops == 1 + again = await _in_the_room_with_a_feed_whose_stop_raises(world) + await world.service.aclose() + assert again.stops == 1 + + +@pytest.mark.parametrize( + ("take_waits_s", "source_waits_s"), + [(0.05, 5.0), (5.0, 0.02)], + ids=["the take's own limit", "the limit of the check's leave"], +) +async def test_a_leave_that_stalls_does_not_hold_the_take_and_finishes_behind_it( + world, monkeypatch, take_waits_s, source_waits_s +): + monkeypatch.setattr(check_module, "YIELD_SECONDS", take_waits_s) + monkeypatch.setattr(pictures_module, "LEAVE_SECONDS", source_waits_s) + await world.joined() + joined = receiver() + # The room does not answer the leave. + FakeReceiver.stop_gate = asyncio.Event() + began = time.monotonic() + await world.service.yield_to_take() + assert time.monotonic() - began < 1.0 + # The check is over for the page and for the take, with its leave still under way. + assert joined.stops == 0 and await refused(world.service.poll(), 404) == ENDED_FOR_TAKE + # A shutdown gives a leave still under way a moment, and goes on without it. + monkeypatch.setattr(check_module, "YIELD_SECONDS", 0.05) + await world.service.aclose() + assert joined.stops == 0 + FakeReceiver.stop_gate.set() + await settled() + assert joined.stops == 1 + + +async def test_whatever_closing_a_checks_pictures_raises_the_check_is_over_and_nobody_is_failed(world, caplog): + await world.joined() + pictures = world.service._check.pictures + close = pictures.close + + async def broken() -> None: + await close() + raise RuntimeError("pictures that could not be given up") + + pictures.close = broken + assert await world.service.stop() == {"phase": "stopped", "note": READS_ONLY} + assert receiver().stops == 1 and await refused(world.service.poll(), 404) == NO_CHECK + assert "The live calibration check did not leave cleanly" in caplog.text + + +async def test_a_check_that_was_replaced_while_its_watcher_waited_is_not_ended_by_it(world): + await world.joined() + first = world.service._check + async with world.service._changing: + # The lease runs out while something else holds the service, and when the watcher is let in the + # check it watched is no longer the one that runs. + world.now += LEASE_SECONDS + 1.0 + await asyncio.sleep(0.05) + world.service._check, world.service._ended = None, "ended by what held the service" + await settled() + # The watcher finds its check gone, ends nothing and says nothing of its own. + assert receiver().stops == 0 + assert await refused(world.service.poll(), 404) == "ended by what held the service" + await first.pictures.close() + assert receiver().stops == 1 + + +async def test_a_check_has_a_longest_length_however_long_a_page_keeps_asking(world): + await world.joined() + # A tab left open asks for ever: each poll renews the lease, and the check still ends. + for _ in range(int(MAX_CHECK_SECONDS / 10.0) + 2): + world.now += 10.0 + await asyncio.sleep(0.02) + if receiver().stops: + break + assert (await world.service.poll())["phase"] == "checking" + assert receiver().stops == 1 + assert await refused(world.service.poll(), 404) == ENDED_LONG + assert ENDED_LONG == "the check ended after ten minutes, its longest: start it again to go on checking" + assert MAX_CHECK_SECONDS == 600.0 + + +async def test_a_join_that_is_given_up_is_said_and_never_waited_for(world): + FakeReceiver.start_gate = asyncio.Event() + await world.service.start({"board": BOARD}) + await settled() + assert (await world.service.poll())["waiting"] == WAITING[JOINING] + # The join is cancelled from outside the check, as a shutdown of its task would. + world.service._check.pictures._joining.cancel() + await settled() + given_up = await world.service.poll() + assert (given_up["waiting"], given_up["available"], given_up["video_room"]) == (None, False, False) + assert given_up["unavailable_reason"] == ( + "the video room was left before this camera's pictures came, so the check has no picture of it: start " + "the check again" + ) + FakeReceiver.start_gate.set() + + +async def test_shutdown_leaves_the_room(world): + await world.joined() + await world.service.aclose() + assert receiver().stops == 1 + # With no check running there is nothing to leave. + await world.service.aclose() + assert receiver().stops == 1 + + +async def test_a_check_started_again_leaves_the_room_before_it_joins_it_again(world): + await world.joined() + first = receiver() + FakeReceiver.start_gate = asyncio.Event() + again = await world.service.start({"board": BOARD}) + await settled() + # The first check's place in the room is given up before the second is taken. + assert first.stops == 1 and len(FakeReceiver.instances) == 2 and receiver().stops == 0 + assert (again["check"], again["waiting"]) == (None, WAITING[JOINING]) + FakeReceiver.start_gate.set() + + +# --- a camera the capture server delivers, beside one that arrives over the room ------------------------------ + + +async def test_a_camera_the_capture_server_delivers_joins_no_room_and_has_no_lease(tmp_path): + world = RoomWorld(tmp_path) + # The head role is filled by a camera the room does not carry. + world.service._room = VideoRoom(lambda camera: None, lambda name: "token", LOCAL_CAPTURE, lambda: world.now) + world.show(0.25) + started = await world.service.start({"board": BOARD}) + assert (started["video_room"], started["waiting"], started["note"]) == (False, None, READS_ONLY) + # Left alone for longer than a lease: it holds nothing, and goes on when the page asks again. + world.now += 3 * LEASE_SECONDS + await asyncio.sleep(0.05) + world.show(0.5) + assert (await world.service.poll())["available"] is True + assert FakeReceiver.instances == [] + # A take ends it all the same: a check and a take never run together. + await world.service.yield_to_take() + assert await refused(world.service.poll(), 404) == ENDED_FOR_TAKE + + +async def test_the_capture_servers_pictures_have_nothing_to_wait_for_and_nothing_to_give_up(): + delivered = DeliveredPictures(SimpleNamespace(camera=lambda name: None), HEAD) + delivered.open() + assert (delivered.in_room, delivered.newest(), delivered.waiting(), delivered.failure()) == ( + False, + None, + None, + None, + ) + await delivered.close() + + +async def test_the_rooms_pictures_hold_no_place_in_the_room_before_they_are_opened_or_after_they_are_closed(): + unopened = RoomPictures(STREAM, lambda room_name: "token") + # They would hold a place in the room, so a forgotten check must not keep them; they hold none yet. + assert (unopened.leased, unopened.in_room) == (True, False) + assert (unopened.newest(), unopened.waiting(), unopened.failure()) == (None, None, None) + # Closing what was never opened joins nothing and leaves nothing. + await unopened.close() + assert FakeReceiver.instances == [] and unopened.in_room is False + + +# --- the application's own wiring ------------------------------------------------------------------------------- + + +def test_the_real_application_joins_the_room_for_a_check_leaves_it_for_a_take_and_leaves_it_at_shutdown( + monkeypatch, unused_tcp_port, tmp_path +): + """The real application against the real CaptureServer in its mock mode. The mock offers its head camera as + JPEGs; the check is told the camera arrives over LiveKit, so that it goes to the room, which is the + recorder's tests' stand-in. Everything between the two is the application's.""" + from egocap_web import app as app_module + from egocap_web.app import app as real_app + + camera, root = "head_human_camera", "/api/calibration" + station_file = tmp_path / "station.yaml" + station_file.write_text(f"video_sources:\n- type: oak_camera\n name: {camera}\n", encoding="utf-8") + calibration = tmp_path / "calibration" + calibration.mkdir() + 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) + # The recorder's token function signs the check's room token; the key pair is made up. + monkeypatch.setenv("LIVEKIT_API_KEY", "key") + monkeypatch.setenv("LIVEKIT_API_SECRET", "secret") + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: tmp_path / "recordings") + server = _ServerThread(unused_tcp_port) + try: + with TestClient(real_app) as client: + check, context, monitor = ( + client.app.state.calibration_check, + client.app.state.recording_context, + client.app.state.monitor, + ) + auth = {"X-Control-Token": context.control_token} + _poll_until_sync(lambda: monitor.snapshot().running and monitor.preview.camera(camera) is not None) + width, height = monitor.camera_size(camera) + stream = dataclasses.replace(livekit_stream(STREAM_ID, width=width, height=height), name=camera) + lens = { + "model": "pinhole", + "K": [[0.7 * width, 0.0, width / 2], [0.0, 0.7 * width, height / 2], [0.0, 0.0, 1.0]], + "dist_coeffs": [0.0, 0.0, 0.0, 0.0, 0.0], + "image_size_wh": [width, height], + } + (calibration / HEAD_INTRINSICS).write_text(json.dumps(lens)) + (calibration / HEAD_EXTRINSICS).write_text( + json.dumps({POSE_SOURCE_KEY: OPENXR_POSES, "T_headset_camera": np.eye(4).tolist()}) + ) + roles = {"camera_roles": {"ego": camera}} + assert client.put("/api/operator-settings", json=roles, headers=auth).status_code == 200 + # The tool reads the overview when it opens, which is when the stored roles are read again; it says + # of this camera what the capture session says: delivered by the capture server. + assert client.get(root, headers=auth).json()["cameras"][0]["video_room"] is False + # The application asks the capture monitor which cameras arrive over LiveKit, and knows the capture + # server is this machine. The mock delivers this camera itself, so the monitor is made to say it + # arrives over LiveKit: the overview and the check both go by it. + assert check._room.stream(camera) is None and check._room._capture_server_url.startswith( + "ws://127.0.0.1:" + ) + monitor.livekit_stream = lambda name: stream if name == camera else None + assert client.get(root, headers=auth).json()["cameras"][0]["video_room"] is True + + started = client.post(f"{root}/check", json={"board": BOARD}, headers=auth) + assert started.status_code == 200, started.json() + assert (started.json()["video_room"], started.json()["waiting"]) == (True, WAITING[JOINING]) + _poll_until_sync(lambda: len(FakeReceiver.instances) == 1) + joined = FakeReceiver.instances[0] + # A token the room would accept: signed, for the stream's room. + assert joined.token.count(".") == 2 and [s.name for s in joined.streams] == [camera] + + def send() -> None: + client.portal.call( + joined.queues[STREAM_ID].put_nowait, room_frame(STREAM_ID, width=width, height=height) + ) + + send() + _poll_until_sync( + lambda: client.get(f"{root}/check", headers=auth).json()["waiting"] != WAITING[JOINING] + ) + + def looked() -> bool: + send() + return client.get(f"{root}/check", headers=auth).json()["check"] is not None + + # The room's pictures reach the check, at times the mock's tracking can be found around. + _poll_until_sync(looked) + status = client.get(f"{root}/check", headers=auth).json() + assert status["available"] is True and status["check"]["board_visible"] is False + assert joined.stops == 0 + + # A take starts: the check has left the room before the recorder prepares its own video. + take = client.post(f"{root}/recording", json={**CAMERA_TAKE, "mode": "intrinsic"}, headers=auth) + assert take.status_code == 200, take.json() + assert joined.stops == 1 + ended = client.get(f"{root}/check", headers=auth) + assert (ended.status_code, ended.json()) == (404, {"detail": ENDED_FOR_TAKE}) + # And none is started beside the take. + beside = client.post(f"{root}/check", json={"board": BOARD}, headers=auth) + assert (beside.status_code, beside.json()) == (409, {"detail": TAKE_RUNNING}) + assert len(FakeReceiver.instances) == 1 + time.sleep(0.3) + assert client.post(f"{root}/recording/cancel", json={}, headers=auth).status_code == 200 + + # The take over, a check joins the room again, and the application leaves it when it shuts down. + again = client.post(f"{root}/check", json={"board": BOARD}, headers=auth) + assert again.status_code == 200, again.json() + _poll_until_sync(lambda: len(FakeReceiver.instances) == 2) + assert FakeReceiver.instances[1].stops == 0 + assert FakeReceiver.instances[1].stops == 1 + finally: + server.stop() + + +def test_a_check_that_cannot_be_closed_does_not_cut_the_applications_shutdown_short( + monkeypatch, unused_tcp_port, tmp_path, caplog +): + """The real application against the real CaptureServer in its mock mode, shut down with a check whose + closing raises: the steps of the shutdown after the check still run.""" + from egocap_web import app as app_module + from egocap_web.app import app as real_app + + 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") + 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(tmp_path / "calibration")) + monkeypatch.delenv("EGOCAP_OPERATOR_SETTINGS_FILE", raising=False) + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: tmp_path / "recordings") + server = _ServerThread(unused_tcp_port) + after: list[str] = [] + try: + with TestClient(real_app) as client: + state = client.app.state + _poll_until_sync(lambda: state.monitor.snapshot().running) + + async def broken() -> None: + raise KeyError("a check that cannot be closed") + + closing = state.calibration.aclose + + async def noted() -> None: + after.append("the calibration tools were closed") + await closing() + + state.calibration_check.aclose = broken + state.calibration.aclose = noted + finally: + server.stop() + assert after == ["the calibration tools were closed"] + assert "The live calibration check could not be closed" in caplog.text diff --git a/examples/egocap/tests/backend/test_calibration_frames.py b/examples/egocap/tests/backend/test_calibration_frames.py index 56456af994..f0a36ea715 100644 --- a/examples/egocap/tests/backend/test_calibration_frames.py +++ b/examples/egocap/tests/backend/test_calibration_frames.py @@ -12,7 +12,7 @@ import numpy as np import pytest -from egocap_web.calibration_frames import DecodedFrame, NewestFrames, WatchedLiveKitSource +from egocap_web.calibration_frames import DecodedFrame, NewestFrames, NotingIngress, WatchedLiveKitSource from recording_service import PixelFormat, VideoSample HEAD, WRIST = "head_camera", "left_wrist_camera" @@ -23,8 +23,10 @@ def picture(blue: int, green: int, red: int) -> np.ndarray: return np.full((4, 6, 3), (blue, green, red), dtype=np.uint8) -def sample(camera: str, image: np.ndarray, pixel_format: PixelFormat = PixelFormat.RGB8) -> VideoSample: - return VideoSample(camera, image, pixel_format, capture_time=1.0, receive_time=1.0) +def sample( + camera: str, image: np.ndarray, pixel_format: PixelFormat = PixelFormat.RGB8, capture_time: float = 1.0 +) -> VideoSample: + return VideoSample(camera, image, pixel_format, capture_time=capture_time, receive_time=1.0) class Source: @@ -75,6 +77,8 @@ def test_the_newest_frame_of_each_camera_is_kept_by_name_with_when_it_came_and_a # The take's own array, not a copy: a frame is noted on its way in, and nothing is spent on it there. assert kept.image is first and kept.pixel_format is PixelFormat.RGB8 assert (kept.received_monotonic, kept.sequence) == (10.0, 1) + # Its time is the one the feed placed it at, which is the time a take records it with. + assert kept.capture_time == 1.0 now[0] = 10.5 frames.note(sample(WRIST, picture(4, 5, 6))) frames.note(sample(HEAD, picture(7, 8, 9))) @@ -101,7 +105,7 @@ def test_anything_but_a_decoded_video_frame_is_nothing_to_look_at(): @pytest.mark.parametrize("pixel_format", [PixelFormat.RGB8, PixelFormat.BGR8]) def test_a_frame_is_handed_out_in_the_order_the_guides_take_as_an_array_of_its_own(pixel_format): stored = picture(10, 20, 30) if pixel_format is PixelFormat.BGR8 else picture(30, 20, 10) - frame = DecodedFrame(stored, pixel_format, received_monotonic=0.0, sequence=1) + frame = DecodedFrame(stored, pixel_format, capture_time=0.0, received_monotonic=0.0, sequence=1) handed = frame.bgr() assert handed[0, 0].tolist() == [10, 20, 30] # Drawing on what was handed out writes nothing into the array the take records. @@ -148,3 +152,39 @@ async def test_the_frames_of_a_take_are_forgotten_also_when_leaving_the_room_fai with pytest.raises(RuntimeError, match="the room is gone"): await watched.stop() assert frames.newest(HEAD) is None + + +def test_an_ingress_that_only_notes_keeps_each_frame_as_its_cameras_newest_and_always_accepts(): + frames = NewestFrames() + ingress = NotingIngress(frames) + first, second = ( + sample(HEAD, picture(1, 2, 3), capture_time=7.25), + sample(HEAD, picture(4, 5, 6), capture_time=7.5), + ) + assert ingress.offer(first) is True and frames.newest(HEAD).capture_time == 7.25 + assert ingress.offer(second) is True + assert frames.newest(HEAD).image is second.image and frames.newest(HEAD).capture_time == 7.5 + # Whatever is no decoded frame is accepted and passed over, as the take's watcher passes it over. + assert ( + ingress.offer(SimpleNamespace(source="pico_controller")) is True + and frames.newest("pico_controller") is None + ) + + +async def test_whatever_must_leave_the_room_for_a_take_has_left_before_the_recorder_joins(): + source, order = Source(), [] + + async def leave() -> None: + order.append("left") + + source.prepare = _then(order, "joined") + watched = WatchedLiveKitSource(source, NewestFrames(), before_join=leave) + await watched.prepare() + assert order == ["left", "joined"] + + +def _then(order: list[str], word: str): + async def noted() -> None: + order.append(word) + + return noted diff --git a/examples/egocap/tests/backend/test_calibration_routes.py b/examples/egocap/tests/backend/test_calibration_routes.py index 7400f4a880..c036b47965 100644 --- a/examples/egocap/tests/backend/test_calibration_routes.py +++ b/examples/egocap/tests/backend/test_calibration_routes.py @@ -928,10 +928,25 @@ def test_the_real_application_records_a_calibration_take_and_gives_the_operators "role": "ego", "camera": "head_human_camera", "live": True, + "video_room": False, "intrinsics_file": "head_camera_intrinsics.json", "default_model": "pinhole", "rectified": False, "rectification_waits": False, + # Said before the take: the mock camera sends another size of picture than the station's lens + # file was solved at, so a lens take would replace that file and a position take contradict it. + "picture_notes": { + "lens": ( + "head_camera_intrinsics.json was solved on a 640x480 picture, and this camera now sends " + "1280x720. A solve from this take replaces it with one for the new size: if the size " + "changed by mistake, set the camera's picture mode back before recording" + ), + "position": ( + "head_camera_intrinsics.json is for a 640x480 picture, and this camera now sends " + "1280x720, so the camera's position cannot be solved against it. Solve the lens as " + "well, or set the camera's picture mode back before recording" + ), + }, } assert overview["recording"] is None and overview["glove_session"] is None diff --git a/examples/egocap/tests/backend/test_calibration_service.py b/examples/egocap/tests/backend/test_calibration_service.py index 55545049ab..773ecba883 100644 --- a/examples/egocap/tests/backend/test_calibration_service.py +++ b/examples/egocap/tests/backend/test_calibration_service.py @@ -16,7 +16,7 @@ import json import logging import threading -from datetime import datetime +from datetime import datetime, timedelta, timezone from pathlib import Path from types import SimpleNamespace @@ -25,7 +25,7 @@ import pytest import zarr -from egocap.calibration import station_store +from egocap.calibration import files, station_store from egocap.calibration.board import BoardSpec, CalibrationError from egocap.calibration.camera_pipeline import CameraCalibrationResult from egocap.calibration.files import OPENXR_POSES, POSE_SOURCE_KEY, pose_source_problem @@ -117,6 +117,7 @@ VideoSample, storage_problem, ) +from tests.backend import test_setup_checks as day_checks from tests.backend.test_recording_adapter import default_tracking_values from tests.backend.test_rectification_service import SMALL_CHOICE, launcher_applied from tests.recording.unit import calibration_synthetic as synthetic @@ -322,10 +323,17 @@ class Gate: def __init__(self): self.failing: dict[str, str] = {} self.asked: list[frozenset[str]] = [] + #: The tracking devices each asking take said it does not record with. + self.unused: list[frozenset[str]] = [] - def __call__(self, ignore: frozenset[str] = frozenset()) -> str | None: + def __call__( + self, ignore: frozenset[str] = frozenset(), unused_devices: frozenset[str] = frozenset() + ) -> str | None: self.asked.append(ignore) - return next((reason for item, reason in self.failing.items() if item not in ignore), None) + self.unused.append(unused_devices) + # An item named for a tracking device holds only a take that records with that device. + left_out = ignore | {f"device:{device}" for device in unused_devices} + return next((reason for item, reason in self.failing.items() if item not in left_out), None) class World: @@ -355,7 +363,13 @@ def __init__( SimpleNamespace(name=LEFT, width=640, height=480), ), offered_camera_names=lambda: self.offered, + camera_size=lambda name: self.sizes.get(name), + livekit_stream=lambda name: SimpleNamespace(name=name) if name in self.over_livekit else None, ) + #: The cameras that reach the backend through the LiveKit room. + self.over_livekit: set[str] = set() + #: The size of the picture the capture session says each camera sends. + self.sizes: dict[str, tuple[int, int]] = {HEAD: (640, 480), LEFT: (640, 480)} self.roles: dict[str, str | None] = {"ego": HEAD, "wrist_left": LEFT, "wrist_right": None} self.station: SimpleNamespace | None = SimpleNamespace(camera_roles=self.roles, camera_type=None) self.stations = SimpleNamespace(registry=SimpleNamespace(selected=self.station)) @@ -938,6 +952,23 @@ async def test_missing_calibration_files_never_hold_the_take_that_produces_them( assert world.gate.asked == [CALIBRATION_ITEMS] and CALIBRATION_ITEMS == frozenset({"calibration"}) +async def test_a_tools_take_is_not_held_for_a_required_device_that_tool_does_not_record_with(world): + held = "Left glove: not reported by the capture session; this station requires it" + world.gate.failing = {"device:glove_left": held} + # The headset calibration records the headset and both controllers, and no glove. + assert (await world.service.start_recording({**CAMERA_TAKE, "mode": "intrinsic"}))["phase"] == "recording" + assert world.gate.unused == [frozenset({"glove_left", "glove_right"})] + await world.service.cancel_recording() + # The controller-glove offset is fitted on the gloves: its take waits for them. + await refused(world.service.start_recording(GLOVE_TAKE), 409, held) + assert world.gate.unused[-1] == frozenset() + # A device the camera take does record with holds it as it holds any take. + world.gate.failing = {"device:controller_left": "Left controller: unavailable; this station requires it"} + await refused( + world.service.start_recording(CAMERA_TAKE), 409, "Left controller: unavailable; this station requires it" + ) + + async def test_a_take_needs_a_camera_the_station_assigns_and_the_session_offers(world): start = world.service.start_recording wrist = {**CAMERA_TAKE, "role": "wrist_right", "mode": "intrinsic"} @@ -2816,6 +2847,62 @@ async def test_a_calibration_solved_for_another_camera_is_not_built_on(world, mo assert (await start(GLOVE_TAKE))["phase"] == "recording" +async def test_the_overview_says_of_each_file_of_a_newer_layout_that_this_software_cannot_read_it(world): + def said(name: str) -> str: + return ( + f"{name} is written in layout 2, and this software reads up to layout 1: update the software, or " + "calibrate again with this one" + ) + + # Every installed file states a newer layout, as on a station rolled back to this build. + world.install("head_camera_intrinsics.json", {"schema_version": 2, "K": [[1, 0, 0], [0, 1, 0], [0, 0, 1]]}) + world.install("head_camera_extrinsics.json", {**POSITION, "schema_version": "2"}) + world.install( + "wrist_calibration_offsets.json", {"n_samples": 40, "pose_source": "openxr", "schema_version": 2.0} + ) + files = {row["name"]: row for row in (await world.service.overview(None))["files"]} + for name in ("head_camera_intrinsics.json", "head_camera_extrinsics.json", "wrist_calibration_offsets.json"): + assert files[name]["problem"] == said(name) + # The layout this build writes is listed without a problem. + world.install("head_camera_extrinsics.json", {**POSITION, "schema_version": 1}) + files = {row["name"]: row for row in (await world.service.overview(None))["files"]} + assert "problem" not in files["head_camera_extrinsics.json"] + + +async def test_a_layout_number_of_any_length_is_a_sentence_in_the_overview_and_at_the_start_of_the_day( + world, tmp_path +): + def said(name: str) -> str: + return ( + f"{name} is written in a layout far newer than any this software knows, and this software reads up " + "to layout 1: update the software, or calibrate again with this one" + ) + + endless = "9" * 5000 + lens = {"schema_version": endless, "K": [[1, 0, 0], [0, 1, 0], [0, 0, 1]]} + world.install("head_camera_intrinsics.json", lens) + world.install("head_camera_extrinsics.json", {**POSITION, "schema_version": endless}) + world.install( + "wrist_calibration_offsets.json", {"n_samples": 40, "pose_source": "openxr", "schema_version": "2.0"} + ) + files = {row["name"]: row for row in (await world.service.overview(None))["files"]} + assert files["head_camera_intrinsics.json"]["problem"] == said("head_camera_intrinsics.json") + assert files["head_camera_extrinsics.json"]["problem"] == said("head_camera_extrinsics.json") + # A number written as text with a fraction part of zero is that number. + assert files["wrist_calibration_offsets.json"]["problem"] == ( + "wrist_calibration_offsets.json is written in layout 2, and this software reads up to layout 1: update " + "the software, or calibrate again with this one" + ) + # The start-of-day item reads the same files: it says the sentence, where it could not be evaluated at all. + checks = tmp_path / "day" + checks.mkdir() + day_checks._calibrate(checks, *day_checks.CALIBRATED) + newer = json.dumps({**POSITION, "schema_version": endless}) + day_checks._calibrate(checks, "head_camera_extrinsics.json", content=newer) + item = day_checks._by_id(day_checks._items(checks))["calibration"] + assert item == (day_checks.WARN, said("head_camera_extrinsics.json")) + + def test_a_position_or_offsets_that_do_not_say_which_tracking_made_them_are_not_trusted(): name = "head_camera_extrinsics.json" assert POSITION["pose_source"] == "openxr" and pose_source_problem(POSITION, name) is None @@ -2917,12 +3004,49 @@ async def test_installing_writes_the_stations_files_archives_them_and_stamps_the entry = station_store.ledger(world.calibration)["headset"] assert entry["operator"] == "Alex_Kim" and entry["files"] == job["installed"] assert len(list((world.calibration / "history").rglob("*.json"))) == 2 + # Each file says from when it is the station's calibration, and that it replaced none; who installed it is + # in the ledger alone. + assert intrinsics["provenance"]["validity"] == {"valid_from": entry["at"], "supersedes": None} + assert position["provenance"]["validity"] == {"valid_from": entry["at"], "supersedes": None} + assert "Alex" not in json.dumps(intrinsics) + json.dumps(position) + first = files.file_sha256(world.calibration / "head_camera_intrinsics.json") # Installing one part again does not list it twice. again = await world.service.install({"operator": "alex", "what": ["intrinsics"]}) assert again["installed"] == job["installed"] + # The same solve installed again is the calibration the station already has: the file is left as it is, + # since sessions hold its hash, and the ledger alone says who installed it again. + assert files.file_sha256(world.calibration / "head_camera_intrinsics.json") == first + assert len(list((world.calibration / "history").rglob("*.json"))) == 2 overview = await world.service.overview(None) assert overview["camera_job"]["installed"] == job["installed"] assert overview["ledger"]["headset"]["operator"] == "alex" + # The note of that second press says it changed nothing, for the page to say so. + assert overview["ledger"]["headset"]["unchanged"] == ["head_camera_intrinsics.json"] + + +async def test_one_install_of_two_files_stands_from_one_moment_which_is_the_ledgers(world, monkeypatch): + class TickingClock(datetime): + """A clock that is a second later at every reading, as two installs either side of a second see it.""" + + ticks = 0 + + @classmethod + def now(cls, tz=None): + cls.ticks += 1 + return datetime(2026, 3, 4, 9, 0, 0, tzinfo=timezone(timedelta(hours=-8))) + timedelta( + seconds=cls.ticks + ) + + await solve_with(world, monkeypatch) + monkeypatch.setattr(station_store, "datetime", TickingClock) + await world.service.install({"operator": "alex", "what": ["intrinsics", "extrinsics"]}) + at = station_store.ledger(world.calibration)["headset"]["at"] + for name in ("head_camera_intrinsics.json", "head_camera_extrinsics.json"): + stated = json.loads((world.calibration / name).read_text())["provenance"]["validity"] + assert stated["valid_from"] == at, name + # One install, one moment: its two archived copies carry one time in their names. + stamps = {path.name.split("_")[0] for path in (world.calibration / "history").rglob("*.json")} + assert len(stamps) == 1 async def test_installing_ends_the_batch_so_the_next_take_opens_a_session_with_the_installed_files( @@ -3524,12 +3648,21 @@ async def test_the_overview_shows_what_is_installed_which_cameras_are_live_and_w "name": "right_wrist_camera_intrinsics.json", "present": False, } - said_of_every_camera = {"default_model": "pinhole", "rectified": False, "rectification_waits": False} + said_of_every_camera = { + "default_model": "pinhole", + "rectified": False, + "rectification_waits": False, + # The head camera's file was solved for another camera, which is said of the file; no size is held + # against it. No other role has a readable lens file. + "picture_notes": {"lens": None, "position": None}, + } assert overview["cameras"] == [ { "role": "ego", "camera": HEAD, "live": True, + # The capture server delivers it: nothing joins a video room to see it. + "video_room": False, "intrinsics_file": "head_camera_intrinsics.json", **said_of_every_camera, }, @@ -3537,6 +3670,7 @@ async def test_the_overview_shows_what_is_installed_which_cameras_are_live_and_w "role": "wrist_left", "camera": LEFT, "live": False, + "video_room": False, "intrinsics_file": "left_wrist_camera_intrinsics.json", **said_of_every_camera, }, @@ -3544,10 +3678,19 @@ async def test_the_overview_shows_what_is_installed_which_cameras_are_live_and_w "role": "wrist_right", "camera": None, "live": False, + "video_room": False, "intrinsics_file": "right_wrist_camera_intrinsics.json", **said_of_every_camera, }, ] + # A camera that reaches the backend through the LiveKit room is said to: the live check joins the room for it. + world.over_livekit = {LEFT} + assert [camera["video_room"] for camera in (await world.service.overview(None))["cameras"]] == [ + False, + True, + False, + ] + world.over_livekit = set() assert ( overview["ledger"] == {} and overview["recording"] is None and overview["camera_job"] == {"state": "idle"} ) @@ -3584,6 +3727,70 @@ async def test_a_ledger_edited_by_hand_is_shown_as_far_as_it_has_the_expected_sh json.dumps(overview, allow_nan=False) +def _picture_notes(overview: dict, role: str = "ego") -> dict: + return next(camera for camera in overview["cameras"] if camera["role"] == role)["picture_notes"] + + +async def test_the_overview_says_before_a_take_when_a_camera_sends_another_size_than_its_lens_file_was_solved_at( + world, +): + nothing = {"lens": None, "position": None} + world.install("head_camera_intrinsics.json", {**good_record(), "camera": HEAD}) + world.install("left_wrist_camera_intrinsics.json", {**good_record(), "camera": LEFT}) + # The size the files were solved at: nothing to say. + assert _picture_notes(await world.service.overview(None)) == nothing + # The camera was started in another picture mode. + world.sizes[HEAD], world.sizes[LEFT] = (1280, 960), (320, 240) + overview = await world.service.overview(None) + assert _picture_notes(overview) == { + "lens": ( + "head_camera_intrinsics.json was solved on a 640x480 picture, and this camera now sends 1280x960. " + "A solve from this take replaces it with one for the new size: if the size changed by mistake, set " + "the camera's picture mode back before recording" + ), + "position": ( + "head_camera_intrinsics.json is for a 640x480 picture, and this camera now sends 1280x960, so the " + "camera's position cannot be solved against it. Solve the lens as well, or set the camera's picture " + "mode back before recording" + ), + } + # A wrist camera has a lens to solve and no position. + wrist = _picture_notes(overview, "wrist_left") + assert wrist["position"] is None + assert wrist["lens"].startswith("left_wrist_camera_intrinsics.json was solved on a 640x480 picture, and this") + # A role with no camera, and one with no lens file, have nothing to hold a size against. + assert _picture_notes(overview, "wrist_right") == nothing + # The note only tells: the take still starts. + world.show(HEAD, board_picture()) + assert (await world.service.start_recording({**CAMERA_TAKE, "mode": "intrinsic"}))["phase"] == "recording" + + +@pytest.mark.parametrize("case", ["size unknown", "another camera's file", "unreadable file", "no file"]) +async def test_a_size_is_held_against_a_lens_file_only_when_both_are_known_and_the_file_is_this_cameras( + world, case +): + world.sizes[HEAD] = (1280, 960) + if case == "size unknown": + world.install("head_camera_intrinsics.json", {**good_record(), "camera": HEAD}) + del world.sizes[HEAD] + elif case == "another camera's file": + # Replaced whatever its size: that is said of the file, not of the picture. + world.install("head_camera_intrinsics.json", {**good_record(), "camera": "cam_a"}) + elif case == "unreadable file": + world.install("head_camera_intrinsics.json", {"K": "not a matrix"}) + assert _picture_notes(await world.service.overview(None)) == {"lens": None, "position": None} + + +async def test_a_corrected_cameras_picture_is_not_held_against_its_lens_files_size(tmp_path): + # The published picture has the size its rectification gave it; that case has its own words on the page. + for streams in (StreamsState(cameras={HEAD: corrected_stream()}), UnreadStreams(problem="unreadable")): + (tmp_path / type(streams).__name__).mkdir() + made = World(tmp_path / type(streams).__name__, streams=streams) + made.install("head_camera_intrinsics.json", {**good_record(), "camera": HEAD}) + made.sizes[HEAD] = (1280, 960) + assert _picture_notes(await made.service.overview(None)) == {"lens": None, "position": None} + + async def test_values_a_hand_left_in_the_calibration_files_never_make_the_overview_impossible_to_send(world): half = "\ud800" # A whole number too large for a float, a length that overflows once it is millimetres, and text holding @@ -3649,6 +3856,13 @@ def test_what_a_file_says_reaches_the_page_only_as_far_as_a_reply_can_carry_it() "headset": {"date": "2026-03-04", "files": ["head_camera_intrinsics.json"]}, "wrist": {"date": "2026-03-03", "operator": "alex", "files": []}, } + # The files an install left unchanged are passed on by name, and only names of the entry's own files. + lens = "head_camera_intrinsics.json" + noted = {"headset": {"files": [lens], "unchanged": [lens, half]}} + assert calibration_service._ledger_rows(noted)["headset"]["unchanged"] == [lens] + for nothing in ("all", [], ["head_camera_extrinsics.json"], [half]): + noted["headset"]["unchanged"] = nothing + assert "unchanged" not in calibration_service._ledger_rows(noted)["headset"] async def test_a_calibration_file_replaced_while_the_overview_reads_it_is_listed_without_its_camera( diff --git a/examples/egocap/tests/backend/test_day_report_real_recorder.py b/examples/egocap/tests/backend/test_day_report_real_recorder.py new file mode 100644 index 0000000000..37bc7e0490 --- /dev/null +++ b/examples/egocap/tests/backend/test_day_report_real_recorder.py @@ -0,0 +1,745 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""End-of-day corrections of sessions a real recorder wrote: the recorder's own lock on a session, a routed +group and the session's routes to it, a take still waiting to be filed, and the modes of the files replaced. + +Every session here is recorded by a ``RecordingService`` with one numeric source, so its manifests, route stamps, +lock file and file modes are the recorder's own and not a test's idea of them. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import stat +from pathlib import Path +from types import SimpleNamespace + +import pytest +import zarr +from fastapi import FastAPI +from fastapi.testclient import TestClient + +import recording_service.recording_service as recorder_module +from egocap.recording.episode_layout import ROUTE_ATTR, route_id +from egocap_web import day_report_routes +from egocap_web.session_locks import SessionLocks +from egocap_web.station_uptime import UptimeLog +from recording_service import ( + Disposition, + EpisodeResult, + FieldSpec, + NumericSample, + NumericSourceSpec, + QcConfig, + RecordingService, + RoutingConfig, + ServiceConfig, + StateError, +) + +TOKEN = "t" * 43 +AUTH = {"X-Control-Token": TOKEN} +#: Takes are routed by the session's studio into a group under that studio's folder. +ROUTED = RoutingConfig(session_studio="Kitchen") +OPEN_IN_A_RECORDER = "this session is open in a recorder; end its batch there before correcting it" +UNSETTLED_TAKE = ( + "an interrupted take of this session must be recovered or discarded first: " + "where it is filed depends on the labels it was recorded under" +) + + +def _config(root: Path, routing: RoutingConfig | None = None) -> ServiceConfig: + return ServiceConfig( + output_root=root, + numeric_sources=(NumericSourceSpec("tracker", (FieldSpec("v", "float64"),), "PicoTrackingFrame"),), + qc=QcConfig(required_sources=("tracker",)), + routing=routing, + station_label="Bench A", + ) + + +async def _take(service: RecordingService, task: str = "Pour water.") -> EpisodeResult: + episode = await service.start_episode(task, "alex") + for index in range(5): + sample = NumericSample("tracker", float(index), float(index), {"v": float(index)}) + service.submit_sample(episode.episode_id, sample) + return await service.stop_episode(episode.episode_id) + + +async def _recorded(root: Path, routing: RoutingConfig | None, takes: int = 1) -> tuple[str, Path]: + """A closed session of kept takes: its id, and the directory its takes are filed in.""" + service = RecordingService(_config(root, routing)) + session = await service.open_session() + results = [await _take(service) for _ in range(takes)] + await service.close() + assert {result.disposition for result in results} == {Disposition.KEPT} + return session.session_id, results[-1].final_path.parent + + +def _dies(*args, **kwargs): + raise OSError("the recorder stopped here") + + +async def _recorded_with_a_take_left_to_file( + root: Path, routing: RoutingConfig | None, monkeypatch: pytest.MonkeyPatch, step: str | None = None +) -> tuple[str, Path, str]: + """A closed session of one kept take and one that was checked, is to be kept, and was interrupted before + it was filed: its id, where the kept take is, and the waiting take's id. ``step`` is the recorder's step + the take stopped at, when not the first one that files it.""" + service = RecordingService(_config(root, routing)) + session = await service.open_session() + kept = await _take(service) + # What a recorder that stops between the check and the filing leaves: with routing, before the take is + # given its group; without, before it is published in the session. + step = step or ("assign_output" if routing is not None else "finalize_episode_dir") + with monkeypatch.context() as stopped: + stopped.setattr(recorder_module, step, _dies) + waiting = await _take(service) + await service.close() + assert waiting.disposition is Disposition.RECOVERY_REQUIRED + return session.session_id, kept.final_path.parent, waiting.episode_id + + +async def _recover(root: Path, routing: RoutingConfig | None, session_id: str, episode_id: str) -> EpisodeResult: + service = RecordingService(_config(root, routing)) + await service.open_session(session_id) + try: + return await service.recover_episode(episode_id) + finally: + await service.close() + + +def _client(root: Path) -> TestClient: + """The report's routes for a backend that has no session of its own open.""" + small = FastAPI() + small.include_router(day_report_routes.router) + idle = SimpleNamespace(snapshot=lambda: SimpleNamespace(service=None, active_operation=None)) + small.state.recording_context = SimpleNamespace(control_token=TOKEN, coordinator=idle) + small.state.station_service = SimpleNamespace(label=lambda: "Bench A") + small.state.station_uptime = UptimeLog(root.parent / "station_status") + small.state.recording_output_root = root + small.state.session_locks = SessionLocks() + return TestClient(small) + + +def _studio(client: TestClient, **body): + return client.post("/api/day-report/studio", json=body, headers=AUTH) + + +def _task(client: TestClient, **body): + return client.post("/api/day-report/correct", json=body, headers=AUTH) + + +def _tree(root: Path) -> dict[str, tuple[bytes, int]]: + """Every file under ``root`` with its bytes and its permission bits, by path relative to it.""" + return { + str(path.relative_to(root)): (path.read_bytes(), stat.S_IMODE(path.stat().st_mode)) + for path in sorted(root.rglob("*")) + if path.is_file() + } + + +def _labels(directory: Path) -> dict: + return json.loads((directory / "zarr.json").read_text())["attributes"] + + +def _manifest(root: Path, session_id: str, index: int) -> dict: + return json.loads((root / session_id / ".recording" / f"episode_{index}.json").read_text()) + + +def _routes(root: Path, session_id: str) -> dict: + return json.loads((root / session_id / ".recording" / "routes.json").read_text()) + + +# --- the recorder's own lock ---------------------------------------------------------------------------------- + + +async def test_a_session_open_in_another_recorder_is_refused_both_corrections_until_that_recorder_closes_it( + tmp_path, +): + root = tmp_path / "recordings" + # Another recorder on the same output: this backend's own recorder knows nothing of its session. + other = RecordingService(_config(root)) + session = await other.open_session() + await _take(other) + client = _client(root) + before = _tree(root) + for refused in ( + _studio(client, session=session.session_id, studio="Pantry"), + _task(client, session=session.session_id, episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": OPEN_IN_A_RECORDER}) + assert _tree(root) == before + # The recorder still owns its session and records into it; once it closes, both takes are corrected as one. + assert (await _take(other)).disposition is Disposition.KEPT + await other.close() + corrected = _studio(client, session=session.session_id, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1"]) + assert {_labels(root / session.session_id / f"episode_{index}")["studio"] for index in (0, 1)} == {"Pantry"} + + +async def test_no_recorder_opens_a_session_between_a_corrections_checks_and_its_last_write(tmp_path, monkeypatch): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + client = _client(root) + second = RecordingService(_config(root, ROUTED)) + loop = asyncio.get_running_loop() + plan = day_report_routes.plan_session_studio + answers: list[str] = [] + + def planning(target: Path, stored: str): + # In the correction's worker, after every check answered and before its first write: where a recorder + # that reopened the session and began a take would have that take refused its group afterwards. + try: + asyncio.run_coroutine_threadsafe(second.open_session(session_id), loop).result(30) + except StateError as refused: + answers.append(str(refused)) + return plan(target, stored) + + monkeypatch.setattr(day_report_routes, "plan_session_studio", planning) + reply = await asyncio.to_thread(_studio, client, session=group.relative_to(root).as_posix(), studio="Pantry") + assert reply.status_code == 200, reply.text + assert answers == [f"session {session_id!r} is owned by another recorder"] + # The correction written, the lock is the recorder's to take again. + await second.open_session(session_id) + assert (await _take(second)).disposition is Disposition.KEPT + await second.close() + + +def test_a_session_no_recorder_ever_locked_is_corrected_without_a_lock_file_being_made_for_it(tmp_path): + root = tmp_path / "recordings" + session = root / "session_20260309-081500_abc123" + (session / ".recording").mkdir(parents=True) + zarr.open_group(str(session / "episode_0"), mode="w") + reply = _studio(_client(root), session=session.name, studio="Pantry") + assert (reply.status_code, reply.json()["updated"]) == (200, ["episode_0"]) + assert sorted(path.name for path in (session / ".recording").iterdir()) == [] + + +# --- a routed group and its session's routes ------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("correct", "label", "corrected"), + [ + (lambda client, group: _studio(client, session=group, studio="Pantry"), "studio", "Pantry"), + ( + lambda client, group: _task(client, session=group, episodes="0", task="Wash the cup."), + "task_description", + "Wash the cup.", + ), + ], + ids=["studio", "task of every take"], +) +async def test_a_take_recorded_after_its_group_was_corrected_is_kept_in_a_fresh_group( + tmp_path, correct, label, corrected +): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + name = group.relative_to(root).as_posix() + assert list(_routes(root, session_id).values()) == [name] + frozen = _manifest(root, session_id, 0) + reply = correct(_client(root), name) + assert reply.status_code == 200, reply.text + # The session no longer sends takes to the group, whose label says something else now; what the take in + # it was recorded under, and where it was filed, stay in its own record. + assert _routes(root, session_id) == {} + assert _manifest(root, session_id, 0) == frozen + assert frozen["assignment"] == {"group": name, "slot": 0} + + # The same session reopened, and a take of the same studio and task recorded the same day. + service = RecordingService(_config(root, ROUTED)) + await service.open_session(session_id) + later = await _take(service) + await service.close() + assert (later.disposition, tuple(later.issues)) == (Disposition.KEPT, ()) + fresh = later.final_path.parent + assert fresh != group and fresh.parent == group.parent + assert (_labels(fresh)["studio"], _labels(fresh)["task_description"]) == ("Kitchen", "Pour water.") + # The corrected group holds the take it held, under its corrected label, and is still that session's. + assert sorted(path.name for path in group.glob("episode_*")) == ["episode_0"] + assert _labels(group)[label] == corrected + assert _labels(group)[ROUTE_ATTR] == route_id(session_id, name) + + +async def test_a_correction_of_some_takes_of_a_group_leaves_it_the_destination_of_later_takes(tmp_path): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED, takes=2) + name = group.relative_to(root).as_posix() + routes = (root / session_id / ".recording" / "routes.json").read_bytes() + reply = _task(_client(root), session=name, episodes="0", task="Wash the cup.") + assert (reply.status_code, reply.json()["updated"]) == (200, ["episode_0"]) + # One take's task is its own: the group still says what its session records under. + assert (root / session_id / ".recording" / "routes.json").read_bytes() == routes + assert _labels(group)["task_description"] == "Pour water." + service = RecordingService(_config(root, ROUTED)) + await service.open_session(session_id) + later = await _take(service) + await service.close() + assert (later.disposition, later.final_path) == (Disposition.KEPT, group / "episode_2") + + +@pytest.mark.parametrize( + "correct", + [ + lambda client, group: _studio(client, session=group, studio="Pantry"), + lambda client, group: _task(client, session=group, episodes="0", task="Wash the cup."), + ], + ids=["studio", "task of every take"], +) +async def test_a_group_whose_session_routes_cannot_be_rewritten_is_refused_with_nothing_changed( + tmp_path, correct, caplog +): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + (root / session_id / ".recording" / "routes.json").write_text("not json") + before = _tree(root) + refused = correct(_client(root), group.relative_to(root).as_posix()) + assert (refused.status_code, refused.json()) == ( + 400, + { + "detail": "the session's record of where its takes are filed cannot be rewritten, " + "so its labels are left as they are" + }, + ) + assert _tree(root) == before + assert "The routes of a corrected group's session could not be rewritten" in caplog.text + + +async def test_a_group_that_outlived_its_session_is_corrected_with_no_session_to_lock_or_to_tell(tmp_path): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + shutil.rmtree(root / session_id) + reply = _studio(_client(root), session=group.relative_to(root).as_posix(), studio="Pantry") + assert (reply.status_code, reply.json()["updated"]) == (200, ["episode_0"]) + # Nothing is made in the place of the session that is gone. + assert not (root / session_id).exists() + assert _labels(group)["studio"] == "Pantry" + + +# --- a take still waiting to be filed ------------------------------------------------------------------------- + + +async def test_a_routed_take_left_to_file_holds_both_corrections_and_is_filed_where_it_belongs_after_them( + tmp_path, monkeypatch +): + root = tmp_path / "recordings" + session_id, group, waiting = await _recorded_with_a_take_left_to_file(root, ROUTED, monkeypatch) + name = group.relative_to(root).as_posix() + record = _manifest(root, session_id, 1) + assert (record["storage_phase"], record["studio"], record["assignment"]) == ("CHECKED", "Kitchen", None) + client = _client(root) + before = _tree(root) + for holder in (name, session_id): + for refused in ( + _studio(client, session=holder, studio="Pantry"), + _task(client, session=holder, episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": UNSETTLED_TAKE}) + assert _tree(root) == before + # Refused, the corrections left the group saying what the waiting take was recorded under: it is filed. + recovered = await _recover(root, ROUTED, session_id, waiting) + assert (recovered.disposition, recovered.final_path) == (Disposition.KEPT, group / "episode_1") + # Every take settled, the correction is taken. + corrected = _studio(client, session=name, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1"]) + + +async def test_a_take_left_to_file_with_routing_off_holds_no_correction_and_is_recovered_after_them( + tmp_path, monkeypatch +): + root = tmp_path / "recordings" + session_id, session, waiting = await _recorded_with_a_take_left_to_file(root, None, monkeypatch) + record = _manifest(root, session_id, 1) + # Recorded to be filed in its own session, by no label. + assert (record["storage_phase"], record["studio"], record["assignment"]) == ("CHECKED", None, None) + client = _client(root) + task = _task(client, session=session_id, episodes="0", task="Wash the cup.") + assert (task.status_code, task.json()["updated"]) == (200, ["episode_0"]) + studio = _studio(client, session=session_id, studio="Pantry") + assert (studio.status_code, studio.json()["updated"]) == (200, ["episode_0"]) + assert _manifest(root, session_id, 1) == record + recovered = await _recover(root, None, session_id, waiting) + assert (recovered.disposition, recovered.final_path) == (Disposition.KEPT, session / "episode_1") + # The recovered take says what it was recorded under; the corrected take says its correction. + assert _labels(session / "episode_1")["task_description"] == "Pour water." + assert _labels(session / "episode_0")["task_description"] == "Wash the cup." + + +@pytest.mark.skipif(os.geteuid() == 0, reason="the administrator can list any directory") +async def test_a_sidecar_that_cannot_be_listed_holds_both_corrections_as_a_take_record_that_cannot_be_read( + tmp_path, monkeypatch +): + root = tmp_path / "recordings" + session_id, group, waiting = await _recorded_with_a_take_left_to_file(root, ROUTED, monkeypatch) + name = group.relative_to(root).as_posix() + client = _client(root) + before = _tree(root) + sidecar = root / session_id / ".recording" + sidecar.chmod(0o000) + try: + replies = [_studio(client, session=holder, studio="Pantry").json() for holder in (name, session_id)] + [ + _task(client, session=name, episodes="0", task="Wash the cup.").json() + ] + finally: + sidecar.chmod(0o755) + # Not "no take": a record that cannot be read may be a take waiting for these labels. + assert ( + replies + == [{"detail": "a take record of this session cannot be read, so its labels are left as they are"}] * 3 + ) + assert _tree(root) == before + recovered = await _recover(root, ROUTED, session_id, waiting) + assert (recovered.disposition, recovered.final_path) == (Disposition.KEPT, group / "episode_1") + + +# --- what a correction replaces on the disk ------------------------------------------------------------------- + + +async def test_every_file_a_correction_replaces_in_a_recorded_group_keeps_the_mode_it_had(tmp_path): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + stamp, take, config = group / "zarr.json", group / "episode_0" / "zarr.json", group / "config.yaml" + # The recorder's route stamp is the owner's alone, as recorded. + assert stat.S_IMODE(stamp.stat().st_mode) == 0o600 + # Someone made the take's metadata read-only and opened the config to a second account. + take.chmod(0o440) + config.chmod(0o644) + modes = {name: mode for name, (_content, mode) in _tree(root).items()} + client = _client(root) + studio = _studio(client, session=group.relative_to(root).as_posix(), studio="Pantry") + assert (studio.status_code, studio.json()["config_updated"]) == (200, True) + task = _task(client, session=group.relative_to(root).as_posix(), episodes="0", task="Wash the cup.") + assert (task.status_code, task.json()["config_updated"]) == (200, True) + assert (_labels(group)["studio"], _labels(group)["task_description"]) == ("Pantry", "Wash the cup.") + assert (_labels(group / "episode_0")["studio"], _labels(group / "episode_0")["task_description"]) == ( + "Pantry", + "Wash the cup.", + ) + after = {name: mode for name, (_content, mode) in _tree(root).items()} + assert after == modes + assert [stat.S_IMODE(path.stat().st_mode) for path in (stamp, take, config)] == [0o600, 0o440, 0o644] + + +async def test_what_an_interrupted_correction_left_in_a_group_is_removed_by_the_next_and_only_under_its_locks( + tmp_path, +): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + name = group.relative_to(root).as_posix() + # What a correction killed between writing a file's replacement and renaming it leaves beside the file. + strays = [group / "episode_0" / "zarr.3c9fa0c9.partial", group / ".config.yaml.s2sswa6m.tmp"] + for stray in strays: + stray.write_text("half written") + os.utime(stray, (0, 0)) + # And what a writer this backend's locks do not cover, a time-aligner run by hand, made a moment ago and + # is about to rename into place. + live = group / "zarr.0a1b2c3d.partial" + live.write_text("being written") + kept = sorted(_tree(root)) + client = _client(root) + # A correction that is refused removes nothing: the session is another recorder's while it is open. + holder = RecordingService(_config(root, ROUTED)) + await holder.open_session(session_id) + refused = _studio(client, session=name, studio="Pantry") + assert (refused.status_code, refused.json()["detail"]) == (400, OPEN_IN_A_RECORDER) + assert sorted(_tree(root)) == kept + await holder.close() + assert _studio(client, session=name, studio="Pantry").status_code == 200 + # The stray files are gone, every recorded file is still there, and so is the file a minute has not aged. + assert sorted(_tree(root)) == sorted(set(kept) - {str(stray.relative_to(root)) for stray in strays}) + assert live.read_text() == "being written" + + +async def test_a_stray_in_a_take_folder_that_is_read_only_is_answered_with_the_take_that_cannot_be_rewritten( + tmp_path, +): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED, takes=2) + name = group.relative_to(root).as_posix() + stray = group / "episode_1" / ".zarr.json.dead.tmp" + stray.write_text("half written") + os.utime(stray, (0, 0)) + client = _client(root) + (group / "episode_1").chmod(0o555) + try: + if os.access(group / "episode_1", os.W_OK): + pytest.skip("this account writes into a folder whatever its mode") + before = _tree(root) + refused = _studio(client, session=name, studio="Larder") + # The stray cannot be removed from that folder; what is said is what the operator can act on. + assert (refused.status_code, refused.json()) == ( + 400, + {"detail": "episode_1 cannot be rewritten (its folder is read-only), so nothing was changed"}, + ) + assert _tree(root) == before + finally: + (group / "episode_1").chmod(0o755) + + +# --- the task correction is all or nothing too ----------------------------------------------------------------- + + +@pytest.mark.parametrize("routing", [None, ROUTED], ids=["routing off", "routing on"]) +async def test_a_take_the_task_correction_cannot_rewrite_refuses_it_whole_and_every_take_keeps_its_task( + tmp_path, routing +): + root = tmp_path / "recordings" + session_id, holder = await _recorded(root, routing, takes=3) + name = holder.relative_to(root).as_posix() + client = _client(root) + (holder / "episode_1").chmod(0o555) + try: + if os.access(holder / "episode_1", os.W_OK): + pytest.skip("this account writes into a folder whatever its mode") + before = _tree(root) + # The same answer on every repeat, and never the first take relabelled and the rest not. + for _again in range(2): + refused = _task(client, session=name, episodes="0-2", task="Wash the cup.") + assert (refused.status_code, refused.json()) == ( + 400, + {"detail": "episode_1 cannot be rewritten (its folder is read-only), so nothing was changed"}, + ) + # Nothing: the takes, the session's own label, and its record of where its takes are filed. + assert _tree(root) == before + finally: + (holder / "episode_1").chmod(0o755) + assert {_labels(holder / f"episode_{index}")["task_description"] for index in range(3)} == {"Pour water."} + corrected = _task(client, session=name, episodes="0-2", task="Wash the cup.") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1", "episode_2"]) + assert {_labels(holder / f"episode_{index}")["task_description"] for index in range(3)} == {"Wash the cup."} + + +async def test_a_task_correction_whose_write_fails_part_way_says_nothing_was_changed_and_nothing_was( + tmp_path, monkeypatch +): + import zarr.storage._local as zarr_files + + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED, takes=3) + name = group.relative_to(root).as_posix() + client = _client(root) + before = _tree(root) + real = zarr_files._put + writes: list[str] = [] + + def put(path, value, *args, **kwargs): + writes.append(str(path)) + # The group's own label and the first take are written; the second take cannot be. + if len(writes) == 3: + raise OSError(28, "No space left on device") + return real(path, value, *args, **kwargs) + + with monkeypatch.context() as full: + full.setattr(zarr_files, "_put", put) + failed = _task(client, session=name, episodes="0-2", task="Wash the cup.") + assert (failed.status_code, failed.json()) == ( + 400, + { + "detail": "the labels could not all be written; those already written were put back, " + "so nothing was changed" + }, + ) + # The disk says what the reply says, the session's route to the group included. + assert _tree(root) == before + assert str(root) not in failed.text + + +# --- a lock file that is not a regular file -------------------------------------------------------------------- + +LOCK_NOT_A_FILE = "this session's lock is not an ordinary file, so its labels are left as they are" + + +def _a_link_out(lock: Path, outside: Path) -> None: + lock.unlink() + lock.symlink_to(outside) + + +def _a_second_name(lock: Path, outside: Path) -> None: + lock.unlink() + os.link(outside, lock) + + +def _a_folder(lock: Path, outside: Path) -> None: + lock.unlink() + lock.mkdir() + + +@pytest.mark.parametrize("swap", [_a_link_out, _a_second_name, _a_folder]) +async def test_a_session_whose_lock_file_is_no_regular_file_is_refused_and_nothing_is_written_through_it( + tmp_path, swap +): + root = tmp_path / "recordings" + session_id, session = await _recorded(root, None) + outside = tmp_path / "an_operators_file.txt" + outside.write_text("something outside the recording output\n") + swap(session / ".recording" / "session.lock", outside) + client = _client(root) + before = _tree(root) + for refused in ( + _studio(client, session=session_id, studio="Pantry"), + _task(client, session=session_id, episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": LOCK_NOT_A_FILE}) + # Taking a recorder's lock opens its file for writing: here that file is somebody else's. + assert outside.read_text() == "something outside the recording output\n" + assert _tree(root) == before + + +# --- a route is forgotten only when a label really differs ----------------------------------------------------- + + +@pytest.mark.parametrize( + "correct", + [ + lambda client, group: _studio(client, session=group, studio="Kitchen"), + lambda client, group: _task(client, session=group, episodes="0", task="Pour water."), + ], + ids=["studio", "task of every take"], +) +async def test_a_correction_to_the_label_a_group_already_has_leaves_it_the_destination_of_later_takes( + tmp_path, correct +): + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + routes = (root / session_id / ".recording" / "routes.json").read_bytes() + reply = correct(_client(root), group.relative_to(root).as_posix()) + assert reply.status_code == 200, reply.text + assert (root / session_id / ".recording" / "routes.json").read_bytes() == routes + service = RecordingService(_config(root, ROUTED)) + await service.open_session(session_id) + later = await _take(service) + await service.close() + # One group for one studio, task and day, as before the correction that changed nothing. + assert (later.disposition, later.final_path) == (Disposition.KEPT, group / "episode_1") + assert sorted(path.name for path in group.parent.iterdir()) == [group.name] + + +async def test_a_correction_that_fails_and_puts_everything_back_leaves_the_group_a_destination( + tmp_path, monkeypatch +): + from egocap.data_processing import update_episode_task_description as relabel + + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + client = _client(root) + before = _tree(root) + real = relabel._replace_file + writes: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + writes.append(path) + # The take is written; the group's own label cannot be. + if len(writes) == 2: + raise OSError(28, "No space left on device") + real(path, content) + + with monkeypatch.context() as full: + full.setattr(relabel, "_replace_file", disk) + failed = _studio(client, session=group.relative_to(root).as_posix(), studio="Pantry") + assert failed.status_code == 400 and "nothing was changed" in failed.json()["detail"] + # Nothing was changed, the session's record of where its takes are filed included. + assert _tree(root) == before + service = RecordingService(_config(root, ROUTED)) + await service.open_session(session_id) + later = await _take(service) + await service.close() + assert (later.disposition, later.final_path) == (Disposition.KEPT, group / "episode_1") + assert sorted(path.name for path in group.parent.iterdir()) == [group.name] + + +async def test_a_route_that_cannot_be_put_back_stays_dropped_so_the_next_take_claims_a_group_of_its_own( + tmp_path, monkeypatch, caplog +): + from egocap.data_processing import update_episode_task_description as relabel + + root = tmp_path / "recordings" + session_id, group = await _recorded(root, ROUTED) + client = _client(root) + real = relabel._replace_file + writes: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + writes.append(path) + if len(writes) == 2: + raise OSError(28, "No space left on device") + real(path, content) + + def no_room(path: Path, data: object) -> None: + raise OSError(28, "No space left on device") + + with monkeypatch.context() as full: + full.setattr(relabel, "_replace_file", disk) + full.setattr(day_report_routes, "write_json_atomic", no_room) + failed = _studio(client, session=group.relative_to(root).as_posix(), studio="Pantry") + assert failed.status_code == 400 and "nothing was changed" in failed.json()["detail"] + assert "The route of a group whose correction failed could not be put back" in caplog.text + # The safe side: the group says what it said and merely stops receiving, so no later take is refused. + assert _routes(root, session_id) == {} + service = RecordingService(_config(root, ROUTED)) + await service.open_session(session_id) + later = await _take(service) + await service.close() + assert later.disposition is Disposition.KEPT and later.final_path.parent != group + + +# --- a take that already has its place in the group ------------------------------------------------------------ + +STILL_TO_BE_FILED = ( + "an interrupted take of this session must be recovered or discarded first: " + "it is still to be filed in this group" +) + + +async def test_a_take_that_already_has_its_place_in_a_group_holds_that_groups_corrections_until_it_is_filed( + tmp_path, monkeypatch +): + root = tmp_path / "recordings" + # The recorder stopped after the take was given its place and before it was moved there. + session_id, group, waiting = await _recorded_with_a_take_left_to_file( + root, ROUTED, monkeypatch, step="finalize_episode_dir" + ) + name = group.relative_to(root).as_posix() + record = _manifest(root, session_id, 1) + assert (record["storage_phase"], record["assignment"]) == ("CHECKED", {"group": name, "slot": 1}) + client = _client(root) + before = _tree(root) + for refused in ( + _studio(client, session=name, studio="Pantry"), + _task(client, session=name, episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": STILL_TO_BE_FILED}) + assert _tree(root) == before + recovered = await _recover(root, ROUTED, session_id, waiting) + assert (recovered.disposition, recovered.final_path) == (Disposition.KEPT, group / "episode_1") + # Filed, it is corrected with the take beside it: the group ends with one studio, not two. + corrected = _studio(client, session=name, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1"]) + assert {_labels(directory)["studio"] for directory in (group, group / "episode_0", group / "episode_1")} == { + "Pantry" + } + + +# --- what the report says of a record it cannot open ----------------------------------------------------------- + + +async def test_the_report_names_a_take_record_it_cannot_open_and_never_its_path(tmp_path): + root = tmp_path / "recordings" + session_id, session = await _recorded(root, None) + record = session / ".recording" / "episode_0.json" + record.chmod(0o000) + try: + if os.access(record, os.R_OK): + pytest.skip("this account reads a file whatever its mode") + report = _client(root).get("/api/day-report", headers=AUTH) + finally: + record.chmod(0o600) + assert report.status_code == 200 + (listed,) = report.json()["report"]["sessions"] + assert listed["problems"] == ["episode_0.json: cannot be opened: Permission denied"] + assert str(tmp_path) not in report.text diff --git a/examples/egocap/tests/backend/test_day_report_routes.py b/examples/egocap/tests/backend/test_day_report_routes.py index 75a6b41d58..0d1c62d84b 100644 --- a/examples/egocap/tests/backend/test_day_report_routes.py +++ b/examples/egocap/tests/backend/test_day_report_routes.py @@ -18,7 +18,14 @@ from fastapi import FastAPI from fastapi.testclient import TestClient +from egocap.data_processing import update_episode_task_description as relabel +from egocap.data_processing.update_episode_task_description import ( + update_episode_task_description, + update_session_studio, +) +from egocap.eod import eod_studio_session_move from egocap.recording.episode_layout import ROUTE_ATTR, EpisodeManifest, manifest_path, route_id, write_manifest +from egocap.recording.route import assign_output from egocap_web import day_report_routes from egocap_web.session_locks import ALIGNER, SessionLocks from egocap_web.station_uptime import DOWN, READY, RECORDING, UptimeLog @@ -190,9 +197,28 @@ def _day(root: Path) -> Path: ) +def _settled_day(root: Path) -> Path: + """The same day once its interrupted take has been discarded: every take is settled, so the session's + labels can be corrected.""" + return _session( + root, + takes=( + _manifest(0, "FINALIZED", duration=12.5), + _manifest(1, "FINALIZED", duration=8.0, qc_decision="FLAGGED_BAD"), + _manifest(2, "REJECTED", duration=3.0), + _manifest(3, "DISCARDED", duration=4.0), + ), + ) + + @pytest.mark.parametrize( ("method", "path"), - [("get", "/api/day-report"), ("post", "/api/day-report/save"), ("post", "/api/day-report/correct")], + [ + ("get", "/api/day-report"), + ("post", "/api/day-report/save"), + ("post", "/api/day-report/correct"), + ("post", "/api/day-report/studio"), + ], ) def test_every_route_needs_the_application_and_the_token(tmp_path, method, path): starting, _ = _client(tmp_path, ready=False) @@ -303,7 +329,7 @@ def _correct(client: TestClient, **body): def test_a_correction_rewrites_the_task_of_the_named_takes_and_shows_in_the_report(tmp_path): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) response = _correct(client, session=SESSION, episodes="0-2", task=" Place the cup on the shelf. ") assert response.status_code == 200, response.text assert response.json() == { @@ -396,7 +422,7 @@ def test_an_aligned_copy_that_leads_out_of_the_output_refuses_the_correction(tmp def test_a_correction_is_refused_for_the_session_being_recorded(tmp_path): client, recorder = _client(tmp_path) - _day(tmp_path) + _settled_day(tmp_path) recorder.session_id = SESSION open_session = _correct(client, session=SESSION, episodes="0", task="x") assert (open_session.status_code, open_session.json()["detail"]) == ( @@ -453,7 +479,7 @@ def test_a_group_of_another_session_is_corrected_while_the_open_one_has_no_direc def test_metadata_that_cannot_be_rewritten_is_refused_without_naming_a_path(tmp_path, caplog): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) (session / "zarr.json").write_text("not json") refused = _correct(client, session=SESSION, episodes="0", task="x") assert (refused.status_code, refused.json()["detail"]) == (400, "the session's metadata could not be updated") @@ -477,7 +503,7 @@ def test_an_interrupted_take_holds_only_its_own_session(tmp_path): def test_a_correction_waits_while_a_take_of_that_session_is_being_time_aligned(tmp_path): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) other = f"session_{TODAY.replace('-', '')}-090000_def456" _session(tmp_path, other, takes=(_manifest(0, "FINALIZED", session=other),)) locks = client.app.state.session_locks @@ -497,16 +523,16 @@ def test_a_correction_waits_while_a_take_of_that_session_is_being_time_aligned(t def test_a_correction_holds_its_session_from_its_first_write_to_its_last(tmp_path, monkeypatch): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) locks = client.app.state.session_locks update = day_report_routes.update_episode_task_description during: list[tuple[str | None, int]] = [] - def writing(target, episodes, *, task_description): + def writing(target, episodes, **keywords): # What the aligner, and a second correction, find while this one is between its files. second = _correct(client, session=SESSION, episodes="0", task="other") during.append((locks.acquire(target, ALIGNER), second.status_code)) - return update(target, episodes, task_description=task_description) + return update(target, episodes, **keywords) monkeypatch.setattr(day_report_routes, "update_episode_task_description", writing) first = _correct(client, session=SESSION, episodes="0", task="Wash the cup.") @@ -516,7 +542,7 @@ def writing(target, episodes, *, task_description): assert locks.acquire(session.resolve(), ALIGNER) is None locks.release(session.resolve()) - def failing(target, episodes, *, task_description): + def failing(target, episodes, **keywords): raise OSError("disk full") monkeypatch.setattr(day_report_routes, "update_episode_task_description", failing) @@ -526,14 +552,14 @@ def failing(target, episodes, *, task_description): def test_two_corrections_of_one_session_never_interleave(tmp_path, monkeypatch): client, _ = _client(tmp_path) - _day(tmp_path) + _settled_day(tmp_path) update = day_report_routes.update_episode_task_description replies: list[tuple[int, str]] = [] - def writing(target, episodes, *, task_description): + def writing(target, episodes, **keywords): second = _correct(client, session=SESSION, episodes="0", task="second") replies.append((second.status_code, second.json()["detail"])) - return update(target, episodes, task_description=task_description) + return update(target, episodes, **keywords) monkeypatch.setattr(day_report_routes, "update_episode_task_description", writing) assert _correct(client, session=SESSION, episodes="0", task="first").status_code == 200 @@ -561,7 +587,7 @@ def test_a_correction_needs_the_session_locks_the_application_sets(tmp_path): ) def test_an_invalid_correction_is_refused_with_the_reason_and_changes_nothing(tmp_path, change, reason): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) before = (session / "config.yaml").read_text() refused = _correct(client, **{"session": SESSION, "episodes": "0", "task": "x", **change}) assert refused.status_code == 400 and reason in refused.json()["detail"] @@ -570,7 +596,7 @@ def test_an_invalid_correction_is_refused_with_the_reason_and_changes_nothing(tm def test_a_correction_never_moves_a_session_and_ignores_fields_it_does_not_take(tmp_path): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) response = _correct(client, session=SESSION, episodes="0", task="x", studio="..", relocate=True) assert response.status_code == 200 and response.json()["session"] == SESSION assert session.is_dir() and "studio" not in yaml.safe_load((session / "config.yaml").read_text())["meta"] @@ -578,7 +604,7 @@ def test_a_correction_never_moves_a_session_and_ignores_fields_it_does_not_take( def test_manifests_are_not_touched_by_a_correction(tmp_path): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) before = manifest_path(session, 0).read_text() assert _correct(client, session=SESSION, episodes="0", task="Place the cup.").status_code == 200 assert manifest_path(session, 0).read_text() == before @@ -586,7 +612,7 @@ def test_manifests_are_not_touched_by_a_correction(tmp_path): def test_a_correction_never_gives_a_session_a_root_group_it_did_not_have(tmp_path): client, _ = _client(tmp_path) - session = _day(tmp_path) + session = _settled_day(tmp_path) response = _correct(client, session=SESSION, episodes="0", task="Place the cup on the shelf.") assert response.status_code == 200 and response.json()["updated"] == ["episode_0"] assert not (session / "zarr.json").exists() @@ -623,7 +649,7 @@ def test_the_recording_state_is_read_on_the_event_loop_not_in_the_worker(tmp_pat import threading client, recorder = _client(tmp_path) - _day(tmp_path) + _settled_day(tmp_path) readers: list[str] = [] real = recorder.snapshot @@ -667,3 +693,556 @@ def is_dir(self): 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] + + +# --- a take that is not settled holds both corrections ---------------------------------------------------------- + + +def _tree(root: Path) -> dict[str, bytes]: + """Every file under ``root`` with its bytes, by path relative to it.""" + return {str(path.relative_to(root)): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} + + +def _studio(client: TestClient, **body): + return client.post("/api/day-report/studio", json=body, headers=AUTH) + + +#: The labels a routed take's manifest freezes, and when the take was recorded. +FROZEN = {"studio": "Kitchen", "task": "Pour water.", "operator": "alex"} +RECORDED = datetime.datetime.combine(datetime.date.today(), datetime.time(8, 20)) + + +def _routed_day(root: Path) -> tuple[Path, str]: + """A routed session: one take kept and filed in its studio's group, and one that was checked and is to be + kept but was interrupted before it was filed. Returns the session and the group the first take is in.""" + filed = _manifest(0, "FINALIZED", studio="Kitchen") + waiting = _manifest(1, "CHECKED", studio="Kitchen", finalization="KEEP") + session = _session(root, takes=(waiting,)) + group, slot = assign_output(session, SESSION, **FROZEN, reserved=[], now=RECORDED) + filed.assignment = {"group": group, "slot": slot} + write_manifest(session, filed) + episode = zarr.open_group(str(root / group / f"episode_{slot}"), mode="w") + episode.attrs.update( + {"recorded_at": f"{TODAY}; 08-20-00", "studio": "Kitchen", "task_description": "Pour water."} + ) + return session, group + + +def _file_the_waiting_take(session: Path, group: str) -> tuple[str, int]: + """What the recording service does when the waiting take is recovered: file it by its frozen labels.""" + return assign_output(session, SESSION, **FROZEN, reserved=[(group, 0)], now=RECORDED) + + +@pytest.mark.parametrize( + ("label", "library_correction", "asked"), + [ + ( + "task", + lambda group_dir: update_episode_task_description(group_dir, "0", task_description="Wash the cup."), + lambda client, group: _correct(client, session=group, episodes="0", task="Wash the cup."), + ), + ( + "studio", + lambda group_dir: update_session_studio(group_dir, "Pantry"), + lambda client, group: _studio(client, session=group, studio="Pantry"), + ), + ], +) +def test_a_correction_would_strand_a_take_still_to_be_filed_so_it_is_refused_until_that_take_is_settled( + tmp_path, label, library_correction, asked +): + import shutil + + root = tmp_path / "recordings" + root.mkdir() + client, _ = _client(root) + session, group = _routed_day(root) + # Uncorrected, the waiting take is filed in the group of its studio and task, in the next slot. + assert _file_the_waiting_take(session, group) == (group, 1) + + # What the correction did before it was held: on a copy of the day, the same rewrite of the group's label + # makes the recording service refuse to file the waiting take, by the values its manifest froze. + unguarded = tmp_path / "unguarded" + shutil.copytree(root, unguarded) + library_correction(unguarded / group) + with pytest.raises(PermissionError, match="holds .* in .*, not 'Pour water.' in 'Kitchen'"): + _file_the_waiting_take(unguarded / SESSION, group) + + # Through the page's route the correction is refused, of the group and of the session alike, nothing is + # written, and the waiting take can still be filed. + before = _tree(root) + for holder in (group, SESSION): + refused = asked(client, holder) + assert (refused.status_code, refused.json()["detail"]) == ( + 400, + "an interrupted take of this session must be recovered or discarded first: " + "where it is filed depends on the labels it was recorded under", + ) + assert _tree(root) == before + assert _file_the_waiting_take(session, group) == (group, 1) + + # Once the take is settled (here discarded) the same correction is taken. + write_manifest(session, _manifest(1, "DISCARDED", studio="Kitchen")) + assert asked(client, group).status_code == 200, label + + +@pytest.mark.parametrize("phase", ["WRITING", "SEALED", "CHECKED"]) +def test_a_routed_take_in_any_unsettled_phase_holds_both_corrections_of_its_session(tmp_path, phase): + client, _ = _client(tmp_path) + # Recorded to be routed by its studio, and not given its place yet: where it goes depends on the labels. + waiting = _manifest(1, phase, studio="Kitchen") + session = _session(tmp_path, takes=(_manifest(0, "FINALIZED"), waiting)) + before = _tree(tmp_path) + for refused in ( + _correct(client, session=SESSION, episodes="0", task="x"), + _studio(client, session=SESSION, studio="Pantry"), + ): + assert refused.status_code == 400 and refused.json()["detail"] == day_report_routes.UNSETTLED_TAKE + assert _tree(tmp_path) == before + # The lock is given back when the correction is refused under it. + assert client.app.state.session_locks.acquire(session.resolve(), ALIGNER) is None + + +@pytest.mark.parametrize( + "unsettled", + [ + # Recorded with routing off: it is filed where it was recorded, by no label. + {}, + # Routed, and its place was frozen before it was interrupted: recovery files it there, by no label. + {"studio": "Kitchen", "assignment": {"group": "Kitchen/2026-03-09-08-15-00", "slot": 1}}, + ], + ids=["routing off", "place already given"], +) +@pytest.mark.parametrize("phase", ["WRITING", "SEALED", "CHECKED"]) +def test_an_unsettled_take_whose_filing_depends_on_no_label_holds_no_correction(tmp_path, phase, unsettled): + client, _ = _client(tmp_path) + session = _session(tmp_path, takes=(_manifest(0, "FINALIZED"), _manifest(1, phase, **unsettled))) + record = manifest_path(session, 1).read_bytes() + task = _correct(client, session=SESSION, episodes="0", task="Wash the cup.") + assert (task.status_code, task.json()["updated"]) == (200, ["episode_0"]) + studio = _studio(client, session=SESSION, studio="Pantry") + assert (studio.status_code, studio.json()["updated"]) == (200, ["episode_0"]) + # The waiting take's record is the recorder's: it says what it said, for the recovery to read. + assert manifest_path(session, 1).read_bytes() == record + + +def test_a_take_record_that_cannot_be_read_holds_both_corrections_since_it_may_be_a_waiting_take(tmp_path): + client, _ = _client(tmp_path) + session = _session(tmp_path, takes=(_manifest(0, "FINALIZED"),)) + (session / ".recording" / "episode_1.json").write_text("not json") + before = _tree(tmp_path) + for refused in ( + _correct(client, session=SESSION, episodes="0", task="x"), + _studio(client, session=SESSION, studio="Pantry"), + ): + assert (refused.status_code, refused.json()["detail"]) == ( + 400, + "a take record of this session cannot be read, so its labels are left as they are", + ) + assert _tree(tmp_path) == before + + +def test_a_routed_group_is_held_by_the_session_its_stamp_names_and_by_no_other(tmp_path): + client, _ = _client(tmp_path) + _session(tmp_path, takes=(_manifest(0, "FINALIZED"), _manifest(1, "SEALED", studio="Kitchen"))) + other = f"session_{TODAY.replace('-', '')}-090000_def456" + _session(tmp_path, other, takes=(_manifest(0, "FINALIZED", session=other),)) + for owner, group in ((SESSION, "Kitchen/2026-03-09-08-15-00"), (other, "Kitchen/2026-03-09-09-00-00")): + stamp = {ROUTE_ATTR: route_id(owner, group)} + zarr.open_group(str(tmp_path / group), mode="w", attributes=stamp).create_group("episode_0") + held = _studio(client, session="Kitchen/2026-03-09-08-15-00", studio="Pantry") + assert (held.status_code, held.json()["detail"]) == (400, day_report_routes.UNSETTLED_TAKE) + assert _studio(client, session="Kitchen/2026-03-09-09-00-00", studio="Pantry").status_code == 200 + + +# --- a studio correction in place ------------------------------------------------------------------------------ + + +def test_a_studio_correction_relabels_the_session_where_it_lies_and_shows_in_the_report(tmp_path): + client, _ = _client(tmp_path) + session = _settled_day(tmp_path) + (session / "episode_0" / "head_camera.mp4").write_bytes(b"recorded video") + + def studios() -> list[str | None]: + report = client.get("/api/day-report", headers=AUTH).json()["report"] + return [episode["studio"] for episode in report["sessions"][0]["episodes"]] + + assert studios() == [None, None, None, None] + before = _tree(tmp_path) + response = _studio(client, session=SESSION, studio=" living room ") + assert response.status_code == 200, response.text + assert response.json() == { + "session": SESSION, + "studio": "living_room", + "updated": ["episode_0", "episode_1"], + "config_updated": True, + } + after = _tree(tmp_path) + # No file was added, removed or moved; only the session's config and its two episodes' metadata changed. + assert sorted(after) == sorted(before) + assert sorted(name for name in after if after[name] != before[name]) == [ + f"{SESSION}/config.yaml", + f"{SESSION}/episode_0/zarr.json", + f"{SESSION}/episode_1/zarr.json", + ] + meta = yaml.safe_load((session / "config.yaml").read_text())["meta"] + assert meta == {"egocap_station_name": "Bench A", "studio": "living_room"} + # Every take of the session is reported under its studio now; its tasks are what they were. + assert studios() == ["living_room"] * 4 + report = client.get("/api/day-report", headers=AUTH).json()["report"] + assert {e["task"] for e in report["sessions"][0]["episodes"]} == {"Pour water."} + assert not (session / "zarr.json").exists() + + +def test_a_studio_correction_of_a_routed_group_changes_its_label_and_never_its_folder(tmp_path, monkeypatch): + def moved(*args, **kwargs): + raise AssertionError("a recording-service session must never be relocated") + + # Whatever the correction does, the legacy move is not part of it. + monkeypatch.setattr(eod_studio_session_move, "relocate_session_to_canonical_studio", moved) + monkeypatch.setattr( + "egocap.data_processing.update_episode_task_description.relocate_session_to_canonical_studio", moved + ) + root = tmp_path / "recordings" + root.mkdir() + client, _ = _client(root) + session, group = _routed_day(root) + write_manifest(session, _manifest(1, "DISCARDED", studio="Kitchen")) + manifests = {path.name: path.read_bytes() for path in (session / ".recording").glob("episode_*.json")} + before = _tree(root) + response = _studio(client, session=group, studio="Pantry", relocate=True, task="ignored") + assert response.status_code == 200, response.text + assert response.json() == { + "session": group, + "studio": "Pantry", + "updated": ["episode_0"], + "config_updated": False, + } + after = _tree(root) + # The group is where it was recorded, under the studio folder it was recorded in; nothing new exists. + assert sorted(after) == sorted(before) and not (root / "Pantry").exists() + # Besides the labels, only the session's record of where its later takes go: the group is dropped from it. + assert sorted(name for name in after if after[name] != before[name]) == [ + f"{group}/episode_0/zarr.json", + f"{group}/zarr.json", + f"{SESSION}/.recording/routes.json", + ] + assert json.loads((session / ".recording" / "routes.json").read_text()) == {} + stamped = json.loads((root / group / "zarr.json").read_text())["attributes"] + assert (stamped["studio"], stamped["task_description"]) == ("Pantry", "Pour water.") + assert stamped[ROUTE_ATTR] == route_id(SESSION, group) + # The manifests keep what each take was recorded under: they are the recorder's record, not a label. + assert {path.name: path.read_bytes() for path in (session / ".recording").glob("episode_*.json")} == manifests + (take,) = [ + e + for e in client.get("/api/day-report", headers=AUTH).json()["report"]["sessions"][0]["episodes"] + if e["disposition"] == "kept" + ] + assert (take["studio"], take["location"]) == ("Pantry", f"{group}/episode_0") + + +def test_a_studio_correction_is_held_to_every_rule_a_task_correction_is(tmp_path): + client, recorder = _client(tmp_path) + session = _settled_day(tmp_path) + before = _tree(tmp_path) + recorder.session_id = SESSION + open_session = _studio(client, session=SESSION, studio="Pantry") + assert (open_session.status_code, open_session.json()["detail"]) == ( + 400, + "this session is still open for recording; start a new batch first", + ) + other = f"session_{TODAY.replace('-', '')}-090000_def456" + recorder.session_id, recorder.episode_id = other, f"{other}/episode_0" + writing = _studio(client, session=SESSION, studio="Pantry") + assert writing.json()["detail"] == "finish or discard the current take before correcting a session" + recorder.session_id, recorder.episode_id = None, None + locks = client.app.state.session_locks + assert locks.acquire(session.resolve(), ALIGNER) is None + aligning = _studio(client, session=SESSION, studio="Pantry") + assert aligning.json()["detail"] == "time alignment of this take is still running; try again in a moment" + locks.release(session.resolve()) + outside = _studio(client, session="../elsewhere", studio="Pantry") + assert (outside.status_code, outside.json()["detail"]) == (400, "the session is outside the recording output") + assert _tree(tmp_path) == before + del client.app.state.session_locks + assert _studio(client, session=SESSION, studio="Pantry").status_code == 503 + + +@pytest.mark.parametrize( + "studio", + [ + None, + 7, + "", + " ", + "x" * 65, + "..", + ".hidden", + "../elsewhere", + "a\nb", + "&&&", + ["Pantry"], + # A folder's bookkeeping names, however they are cased or underscored. + "_unmatched", + "__unmatched", + "_Unmatched", + "UNMATCHED", + "unknown", + "Unknown", + "UNKNOWN", + "un known", + ], +) +def test_a_studio_that_is_not_a_name_is_refused_and_changes_nothing(tmp_path, studio): + client, _ = _client(tmp_path) + _settled_day(tmp_path) + before = _tree(tmp_path) + refused = _studio(client, session=SESSION, studio=studio) + assert (refused.status_code, refused.json()["detail"]) == ( + 400, + "studio must be a name of 1 to 64 characters, such as Kitchen", + ) + assert _tree(tmp_path) == before + + +def test_a_studio_correction_that_cannot_be_written_is_refused_without_naming_a_path(tmp_path, caplog): + client, _ = _client(tmp_path) + session = _settled_day(tmp_path) + (session / "episode_1" / "zarr.json").write_text("not json") + before = _tree(tmp_path) + refused = _studio(client, session=SESSION, studio="Pantry") + # Found before the first write: the take is named as the session names it, and nothing was changed. + assert refused.status_code == 400 + assert refused.json() == {"detail": "episode_1 cannot be read, so nothing was changed"} + assert _tree(tmp_path) == before + assert "A studio correction could not be written" in caplog.text + assert str(tmp_path) not in refused.text + # The lock is given back, and the same correction completes once the cause is gone. + assert client.app.state.session_locks.acquire(session.resolve(), ALIGNER) is None + client.app.state.session_locks.release(session.resolve()) + zarr.open_group(str(session / "episode_1"), mode="w") + assert _studio(client, session=SESSION, studio="Pantry").json()["updated"] == ["episode_0", "episode_1"] + + +def test_a_studio_correction_of_a_session_with_no_recorded_take_changes_nothing(tmp_path): + client, _ = _client(tmp_path) + _session(tmp_path, takes=(_manifest(0, "DISCARDED"),)) + before = _tree(tmp_path) + response = _studio(client, session=SESSION, studio="Pantry") + assert response.status_code == 200 + assert (response.json()["updated"], response.json()["config_updated"]) == ([], False) + assert _tree(tmp_path) == before + + +def test_a_studio_typed_in_either_unicode_form_is_stored_as_one_studio(tmp_path): + client, _ = _client(tmp_path) + session = _settled_day(tmp_path) + combining = _studio(client, session=SESSION, studio="Cafe\u0301") + assert (combining.status_code, combining.json()["studio"]) == (200, "Caf\u00e9") + assert yaml.safe_load((session / "config.yaml").read_text(encoding="utf-8"))["meta"]["studio"] == "Caf\u00e9" + + +# --- all or nothing -------------------------------------------------------------------------------------------- + +ONE_STUDIO_STILL = ( + "the labels could not all be written; those already written were put back, so nothing was changed" +) + + +@pytest.mark.skipif(os.geteuid() == 0, reason="the administrator writes into any directory") +def test_a_take_whose_folder_is_read_only_refuses_the_studio_correction_with_every_label_as_it_was(tmp_path): + client, _ = _client(tmp_path) + session = _settled_day(tmp_path) + (session / "episode_1").chmod(0o555) + try: + before = _tree(tmp_path) + # Found before the first take is written, and found again on every repeat: never half a relabel. + for _ in range(2): + refused = _studio(client, session=SESSION, studio="Pantry") + assert (refused.status_code, refused.json()) == ( + 400, + {"detail": "episode_1 cannot be rewritten (its folder is read-only), so nothing was changed"}, + ) + assert _tree(tmp_path) == before + finally: + (session / "episode_1").chmod(0o755) + assert _studio(client, session=SESSION, studio="Pantry").json()["updated"] == ["episode_0", "episode_1"] + + +def test_a_studio_correction_whose_write_fails_part_way_answers_a_failure_with_one_studio_in_the_session( + tmp_path, monkeypatch +): + client, _ = _client(tmp_path) + _settled_day(tmp_path) + before = _tree(tmp_path) + real = relabel._replace_file + + def disk(path: Path, content: bytes) -> None: + # Both takes are written, and then the session's own label cannot be. + if path.name == "config.yaml": + raise OSError(28, "No space left on device") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + refused = _studio(client, session=SESSION, studio="Pantry") + assert (refused.status_code, refused.json()) == (400, {"detail": ONE_STUDIO_STILL}) + # The takes written before the failure say what they said, byte for byte. + assert _tree(tmp_path) == before + report = client.get("/api/day-report", headers=AUTH).json()["report"] + assert {episode["studio"] for episode in report["sessions"][0]["episodes"]} == {None} + + +def test_a_label_that_could_not_be_put_back_is_named_in_the_reply_and_in_a_field_of_its_own(tmp_path, monkeypatch): + client, _ = _client(tmp_path) + _settled_day(tmp_path) + before = _tree(tmp_path) + real = relabel._replace_file + wrote: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + wrote.append(path) + # The session's own label cannot be written, and after that neither can the first take: it stays. + if path.name == "config.yaml" or (path.parent.name == "episode_0" and len(wrote) > 2): + raise OSError(5, "Input/output error") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + refused = _studio(client, session=SESSION, studio="Pantry") + assert (refused.status_code, refused.json()) == ( + 400, + { + "detail": "the labels could not all be written, and episode_0 could not be put back: " + "it says Pantry now, and the rest what they said before", + "left_changed": ["episode_0"], + }, + ) + after = _tree(tmp_path) + assert sorted(name for name in after if after[name] != before[name]) == [f"{SESSION}/episode_0/zarr.json"] + assert str(tmp_path) not in refused.text + + +@pytest.mark.parametrize( + ("content", "reason"), + [ + (b"- numeric_sources\n", "config.yaml does not hold the session's settings, so nothing was changed"), + (b"meta:\n station: Caf\xe9\n", "config.yaml cannot be read, so nothing was changed"), + ], + ids=["a list", "not UTF-8"], +) +def test_a_config_that_would_not_be_rewritten_refuses_both_corrections_with_nothing_changed( + tmp_path, content, reason +): + client, _ = _client(tmp_path) + session = _settled_day(tmp_path) + (session / "config.yaml").write_bytes(content) + before = _tree(tmp_path) + for refused in ( + _correct(client, session=SESSION, episodes="0-1", task="Wash the cup."), + _studio(client, session=SESSION, studio="Pantry"), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": reason}) + assert _tree(tmp_path) == before + + +def test_a_config_that_was_not_rewritten_is_a_failure_and_never_a_success_that_says_so_in_a_field( + tmp_path, monkeypatch +): + client, _ = _client(tmp_path) + _settled_day(tmp_path) + before = _tree(tmp_path) + real = relabel._replace_file + failed: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + # The config cannot be written once; the takes written before it are then put back. + if path.name == "config.yaml" and not failed: + failed.append(path) + raise OSError(28, "No space left on device") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + refused = _correct(client, session=SESSION, episodes="0-1", task="Wash the cup.") + assert refused.status_code == 400 + assert refused.json() == {"detail": ONE_STUDIO_STILL} + # A failure, and what it says of the disk is so: both takes say the task they said. + assert _tree(tmp_path) == before + monkeypatch.undo() + # The fault gone, the same correction says the config was written. + assert _correct(client, session=SESSION, episodes="0-1", task="Wash the cup.").json()["config_updated"] is True + + +# --- answers in sentences -------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("content", ["[]", "null", "7", '"text"', "{}"]) +def test_a_take_record_that_is_json_and_no_record_is_answered_in_a_sentence_by_every_route(tmp_path, content): + client, _ = _client(tmp_path) + session = _settled_day(tmp_path) + (session / ".recording" / "episode_9.json").write_text(content) + before = _tree(tmp_path) + for refused in ( + _correct(client, session=SESSION, episodes="0", task="x"), + _studio(client, session=SESSION, studio="Pantry"), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": day_report_routes.UNREADABLE_TAKE}) + # The report still lists the takes whose records can be read. + report = client.get("/api/day-report", headers=AUTH) + assert report.status_code == 200 + assert len(report.json()["report"]["sessions"][0]["episodes"]) == 4 + assert _tree(tmp_path) == before + + +@pytest.mark.parametrize( + ("path", "rest"), + [ + ("/api/day-report/studio", '"studio": "Pantry"'), + ("/api/day-report/correct", '"episodes": "0", "task": "x"'), + ], +) +def test_a_session_name_that_cannot_be_encoded_is_not_a_session(tmp_path, path, rest): + client, _ = _client(tmp_path) + _settled_day(tmp_path) + before = _tree(tmp_path) + # Half of a surrogate pair: text no filesystem name can hold. + body = ('{"session": "\\ud800", %s}' % rest).encode() + refused = client.post(path, content=body, headers={**AUTH, "Content-Type": "application/json"}) + assert (refused.status_code, refused.json()) == (400, {"detail": "that directory is not a recorded session"}) + assert _tree(tmp_path) == before + + +def _routed_group_with_its_copy(root: Path) -> Path: + """A routed group of a session that is gone, and its time-aligned copy beside it.""" + group = root / "Kitchen" / "2026-03-09-08-15-00" + stamp = {ROUTE_ATTR: route_id(SESSION, "Kitchen/2026-03-09-08-15-00"), "studio": "Kitchen"} + for directory in (group, group.with_name(f"{group.name}_aligned")): + zarr.open_group(str(directory), mode="w", attributes=stamp).create_group("episode_0") + return group + + +@pytest.mark.parametrize("suffix", ["_aligned", "_ALIGNED", "_Aligned"]) +def test_the_aligned_copy_is_never_corrected_by_its_own_name_however_the_name_is_cased(tmp_path, suffix): + client, _ = _client(tmp_path) + group = _routed_group_with_its_copy(tmp_path) + before = _tree(tmp_path) + # On a disk that folds case every spelling names the copy; it carries the group's stamp, and is no group. + refused = _studio(client, session=f"Kitchen/{group.name}{suffix}", studio="Other") + assert (refused.status_code, refused.json()) == (400, {"detail": "that directory is not a recorded session"}) + assert _tree(tmp_path) == before + + +def test_a_correction_by_another_spelling_of_a_directory_finds_it_held_by_the_aligner(tmp_path): + client, _ = _client(tmp_path) + group = _routed_group_with_its_copy(tmp_path) + folds_case = (tmp_path / "KITCHEN").exists() + locks = client.app.state.session_locks + assert locks.acquire(group.resolve(), ALIGNER) is None + before = _tree(tmp_path) + refused = _studio(client, session=f"KITCHEN/{group.name}", studio="Pantry") + # Where the other spelling is the same directory it is the same lock; elsewhere it names nothing. + reason = ( + "time alignment of this take is still running; try again in a moment" + if folds_case + else "that directory is not a recorded session" + ) + assert (refused.status_code, refused.json()) == (400, {"detail": reason}) + assert _tree(tmp_path) == before diff --git a/examples/egocap/tests/backend/test_glove_offset_session.py b/examples/egocap/tests/backend/test_glove_offset_session.py index 1a53d743d9..db50fd9078 100644 --- a/examples/egocap/tests/backend/test_glove_offset_session.py +++ b/examples/egocap/tests/backend/test_glove_offset_session.py @@ -91,6 +91,9 @@ def _library_test_helpers(name: str): "corr_right_deg", "left", "right", + # Added beside the keys readers outside this repository use, which are the ones above. + "schema_version", + "provenance", ] #: What a head-camera position and wrist offsets say of the tracking their poses came from, as this project's #: tools write it, and the sentence for a file that does not. @@ -1132,6 +1135,25 @@ def test_installing_writes_the_offsets_file_archives_it_and_stamps_the_ledger(re entry = json.loads((station / LEDGER_NAME).read_text())["wrist"] assert entry["operator"] == "alex" and entry["files"] == [WRIST_OFFSETS] assert entry["at"].startswith(entry["date"]) and archived[0].parent.name == entry["date"] + # The file states what made it, the rule its install was held to and what each hand's fit rested on, and + # from when it is the station's. The operator is in the ledger, not in the file. + stated = record["provenance"] + assert record["schema_version"] == 1 and stated["producer"]["tool"] == "wrist_offset_fit" + assert stated["grade"] is None + assert stated["install_rule"] == ( + "Wrist offsets are installed once every hand fitted rests on at least 8 clicks over at least 3 frames " + "and its fit did not stop at the translation limit. The fit's error is shown to the operator and not " + "limited." + ) + for side in SIDES: + assert stated["evidence"][side] == { + "rms_px": summary["fits"][side]["rms_px"], + "clicks": PINNING, + "frames": 3, + "at_translation_limit": False, + } + assert stated["validity"] == {"valid_from": entry["at"], "supersedes": None} + assert "alex" not in json.dumps(record) @pytest.mark.parametrize( @@ -1734,6 +1756,23 @@ def test_offsets_made_with_another_tracking_source_are_not_started_from_and_the_ assert (again["start"], again["warnings"]) == ("installed", []) +def test_installed_offsets_of_a_newer_layout_are_not_started_from_and_the_session_says_so_before_any_click( + recorded, station, monkeypatch +): + monkeypatch.setattr(glove_offset_session, "optimize", FakeFits()) + newer = {**offsets_record(near_truth(), n_samples=12), "schema_version": 2} + (station / WRIST_OFFSETS).write_text(json.dumps(newer)) + summary = _build(recorded, station).summary() + # Nothing of the file is taken, and the operator is told what an install will then replace. + assert summary["start"] == "zero" and offset_of(summary, "left") == WristOffset() + assert summary["warnings"] == [ + "wrist_calibration_offsets.json is written in layout 2, and this software reads up to layout 1: update " + "the software, or calibrate again with this one. The fit starts from zero, and installing replaces " + "that file." + ] + assert summary["install"] == {"allowed": False, "reason": "Fit both hands first"} + + def test_a_skeleton_whose_joints_are_not_in_the_expected_order_is_said_before_any_click( recorded, station, monkeypatch ): diff --git a/examples/egocap/tests/backend/test_livekit_receiver.py b/examples/egocap/tests/backend/test_livekit_receiver.py index cfdbad133d..2af2ba77f1 100644 --- a/examples/egocap/tests/backend/test_livekit_receiver.py +++ b/examples/egocap/tests/backend/test_livekit_receiver.py @@ -462,6 +462,25 @@ async def test_stop_cancels_readers_disconnects_once_and_keeps_queued_frames(): assert (await asyncio.wait_for(rx.next_frame(1), 1)).frame_id == 1 +async def test_stop_leaves_the_room_whatever_an_earlier_step_of_the_leave_raises(): + rx = lr.LiveKitFrameReceiver([camera(1, "left")], TOKEN) + await rx.start() + room = room_of(rx) + subscribe(rx) + await settle() + reader = rx._readers[1] + + async def broken() -> None: + raise RuntimeError("the clock sync could not be stopped") + + rx.clock_sync = SimpleNamespace(stop=broken) + # The failure is the caller's to hear of, after the room was left and the reader stopped. + with pytest.raises(RuntimeError, match="the clock sync could not be stopped"): + await rx.stop() + assert room.disconnects == 1 and reader.cancelled() and not rx._readers + assert not rx.counters[1].subscribed + + async def test_stop_before_start_is_harmless(): rx = lr.LiveKitFrameReceiver([camera(1, "left")], TOKEN) await rx.stop() diff --git a/examples/egocap/tests/backend/test_livekit_recording_source.py b/examples/egocap/tests/backend/test_livekit_recording_source.py index d82cff1abf..3518268f3a 100644 --- a/examples/egocap/tests/backend/test_livekit_recording_source.py +++ b/examples/egocap/tests/backend/test_livekit_recording_source.py @@ -260,6 +260,38 @@ async def test_a_quiet_stream_times_out_and_leaves_the_room(): assert FakeReceiver.instances[0].stops == 1 +async def test_the_source_says_what_prepare_is_waiting_for_and_where_a_failed_one_stopped(): + streams = [livekit_stream(16)] + FakeReceiver.start_gate = asyncio.Event() + FakeReceiver.mapping_ready = False + source = make_source(streams, timeout=0.05) + assert source.stage is None + + async def turns() -> None: + for _ in range(5): + await asyncio.sleep(0) + + task = asyncio.ensure_future(source.prepare()) + await turns() + assert source.stage == lrec.JOINING + FakeReceiver.start_gate.set() + await turns() + assert source.stage == lrec.FIRST_FRAME + preload(streams) + await turns() + assert source.stage == lrec.CLOCK_MAPPING + with pytest.raises(RuntimeError, match="did not answer clock-sync requests"): + _ = await task + # A failed prepare still says how far it had come; the room has been left. + assert source.stage == lrec.CLOCK_MAPPING and FakeReceiver.instances[0].stops == 1 + # One that succeeds is waiting for nothing, and the next begins from nothing. + FakeReceiver.start_gate, FakeReceiver.mapping_ready = None, True + FakeReceiver.instances.clear() + await prepare_with_frames(source, streams) + assert source.stage is None + await source.stop() + + async def test_no_clock_mapping_before_the_timeout_fails_naming_clock_sync_and_leaves_the_room(): FakeReceiver.mapping_ready = False streams = [livekit_stream(16)] diff --git a/examples/egocap/tests/backend/test_livekit_sightings.py b/examples/egocap/tests/backend/test_livekit_sightings.py new file mode 100644 index 0000000000..a3676eb580 --- /dev/null +++ b/examples/egocap/tests/backend/test_livekit_sightings.py @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What operator pages report seeing of the LiveKit cameras: kept per page, aged, and the best one read.""" + +from __future__ import annotations + +import pytest + +from egocap_web.livekit_sightings import ( + FRESH_SECONDS, + MAX_PAGES, + MAX_STREAMS, + NO_TRACK, + NOT_CONNECTED, + RECEIVING, + SILENT, + LiveKitSightings, + SightingError, +) + + +class _Clock: + def __init__(self) -> None: + self.now = 100.0 + + def __call__(self) -> float: + return self.now + + +def _sightings() -> tuple[LiveKitSightings, _Clock]: + clock = _Clock() + return LiveKitSightings(clock), clock + + +def test_nothing_is_known_of_a_camera_until_a_page_reports_it(): + sightings, _ = _sightings() + assert sightings.seen() == {} + sightings.report("page-a", {"Head left": RECEIVING}) + assert sightings.seen() == {"Head left": RECEIVING} + + +def test_a_page_replaces_its_own_report_and_a_stream_it_stops_naming_is_no_longer_known(): + sightings, _ = _sightings() + sightings.report("page-a", {"Head left": RECEIVING, "Left wrist": SILENT}) + sightings.report("page-a", {"Head left": NO_TRACK}) + assert sightings.seen() == {"Head left": NO_TRACK} + sightings.report("page-a", {}) + assert sightings.seen() == {} + + +def test_a_report_speaks_for_a_camera_only_while_it_is_fresh(): + sightings, clock = _sightings() + sightings.report("page-a", {"Head left": RECEIVING}) + clock.now += FRESH_SECONDS + assert sightings.seen() == {"Head left": RECEIVING} + clock.now += 0.1 + # The page closed, or went out of view and stopped reporting: nobody is watching the camera any more. + assert sightings.seen() == {} + + +@pytest.mark.parametrize( + ("first", "second", "best"), + [ + (SILENT, RECEIVING, RECEIVING), + (RECEIVING, NOT_CONNECTED, RECEIVING), + (NO_TRACK, SILENT, SILENT), + (NOT_CONNECTED, NO_TRACK, NO_TRACK), + (NOT_CONNECTED, NOT_CONNECTED, NOT_CONNECTED), + ], +) +def test_one_page_receiving_frames_shows_they_arrive_whatever_another_page_fails_to_show(first, second, best): + sightings, clock = _sightings() + sightings.report("page-a", {"Head left": first}) + sightings.report("page-b", {"Head left": second, "Left wrist": SILENT}) + assert sightings.seen() == {"Head left": best, "Left wrist": SILENT} + # A stale report does not count, however good it was. + clock.now += FRESH_SECONDS - 1 + sightings.report("page-b", {"Head left": second}) + clock.now += 2 + assert sightings.seen() == {"Head left": second} + + +def test_the_pages_remembered_are_bounded_and_the_one_silent_longest_gives_way(): + sightings, _ = _sightings() + for index in range(MAX_PAGES): + sightings.report(f"page-{index}", {f"cam-{index}": RECEIVING}) + # Reporting again makes a page the newest, so it is not the one to go. + sightings.report("page-0", {"cam-0": RECEIVING}) + sightings.report("page-new", {"cam-new": RECEIVING}) + seen = sightings.seen() + assert len(seen) == MAX_PAGES and "cam-1" not in seen + assert {"cam-0", "cam-new", f"cam-{MAX_PAGES - 1}"} <= set(seen) + + +_STATES = "each stream must be one of receiving, silent, no_track, not_connected" + + +@pytest.mark.parametrize( + ("page", "streams", "reason"), + [ + (None, {}, "page must be a short text id"), + ("", {}, "page must be a short text id"), + ("p" * 129, {}, "page must be a short text id"), + (7, {}, "page must be a short text id"), + ("page-a", None, f"streams must be an object of at most {MAX_STREAMS} stream names"), + ("page-a", ["Head left"], f"streams must be an object of at most {MAX_STREAMS} stream names"), + ( + "page-a", + {f"cam-{index}": RECEIVING for index in range(MAX_STREAMS + 1)}, + f"streams must be an object of at most {MAX_STREAMS} stream names", + ), + ("page-a", {"c" * 129: RECEIVING}, "a stream name is too long"), + ("page-a", {"Head left": "fine"}, "each stream must be one of receiving, silent, no_track, not_connected"), + ("page-a", {"Head left": 30}, "each stream must be one of receiving, silent, no_track, not_connected"), + ( + "page-a", + {"Head left": ["receiving"]}, + "each stream must be one of receiving, silent, no_track, not_connected", + ), + ], +) +def test_a_malformed_report_is_refused_with_the_reason_and_changes_nothing(page, streams, reason): + sightings, _ = _sightings() + sightings.report("page-a", {"Head left": RECEIVING}) + with pytest.raises(SightingError) as refused: + sightings.report(page, streams) + assert refused.value.public_message == reason + assert sightings.seen() == {"Head left": RECEIVING} diff --git a/examples/egocap/tests/backend/test_session_locks.py b/examples/egocap/tests/backend/test_session_locks.py new file mode 100644 index 0000000000..ea248a14ef --- /dev/null +++ b/examples/egocap/tests/backend/test_session_locks.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The lock of a recorded session's labels: one holder at a time, and one lock per directory on the disk.""" + +from __future__ import annotations + +from egocap_web.session_locks import ALIGNER, CORRECTION, SessionLocks + + +def test_a_held_session_names_its_holder_and_is_free_again_once_given_back(tmp_path): + locks = SessionLocks() + session = tmp_path / "session" + session.mkdir() + assert locks.acquire(session, ALIGNER) is None + assert locks.acquire(session, CORRECTION) == ALIGNER + # Another session is another lock. + other = tmp_path / "other" + other.mkdir() + assert locks.acquire(other, CORRECTION) is None + locks.release(session) + assert locks.acquire(session, CORRECTION) is None + + +def test_two_spellings_of_one_directory_are_one_lock(tmp_path): + locks = SessionLocks() + session = tmp_path / "session" + session.mkdir() + (tmp_path / "beside").mkdir() + # The same directory by another path, as another letter case is on a disk that folds case. + respelled = tmp_path / "beside" / ".." / "session" + assert respelled != session and respelled.samefile(session) + assert locks.acquire(session, ALIGNER) is None + assert locks.acquire(respelled, CORRECTION) == ALIGNER + locks.release(session) + assert locks.acquire(respelled, CORRECTION) is None + assert locks.acquire(session, ALIGNER) == CORRECTION + + +def test_a_lock_is_given_back_after_its_directory_was_renamed_or_removed(tmp_path): + locks = SessionLocks() + session = tmp_path / "session" + session.mkdir() + assert locks.acquire(session, ALIGNER) is None + moved = session.rename(tmp_path / "moved") + # The directory is held where it went, and is released under the path it was taken with. + assert locks.acquire(moved, CORRECTION) == ALIGNER + locks.release(session) + assert locks.acquire(moved, CORRECTION) is None + + +def test_a_directory_that_is_not_there_is_locked_under_its_path(tmp_path): + locks = SessionLocks() + missing = tmp_path / "gone" + assert locks.acquire(missing, ALIGNER) is None + assert locks.acquire(missing, CORRECTION) == ALIGNER + locks.release(missing) + assert locks.acquire(missing, CORRECTION) is None + + +def test_giving_back_a_lock_that_was_never_taken_changes_nothing(tmp_path): + locks = SessionLocks() + session = tmp_path / "session" + session.mkdir() + assert locks.acquire(session, ALIGNER) is None + locks.release(tmp_path / "never_taken") + assert locks.acquire(session, CORRECTION) == ALIGNER diff --git a/examples/egocap/tests/backend/test_setup_checks.py b/examples/egocap/tests/backend/test_setup_checks.py index dd69da8aef..d973cf84a4 100644 --- a/examples/egocap/tests/backend/test_setup_checks.py +++ b/examples/egocap/tests/backend/test_setup_checks.py @@ -23,11 +23,12 @@ first_failure, first_warning, free_bytes_under, + tracking_device_kind, ) -HEADSET = DeviceFact("Headset", True, headset=True) -LEFT = DeviceFact("Left controller", True) -RIGHT = DeviceFact("Right controller", True) +HEADSET = DeviceFact("Headset", True, headset=True, kind="headset") +LEFT = DeviceFact("Left controller", True, kind="controller_left") +RIGHT = DeviceFact("Right controller", True, kind="controller_right") ROLES = {"ego": "cam_head", "wrist_left": "cam_left", "wrist_right": None} CALIBRATED = ( "head_camera_intrinsics.json", @@ -47,7 +48,9 @@ def _facts(**overrides) -> CaptureFacts: return CaptureFacts(**{**base, **overrides}) -def _items(tmp_path, facts=None, roles=ROLES, free=50 * 1024**3, require_calibration=False) -> list[CheckItem]: +def _items( + tmp_path, facts=None, roles=ROLES, free=50 * 1024**3, require_calibration=False, required_devices=() +) -> list[CheckItem]: def free_bytes(path): if isinstance(free, OSError): raise free @@ -60,6 +63,7 @@ def free_bytes(path): output_root=tmp_path / "recordings", free_bytes=free_bytes, require_calibration=require_calibration, + required_devices=required_devices, ) @@ -116,6 +120,181 @@ def test_a_device_that_is_not_connected_warns_with_its_own_reason_and_holds_noth assert first_warning(items) == "Left controller: degraded" +def test_a_device_the_station_requires_fails_when_it_is_not_connected_and_the_others_still_warn(tmp_path): + devices = ( + DeviceFact("Headset", False, "initializing", headset=True, kind="headset"), + DeviceFact("Left controller", False, kind="controller_left"), + DeviceFact("Left hand", False, "unavailable", kind="glove_left"), + DeviceFact("Right hand", True, kind="glove_right"), + ) + items = _items( + tmp_path, _facts(devices=devices, mock=True), required_devices=("headset", "glove_left", "glove_right") + ) + assert _by_id(items) | {"calibration": None, "disk": None} == { + "device:0": (FAIL, "initializing; this station requires it"), + # Not required here: the same state as at a station that says nothing. + "device:1": (WARN, "not connected"), + "device:2": (FAIL, "unavailable; this station requires it"), + # Required and connected: a plain pass. + "device:3": (PASS, None), + "camera:ego": (PASS, None), + "camera:wrist_left": (PASS, None), + "camera:wrist_right": (SKIP, "not used by this station"), + "calibration": None, + "disk": None, + } + assert first_failure(items) == "Headset: initializing; this station requires it" + assert first_warning(items) == "Left controller: not connected" + + +def test_a_device_the_station_requires_is_named_as_the_station_tab_names_it_and_no_other_device_is(tmp_path): + # The capture session describes its devices in its own words; a glove is a "hand" to it. + devices = ( + DeviceFact("Pico headset", True, headset=True, kind="headset"), + DeviceFact("Left hand", False, "unavailable", kind="glove_left"), + DeviceFact("Right hand", False, "unavailable", kind="glove_right"), + DeviceFact("Waist tracker", False, "degraded"), + ) + said = _items(tmp_path, _facts(devices=devices, mock=True)) + # A station that requires nothing shows every device exactly as the session describes it, as it always did. + assert [(item.label, item.status) for item in said if item.group == "tracking"] == [ + ("Pico headset", PASS), + ("Left hand", WARN), + ("Right hand", WARN), + ("Waist tracker", WARN), + ] + items = _items(tmp_path, _facts(devices=devices, mock=True), required_devices=("glove_left",)) + # Only the row of a device the station requires takes the station's word, so the box that was ticked and + # the row that fails name one thing. + assert [(item.label, item.status) for item in items if item.group == "tracking"] == [ + ("Pico headset", PASS), + ("Left glove", FAIL), + ("Right hand", WARN), + ("Waist tracker", WARN), + ] + assert first_failure(items) == "Left glove: unavailable; this station requires it" + + +def test_a_required_device_that_is_degraded_meets_its_requirement_only_while_it_still_delivers(tmp_path): + def glove(detail: str, reason: str | None) -> DeviceFact: + return DeviceFact("Left hand", False, detail, kind="glove_left", degraded=True, reason=reason) + + def tracking(device: DeviceFact) -> tuple[list[tuple[str, str, str | None]], str | None]: + items = _items(tmp_path, _facts(devices=(HEADSET, device), mock=True), required_devices=("glove_left",)) + return [(item.label, item.status, item.detail) for item in items if item.group == "tracking"], ( + first_failure(items) + ) + + # A glove streaming with a calibration file it rejected is there and delivering: its own warning stays, + # with the device's reason, and it is not said to hold anything. + assert tracking(glove("glove calibration failed", "CALIBRATION_FAILED")) == ( + [("Headset", PASS, None), ("Left glove", WARN, "glove calibration failed")], + None, + ) + # Degraded for any other reason, the session says it has nothing to send: Record is held. + for detail, reason in [ + ("glove present but has no current usable skeleton data", "NO_CURRENT_DATA"), + ("device error", "DEVICE_ERROR"), + # A reason nobody has read for what it means for the data, and a fact that carries none. + ("degraded", "SOMETHING_NEWER"), + ("degraded", None), + ]: + rows, held = tracking(glove(detail, reason)) + assert rows[1] == ("Left glove", FAIL, f"{detail}; this station requires it") + assert held == f"Left glove: {detail}; this station requires it" + # A station that does not require the glove only warns of it, in every one of those states. + unrequired = _items(tmp_path, _facts(devices=(HEADSET, glove("device error", "DEVICE_ERROR")), mock=True)) + assert first_failure(unrequired) is None + assert ("Left hand", WARN, "device error") in [(item.label, item.status, item.detail) for item in unrequired] + # Any other state than connected is not there to record with: each holds the take. + for state in ("unavailable", "unknown", "initializing", "disconnected", "failed"): + gone = (HEADSET, DeviceFact("Left hand", False, state, kind="glove_left")) + held = _items(tmp_path, _facts(devices=gone, mock=True), required_devices=("glove_left",)) + assert first_failure(held) == f"Left glove: {state}; this station requires it" + + +def test_a_required_device_switched_off_in_the_capture_configuration_holds_a_take_in_its_own_sentence(tmp_path): + facts = _facts(devices=(HEADSET, LEFT), disabled=("glove_right", "controller_right"), mock=True) + # A device that is switched off is no part of a station that does not require it: no row, as before. + assert [item.id for item in _items(tmp_path, facts) if item.group == "tracking"] == ["device:0", "device:1"] + items = _items(tmp_path, facts, required_devices=("glove_right", "glove_left")) + tracking = [(item.id, item.label, item.status, item.detail) for item in items if item.group == "tracking"] + assert tracking == [ + ("device:0", "Headset", PASS, None), + ("device:1", "Left controller", PASS, None), + ( + "device:required:glove_left", + "Left glove", + FAIL, + "not reported by the capture session; this station requires it", + ), + ( + "device:required:glove_right", + "Right glove", + FAIL, + "switched off in the capture configuration; this station requires it", + ), + ] + + +def test_a_requirement_this_software_does_not_know_can_never_be_met_and_is_shown_as_a_failing_row(tmp_path): + # Read from a stations file a newer build or a hand wrote: kept, never dropped, and never met here. + required = ("headset", "tracker_waist", "Headset") + items = _items(tmp_path, _facts(devices=(HEADSET,), mock=True), required_devices=required) + unknown = "not a tracking device this software knows; this station requires it" + assert [(item.id, item.label, item.status, item.detail) for item in items if item.group == "tracking"] == [ + ("device:0", "Headset", PASS, None), + ("device:required:tracker_waist", "tracker_waist", FAIL, unknown), + ("device:required:Headset", "Headset", FAIL, unknown), + ] + assert first_failure(items) == f"tracker_waist: {unknown}" + + +def test_a_required_device_the_session_does_not_report_fails_under_the_name_the_operator_knows(tmp_path): + # A glove whose software never started has no entry in the session's report at all. + items = _items( + tmp_path, + _facts(devices=(HEADSET, LEFT), mock=True), + required_devices=("glove_right", "controller_left", "controller_right", "glove_left"), + ) + tracking = [(item.id, item.label, item.status, item.detail) for item in items if item.group == "tracking"] + unreported = "not reported by the capture session; this station requires it" + assert tracking == [ + ("device:0", "Headset", PASS, None), + ("device:1", "Left controller", PASS, None), + # In the order the devices are listed to the operator, whatever order the station named them in. + ("device:required:controller_right", "Right controller", FAIL, unreported), + ("device:required:glove_left", "Left glove", FAIL, unreported), + ("device:required:glove_right", "Right glove", FAIL, unreported), + ] + assert first_failure(items) == f"Right controller: {unreported}" + # With no device reported at all there is no tracking data to be late, only the device to be missing. + alone = _items(tmp_path, _facts(devices=(), tracking_fresh=False, mock=True), required_devices=("headset",)) + assert [(item.id, item.status) for item in alone if item.group == "tracking"] == [ + ("device:required:headset", FAIL) + ] + + +@pytest.mark.parametrize( + ("device_type", "path", "kind"), + [ + ("headset", "/headset", "headset"), + ("headset", "/head/headset", "headset"), + ("controller", "/controller/left", "controller_left"), + ("controller", "/controller/right", "controller_right"), + # Every provider of hand tracking reports at the hand's path, under its own type and description. + ("hand_tracker", "/hand/left", "glove_left"), + ("hand", "/hand/right", "glove_right"), + ("hand_tracker", "/hand/both", None), + ("gamepad", "/gamepad", None), + ("se3_tracker", "/tracker/left", None), + ("controller", "", None), + ], +) +def test_a_reported_device_is_recognised_by_its_path_whatever_its_provider_calls_it(device_type, path, kind): + assert tracking_device_kind(device_type, path) == kind + + def test_only_devices_the_session_reports_are_judged(tmp_path): # No glove is reported, so there is no glove item to fail, whatever the deployment asked for. items = _by_id(_items(tmp_path, _facts(devices=(HEADSET,), mock=True))) @@ -153,21 +332,63 @@ def test_a_camera_that_delivers_frames_in_another_state_than_connected_only_warn assert _by_id(_items(tmp_path, _facts(cameras=cameras)))["camera:wrist_left"] == (WARN, "not connected") -def test_a_livekit_camera_passes_when_offered_and_fails_with_why_it_cannot_be_recorded(tmp_path): - offered = _facts(cameras={}, livekit_cameras=frozenset({"cam_head", "cam_left"})) - assert _by_id(_items(tmp_path, offered))["camera:ego"] == (PASS, None) +def test_a_livekit_camera_passes_only_while_a_page_sees_its_frames_arriving(tmp_path): + offered = frozenset({"cam_head", "cam_left"}) + + def camera(role: str, seen: dict[str, str] | None) -> tuple[str, str | None]: + facts = _facts(cameras={}, livekit_cameras=offered, livekit_seen=seen) + return _by_id(_items(tmp_path, facts))[f"camera:{role}"] + + # Offered and recordable is not received: with nothing seen of it the camera warns, and never fails. + unseen = ( + "not checked here: keep this page in view with the control token entered; " + "the recorder checks this camera itself when a take starts" + ) + assert camera("ego", None) == camera("ego", {}) == (WARN, unseen) + seen = {"cam_head": "receiving", "cam_left": "silent"} + assert camera("ego", seen) == (PASS, "frames are arriving in the preview") + assert camera("wrist_left", seen) == ( + WARN, + "no frames in the preview: check the camera and its sender; " + "the recorder checks this camera itself when a take starts", + ) + assert camera("ego", {"cam_head": "no_track"}) == ( + WARN, + "its sender is not publishing it: start the camera sender; " + "the recorder checks this camera itself when a take starts", + ) + assert camera("ego", {"cam_head": "not_connected"}) == ( + WARN, + "the preview cannot join the video room; the recorder checks this camera itself when a take starts", + ) + # What a page sees of another camera says nothing of this one. + assert camera("ego", {"cam_left": "receiving"}) == (WARN, unseen) + # A page's word never holds a take: the recorder joins the room itself and refuses the take then. + silent = _items( + tmp_path, _facts(cameras={}, livekit_cameras=offered, livekit_seen={"cam_left": "silent"}, mock=True) + ) + assert first_failure(silent) is None and first_warning(silent).startswith( + "Ego (head): cam_head: not checked here" + ) + + +def test_a_livekit_camera_that_cannot_be_recorded_fails_whatever_a_page_sees_of_it(tmp_path): blocked = _facts( - cameras=None, livekit_cameras=frozenset({"cam_head", "cam_left"}), livekit_blocked="no capture time" + cameras=None, + livekit_cameras=frozenset({"cam_head", "cam_left"}), + livekit_blocked="no capture time", + livekit_seen={"cam_head": "receiving"}, ) assert _by_id(_items(tmp_path, blocked))["camera:ego"] == (FAIL, "no capture time") def test_without_a_station_every_offered_camera_is_checked_by_name(tmp_path): - items = _items(tmp_path, _facts(livekit_cameras=frozenset({"lk_cam"})), roles=None) - assert [item.id for item in items if item.group == "cameras"] == [ - "camera:cam_head", - "camera:cam_left", - "camera:lk_cam", + seen = {"lk_cam": "receiving"} + items = _items(tmp_path, _facts(livekit_cameras=frozenset({"lk_cam"}), livekit_seen=seen), roles=None) + assert [(item.id, item.status) for item in items if item.group == "cameras"] == [ + ("camera:cam_head", PASS), + ("camera:cam_left", PASS), + ("camera:lk_cam", PASS), ] assert _by_id(items)["calibration"] == (SKIP, "no station in use") @@ -190,6 +411,36 @@ def required(**kwargs): ] == (PASS, None) +def test_a_calibration_file_of_a_newer_layout_than_this_software_reads_is_said_at_the_start_of_the_day(tmp_path): + def calibration(**kwargs): + return _by_id(_items(tmp_path, **kwargs))["calibration"] + + def newer(name: str, layout: object = 2) -> str: + return ( + f"{name} is written in layout {layout}, and this software reads up to layout 1: update the " + "software, or calibrate again with this one" + ) + + lens, position = "head_camera_intrinsics.json", "head_camera_extrinsics.json" + _calibrate(tmp_path, *CALIBRATED) + assert calibration() == (PASS, None) + # A station rolled back to this build after a newer one calibrated it: no reader here takes such a file, + # and nothing else at the start of the day would say so. + _calibrate(tmp_path, position, content='{"pose_source": "openxr", "schema_version": 2}') + assert calibration() == (WARN, newer(position)) + assert calibration(require_calibration=True) == (FAIL, newer(position)) + # A lens file is asked too, however the number was written, each file in the order the station needs them. + _calibrate(tmp_path, lens, content='{"schema_version": "3"}') + assert calibration() == (WARN, f"{newer(lens, 3)}; {newer(position)}") + # A lens file that cannot be read at all is not this item's to say, as before; its own row lists it. + _calibrate(tmp_path, lens, content="not json") + assert calibration() == (WARN, newer(position)) + # The layout this build writes says nothing, and neither does a lens file that states none. + _calibrate(tmp_path, lens, content='{"schema_version": 1}') + _calibrate(tmp_path, position, content='{"pose_source": "openxr", "schema_version": 1}') + assert calibration() == (PASS, None) + + def test_a_position_or_offsets_made_with_another_tracking_source_are_no_calibration_of_this_station(tmp_path): def calibration(**kwargs): return _by_id(_items(tmp_path, **kwargs))["calibration"] diff --git a/examples/egocap/tests/backend/test_setup_routes.py b/examples/egocap/tests/backend/test_setup_routes.py index e9ef5d4dbf..909ba3bd00 100644 --- a/examples/egocap/tests/backend/test_setup_routes.py +++ b/examples/egocap/tests/backend/test_setup_routes.py @@ -6,6 +6,7 @@ from __future__ import annotations +import time from dataclasses import dataclass from types import SimpleNamespace @@ -16,6 +17,8 @@ from egocap_web import setup_routes from egocap_web.app import app as real_app from egocap_web.host_addresses import HostAddress +from egocap_web.livekit_sightings import LiveKitSightings +from egocap_web.recording_command import handle_recording_command, parse_recording_command from egocap_web.setup_checks import CameraFact, CaptureFacts, DeviceFact from egocap_web.setup_service import SetupService from egocap_web.station_routes import router as station_router @@ -40,6 +43,11 @@ class _World: headset_connected = True tracking_fresh = True + #: The cameras the session offers over LiveKit, by name. + livekit_cameras: frozenset[str] = frozenset() + + def __init__(self) -> None: + self.sightings = LiveKitSightings() async def _rotate() -> None: @@ -61,6 +69,8 @@ def facts() -> CaptureFacts: tracking_fresh=world.tracking_fresh, devices=(DeviceFact("Headset", world.headset_connected, "disconnected", headset=True),), cameras={"cam_head": CameraFact(True, True)}, + livekit_cameras=world.livekit_cameras, + livekit_seen=world.sightings.seen(), ) uptime = UptimeLog(tmp_path / "station_status") @@ -86,6 +96,7 @@ def facts() -> CaptureFacts: ) small.state.recording_context = _Context(control_token=TOKEN) small.state.settings = SimpleNamespace(capture=SimpleNamespace(capture_server_url="ws://127.0.0.1:8082")) + small.state.livekit_sightings = world.sightings return TestClient(small) @@ -301,6 +312,85 @@ def test_a_host_with_no_address_reports_none(tmp_path, monkeypatch): } +def _ego(client: TestClient) -> tuple[str, str | None]: + ego = next(item for item in client.get("/api/setup").json()["checks"] if item["id"] == "camera:ego") + return ego["status"], ego["detail"] + + +def test_a_livekit_camera_passes_once_an_operators_page_reports_its_frames_and_warns_again_when_none_does( + tmp_path, monkeypatch +): + _host(monkeypatch, "10.0.0.42") + world = _World() + world.livekit_cameras = frozenset({"cam_head"}) + client = _client(tmp_path, world) + _use_bench(client) + unseen = ( + "not checked here: keep this page in view with the control token entered; " + "the recorder checks this camera itself when a take starts" + ) + assert _ego(client) == ("warn", unseen) + assert client.get("/api/setup").json()["blocked_reason"] is None + report = {"page": "page-a", "streams": {"cam_head": "receiving"}} + answered = client.post("/api/setup/livekit-preview", json=report, headers=AUTH) + assert (answered.status_code, answered.json(), answered.headers["cache-control"]) == (200, {}, "no-store") + assert _ego(client) == ("pass", "frames are arriving in the preview") + client.post( + "/api/setup/livekit-preview", json={"page": "page-a", "streams": {"cam_head": "no_track"}}, headers=AUTH + ) + assert _ego(client) == ( + "warn", + "its sender is not publishing it: start the camera sender; " + "the recorder checks this camera itself when a take starts", + ) + # Never a hold: the recorder joins the room itself when a take starts. + assert client.get("/api/setup").json()["blocked_reason"] is None + # A page that stops reporting (closed, or out of view) is no longer watching the camera. + client.post("/api/setup/livekit-preview", json=report, headers=AUTH) + monkeypatch.setattr(world.sightings, "_monotonic", lambda: 1e9) + assert _ego(client) == ("warn", unseen) + + +@pytest.mark.parametrize( + ("body", "headers", "status", "detail"), + [ + ({"page": "page-a", "streams": {"cam_head": "receiving"}}, {}, 403, "control token rejected"), + ( + {"page": "page-a", "streams": {"cam_head": "receiving"}}, + {"X-Control-Token": "wrong"}, + 403, + "control token rejected", + ), + ({"streams": {"cam_head": "receiving"}}, AUTH, 400, "page must be a short text id"), + ( + {"page": "page-a", "streams": {"cam_head": "live"}}, + AUTH, + 400, + "each stream must be one of receiving, silent, no_track, not_connected", + ), + ({"page": "page-a", "streams": {"cam_head": "receiving"}, "padding": "x" * 9000}, AUTH, 413, None), + ], +) +def test_a_preview_report_needs_the_token_and_a_well_formed_bounded_body_and_otherwise_changes_nothing( + tmp_path, monkeypatch, body, headers, status, detail +): + _host(monkeypatch, "10.0.0.42") + world = _World() + world.livekit_cameras = frozenset({"cam_head"}) + client = _client(tmp_path, world) + _use_bench(client) + refused = client.post("/api/setup/livekit-preview", json=body, headers=headers) + assert refused.status_code == status + assert detail is None or refused.json()["detail"] == detail + assert world.sightings.seen() == {} and _ego(client)[0] == "warn" + + +def test_a_preview_report_before_the_application_has_started_is_answered_503(tmp_path): + report = {"page": "page-a", "streams": {}} + response = _client(tmp_path, ready=False).post("/api/setup/livekit-preview", json=report, headers=AUTH) + assert response.status_code == 503 and response.json() == {"detail": "setup is not available yet"} + + def test_a_station_with_a_missing_device_cannot_record_and_says_why(monkeypatch, unused_tcp_port, tmp_path): """The real application against the real CaptureServer in its mock mode.""" from egocap_web import app as app_module @@ -352,3 +442,193 @@ def add(name: str, ego: str) -> str: _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) finally: server.stop() + + +#: A board a calibration take can be asked for; nothing here looks at one. +BOARD = { + "charuco_squares": [8, 6], + "square_length_m": 0.05, + "marker_length_m": 0.0375, + "aruco_dict": "DICT_4X4_50", +} + + +def _command(client, context, action: str) -> dict: + """One recording command, sent as the page's socket handler sends it; the reply.""" + parsed = parse_recording_command( + { + "request_id": f"r-{time.monotonic_ns()}", + "action": action, + "payload": {"batch_id": context.batch_id}, + "operator_token": "alex", + "control_token": context.control_token, + } + ) + return client.portal.call(handle_recording_command, parsed, context) + + +def test_a_station_that_requires_a_tracking_device_the_session_does_not_have_cannot_record_and_says_why( + monkeypatch, unused_tcp_port, tmp_path +): + """The real application against the real CaptureServer in its mock mode, which reports a headset and two + controllers and, with no glove plugin asked for, no glove.""" + 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") + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(station_file)) + monkeypatch.setenv("EGOCAP_CAPTURE_SERVER_URL", f"ws://127.0.0.1:{unused_tcp_port}") + monkeypatch.delenv("EGOCAP_OPERATOR_SETTINGS_FILE", raising=False) + monkeypatch.delenv("EGOCAP_CAPTURE_PLUGINS", raising=False) + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: tmp_path) + 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} + monitor = client.app.state.monitor + _poll_until_sync( + lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None + ) + context.coordinator.set_task("Pour water.") + fields = {"name": "Bench A", "camera_roles": {"ego": "head_human_camera"}} + bench = client.post("/api/stations", json=fields, headers=auth).json()["stations"][-1]["id"] + client.post("/api/stations/select", json={"id": bench}, headers=auth) + + # A station that says nothing records with whatever tracking devices the session has. + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + reported = [item for item in client.get("/api/setup").json()["checks"] if item["group"] == "tracking"] + assert [item["status"] for item in reported] == ["pass"] * len(reported) and len(reported) >= 1 + + # Requiring what the session reports changes nothing; requiring a glove it does not have holds a take. + required = {"required_devices": ["headset", "controller_left", "controller_right"]} + listing = client.put(f"/api/stations/{bench}", json=required, headers=auth).json() + assert listing["stations"][0]["required_devices"] == required["required_devices"] + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + gloved = {"required_devices": ["headset", "glove_left"]} + client.put(f"/api/stations/{bench}", json=gloved, headers=auth) + missing = "Left glove: not reported by the capture session; this station requires it" + _poll_until_sync(lambda: client.get("/api/setup").json()["blocked_reason"] == missing) + held = client.get("/api/setup").json() + assert _steps(held)["devices"] == ("attention", missing) + glove = next(item for item in held["checks"] if item["id"] == "device:required:glove_left") + assert (glove["group"], glove["label"], glove["status"]) == ("tracking", "Left glove", "fail") + # The same sentence is why Record refuses, and the command itself is refused with it. + assert context.snapshot()["not_ready_reason"] == missing + assert context.snapshot()["ready_to_record"] is False + refused = _command(client, context, "start_episode") + assert (refused["outcome"], refused["reason"]) == ("rejected", missing) + assert context.snapshot()["episode_phase"] == "IDLE" + + # The headset calibration records no glove, so its take is not held for one: a station that + # requires gloves can still calibrate its camera before they are on. + camera_take = { + "tool": "camera", + "role": "ego", + "mode": "intrinsic", + "operator": "alex", + "board": BOARD, + } + take = client.post("/api/calibration/recording", json=camera_take, headers=auth) + assert take.status_code == 200, take.json() + assert client.post("/api/calibration/recording/cancel", json={}, headers=auth).status_code == 200 + # The controller-glove offset is fitted on the gloves: its take waits for them. + glove_take = client.post( + "/api/calibration/recording", json={"tool": "glove", "operator": "alex"}, headers=auth + ) + assert (glove_take.status_code, glove_take.json()) == (409, {"detail": missing}) + + # Clearing the requirement is all it takes: nothing is run. + client.put(f"/api/stations/{bench}", json={"required_devices": []}, headers=auth) + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + assert client.get("/api/setup").json()["blocked_reason"] is None + finally: + server.stop() + + +def test_a_required_glove_that_is_there_and_delivers_nothing_cannot_record(monkeypatch, unused_tcp_port, tmp_path): + """The real application against the real CaptureServer in its mock mode, with its glove plugin. The mock + reports a glove only as connected or unavailable, so the state a real glove reports while it has no + skeleton to send is put in place of the left glove's, in the protocol's own types, where the application + reads the session's status.""" + import dataclasses + + from capture_server import protocol as p + from egocap_web import app as app_module + from egocap_web.config import config_from_env + from egocap_web.setup_service import capture_facts + + 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") + monkeypatch.setenv("EGOCAP_STATION_CONFIG", str(station_file)) + monkeypatch.setenv("EGOCAP_CAPTURE_SERVER_URL", f"ws://127.0.0.1:{unused_tcp_port}") + monkeypatch.delenv("EGOCAP_OPERATOR_SETTINGS_FILE", raising=False) + monkeypatch.setenv("EGOCAP_CAPTURE_PLUGINS", "manus") + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: tmp_path) + 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} + monitor = client.app.state.monitor + _poll_until_sync( + lambda: monitor.snapshot().running and monitor.preview.camera("head_human_camera") is not None + ) + context.coordinator.set_task("Pour water.") + fields = { + "name": "Bench A", + "camera_roles": {"ego": "head_human_camera"}, + "required_devices": ["headset", "glove_left"], + } + bench = client.post("/api/stations", json=fields, headers=auth).json()["stations"][-1]["id"] + client.post("/api/stations/select", json={"id": bench}, headers=auth) + # Every required device connected: the station records. + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + + class _Native: + """The session as the application's monitor holds it, saying one thing else of the left glove.""" + + state: tuple[p.DeviceState, p.StatusReason, str] + + def __getattr__(self, name): + return getattr(monitor.native, name) + + @property + def latest_status(self): + real = monitor.native.latest_status + status, reason, error = self.state + devices = tuple( + dataclasses.replace(device, status=status, reason=reason, error=error) + if device.path == "/hand/left" + else device + for device in real.devices + ) + return dataclasses.replace(real, devices=devices) + + native = _Native() + said = SimpleNamespace(native=native, preview=monitor.preview, snapshot=monitor.snapshot) + service, config = client.app.state.setup_service, config_from_env() + monkeypatch.setattr(service, "_facts", lambda: capture_facts(said, config)) + + # Present, with no usable skeleton to send: the session calls the glove degraded, and Record is held. + silent = "glove present but has no current usable skeleton data" + native.state = (p.DeviceState.DEGRADED, p.StatusReason.NO_CURRENT_DATA, silent) + held = f"Left glove: {silent}; this station requires it" + _poll_until_sync(lambda: client.get("/api/setup").json()["blocked_reason"] == held) + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is False) + assert context.snapshot()["not_ready_reason"] == held + refused = _command(client, context, "start_episode") + assert (refused["outcome"], refused["reason"]) == ("rejected", held) + assert context.snapshot()["episode_phase"] == "IDLE" + + # Streaming with a calibration file it rejected, the glove delivers: the row warns, Record is free. + native.state = (p.DeviceState.DEGRADED, p.StatusReason.CALIBRATION_FAILED, "glove calibration failed") + _poll_until_sync(lambda: client.get("/api/setup").json()["blocked_reason"] is None) + rows = {item["label"]: item for item in client.get("/api/setup").json()["checks"]} + assert (rows["Left glove"]["status"], rows["Left glove"]["detail"]) == ( + "warn", + "glove calibration failed", + ) + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + finally: + server.stop() diff --git a/examples/egocap/tests/backend/test_setup_service.py b/examples/egocap/tests/backend/test_setup_service.py index 9de7013b46..4045c820cb 100644 --- a/examples/egocap/tests/backend/test_setup_service.py +++ b/examples/egocap/tests/backend/test_setup_service.py @@ -7,14 +7,23 @@ from __future__ import annotations import asyncio +import importlib.util +import json +import sys import threading import time +import types +from pathlib import Path from types import SimpleNamespace +import pytest +import yaml + from capture_server import protocol as p +from capture_server.acquisition.isaac_capture import IsaacCaptureAdapter from egocap_web.config import CaptureStatusConfig -from egocap_web.setup_checks import CameraFact, CaptureFacts, DeviceFact -from egocap_web.setup_service import CHECKS_PENDING, SetupService, capture_facts +from egocap_web.setup_checks import CameraFact, CaptureFacts, DeviceFact, checklist, first_failure +from egocap_web.setup_service import CHECKS_PENDING, SetupService, capture_facts, reported_tracking_devices from egocap_web.station_service import StationService, session_adapter from egocap_web.stations import StationStore @@ -237,6 +246,184 @@ async def test_a_device_that_is_not_connected_does_not_hold_a_take(tmp_path): assert _steps(setup)["devices"] == ("done", "Glove: degraded; takes are not held") +async def test_a_device_the_station_requires_holds_a_take_until_it_connects_and_says_why(tmp_path): + setup, stations, world = await _with_station_in_use(tmp_path) + headset = DeviceFact("Headset", True, headset=True, kind="headset") + world.facts = _healthy(devices=(headset, DeviceFact("Left hand", False, "unavailable", kind="glove_left"))) + await setup.refresh() + assert setup.block_reason() is None + # Requiring it changes what is judged, so the earlier result no longer speaks for the station. + await stations.update(stations.registry.selected_id, {"required_devices": ["glove_left", "glove_right"]}) + assert setup.block_reason() == CHECKS_PENDING + await setup.refresh() + held = "Left glove: unavailable; this station requires it" + assert setup.block_reason() == held + status = _status(setup) + assert status["blocked_reason"] == held and _steps(setup)["devices"] == ("attention", held) + assert [(item["id"], item["label"], item["status"], item["detail"]) for item in status["checks"][:3]] == [ + ("device:0", "Headset", "pass", None), + ("device:1", "Left glove", "fail", "unavailable; this station requires it"), + # The session reports no right glove at all, which is as missing as one that is switched off. + ( + "device:required:glove_right", + "Right glove", + "fail", + "not reported by the capture session; this station requires it", + ), + ] + right = DeviceFact("Right glove", True, kind="glove_right") + world.facts = _healthy(devices=(headset, DeviceFact("Left glove", True, kind="glove_left"), right)) + await setup.refresh() + assert setup.block_reason() is None and _steps(setup)["devices"] == ("done", "all checks pass") + # A device this station does not require still only warns, at the same station. + world.facts = _healthy(devices=(DeviceFact("Headset", False, "disconnected", headset=True, kind="headset"),)) + await stations.update(stations.registry.selected_id, {"required_devices": []}) + await setup.refresh() + assert setup.block_reason() is None + assert _steps(setup)["devices"] == ("done", "Headset: disconnected; takes are not held") + + +async def test_a_required_device_that_still_delivers_with_a_problem_does_not_hold_the_station(tmp_path): + setup, stations, world = await _with_station_in_use(tmp_path) + await stations.update(stations.registry.selected_id, {"required_devices": ["glove_left"]}) + headset = DeviceFact("Headset", True, headset=True, kind="headset") + + def glove(detail: str, reason: str) -> DeviceFact: + return DeviceFact("Left hand", False, detail, kind="glove_left", degraded=True, reason=reason) + + # The glove streams with a calibration file it rejected: the session calls it degraded, and it delivers. + world.facts = _healthy(devices=(headset, glove("glove calibration failed", "CALIBRATION_FAILED"))) + await setup.refresh() + assert setup.block_reason() is None + assert _steps(setup)["devices"] == ("done", "Left glove: glove calibration failed; takes are not held") + # Degraded with nothing to send, it holds: Record would save a take without the glove's data. + silent = "glove present but has no current usable skeleton data" + world.facts = _healthy(devices=(headset, glove(silent, "NO_CURRENT_DATA"))) + await setup.refresh() + assert setup.block_reason() == f"Left glove: {silent}; this station requires it" + assert _steps(setup)["devices"] == ("attention", f"Left glove: {silent}; this station requires it") + + +async def test_a_stations_file_with_a_requirement_this_build_cannot_read_still_holds_recording(tmp_path): + # Written by a newer build that knows a sixth device, with the headset required as well. Read strictly, + # the whole file was unreadable: no station, nothing in use, and takes recorded under no requirement. + bench = {"id": "st_a", "name": "Bench A", "camera_roles": {"ego": "cam_head"}} + stored = {"selected": "st_a", "stations": [{**bench, "required_devices": ["headset", "tracker_waist"]}]} + (tmp_path / "stations.json").write_text(json.dumps(stored)) + setup, stations, world = _service(tmp_path) + world.facts = _healthy(devices=(DeviceFact("Headset", False, "disconnected", headset=True, kind="headset"),)) + await setup.refresh() + listing = stations.listing(private=False) + assert [station["name"] for station in listing["stations"]] == ["Bench A"] and listing["selected"] == "st_a" + assert "warning" not in listing and stations.label() == "Bench A" + # The gate holds: for the headset that is off, and for the requirement nothing here can meet. + assert setup.block_reason() == "Headset: disconnected; this station requires it" + world.facts = _healthy(devices=(DeviceFact("Headset", True, headset=True, kind="headset"),)) + await setup.refresh() + unknown = "tracker_waist: not a tracking device this software knows; this station requires it" + assert setup.block_reason() == unknown + assert _steps(setup)["devices"] == ("attention", unknown) + # The operator clears it on the Station tab by saving the requirement without it. + await stations.update("st_a", {"required_devices": ["headset"]}) + await setup.refresh() + assert setup.block_reason() is None + + +#: Why recording is held while the stored stations cannot be read: the Station tab's warning, carried as every +#: reason is, without the closing full stop the page adds. +UNREADABLE = "Saved stations are unreadable. Adding a station replaces them" +_STORED_BENCH = { + "id": "st_a", + "name": "Bench A", + "camera_type": None, + "camera_roles": {"ego": "cam_head", "wrist_left": None, "wrist_right": None}, + "headset_address": None, + "required_devices": ["headset"], +} + + +def _stored_with(**other) -> str: + return json.dumps({"selected": "st_a", "stations": [{**_STORED_BENCH, **other}]}, indent=2) + + +@pytest.mark.parametrize( + "text", + [ + _stored_with(camera_type="zed_x"), + _stored_with(camera_roles={**_STORED_BENCH["camera_roles"], "chest": "cam_chest"}), + _stored_with(headset_address="headset.local"), + _stored_with(name="B" * 200), + '{"selected": "st_a", "stations": [{"id": "st_a", "name": "Bench A", "required_devices": ["headset"],}]}', + _stored_with(required_devices=["headset", *(f"device_{index}" for index in range(100_000))]), + ], + ids=[ + "a newer camera type", + "a newer camera role", + "an address as a host name", + "a long name", + "a comma", + "a requirement list without end", + ], +) +async def test_a_stations_file_this_build_cannot_read_holds_recording_until_it_is_replaced(tmp_path, text): + # The station requires its headset, and the headset is off. A file this build cannot read in any one + # field says nothing of that requirement here, so nothing may be recorded on its silence. + (tmp_path / "stations.json").write_text(text) + setup, stations, world = _service(tmp_path) + world.facts = _healthy(devices=(DeviceFact("Headset", False, "disconnected", headset=True, kind="headset"),)) + await setup.refresh() + listing = stations.listing(private=False) + assert (listing["stations"], listing["warning"], stations.label()) == ([], f"{UNREADABLE}.", "Deployment") + # Held with the sentence the Station tab shows, for a recording and for a calibration tool's take alike. + assert setup.block_reason() == UNREADABLE + tool_take = setup.block_reason(ignore=frozenset({"calibration"}), unused_devices=frozenset({"headset"})) + assert tool_take == UNREADABLE + assert _status(setup)["blocked_reason"] == UNREADABLE + assert _steps(setup)["station"] == ("attention", UNREADABLE) + # Replaced from the Station tab, the file is this build's again: one station, to be put in use. + added = await stations.add(BENCH) + await setup.refresh() + assert "warning" not in stations.listing(private=False) + assert setup.block_reason() == "select a station before recording" + await stations.select(added.station_id) + world.facts = _healthy() + await setup.refresh() + assert setup.block_reason() is None + + +async def test_no_stations_file_is_still_no_stations_and_holds_nothing(tmp_path): + setup, stations, world = _service(tmp_path) + world.facts = _healthy(devices=(DeviceFact("Headset", False, "disconnected", headset=True, kind="headset"),)) + await setup.refresh() + assert "warning" not in stations.listing(private=False) + assert setup.block_reason() is None + assert _steps(setup)["station"] == ("skipped", "no stations set up") + + +def test_a_take_that_does_not_use_a_device_is_not_held_by_a_stations_requirement_of_it(tmp_path): + async def held() -> tuple[SetupService, str | None]: + setup, stations, world = await _with_station_in_use(tmp_path) + await stations.update(stations.registry.selected_id, {"required_devices": ["headset", "glove_left"]}) + world.facts = _healthy(devices=(DeviceFact("Headset", True, headset=True, kind="headset"),)) + await setup.refresh() + return setup, setup.block_reason() + + setup, reason = asyncio.run(held()) + assert reason == "Left glove: not reported by the capture session; this station requires it" + # A camera calibration records no glove: the requirement of one does not hold it. + assert setup.block_reason(unused_devices=frozenset({"glove_left", "glove_right"})) is None + # A device the take does use still holds it, and so does every other item. + assert setup.block_reason(unused_devices=frozenset({"glove_right"})) == reason + + +async def test_with_no_station_in_use_nothing_is_required(tmp_path): + setup, stations, world = _service(tmp_path) + await stations.add({**BENCH, "required_devices": ["glove_left"]}) + await setup.refresh() + # The station exists and is not in use, so its requirement judges nothing. + assert [item["id"] for item in _status(setup)["checks"]][:2] == ["device:0", "camera:cam_head"] + + async def test_the_gate_answers_from_memory_and_the_files_are_read_in_a_worker_thread(tmp_path): setup, _, world = await _with_station_in_use(tmp_path) reads, disk_reads = world.fact_reads, len(world.free_reads_on) @@ -389,15 +576,22 @@ async def test_whether_a_headset_is_connected_comes_from_the_same_evaluation(tmp # --- reading the capture session --------------------------------------------------------------------------------- -def _device(kind: str, description: str, state: p.DeviceState, error: str = "") -> p.DeviceStatus: +def _device( + kind: str, + description: str, + state: p.DeviceState, + error: str = "", + path: str | None = None, + reason: p.StatusReason = p.StatusReason.NONE, +) -> p.DeviceStatus: return p.DeviceStatus( id=f"device-{description}", - path=f"/{kind}", + path=path or f"/{kind}", type=kind, description=description, provider_id="provider", status=state, - reason=p.StatusReason.NONE, + reason=reason, error=error, ) @@ -439,15 +633,28 @@ def _monitor( ) +_OFF = p.DeviceState.DISCONNECTED + + def test_capture_facts_read_devices_cameras_and_freshness_from_the_session(): status = p.StatusSnapshot( updated_at_ns=1, devices=( _device("headset", "Headset", p.DeviceState.CONNECTED), - _device("controller", "Left controller", p.DeviceState.DISCONNECTED, "battery empty"), + _device("controller", "Left controller", _OFF, "battery empty", "/controller/left"), # A glove is whatever the capture session calls it; the checklist never depends on that label. - _device("hand_tracker", "", p.DeviceState.DEGRADED), - _device("hand_tracker", "Right glove", p.DeviceState.DISABLED), + _device( + "hand_tracker", + "", + p.DeviceState.DEGRADED, + path="/hand/left", + reason=p.StatusReason.CALIBRATION_FAILED, + ), + _device("hand_tracker", "Right glove", p.DeviceState.DISABLED, path="/hand/right"), + # A device no station can name is still listed, and judged as before. + _device("gamepad", "Gamepad", p.DeviceState.CONNECTED), + # Switched off, and nothing a station can require: no part of any station. + _device("gamepad", "Spare gamepad", p.DeviceState.DISABLED), ), cameras=( p.CameraStatus("cam_head", 1, p.DeviceState.CONNECTED, p.StatusReason.NONE, ""), @@ -458,10 +665,20 @@ def test_capture_facts_read_devices_cameras_and_freshness_from_the_session(): facts = capture_facts(_monitor(status=status, fresh=("tracking", "cam_head")), CaptureStatusConfig()) assert (facts.running, facts.error, facts.mock, facts.tracking_fresh) == (True, None, False, True) assert facts.devices == ( - DeviceFact("Headset", True, "connected", headset=True), - DeviceFact("Left controller", False, "battery empty"), - DeviceFact("device-", False, "degraded"), + DeviceFact("Headset", True, "connected", headset=True, kind="headset", reason="NONE"), + DeviceFact("Left controller", False, "battery empty", kind="controller_left", reason="NONE"), + # Degraded is the session's word for a device that is there with a problem of its own; the reason it + # gives, carried by its own name, says whether the device still delivers. + DeviceFact("device-", False, "degraded", kind="glove_left", degraded=True, reason="CALIBRATION_FAILED"), + DeviceFact("Gamepad", True, "connected", reason="NONE"), ) + assert [device.delivers for device in facts.devices] == [True, False, True, True] + # A device switched off in the capture configuration is not listed; a station that requires it is told so. + assert facts.disabled == ("glove_right",) + # The Station tab is told which devices a station can require this session reports: not the one switched off. + monitor = _monitor(status=status, fresh=("tracking", "cam_head")) + assert reported_tracking_devices(monitor) == frozenset({"headset", "controller_left", "glove_left"}) + assert reported_tracking_devices(_monitor(started=False)) is None assert facts.headset_connected is True assert facts.cameras == { "cam_head": CameraFact(True, True, "connected"), @@ -483,6 +700,11 @@ def test_capture_facts_report_livekit_cameras_and_why_they_cannot_be_recorded(): local = CaptureStatusConfig(capture_server_url="ws://127.0.0.1:8082") facts = capture_facts(_monitor(streams=(_livekit("lk_head"),)), local) assert (facts.livekit_cameras, facts.livekit_blocked) == (frozenset({"lk_head"}), None) + # The backend receives none of their video between takes; what a page saw of each is handed in. + assert facts.livekit_seen == {} + seen = {"lk_head": "receiving"} + watched = capture_facts(_monitor(streams=(_livekit("lk_head"),)), local, seen) + assert watched.livekit_seen == seen and watched.livekit_seen is not seen remote = CaptureStatusConfig(capture_server_url="ws://192.168.1.50:8082") assert capture_facts(_monitor(streams=(_livekit("lk_head"),)), remote).livekit_blocked is not None @@ -506,3 +728,236 @@ async def test_an_evaluation_outlives_a_caller_that_went_away(tmp_path): answered = await waiting assert answered.items and len(world.free_reads_on) == reads assert setup.block_reason() == "Free disk space: 1.0 GB free; 10 GB needed" + + +# --- a required device must be delivering its data ----------------------------------------------------------- + +_STATE, _WHY = p.DeviceState, p.StatusReason +#: A hand-tracking glove in every state and reason the capture session accepts from its provider or states +#: itself, with the session's own words, and whether a station that requires the glove records in it. +GLOVE_STATES = [ + (_STATE.CONNECTED, _WHY.NONE, "", True), + # There and streaming, with a calibration file it rejected: the data is still delivered. + (_STATE.DEGRADED, _WHY.CALIBRATION_FAILED, "glove calibration failed", True), + # Degraded and delivering nothing: present, with no skeleton to send, or with an error of its own. + (_STATE.DEGRADED, _WHY.NO_CURRENT_DATA, "glove present but has no current usable skeleton data", False), + (_STATE.DEGRADED, _WHY.DEVICE_ERROR, "device error", False), + (_STATE.UNKNOWN, _WHY.NO_HARDWARE_SIGNAL, "", False), + (_STATE.UNKNOWN, _WHY.NO_CURRENT_DATA, "", False), + (_STATE.UNKNOWN, _WHY.DEVICE_ERROR, "", False), + (_STATE.UNKNOWN, _WHY.NO_REPORT, "", False), + (_STATE.UNKNOWN, _WHY.STALE_REPORT, "plugin status report is stale", False), + (_STATE.UNKNOWN, _WHY.MALFORMED_REPORT, "plugin status report contains invalid state/reason pair", False), + (_STATE.UNKNOWN, _WHY.UNSUPPORTED_SCHEMA_VERSION, "unsupported plugin status schema version 2", False), + (_STATE.DISCONNECTED, _WHY.NO_HARDWARE_SIGNAL, "", False), + (_STATE.FAILED, _WHY.DEVICE_ERROR, "driver failed", False), + (_STATE.INITIALIZING, _WHY.PROVIDER_INITIALIZING, "", False), + (_STATE.UNAVAILABLE, _WHY.PROVIDER_FAILED, "process exited with code 1", False), + (_STATE.UNAVAILABLE, _WHY.PROVIDER_STOPPED, "", False), + # A degraded state under a reason this build was never told delivers: not taken on trust. + (_STATE.DEGRADED, _WHY.NONE, "", False), + (_STATE.DEGRADED, _WHY.RUNTIME_UPDATE_FAILED, "", False), +] +#: The same for a controller, whose degraded state the session gives one reason whichever pose is lost. +CONTROLLER_STATES = [ + (_STATE.CONNECTED, _WHY.NONE, "", True), + (_STATE.DEGRADED, _WHY.NO_CURRENT_DATA, "aim pose tracking unavailable for at least 1 second", False), + (_STATE.DEGRADED, _WHY.NO_CURRENT_DATA, "grip pose tracking unavailable for at least 1 second", False), + (_STATE.DEGRADED, _WHY.NO_CURRENT_DATA, "aim and grip pose tracking unavailable for at least 1 second", False), + (_STATE.DISCONNECTED, _WHY.NO_CURRENT_DATA, "controller is inactive for at least 1 second", False), + (_STATE.UNKNOWN, _WHY.NO_CURRENT_DATA, "waiting for the first controller tracking sample", False), + (_STATE.UNKNOWN, _WHY.OPENXR_POLL_ERROR, "poll failed", False), + (_STATE.INITIALIZING, _WHY.PROVIDER_INITIALIZING, "", False), +] + + +def _judged(status: p.StatusSnapshot, required: tuple[str, ...], tmp_path) -> list: + """The checklist of a station that requires ``required``, over the facts read from one status.""" + facts = capture_facts(_monitor(status=status, fresh=("tracking",)), CaptureStatusConfig()) + return checklist( + facts, + {"ego": None}, + calibration_dir=tmp_path / "calibration", + output_root=tmp_path, + free_bytes=lambda path: 50 * 1024**3, + required_devices=required, + ) + + +@pytest.mark.parametrize( + ("kind", "name", "path", "description", "states"), + [ + ("glove_left", "Left glove", "/hand/left", "Left hand", GLOVE_STATES), + ("controller_left", "Left controller", "/controller/left", "Left controller", CONTROLLER_STATES), + ], + ids=["glove", "controller"], +) +def test_a_required_device_meets_its_requirement_only_in_a_state_in_which_it_delivers_its_data( + tmp_path, kind, name, path, description, states +): + headset = _device("headset", "Headset", _STATE.CONNECTED) + for state, reason, error, delivers in states: + device = _device("hand_tracker", description, state, error, path, reason) + status = p.StatusSnapshot(updated_at_ns=1, devices=(headset, device)) + said = error or state.name.lower() + # Tracking as a whole is fresh throughout: the headset streams, which is all the freshness item asks. + held = first_failure(_judged(status, (kind,), tmp_path)) + expected = None if delivers else f"{name}: {said}; this station requires it" + assert held == expected, (state.name, reason.name) + # A station that does not require the device is never held by it, whatever it reports. + assert first_failure(_judged(status, (), tmp_path)) is None, (state.name, reason.name) + + +#: Where the capture session's own status monitor and its glove plugin's manifest lie beside this example. +_REPOSITORY = Path(__file__).resolve().parents[4] +_SESSION_SOURCES = _REPOSITORY / "src" / "python" / "isaaccapture" / "teleop_session_manager" +_GLOVE_MANIFEST = _REPOSITORY / "src" / "plugins" / "manus" / "plugin.yaml" +_T0 = 10_000_000_000 + + +def _session_monitor(monkeypatch): + """The capture session's own status monitor with its glove plugin and controllers, and the stand-in the + plugin's reports are read from. Its modules are loaded from their files, under a name of this test's, + and are gone from the interpreter's table when the test ends.""" + package = types.ModuleType("egocap_test_session") + package.__path__ = [str(_SESSION_SOURCES)] + monkeypatch.setitem(sys.modules, package.__name__, package) + for module_name in ("status", "status_monitor"): + spec = importlib.util.spec_from_file_location( + f"{package.__name__}.{module_name}", _SESSION_SOURCES / f"{module_name}.py" + ) + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + manifest = yaml.safe_load(_GLOVE_MANIFEST.read_text(encoding="utf-8")) + reports = SimpleNamespace(report=None) + reports.get_device_status_snapshot = lambda session: reports.report + process = SimpleNamespace( + get_process_snapshot=lambda: SimpleNamespace( + state=SimpleNamespace(name="RUNNING"), + pid=42, + error="", + exit_code=None, + term_signal=None, + reason=SimpleNamespace(name="NONE"), + ) + ) + monitor = module.StatusMonitor() + provider = module.PluginProviderSpec( + plugin_root_id="manus", + name=manifest["name"], + devices=tuple(SimpleNamespace(**device) for device in manifest["devices"]), + tracker=reports, + ) + monitor.rebuild( + (provider,), include_openxr=True, external_openxr=False, include_openxr_controllers=True, now_ns=_T0 + ) + monitor.bind_plugin_context("plugin/manus", process) + monitor.mark_available(now_ns=_T0) + return monitor, reports + + +def _glove_report(now_ns: int, left: tuple[str, str, str]) -> SimpleNamespace: + """One report of the glove plugin: the left hand as given, the right hand connected.""" + hands = (("left", left), ("right", ("CONNECTED", "NONE", ""))) + return SimpleNamespace( + schema_version=1, + report_time_ns=now_ns, + devices=[ + SimpleNamespace( + path=f"/hand/{side}", + state=SimpleNamespace(name=state), + reason=SimpleNamespace(name=reason), + error=error, + ) + for side, (state, reason, error) in hands + ], + ) + + +def _headset_tracked() -> SimpleNamespace: + """The headset's provider as the session sees it while the headset is tracked.""" + snapshot = SimpleNamespace( + state=SimpleNamespace(name="AVAILABLE"), + headset_state=SimpleNamespace(name="CONNECTED"), + reason=SimpleNamespace(name="NONE"), + error="", + result_code=None, + ) + return SimpleNamespace(get_provider_snapshot=lambda: snapshot) + + +def _controller_pose(aim: bool = True, grip: bool = True) -> SimpleNamespace: + return SimpleNamespace(aim_pose=SimpleNamespace(is_valid=aim), grip_pose=SimpleNamespace(is_valid=grip)) + + +def _held_by(monitor, device_id: str, kind: str, tmp_path) -> tuple[str, str, str | None]: + """A device's state and reason as the session's monitor states them, mapped as the capture server maps + them, and what holds a station that requires the device.""" + status = IsaacCaptureAdapter._map_status(monitor.get_status(), 1) + device = next(device for device in status.devices if device.id == device_id) + return device.status.name, device.reason.name, first_failure(_judged(status, (kind,), tmp_path)) + + +@pytest.mark.skipif( + not (_SESSION_SOURCES / "status_monitor.py").is_file() or not _GLOVE_MANIFEST.is_file(), + reason="the capture session's sources are not beside this example", +) +def test_the_capture_sessions_own_monitor_holds_a_required_device_in_every_state_that_delivers_nothing( + tmp_path, monkeypatch +): + tracked = {"left": _controller_pose(), "right": _controller_pose()} + held = "this station requires it" + # The glove, in each degraded state its plugin can report. + for left, expected in [ + (("CONNECTED", "NONE", ""), ("CONNECTED", "NONE", None)), + ( + ("DEGRADED", "CALIBRATION_FAILED", "glove calibration failed"), + ("DEGRADED", "CALIBRATION_FAILED", None), + ), + ( + ("DEGRADED", "NO_CURRENT_DATA", "glove present but has no current usable skeleton data"), + ( + "DEGRADED", + "NO_CURRENT_DATA", + f"Left glove: glove present but has no current usable skeleton data; {held}", + ), + ), + ( + ("DEGRADED", "DEVICE_ERROR", "device error"), + ("DEGRADED", "DEVICE_ERROR", f"Left glove: device error; {held}"), + ), + ]: + monitor, reports = _session_monitor(monkeypatch) + reports.report = _glove_report(_T0 + 1, left) + monitor.refresh(None, _headset_tracked(), openxr_controllers=tracked, now_ns=_T0 + 1) + assert _held_by(monitor, "manus/hand/left", "glove_left", tmp_path) == expected + + # The left controller, some time after one tracked sample. + def controller(left, seconds: float) -> tuple[str, str, str | None]: + monitor, reports = _session_monitor(monkeypatch) + for moment in (_T0 + 1, _T0 + 2, _T0 + int(seconds * 1e9)): + reports.report = _glove_report(moment, ("CONNECTED", "NONE", "")) + poses = tracked if moment == _T0 + 1 else {"left": left, "right": _controller_pose()} + monitor.refresh(None, _headset_tracked(), openxr_controllers=poses, now_ns=moment) + return _held_by(monitor, "openxr/controller/left", "controller_left", tmp_path) + + lost = "pose tracking unavailable for at least 1 second" + assert controller(_controller_pose(), 1.5) == ("CONNECTED", "NONE", None) + # Set down for under a second, the session still calls it connected: that pause is the session's own. + assert controller(_controller_pose(aim=False, grip=False), 0.5) == ("CONNECTED", "NONE", None) + assert controller(_controller_pose(aim=False), 1.5) == ( + "DEGRADED", + "NO_CURRENT_DATA", + f"Left controller: aim {lost}; {held}", + ) + assert controller(_controller_pose(aim=False, grip=False), 1.5) == ( + "DEGRADED", + "NO_CURRENT_DATA", + f"Left controller: aim and grip {lost}; {held}", + ) + assert controller(None, 1.5) == ( + "DISCONNECTED", + "NO_CURRENT_DATA", + f"Left controller: controller is inactive for at least 1 second; {held}", + ) diff --git a/examples/egocap/tests/backend/test_station_routes.py b/examples/egocap/tests/backend/test_station_routes.py index d637531910..5459f2e03a 100644 --- a/examples/egocap/tests/backend/test_station_routes.py +++ b/examples/egocap/tests/backend/test_station_routes.py @@ -117,6 +117,23 @@ def test_stations_are_added_edited_selected_and_deleted(tmp_path): assert client.post("/api/stations/select", json={"id": None}, headers=AUTH).status_code == 200 +def test_the_devices_a_station_requires_are_saved_listed_openly_and_a_name_that_is_no_device_is_refused(tmp_path): + client = _client(tmp_path) + bench = _add(client, {**BENCH, "required_devices": ["glove_left", "headset"]}) + listing = client.get("/api/stations").json() + assert listing["stations"][0]["required_devices"] == ["headset", "glove_left"] + assert {"id": "glove_left", "name": "Left glove"} in listing["tracking_devices"] + cleared = client.put(f"/api/stations/{bench}", json={"required_devices": []}, headers=AUTH).json() + assert cleared["stations"][0]["required_devices"] == [] + refused = client.put(f"/api/stations/{bench}", json={"required_devices": ["elbow"]}, headers=AUTH) + assert (refused.status_code, refused.json()["detail"]) == ( + 400, + "unknown tracking device(s): 'elbow'; a station can require " + "headset, controller_left, controller_right, glove_left, glove_right", + ) + assert StationStore(tmp_path / "stations.json").load().find(bench).required_devices == () + + def test_the_headset_address_is_shown_only_to_a_caller_with_the_token(tmp_path): client = _client(tmp_path) _add(client, {**BENCH, "headset_address": "192.168.4.20"}) @@ -173,6 +190,39 @@ def test_a_refused_change_says_why_and_an_unknown_station_is_not_found(tmp_path) assert (response.status_code, response.json()["detail"]) == (404, "no such station") +@pytest.mark.parametrize( + ("method", "path", "body", "refusal"), + [ + ( + "put", + "/api/stations/{id}", + b'{"required_devices": ["\\ud800"]}', + "unknown tracking device(s): '\\ud800'; ", + ), + ( + "post", + "/api/stations", + b'{"name": "N", "required_devices": ["\\ud800"]}', + "unknown tracking device(s): '\\ud800'; ", + ), + ("put", "/api/stations/{id}", b'{"\\ud800": 1}', "unknown station field(s): '\\ud800'"), + ], + ids=["a requirement on a change", "a requirement on a new station", "a field"], +) +def test_a_name_that_no_reply_can_carry_is_refused_in_a_sentence_that_shows_it_escaped( + tmp_path, method, path, body, refusal +): + client = _client(tmp_path) + bench = _add(client) + before = client.get("/api/stations").json() + # Half of a surrogate pair: sent as JSON it is text, and no reply can be encoded with it in. + sent = {**AUTH, "Content-Type": "application/json"} + response = getattr(client, method)(path.format(id=bench), content=body, headers=sent) + assert response.status_code == 400 + assert response.json()["detail"].startswith(refusal) + assert client.get("/api/stations").json() == before + + def test_the_station_in_use_cannot_change_during_a_take(tmp_path): live = _Live() client = _client(tmp_path, live) diff --git a/examples/egocap/tests/backend/test_station_service.py b/examples/egocap/tests/backend/test_station_service.py index a3e6332f67..437055f430 100644 --- a/examples/egocap/tests/backend/test_station_service.py +++ b/examples/egocap/tests/backend/test_station_service.py @@ -6,6 +6,8 @@ from __future__ import annotations +import json + import pytest from egocap_web.station_service import STATION_CHANGING, TAKE_IN_PROGRESS, StationService, session_adapter @@ -24,6 +26,8 @@ def __init__(self): self.rotation_refusal: str | None = None self.rename_failure: OSError | None = None self.events: list[tuple[str, str]] = [] + #: The tracking devices the capture session reports; None while it has said nothing yet. + self.reported: frozenset[str] | None = None def adapter(self): return session_adapter( @@ -32,6 +36,7 @@ def adapter(self): show_label=lambda label: self.events.append(("show", label)), rotate_batch=self._rotate, renamed=self._renamed, + reported_devices=lambda: self.reported, ) def _renamed(self, previous: str, name: str) -> None: @@ -65,6 +70,13 @@ async def test_an_empty_registry_keeps_the_deployment_label_and_blocks_nothing(t "selected": None, "roles": ["ego", "wrist_left", "wrist_right"], "camera_types": ["sensing_gmsl", "oak_d"], + "tracking_devices": [ + {"id": "headset", "name": "Headset"}, + {"id": "controller_left", "name": "Left controller"}, + {"id": "controller_right", "name": "Right controller"}, + {"id": "glove_left", "name": "Left glove"}, + {"id": "glove_right", "name": "Right glove"}, + ], "label": "Deployment", "locked_reason": None, } @@ -280,10 +292,15 @@ async def test_the_registry_survives_a_restart(tmp_path): async def test_an_unreadable_registry_starts_empty_with_a_warning_until_it_is_replaced(tmp_path): (tmp_path / "stations.json").write_text("not json") service, _ = _service(tmp_path) - assert service.registry.stations == () and service.block_reason() is None - assert "unreadable" in service.listing(private=False)["warning"] + unreadable = "Saved stations are unreadable. Adding a station replaces them." + assert service.registry.stations == () + assert service.listing(private=False)["warning"] == unreadable + # Whatever the file held of stations and what they require is not known here: nothing is recorded on it. + # The reason is the warning's words, without the full stop each place that prints a reason adds. + assert service.block_reason() == "Saved stations are unreadable. Adding a station replaces them" await service.add(BENCH) assert "warning" not in service.listing(private=False) + assert service.block_reason() == "select a station before recording" assert (tmp_path / "stations.json.invalid").read_text() == "not json" @@ -298,10 +315,11 @@ def denied(self): monkeypatch.setattr(StationStore, "load", denied) service, _ = _service(tmp_path) - assert service.registry.stations == () and service.block_reason() is None - assert service.listing(private=False)["warning"] == ( - "Saved stations cannot be read. Check the registry file's permissions." - ) + denied_sentence = "Saved stations cannot be read. Check the registry file's permissions." + assert service.registry.stations == () + assert service.listing(private=False)["warning"] == denied_sentence + # Held with the same words: the file may hold stations that require devices. + assert service.block_reason() == "Saved stations cannot be read. Check the registry file's permissions" assert path.exists() and not (tmp_path / "stations.json.invalid").exists() @@ -318,3 +336,71 @@ async def test_an_address_decided_for_another_station_or_another_saved_address_i assert StationStore(tmp_path / "stations.json").load().selected.headset_address == "10.0.0.9" await service.remember_headset_address(cart_id, "10.0.0.9", "10.0.0.42") assert service.registry.selected.headset_address == "10.0.0.42" + + +async def test_the_listing_says_what_each_station_requires_and_what_a_station_can_require(tmp_path): + service, session, bench_id, cart_id = await _with_two_stations(tmp_path) + await service.update(cart_id, {"required_devices": ["glove_right", "headset"]}) + listing = service.listing(private=False) + assert [station["required_devices"] for station in listing["stations"]] == [[], ["headset", "glove_right"]] + assert [device["id"] for device in listing["tracking_devices"]] == [ + "headset", + "controller_left", + "controller_right", + "glove_left", + "glove_right", + ] + assert StationStore(tmp_path / "stations.json").load().find(cart_id).required_devices == ( + "headset", + "glove_right", + ) + # While the capture session has said nothing of its devices, nothing is said of what it lacks. + assert [station["unreported_devices"] for station in listing["stations"]] == [[], []] + # A device a station requires that the capture session here does not report can never be connected here: + # the listing says so, so the Station tab can, before anybody presses Record. + session.reported = frozenset({"headset", "controller_left", "controller_right"}) + assert [station["unreported_devices"] for station in service.listing(private=False)["stations"]] == [ + [], + ["glove_right"], + ] + session.reported = frozenset({"headset", "glove_right"}) + assert service.listing(private=False)["stations"][1]["unreported_devices"] == [] + # Nothing recorded changes with a requirement: no rotation and no new label, even for the station in use. + await service.select(cart_id) + session.events.clear() + await service.update(cart_id, {"required_devices": []}) + assert session.events == [] and service.registry.selected.required_devices == () + + +async def test_what_the_station_in_use_requires_cannot_change_during_a_take(tmp_path): + service, session, bench_id, cart_id = await _with_two_stations(tmp_path) + await service.select(bench_id) + session.blocked = TAKE_IN_PROGRESS + with pytest.raises(StationError) as refused: + await service.update(bench_id, {"required_devices": ["headset"]}) + assert refused.value.public_message == TAKE_IN_PROGRESS + assert service.registry.selected.required_devices == () + # A station that is not in use can be changed at any time. + await service.update(cart_id, {"required_devices": ["headset"]}) + assert service.registry.find(cart_id).required_devices == ("headset",) + + +async def test_a_requirement_read_from_the_file_that_names_no_known_device_is_listed_as_one_nothing_reports( + tmp_path, +): + bench = {"id": "st_a", "name": "Bench A", "required_devices": ["headset", "tracker_waist"]} + (tmp_path / "stations.json").write_text(json.dumps({"selected": "st_a", "stations": [bench]})) + service, session = _service(tmp_path) + session.reported = frozenset({"headset"}) + listed = service.listing(private=False)["stations"][0] + assert listed["required_devices"] == ["headset", "tracker_waist"] + assert listed["unreported_devices"] == ["tracker_waist"] + # An adapter built without the session's devices says nothing of them. + quiet = session_adapter( + offered_cameras=lambda: None, + change_blocked=lambda: None, + show_label=lambda label: None, + rotate_batch=session._rotate, + renamed=lambda previous, name: None, + ) + assert quiet.reported_devices() is None diff --git a/examples/egocap/tests/backend/test_stations.py b/examples/egocap/tests/backend/test_stations.py index f5c345ca97..2575695656 100644 --- a/examples/egocap/tests/backend/test_stations.py +++ b/examples/egocap/tests/backend/test_stations.py @@ -13,6 +13,7 @@ from egocap_web.stations import ( MAX_STATION_NAME_CHARS, MAX_STATIONS, + TRACKING_DEVICES, Station, StationError, StationNotFoundError, @@ -92,7 +93,7 @@ def test_a_camera_in_two_roles_is_refused_naming_the_camera_and_both_roles(): ({"name": "New", "camera_roles": ["cam"]}, "camera_roles must be an object"), ({"name": "New", "headset_address": "headset.local"}, "'headset.local' is not an IP address"), ({"name": "New", "headset_address": 7}, "headset_address must be an IP address or null"), - ({"name": "New", "colour": "red", "size": 1}, "unknown station field(s): colour, size"), + ({"name": "New", "colour": "red", "size": 1}, "unknown station field(s): 'colour', 'size'"), ], ) def test_an_invalid_new_station_is_refused_with_a_specific_reason(fields, reason): @@ -142,6 +143,185 @@ def test_an_update_changes_only_the_fields_it_names(): assert registry.find("st_1") == _two_stations().find("st_1") +def test_a_station_names_the_tracking_devices_it_requires_and_one_that_names_none_stores_what_it_always_did( + tmp_path, +): + store = StationStore(tmp_path / "stations.json") + # Named in any order, with a repeat: kept once each, in the order the operator is shown them. + asked = {**CART, "required_devices": ["glove_right", "headset", "glove_right", "glove_left"]} + registry = StationRegistry().added(BENCH, _ids()).added(asked, lambda: "st_cart") + assert registry.find("st_0").required_devices == () + assert registry.find("st_cart").required_devices == ("headset", "glove_left", "glove_right") + store.save(registry) + bench, cart = json.loads(store.path.read_text())["stations"] + assert "required_devices" not in bench + assert cart["required_devices"] == ["headset", "glove_left", "glove_right"] + assert store.load() == registry + # A file written before stations could require anything reads as requiring nothing. + assert parse_registry({"stations": [{"id": "st_old", "name": "Old"}]}).find("st_old").required_devices == () + # An edit replaces the whole list, leaves every other field alone, and an empty or null list clears it. + edited = registry.updated("st_cart", {"required_devices": ["controller_left"]}) + assert edited.find("st_cart").required_devices == ("controller_left",) + assert edited.find("st_cart").camera_roles == registry.find("st_cart").camera_roles + assert registry.updated("st_cart", {"name": "Cart C"}).find("st_cart").required_devices == ( + "headset", + "glove_left", + "glove_right", + ) + for nothing in ([], None): + assert registry.updated("st_cart", {"required_devices": nothing}).find("st_cart").required_devices == () + + +@pytest.mark.parametrize( + ("named", "reason"), + [ + ("headset", "required_devices must be a list of tracking device names"), + (["headset", 7], "required_devices must be a list of tracking device names"), + ( + ["headset", "pedal", "elbow"], + "unknown tracking device(s): 'elbow', 'pedal'; a station can require " + "headset, controller_left, controller_right, glove_left, glove_right", + ), + ], +) +def test_a_requirement_sent_that_names_no_known_tracking_device_is_refused_and_changes_nothing(named, reason): + registry = _two_stations() + assert _refusal(lambda: registry.added({"name": "New", "required_devices": named})) == reason + assert _refusal(lambda: registry.updated("st_0", {"required_devices": named})) == reason + + +def test_a_refused_requirement_echoes_a_few_short_names_and_never_fails_on_one_that_cannot_be_encoded(): + registry = _two_stations() + # A name no reply could be encoded with, and far more text than a sentence should carry back. + unencodable = _refusal(lambda: registry.updated("st_0", {"required_devices": ["\ud800"]})) + assert unencodable.startswith("unknown tracking device(s): '\\ud800'; a station can require headset") + unencodable.encode("utf-8") + many = [f"device_{index}_" + "x" * 5000 for index in range(40)] + echoed = _refusal(lambda: registry.updated("st_0", {"required_devices": many})) + assert len(echoed) < 400 and echoed.count("device_") == 5 and "and 35 more" in echoed + # The same for a field no station has. + field = _refusal(lambda: registry.updated("st_0", {"\ud800": 1, **{f"f{index}": 1 for index in range(30)}})) + assert field.startswith("unknown station field(s): ") and len(field) < 400 + field.encode("utf-8") + + +@pytest.mark.parametrize( + ("stored", "kept"), + [ + # A name a newer build wrote: the devices this build knows first, then what it does not know, as written. + (["tracker_waist", "headset"], ("headset", "tracker_waist")), + # Edits by hand. A name is the device's id exactly; anything else is a requirement nothing can meet. + (["Headset"], ("Headset",)), + (["headset "], ("headset",)), + ("headset", ("headset",)), + ([["headset"]], ("['headset']",)), + ({"headset": True}, ("{'headset': True}",)), + (1, ("1",)), + (False, ("False",)), + ([""], ("''",)), + (["glove_right", "headset", "headset"], ("headset", "glove_right")), + (["x" * 500], ("x" * 40,)), + (["\ud800"], ("'\\ud800'",)), + (None, ()), + ([], ()), + ], +) +def test_a_requirement_read_from_the_file_is_never_dropped_whatever_it_holds(stored, kept, tmp_path): + bench = {"id": "st_a", "name": "Bench A", "required_devices": stored} + registry = parse_registry({"selected": "st_a", "stations": [bench, {"id": "st_b", "name": "Cart B"}]}) + # Every station is kept and the one in use stays in use: a file this build cannot fully read must not + # turn into "no stations", which requires nothing. + assert [station.name for station in registry.stations] == ["Bench A", "Cart B"] + assert registry.selected_id == "st_a" + assert registry.find("st_a").required_devices == kept + # What is written back keeps a name this build does not know, for the build that does. + path = tmp_path / "stations.json" + StationStore(path).save(registry) + again = StationStore(path).load() + assert again.find("st_a").required_devices == kept + # Changing another field keeps the requirement; the wire still refuses to be sent one it does not know. + assert registry.updated("st_a", {"name": "Bench Z"}).find("st_a").required_devices == kept + if any(name not in TRACKING_DEVICES for name in kept): + assert _refusal(lambda: registry.updated("st_a", {"required_devices": list(kept)})).startswith( + "unknown tracking device(s): " + ) + + +@pytest.mark.parametrize( + "planted", + [ + # A name of a newer build, longer than this build shows; a known name a hand left spaces around; a + # newer build's richer form; a bare string; and the list this build writes itself. + ["headset", "tracker_" + "w" * 52], + [" headset "], + [{"device": "headset", "min_battery": 20}, {"device": "glove_left"}], + "headset", + ["headset", "\ud800"], + [], + ["headset", "glove_left"], + ], + ids=["a long name", "spaces", "objects", "a bare string", "half a surrogate pair", "empty", "this build's"], +) +def test_a_stored_requirement_is_written_back_as_it_was_read_until_the_requirement_itself_is_edited( + tmp_path, planted +): + path = tmp_path / "stations.json" + bench = {"id": "st_a", "name": "Bench A", "required_devices": planted} + path.write_text(json.dumps({"selected": "st_a", "stations": [bench, {"id": "st_b", "name": "Cart B"}]})) + store = StationStore(path) + + def stored() -> object: + return json.loads(path.read_text())["stations"][0].get("required_devices", "") + + # Every save that is not an edit of the requirement: the other station, this station's other fields, + # the selection, a station added and removed. + for change in ( + lambda registry: registry.updated("st_b", {"name": "Cart B2"}), + lambda registry: registry.updated("st_a", {"name": "Bench A1", "camera_roles": {"ego": "cam_head"}}), + lambda registry: registry.selecting(None), + lambda registry: registry.selecting("st_a"), + lambda registry: registry.added({"name": "Third"}, lambda: "st_c"), + lambda registry: registry.removed("st_c"), + ): + _before, after = store.change(change) + assert stored() == planted + # What this build makes of it is the same before and after: the requirement is neither lost nor grown. + assert after.find("st_a").required_devices == store.load().find("st_a").required_devices + # The requirement edited from the Station tab is what this build writes from then on. + store.change(lambda registry: registry.updated("st_a", {"required_devices": ["glove_left", "headset"]})) + assert stored() == ["headset", "glove_left"] + store.change(lambda registry: registry.updated("st_a", {"required_devices": []})) + assert stored() == "" + + +@pytest.mark.parametrize( + "stored", + [ + [f"device_{index}" for index in range(100_000)], + ["headset"] * 100_000, + ["headset"] * 33, + "x" * 10_000_000, + ["y" * 10_000_000], + [{"device": "headset", "notes": "n" * 5000}], + ], + ids=["100000 names", "100000 copies", "33 entries", "a 10 MB string", "a 10 MB name", "a 5 KB object"], +) +def test_a_stored_requirement_larger_than_any_station_could_have_makes_the_file_unreadable(stored): + bench = {"id": "st_a", "name": "Bench A", "required_devices": stored} + with pytest.raises(StationError) as refused: + parse_registry({"selected": "st_a", "stations": [bench]}) + assert refused.value.public_message == "required_devices holds more than a station can require" + + +def test_the_largest_stored_requirement_is_kept_whole_and_stays_small_in_memory(): + names = [f"tracker_{index:02d}_" + "w" * 80 for index in range(32)] + registry = parse_registry({"stations": [{"id": "st_a", "name": "Bench A", "required_devices": names}]}) + kept = registry.find("st_a").required_devices + # Every one is a requirement nothing here can meet; each is shown cut short. + assert len(kept) == 32 and {len(name) for name in kept} == {40} + assert registry.stored()["stations"][0]["required_devices"] == names + + def test_an_update_is_refused_for_a_taken_name_or_bad_roles(): registry = _two_stations() assert _refusal(lambda: registry.updated("st_0", {"name": "CART B"})) == ( diff --git a/examples/egocap/tests/recording/unit/test_align_kept_episode.py b/examples/egocap/tests/recording/unit/test_align_kept_episode.py index fcaef82f8d..b9c750afa4 100644 --- a/examples/egocap/tests/recording/unit/test_align_kept_episode.py +++ b/examples/egocap/tests/recording/unit/test_align_kept_episode.py @@ -13,6 +13,7 @@ import pytest import zarr +from egocap.calibration import provenance from egocap.calibration.camera_lag import LATENCY_UNKNOWN from egocap.calibration.files import HEAD_EXTRINSICS, OPENXR_POSES, POSE_SOURCE_KEY from egocap.recording.aligned_writer import ( @@ -379,6 +380,44 @@ def test_cli_refused_episode_exits_1(tmp_path, capsys): assert not (tmp_path / "raw_aligned").exists() +def test_cli_a_session_file_of_a_newer_layout_exits_3_since_an_updated_build_aligns_the_take( + tmp_path, capsys, monkeypatch +): + session = tmp_path / "raw" + build_raw(session, timing=timing_under(0.02)) + state_a_lag(session) + record = json.loads((session / HEAD_EXTRINSICS).read_text()) + (session / HEAD_EXTRINSICS).write_text(json.dumps({**record, "schema_version": 2})) + store_manifest(session) + # Not a refusal of the take, which would be the same every time: this build cannot read the file yet. + assert run_cli(session, "--episode", 0, "--index-source", INDEX) == align_episode.NEWER_SOFTWARE_NEEDED == 3 + assert capsys.readouterr().err == ( + "not aligned: this session's head_camera_extrinsics.json is written in layout 2, and this software " + "reads up to layout 1: the take is not aligned, since the camera's lag is stated in that file; update " + "the software to align it\n" + ) + assert not (tmp_path / "raw_aligned").exists() + # The build the sentence asks for reads that layout, and aligns the same take with the lag taken off. + monkeypatch.setattr(provenance, "SCHEMA_VERSION", 2) + assert run_cli(session, "--episode", 0, "--index-source", INDEX) == 0 + assert capsys.readouterr().out.endswith("frames, 70.0 ms of camera lag taken off\n") + + +def test_cli_a_layout_number_of_any_length_is_answered_in_the_sentence_and_never_as_a_crash(tmp_path, capsys): + session = tmp_path / "raw" + build_raw(session, timing=timing_under(0.02)) + state_a_lag(session) + record = json.loads((session / HEAD_EXTRINSICS).read_text()) + (session / HEAD_EXTRINSICS).write_text(json.dumps({**record, "schema_version": "9" * 5000})) + store_manifest(session) + assert run_cli(session, "--episode", 0, "--index-source", INDEX) == align_episode.NEWER_SOFTWARE_NEEDED + assert capsys.readouterr().err == ( + "not aligned: this session's head_camera_extrinsics.json is written in a layout far newer than any this " + "software knows, and this software reads up to layout 1: the take is not aligned, since the camera's " + "lag is stated in that file; update the software to align it\n" + ) + + def test_cli_manifest_session_option(tmp_path, raw, capsys): other = tmp_path / "other" other.mkdir() diff --git a/examples/egocap/tests/recording/unit/test_aligned_camera_lag.py b/examples/egocap/tests/recording/unit/test_aligned_camera_lag.py index afe8e1d662..4abc95146a 100644 --- a/examples/egocap/tests/recording/unit/test_aligned_camera_lag.py +++ b/examples/egocap/tests/recording/unit/test_aligned_camera_lag.py @@ -495,11 +495,47 @@ def test_a_take_that_does_not_say_its_tracking_latency_is_refused_a_lag_stored_f with pytest.raises(AlignedWriteError) as refusal: write(raw, tmp_path / "aligned", 0, HEAD, qualified=QUALIFIED, continuity=CONTINUITY) assert str(refusal.value) == LATENCY_UNKNOWN + # A refusal of the take itself, the same under any build. + assert not isinstance(refusal.value, aligned_writer.NewerLayoutError) # Refused before anything is written: no aligned session, no staging left behind, the raw one untouched. assert sorted(path.name for path in tmp_path.iterdir()) == ["raw"] assert listing(raw) == before +@pytest.mark.parametrize( + "written", [2, "2", 2.0, 7, "2.0", "9" * 5000], ids=["2", "text", "2.0", "7", "text 2.0", "5000 digits"] +) +def test_a_session_whose_extrinsics_file_is_of_a_newer_layout_is_not_aligned_and_the_refusal_says_why( + tmp_path, written +): + # A station rolled back to this build, or data aligned by an older build than the one that recorded it: the + # keys of a newer layout may not mean what they mean here, the camera's lag among them. + raw = tmp_path / "raw" + write_session(raw, head_extrinsics={**extrinsics(camera_latency_s=LAG_S), "schema_version": written}) + before = tree(raw) + with pytest.raises(AlignedWriteError) as refusal: + align(raw, tmp_path / "aligned") + # A number of any length is named without being printed. + endless = len(str(written)) > 9 + layout = "a layout far newer than any this software knows" if endless else f"layout {int(float(written))}" + assert str(refusal.value) == ( + f"this session's head_camera_extrinsics.json is written in {layout}, and this software reads up " + "to layout 1: the take is not aligned, since the camera's lag is stated in that file; update the " + "software to align it" + ) + # A refusal of its own kind: the take is not at fault, and a build that reads the layout aligns it. + assert type(refusal.value) is aligned_writer.NewerLayoutError + # Not aligned without the lag either: nothing was written, and the recording is as it was. + assert not (tmp_path / "aligned").exists() and tree(raw) == before + # The layout this build writes, stated or not, is aligned with the lag taken off. + for stated in ({"schema_version": 1}, {}): + readable = tmp_path / f"raw{len(stated)}" + write_session(readable, head_extrinsics={**extrinsics(camera_latency_s=LAG_S), **stated}) + align(readable, tmp_path / f"aligned{len(stated)}") + taken_off = dict(aligned_episode(tmp_path / f"aligned{len(stated)}").attrs)[CAMERA_LAG_ATTR] + assert taken_off["taken_off_s"] == LAG_S + + def test_a_take_that_cannot_be_read_for_its_tracking_latency_is_refused_in_the_takes_own_words( tmp_path, monkeypatch ): diff --git a/examples/egocap/tests/recording/unit/test_calibration_camera_pipeline.py b/examples/egocap/tests/recording/unit/test_calibration_camera_pipeline.py index b2a4f0add3..be439e4422 100644 --- a/examples/egocap/tests/recording/unit/test_calibration_camera_pipeline.py +++ b/examples/egocap/tests/recording/unit/test_calibration_camera_pipeline.py @@ -30,7 +30,7 @@ write_episode, ) -from egocap.calibration import camera_pipeline +from egocap.calibration import camera_pipeline, provenance from egocap.calibration.board import BoardDetector, BoardSpec, BoardView, CalibrationError, Detection from egocap.calibration.camera_pipeline import ( DEFAULT_PICKS, @@ -577,6 +577,30 @@ def test_an_extrinsics_only_run_solves_against_the_installed_intrinsics(episode, assert not any(line.startswith(("Intrinsics", "Corners seen", "Field of view")) for line in result.log) +def test_each_solved_record_states_what_made_it_its_grade_and_the_rule_it_is_installed_under(episode, tmp_path): + work = tmp_path / "review" + result = _run(episode, work_dir=work) + for part, record in (("intrinsics", result.intrinsics), ("extrinsics", result.extrinsics)): + stated = provenance.read(record) + assert (stated["schema_version"], stated["software"], stated["tool"]) == ( + 1, + "egocap", + "camera_calibration", + ) + assert stated["version"] == provenance.software_version() + # The grade and the rule are the ones the result reports, so the file and the page say the same. + assert stated["grade"] == result.grade[part]["grade"] + assert stated["install_rule"] == result.grade[part]["install_rule"] + # Not yet installed, so nothing says from when it stands. + assert stated["valid_from"] is None and "validity" not in record["provenance"] + # The copies left for review are the records, statements included. + assert json.loads((work / INTRINSICS_FILE).read_text())["provenance"] == result.intrinsics["provenance"] + assert json.loads((work / EXTRINSICS_FILE).read_text())["provenance"] == result.extrinsics["provenance"] + # A position solved alone is graded alone, and its rule names no intrinsics. + alone = _run(episode, mode="extrinsic", installed_intrinsics=INSTALLED).extrinsics + assert provenance.read(alone)["install_rule"] == "Extrinsics are installed unless graded bad." + + def test_an_extrinsics_only_run_without_usable_installed_intrinsics_is_refused(episode): with pytest.raises(CalibrationError) as refused: _run(episode, mode="extrinsic") diff --git a/examples/egocap/tests/recording/unit/test_calibration_files.py b/examples/egocap/tests/recording/unit/test_calibration_files.py index bcf1e2553b..3de3d67953 100644 --- a/examples/egocap/tests/recording/unit/test_calibration_files.py +++ b/examples/egocap/tests/recording/unit/test_calibration_files.py @@ -32,6 +32,7 @@ load_intrinsics, load_intrinsics_with_sha256, other_camera_problem, + picture_size_note, pose_source_problem, read_json_object, write_json, @@ -145,6 +146,60 @@ def test_headset_extrinsics_are_the_camera_pose_in_the_headset_frame(tmp_path): load_headset_extrinsics(_write(tmp_path, {"T_headset_camera": pose}, HEAD_EXTRINSICS)) +def test_a_file_written_in_a_newer_layout_is_refused_by_name_and_an_older_or_unstated_one_reads_as_before( + tmp_path, +): + pose = {"T_headset_camera": np.eye(4).tolist()} + newer = ( + "{name} is written in layout 2, and this software reads up to layout 1: " + "update the software, or calibrate again with this one" + ) + with pytest.raises(CalibrationFileError) as lens: + load_intrinsics(_write(tmp_path, {**GOOD, "schema_version": 2})) + assert str(lens.value) == newer.format(name=HEAD_INTRINSICS) + # Refused before any key is taken for what it means here: also a file that would otherwise be malformed. + with pytest.raises(CalibrationFileError) as lens: + load_intrinsics_with_sha256(_write(tmp_path, {"schema_version": 7, "K": "not a matrix"})) + assert "layout 7" in str(lens.value) + with pytest.raises(CalibrationFileError) as position: + load_headset_extrinsics(_write(tmp_path, {**pose, "schema_version": 2}, HEAD_EXTRINSICS)) + assert str(position.value) == newer.format(name=HEAD_EXTRINSICS) + # A newer layout is one however the number was written: as text, or as a float with a whole value. + for written in ("2", 2.0, " 3 "): + with pytest.raises(CalibrationFileError, match="is written in layout [23], and this software reads up to"): + load_intrinsics(_write(tmp_path, {**GOOD, "schema_version": written})) + with pytest.raises(CalibrationFileError, match="is written in layout [23], and this software reads up to"): + load_headset_extrinsics(_write(tmp_path, {**pose, "schema_version": written}, HEAD_EXTRINSICS)) + # Also as text with a fraction part of zero, and a number of any length: refused in the sentence, never raised. + with pytest.raises(CalibrationFileError, match="is written in layout 2, and this software reads up to"): + load_intrinsics(_write(tmp_path, {**GOOD, "schema_version": "2.0"})) + for reader, record, name in ( + (load_intrinsics, GOOD, HEAD_INTRINSICS), + (load_intrinsics_with_sha256, GOOD, HEAD_INTRINSICS), + (load_headset_extrinsics, pose, HEAD_EXTRINSICS), + ): + with pytest.raises(CalibrationFileError) as endless: + reader(_write(tmp_path, {**record, "schema_version": "9" * 5000}, name)) + assert str(endless.value) == ( + f"{name} is written in a layout far newer than any this software knows, and this software reads up " + "to layout 1: update the software, or calibrate again with this one" + ) + # The layout this build writes, an older one, none, and anything a hand edit left that is no layout number. + for stated in (1, 0, None, "1", 1.0, "two", 2.5, True, [2]): + assert load_intrinsics(_write(tmp_path, {**GOOD, "schema_version": stated})).image_size_wh == (640, 480) + extrinsics = _write(tmp_path, {**pose, "schema_version": stated}, HEAD_EXTRINSICS) + assert load_headset_extrinsics(extrinsics).shape == (4, 4) + # What a file states of how it came to be changes nothing a reader of the calibration takes from it. + stated = { + **GOOD, + "schema_version": 1, + "provenance": {"producer": {"software": "egocap"}, "grade": "excellent"}, + } + assert intrinsics_identity(load_intrinsics(_write(tmp_path, stated))) == intrinsics_identity( + load_intrinsics(_write(tmp_path, GOOD)) + ) + + def test_a_distortion_vector_saved_as_one_row_or_as_one_column_reads_the_same(tmp_path): flat = GOOD["dist_coeffs"] for saved in ([flat], [[value] for value in flat]): @@ -264,6 +319,25 @@ def test_a_calibration_that_names_this_camera_or_none_that_can_be_shown_may_be_u assert other_camera_problem(record, camera, HEAD_INTRINSICS) is None +def test_a_camera_whose_picture_is_not_the_size_its_lens_file_was_solved_at_is_said_before_a_take(tmp_path): + installed = load_intrinsics(_write(tmp_path, GOOD)) + # The size the file was solved at needs no word, whatever the take is for. + assert picture_size_note(installed, (640, 480), HEAD_INTRINSICS, lens_solved=True) is None + assert picture_size_note(installed, [640, 480], HEAD_INTRINSICS, lens_solved=False) is None + # A take that solves the lens would replace a calibration made at another size. + assert picture_size_note(installed, (1280, 960), HEAD_INTRINSICS, lens_solved=True) == ( + "head_camera_intrinsics.json was solved on a 640x480 picture, and this camera now sends 1280x960. " + "A solve from this take replaces it with one for the new size: if the size changed by mistake, set " + "the camera's picture mode back before recording" + ) + # A take that solves the position alone builds on the file, which another size contradicts. + assert picture_size_note(installed, (640, 360), HEAD_INTRINSICS, lens_solved=False) == ( + "head_camera_intrinsics.json is for a 640x480 picture, and this camera now sends 640x360, so the " + "camera's position cannot be solved against it. Solve the lens as well, or set the camera's picture " + "mode back before recording" + ) + + def test_every_camera_role_has_a_lens_file_name_of_its_own_for_a_session_of_corrected_video(): lens, picture = calibration_files.ROLE_LENS_INTRINSICS, calibration_files.ROLE_INTRINSICS assert set(lens) == set(picture) diff --git a/examples/egocap/tests/recording/unit/test_calibration_grading.py b/examples/egocap/tests/recording/unit/test_calibration_grading.py index 6fad66b88c..ea6bdd8eaf 100644 --- a/examples/egocap/tests/recording/unit/test_calibration_grading.py +++ b/examples/egocap/tests/recording/unit/test_calibration_grading.py @@ -189,6 +189,7 @@ def test_excellent_results_are_installable_and_come_with_no_advice(intrinsics, e "field_of_view", "installable", "not_installable_reason", + "install_rule", ] assert (part["grade"], part["rms_px"], part["installable"], part["not_installable_reason"]) == ( EXCELLENT, @@ -196,6 +197,8 @@ def test_excellent_results_are_installable_and_come_with_no_advice(intrinsics, e True, None, ) + # The rule is stated whether or not the solve met it, for the file an install writes to carry. + assert part["install_rule"] == "Intrinsics are installed only when excellent." assert part["field_of_view"] == field_of_view_line(**_angles(intrinsics)) assert graded["extrinsics"] == { "grade": EXCELLENT, @@ -203,6 +206,10 @@ def test_excellent_results_are_installable_and_come_with_no_advice(intrinsics, e "mean_pnp_reproj_rms_px": 0.4, "installable": True, "not_installable_reason": None, + "install_rule": ( + "Extrinsics are installed unless graded bad, and only with the intrinsics they were solved with " + "when those may be installed." + ), "with_intrinsics": True, } assert json.loads(json.dumps(graded)) == graded @@ -322,6 +329,10 @@ def test_a_position_solved_with_intrinsics_that_cannot_be_installed_is_not_insta def test_a_position_solved_under_the_installed_intrinsics_stands_on_its_own(): part = grade_calibration(None, _extrinsics(0.002, 0.4))["extrinsics"] assert part["installable"] is True and "with_intrinsics" not in part + # Its rule names no intrinsics to be installed with, and is stated whether or not the solve met it. + assert part["install_rule"] == "Extrinsics are installed unless graded bad." + refused = grade_calibration(None, _extrinsics(0.02, 0.4))["extrinsics"] + assert refused["installable"] is False and refused["install_rule"] == part["install_rule"] # --- whether the views pin the answer --------------------------------------------------------------------------- diff --git a/examples/egocap/tests/recording/unit/test_calibration_live_check.py b/examples/egocap/tests/recording/unit/test_calibration_live_check.py new file mode 100644 index 0000000000..676fd9308a --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_calibration_live_check.py @@ -0,0 +1,456 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The live check of an installed head-camera calibration: what it reports of a true and of a wrong one, and +each case in which it says it cannot judge. The pictures are rendered and the head track is written out.""" + +from __future__ import annotations + +import numpy as np +import pytest +from calibration_synthetic import ( + IDEAL_CAMERA, + SIZE, + SPEC, + T_HEADSET_CAMERA, + blank_frame, + board_pose, + head_pose_for, + render, + sweep_pose, + worn_head_track, +) +from scipy.spatial.transform import Rotation + +from egocap.calibration import live_check +from egocap.calibration.board import Detection +from egocap.calibration.frames import homogeneous +from egocap.calibration.live_check import ( + ANCHOR_VIEWS, + CHECKING, + ENOUGH, + FIXING, + HEAD_LOST, + HEAD_MOVING, + HOLD_STILL, + LAG_UNTESTED, + MOVE_HEAD, + NO_HEAD_POSE, + NOT_FOUND, + SECOND_AXIS, + TILT_TOO, + TOO_LITTLE, + VIEWS_NEEDED, + LiveCheck, +) + +#: How fast the synthetic head goes along its sweep: a full sweep in fifty seconds. +PACE = 0.02 +#: How often a picture is looked at, and how often a head pose arrives. +LOOK_S, POSE_S = 0.25, 0.01 + + +#: How long the synthetic head holds still before it sets off, as the check asks while it fixes the board's place. +HOLD_S = 2.0 + + +def board_at(seconds: float) -> np.ndarray: + """The board's pose in the camera at a moment: held at the sweep's start, then along the sweep.""" + return sweep_pose(PACE * max(seconds - HOLD_S, 0.0)) + + +def head_at(seconds: float) -> np.ndarray: + """The head pose (world from head, OpenXR axes) at a moment of the sweep, for the true camera position.""" + return head_pose_for(board_at(seconds)) + + +class Sweep: + """Feeds a check the pictures and the head poses of a head that moves round a still board. + + ``path`` says where the board is in the camera at each moment (the sweep, unless another is given), and + the head poses are the ones that put the camera there. ``late_s`` is an error in the camera's stored lag: + each picture is handed over as taken that much later than it was. + """ + + def __init__( + self, + headset_camera: np.ndarray = T_HEADSET_CAMERA, + camera=IDEAL_CAMERA, + size=SIZE, + path=board_at, + late_s: float = 0.0, + ): + self.check = LiveCheck(SPEC, camera, headset_camera, size) + self.path = path + self.late_s = late_s + self.fed = 0.0 + self.now = 0.5 + + def head(self, seconds: float) -> np.ndarray: + """The head pose that puts the camera where the path has it at a moment.""" + return head_pose_for(self.path(seconds)) + + def poses_until(self, seconds: float, head=None) -> list[tuple[float, np.ndarray]]: + """Every head pose not yet handed over, up to a little after ``seconds``, as tracking runs ahead of + the pictures.""" + head = self.head if head is None else head + track = [(float(t), head(t)) for t in np.arange(self.fed, seconds + 3 * POSE_S, POSE_S)] + self.fed = track[-1][0] + POSE_S + return track + + def look(self, frame: np.ndarray | None = None, head=None, track=None) -> dict: + """One look: the picture of this moment, unless another is given, with the poses that arrived.""" + picture = render(self.path(self.now)) if frame is None else frame + said = self.now + self.late_s + record = self.check.observe(picture, said, self.poses_until(said, head) if track is None else track) + self.now += LOOK_S + return record + + def looks(self, count: int, **options) -> dict: + """``count`` looks; the last one's record.""" + record = {} + for _ in range(count): + record = self.look(**options) + return record + + def fix(self) -> dict: + """Look until the board's place is fixed; the record of the look that fixed it.""" + return self.looks(ANCHOR_VIEWS) + + +def test_a_true_calibration_predicts_the_boards_corners_within_a_pixel_and_is_graded_excellent(): + sweep = Sweep() + first = sweep.look() + # The place is fixed first, from views that are each a look at the board through the installed files. + assert (first["phase"], first["judged"], first["hints"]) == (FIXING, True, [HOLD_STILL]) + assert first["fixing"] == {"views": 1, "views_needed": ANCHOR_VIEWS} + assert (first["error_px"], first["predicted_points"], first["verdict"], first["views"]) == (None, [], None, 0) + assert first["board_visible"] and first["corners"] == len(first["corner_points"]) > 8 + fixed = sweep.looks(ANCHOR_VIEWS - 1) + assert (fixed["phase"], fixed["fixing"]["views"], fixed["hints"]) == (CHECKING, 0, [MOVE_HEAD]) + # Seen again from where the place was fixed, a picture has an error to show and tests nothing yet. + near = sweep.look() + assert near["error_px"] < 1.0 and near["views"] == 0 and near["verdict"] is None + assert len(near["predicted_points"]) == near["corners"] + assert np.abs(np.asarray(near["predicted_points"]) - near["corner_points"]).max() < 2.0 + done = sweep.looks(40) + assert done["judged"] and done["views"] >= VIEWS_NEEDED and done["head_turn_deg"] > 15.0 + assert (done["enough"], done["verdict"], done["hints"]) == (True, "excellent", [ENOUGH]) + assert done["error_px"] < 1.0 and done["rms_px"] < 1.0 and done["rms_px"] <= done["worst_px"] < 1.5 + # The solve's own two figures of a position's fit, against the solve's own limits. + assert done["board_wander_m"] < 0.002 and done["pose_fit_px"] < 0.5 + assert done["limits"] == { + "board_wander_m": [0.005, 0.010], + "pose_fit_px": [1.0, 2.0], + "camera_offset_m": [0.005, 0.010], + "camera_lag_off_s": [0.01, 0.02], + } + assert (done["views_needed"], done["head_turn_needed_deg"], done["restarts"]) == (10, 15.0, 0) + assert done["image_size_wh"] == [640, 480] + + +def test_a_camera_position_that_is_off_shows_as_pixels_of_error_and_is_graded_bad(): + off = T_HEADSET_CAMERA @ homogeneous(Rotation.from_euler("y", 2, degrees=True).as_matrix(), [0.03, 0.0, 0.0]) + sweep = Sweep(off) + sweep.fix() + done = sweep.looks(50) + assert done["judged"] and done["enough"] and done["verdict"] == "bad" + assert done["rms_px"] > 10.0 and done["worst_px"] >= done["error_px"] > 10.0 + assert done["board_wander_m"] > 0.010 and done["pose_fit_px"] < 0.5 + + +def _moved_in_the_headsets_axes(offset_m) -> np.ndarray: + """The true camera position with the camera moved by ``offset_m`` along the headset's own axes.""" + return homogeneous(np.eye(3), offset_m) @ T_HEADSET_CAMERA + + +@pytest.mark.parametrize( + "offset_m", + [(0.01, 0, 0), (0, 0.01, 0), (0, 0, 0.01), (-0.01, 0, 0), (0, -0.01, 0), (0, 0, -0.01)], + ids=["forward", "left", "up", "back", "right", "down"], +) +def test_a_camera_position_one_centimetre_off_in_any_direction_is_never_graded_excellent(offset_m): + sweep = Sweep(_moved_in_the_headsets_axes(offset_m)) + sweep.fix() + done = sweep.looks(60) + assert done["judged"] and done["enough"] and done["verdict"] in ("acceptable", "bad") + # The board's wander is explained as the camera standing a centimetre from where the file has it, which + # is what the grade holds against the solve's own limits for a camera's position. + assert done["camera_offset_m"] == pytest.approx(0.010, abs=0.002) + assert done["limits"]["camera_offset_m"] == [0.005, 0.010] + # The pixels say so too, and were saying so all along. + assert done["rms_px"] > 1.0 and done["no_verdict"] is None + + +def test_a_true_calibration_implies_no_offset_and_no_lag_worth_the_name(): + sweep = Sweep() + sweep.fix() + done = sweep.looks(60) + assert (done["verdict"], done["no_verdict"], done["notes"]) == ("excellent", None, []) + assert done["camera_offset_m"] < 0.002 and done["camera_offset_uncertainty_m"] < 0.0025 + assert abs(done["camera_lag_off_s"]) < 0.005 + assert done["limits"]["camera_lag_off_s"] == [0.01, 0.02] + + +def test_a_camera_lag_that_is_wrong_is_not_graded_excellent_even_with_a_head_that_moves_slowly(): + # Every picture is taken for 30 ms later than it was; the sweep turns the head some ten degrees a second. + sweep = Sweep(late_s=0.03) + sweep.fix() + done = sweep.looks(60) + assert done["judged"] and done["enough"] and done["verdict"] in ("acceptable", "bad") + assert done["camera_lag_off_s"] == pytest.approx(0.03, abs=0.008) + # The camera's place is not blamed for what the clock did. + assert done["camera_offset_m"] < 0.005 + + +def _orbit(seconds: float) -> np.ndarray: + """The board in the camera while the head, after holding still, goes round it about one axis only, a + turn of 20 degrees either way.""" + return board_pose(0.0, 20.0 * np.sin(0.25 * max(seconds - HOLD_S, 0.0)), 0.0, (0.0, 0.0, 0.62)) + + +@pytest.mark.parametrize("offset_m", [(0, 0, 0), (0.02, 0, 0), (0, 0.02, 0), (0, 0, 0.02)]) +def test_a_head_that_turned_about_one_axis_only_gets_no_verdict_and_is_told_what_to_do(offset_m): + sweep = Sweep(_moved_in_the_headsets_axes(offset_m), path=_orbit) + sweep.fix() + done = sweep.looks(60) + # Enough views and a far enough turn by the count, and still nothing is said of the calibration: the + # camera's place along the axis the head turned about is not tested by any of them. + assert done["judged"] and done["views"] >= VIEWS_NEEDED and done["head_turn_deg"] >= 15.0 + assert (done["enough"], done["verdict"]) == (False, None) + assert done["no_verdict"] == SECOND_AXIS and done["hints"] == [TILT_TOO] + assert done["camera_offset_m"] is None + # What was measured is still shown. + assert done["rms_px"] is not None and done["board_wander_m"] is not None + + +def _steps(seconds: float) -> np.ndarray: + """The board in the camera while the head goes from one place of the sweep to the next and holds still + there: a move of a quarter of a second, then a hold of three quarters.""" + whole, part = divmod(seconds, 1.0) + # Eased, so the head starts and stops as a head does. + eased = 0.5 - 0.5 * np.cos(np.pi * min(part / 0.25, 1.0)) + return sweep_pose(0.05 * (whole + eased)) + + +def test_a_head_that_was_still_in_every_picture_gets_a_verdict_that_says_the_lag_was_not_tested(): + sweep = Sweep(path=_steps, late_s=0.03) + # Looked at once a second, in the middle of each hold. + sweep.now = 0.6 + record = {} + for _ in range(40): + record = sweep.look() + sweep.now += 1.0 - LOOK_S + assert record["judged"] and record["enough"] and record["verdict"] == "excellent" + # A wrong lag shows only while the head moves, and none of these pictures was taken then. + assert record["camera_lag_off_s"] is None and record["notes"] == [LAG_UNTESTED] + + +def test_the_boards_place_is_fixed_only_from_pictures_taken_with_the_head_still_enough(): + # A quick head: the sweep in five seconds. + quick = Sweep(path=lambda seconds: sweep_pose(0.2 * seconds)) + moving = quick.looks(ANCHOR_VIEWS + 3) + assert (moving["phase"], moving["judged"], moving["fixing"]["views"]) == (FIXING, False, 0) + assert moving["cannot_judge"] == HEAD_MOVING and moving["hints"] == [HEAD_MOVING] + # The slow sweep fixes it as before. + assert Sweep().fix()["phase"] == CHECKING + + +def test_a_view_from_where_the_place_was_fixed_tests_nothing_however_many_there_are(): + sweep = Sweep() + sweep.fix() + still = sweep.now + # The head holds where it was: the same picture again and again, and head poses that stand still. + held = sweep.looks(12, frame=render(board_at(still)), head=lambda seconds: head_at(still)) + assert held["judged"] and held["error_px"] is not None + assert (held["views"], held["verdict"], held["rms_px"], held["board_wander_m"]) == (0, None, None, None) + assert held["hints"] == [MOVE_HEAD] + + +def test_a_picture_without_the_board_or_with_too_little_of_it_is_not_judged_and_says_why(monkeypatch): + sweep = Sweep() + unseen = sweep.look(blank_frame()) + assert (unseen["judged"], unseen["cannot_judge"], unseen["board_visible"]) == (False, NOT_FOUND, False) + assert unseen["corner_points"] == [] and unseen["hints"] == [NOT_FOUND] and unseen["fixing"]["views"] == 0 + detect = sweep.check._detector.detect + + def a_few_corners(gray): + found = detect(gray) + return Detection(found.corners[:6], found.ids[:6], found.legacy) + + monkeypatch.setattr(sweep.check._detector, "detect", a_few_corners) + few = sweep.look() + assert (few["judged"], few["cannot_judge"], few["corners"]) == (False, TOO_LITTLE, 6) + assert few["board_visible"] and few["fixing"]["views"] == 0 + + def one_row(gray): + found = detect(gray) + # The board's inner corners are numbered row by row: the first row's lie on one line. + row = np.flatnonzero(found.ids.ravel() < SPEC.squares[0] - 1) + return Detection(found.corners[row], found.ids[row], found.legacy) + + # Corners along one line fix no pose, however many they are. + monkeypatch.setattr(live_check, "MIN_CORNERS", 4) + monkeypatch.setattr(sweep.check._detector, "detect", one_row) + line = sweep.look() + assert (line["judged"], line["cannot_judge"]) == (False, TOO_LITTLE) and line["corners"] >= 4 + + +def test_a_picture_with_no_head_pose_at_its_time_is_not_judged(): + # A head that holds still throughout: what is asked here is only whether the track reaches the picture. + sweep = Sweep(path=lambda seconds: board_at(0.0)) + head_at = sweep.head + # No tracking at all. + assert sweep.look(track=[])["cannot_judge"] == NO_HEAD_POSE + # Poses that are none, and one that is no later than the last, place nothing. + holes = np.full((4, 4), np.nan) + mirrored = np.diag([1.0, 1.0, -1.0, 1.0]) + unusable = sweep.look(track=[(0.1, holes), (0.2, mirrored)]) + assert (unusable["judged"], unusable["cannot_judge"]) == (False, NO_HEAD_POSE) + # Tracking that ends before the picture, or begins after it, does not reach the picture's time. + sweep.now = 2.0 + early = sweep.look(track=[(1.90, head_at(1.90)), (1.95, head_at(1.95)), (1.95, head_at(1.0))]) + assert early["cannot_judge"] == NO_HEAD_POSE + sweep.now = 1.0 + assert sweep.look(track=[(2.5, head_at(2.5))])["cannot_judge"] == NO_HEAD_POSE + # A hole in the tracking around the picture is not bridged. + sweep.now = 2.6 + assert sweep.look(track=[(2.9, head_at(2.9))])["cannot_judge"] == NO_HEAD_POSE + # Samples close either side of it give its pose. + sweep.now = 2.92 + assert sweep.look(track=[(2.95, head_at(2.95))])["judged"] is True + # Two samples that only just bracket a picture give its pose and nothing of how the head was moving: + # it is taken for still, and the picture is used. + sweep.now = 3.5 + alone = sweep.look(track=[(3.495, head_at(3.495)), (3.505, head_at(3.505))]) + assert (alone["judged"], alone["fixing"]["views"]) == (True, 2) + + +def test_a_head_pose_is_the_one_at_the_pictures_time_not_the_newest(): + # The newest pose is later than the picture by what the camera lags: used in the picture's place, a + # turning head would be off by the turn it made meanwhile. + late = Sweep() + late.fix() + lagging = late.looks(30, head=lambda seconds: head_at(seconds + 0.3)) + true = Sweep() + true.fix() + exact = true.looks(30) + assert exact["rms_px"] < 1.0 < 3.0 < lagging["rms_px"] + + +def test_a_headset_that_loses_its_position_is_said_and_starts_the_check_over(): + sweep = Sweep() + sweep.fix() + assert sweep.looks(4)["phase"] == CHECKING + # From the last pose the tracking handed over, so that nothing leaps where the turning begins. + began = sweep.fed + held = head_at(began) + + def turning_in_place(seconds: float) -> np.ndarray: + # The headset goes on reporting its turns, from where it was, and no longer where it is. + turned = held.copy() + turn = Rotation.from_euler("y", 10.0 * max(seconds - began, 0.0), degrees=True) + turned[:3, :3] = turn.as_matrix() @ held[:3, :3] + return turned + + lost = sweep.looks(12, head=turning_in_place) + assert (lost["judged"], lost["cannot_judge"], lost["hints"]) == (False, HEAD_LOST, [HEAD_LOST]) + # What was fixed is forgotten: it was fixed in a world the headset has left. + assert (lost["phase"], lost["restarts"], lost["views"], lost["verdict"]) == (FIXING, 1, 0, None) + # Lost with nothing fixed yet, there is nothing to start over. + assert sweep.looks(3, head=turning_in_place)["restarts"] == 1 + + +def test_a_position_that_leaps_starts_the_check_over_in_the_new_frame(monkeypatch): + # The head of this track never holds still, and one picture stands for all it sees: the stillness the + # fixing asks for is not what is tested here. + monkeypatch.setattr(live_check, "STILL_M_PER_S", np.inf) + times, poses = worn_head_track(12.0, 100) + moved = poses.copy() + moved[times >= 6.0, :3, 3] += [0.05, 0.0, 0.0] + check = LiveCheck(SPEC, IDEAL_CAMERA, T_HEADSET_CAMERA, SIZE) + picture = render(board_at(0.0)) + records, fed = [], 0 + for now in np.arange(0.5, 11.5, LOOK_S): + upto = int(np.searchsorted(times, now + 0.03)) + records.append(check.observe(picture, float(now), list(zip(times[fed:upto], moved[fed:upto])))) + fed = upto + before = [record for record, now in zip(records, np.arange(0.5, 11.5, LOOK_S)) if now < 5.9] + assert before[-1]["phase"] == CHECKING and before[-1]["restarts"] == 0 + # The place is fixed again after the leap, from views in the frame the headset now reports. + assert records[-1]["restarts"] == 1 and records[-1]["phase"] == CHECKING + + +def test_a_position_that_leaps_away_and_back_starts_the_check_over_where_it_came_back_to(monkeypatch): + # As above: a head that never holds still, and one picture for all it sees. + monkeypatch.setattr(live_check, "STILL_M_PER_S", np.inf) + times, poses = worn_head_track(16.0, 100) + moved = poses.copy() + # The tracked position leaps three centimetres at five seconds and back again at nine. + moved[(times >= 5.0) & (times < 9.0), :3, 3] += [0.03, 0.0, 0.0] + check = LiveCheck(SPEC, IDEAL_CAMERA, T_HEADSET_CAMERA, SIZE) + picture = render(board_at(0.0)) + records, fed = {}, 0 + for now in np.arange(0.5, 15.5, LOOK_S): + upto = int(np.searchsorted(times, now + 0.03)) + track = list(zip(times[fed:upto], moved[fed:upto])) + records[round(float(now), 2)] = check.observe(picture, float(now), track) + fed = upto + # Fixed before the leap, fixed again in the frame it leapt to, and once more on the way back: the place + # fixed while away is not one the pictures after the return can be held against. + assert records[4.5]["restarts"] == 0 and records[8.5]["restarts"] == 1 + assert records[8.5]["phase"] == CHECKING + assert records[15.25]["restarts"] == 2 and records[15.25]["phase"] == CHECKING + + +def test_a_board_predicted_where_the_lens_cannot_show_it_has_no_pixels_and_counts_for_nothing(): + sweep = Sweep() + sweep.fix() + here, picture = sweep.now, render(board_at(sweep.now)) + start = head_at(here) + + def walking_round(seconds: float) -> np.ndarray: + # A tracked head that turns right round, on an arm so that its place moves with the turn, while the + # picture goes on showing the board: the board is then predicted behind the camera. + if seconds <= here: + return head_at(seconds) + turn = Rotation.from_euler("y", 20.0 * (seconds - here), degrees=True).as_matrix() + arm = np.array([0.0, 0.0, 0.3]) + return homogeneous(turn, turn @ arm - arm) @ start + + records = [sweep.look(picture, head=walking_round) for _ in range(40)] + assert all(record["phase"] == CHECKING and record["judged"] for record in records) + assert records[-1]["restarts"] == 0 + behind = [record for record in records if record["predicted_points"] == []] + assert behind and all(record["error_px"] is None for record in behind) + # Such a picture adds nothing to what the verdict is taken from. + counted = [record["views"] for record in records] + assert counted[records.index(behind[0])] == counted[records.index(behind[0]) - 1] > 0 + + +def test_a_picture_handed_in_smaller_is_judged_in_the_full_pictures_pixels(): + sweep = Sweep() + record = {} + for _ in range(ANCHOR_VIEWS + 60): + frame = render(board_at(sweep.now)) + record = sweep.look(frame[::2, ::2].copy()) + assert record["image_size_wh"] == [640, 480] and np.asarray(record["corner_points"]).max() > 330 + # Half the pixels read the corners a little less exactly; the verdict is the same. + assert record["verdict"] == "excellent" and record["rms_px"] < 2.0 + + +def test_poses_are_kept_only_as_long_as_a_picture_can_be_old(): + sweep = Sweep() + sweep.looks(20) + kept = [seconds for seconds, _ in sweep.check._track] + assert kept[-1] - kept[0] <= 3.0 + 1e-9 and len(kept) <= 302 + + +@pytest.mark.parametrize("share", [0.0, 0.25, 1.0]) +def test_a_pose_between_two_samples_lies_on_the_line_and_the_shortest_turn_between_them(share): + first = homogeneous(Rotation.from_euler("z", 10, degrees=True).as_matrix(), [0.0, 0.0, 1.0]) + second = homogeneous(Rotation.from_euler("z", 50, degrees=True).as_matrix(), [0.4, 0.0, 1.0]) + pose = live_check._between((2.0, first), (4.0, second), 2.0 + 2.0 * share) + assert np.allclose(pose[:3, 3], [0.4 * share, 0.0, 1.0]) + assert np.allclose(pose[:3, :3], Rotation.from_euler("z", 10 + 40 * share, degrees=True).as_matrix()) diff --git a/examples/egocap/tests/recording/unit/test_calibration_provenance.py b/examples/egocap/tests/recording/unit/test_calibration_provenance.py new file mode 100644 index 0000000000..e133c83405 --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_calibration_provenance.py @@ -0,0 +1,319 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What a calibration file states of how it came to be: what is written, what an older file reads as, and the +one case a reader refuses.""" + +from __future__ import annotations + +import copy +import json +from importlib import metadata + +import pytest + +from egocap.calibration import provenance +from egocap.calibration.provenance import ( + CAMERA_CALIBRATION, + PROVENANCE_KEY, + SCHEMA_VERSION, + SCHEMA_VERSION_KEY, + layout_problem, + read, + software_version, + stamp, + with_validity, + without_validity, +) + +#: A calibration file as it was written before any of these keys existed. +OLDER = {"calibrated_at": "2026-01-02T09:00:00+00:00", "camera": "head", "K": [[1, 0, 2], [0, 1, 3], [0, 0, 1]]} +NOTHING_STATED = { + SCHEMA_VERSION_KEY: None, + "software": None, + "version": None, + "tool": None, + "grade": None, + "install_rule": None, + "valid_from": None, +} + + +def test_a_stamp_states_the_layout_what_made_the_file_its_grade_and_its_rule_beside_the_files_own_keys(): + record = copy.deepcopy(OLDER) + stamp( + record, + tool=CAMERA_CALIBRATION, + grade="excellent", + install_rule="Intrinsics are installed only when excellent.", + ) + # Every key the file had is as it was; two were added. + assert {key: record[key] for key in OLDER} == OLDER + assert sorted(set(record) - set(OLDER)) == [PROVENANCE_KEY, SCHEMA_VERSION_KEY] + assert record[SCHEMA_VERSION_KEY] == SCHEMA_VERSION == 1 + assert record[PROVENANCE_KEY] == { + "producer": {"software": "egocap", "version": metadata.version("egocap"), "tool": "camera_calibration"}, + "grade": "excellent", + "install_rule": "Intrinsics are installed only when excellent.", + } + assert json.loads(json.dumps(record)) == record + + +def test_a_stamp_states_what_a_rule_was_held_against_only_when_the_caller_gives_it(): + record: dict = {} + figures = {"left": {"rms_px": 3.5, "clicks": 9, "frames": 4}, "right": None} + stamp(record, tool=provenance.WRIST_OFFSET_FIT, install_rule="at least 8 clicks", evidence=figures) + statement = record[PROVENANCE_KEY] + # A kind of calibration that is not graded says so with a null, never with a made-up grade. + assert (statement["grade"], statement["evidence"]) == (None, figures) + assert statement["evidence"] is not figures + assert statement["producer"]["tool"] == "wrist_offset_fit" + + +def test_a_stamp_writes_a_closed_set_of_keys_whatever_a_caller_passes(): + record: dict = {} + passed = { + "left": { + "rms_px": 3.5, + "clicks": 9, + "frames": 4, + "at_translation_limit": False, + # Nothing of these is a figure a rule is held against. + "operator": "someone", + "path": "/somewhere/else", + }, + "right": None, + "host": "a machine", + "head": {"rms_px": 1.0}, + } + stamp(record, tool=provenance.WRIST_OFFSET_FIT, install_rule=" at least\n8 clicks ", evidence=passed) + statement = record[PROVENANCE_KEY] + assert sorted(statement) == ["evidence", "grade", "install_rule", "producer"] + assert sorted(statement["producer"]) == ["software", "tool", "version"] + assert statement["evidence"] == { + "left": {"rms_px": 3.5, "clicks": 9, "frames": 4, "at_translation_limit": False}, + "right": None, + } + # The rule is one line of text. + assert statement["install_rule"] == "at least 8 clicks" + # A figure that is no number is left out, and one that is not finite is a null a strict reader accepts. + stamp(record, tool=provenance.WRIST_OFFSET_FIT, evidence={"left": {"rms_px": float("nan"), "clicks": "nine"}}) + assert record[PROVENANCE_KEY]["evidence"] == {"left": {"rms_px": None}} + assert json.loads(json.dumps(record, allow_nan=False)) == record + # Evidence that is no table of hands says nothing. + stamp(record, tool=provenance.WRIST_OFFSET_FIT, evidence={"left": "good"}) + assert record[PROVENANCE_KEY]["evidence"] == {} + + +@pytest.mark.parametrize( + "passed", + [ + {"tool": "my_own_tool"}, + {"tool": provenance.CAMERA_CALIBRATION, "grade": "superb"}, + {"tool": provenance.CAMERA_CALIBRATION, "grade": 3}, + {"tool": provenance.CAMERA_CALIBRATION, "install_rule": ["a", "rule"]}, + ], +) +def test_a_stamp_refuses_a_solver_a_grade_or_a_rule_that_is_not_one_and_leaves_the_record_as_it_was(passed): + record = copy.deepcopy(OLDER) + with pytest.raises(ValueError): + stamp(record, **passed) + assert record == OLDER + + +def test_nothing_that_names_the_machine_is_written(): + record: dict = {} + stamp(record, tool=CAMERA_CALIBRATION, grade="excellent", install_rule="rule", evidence={"n": 1}) + replaced = {"sha256": "ab", "calibrated_at": None} + statement = with_validity(record, valid_from="2026-01-02T09:00:00+00:00", supersedes=replaced)[PROVENANCE_KEY] + # A closed set of keys: no host, no account, no path has a place to be written. + assert sorted(statement) == ["evidence", "grade", "install_rule", "producer", "validity"] + assert sorted(statement["producer"]) == ["software", "tool", "version"] + assert sorted(statement["validity"]) == ["supersedes", "valid_from"] + assert sorted(statement["validity"]["supersedes"]) == ["calibrated_at", "sha256"] + + +def test_the_version_is_unknown_where_the_software_runs_without_being_installed(monkeypatch): + def not_installed(name): + raise metadata.PackageNotFoundError(name) + + monkeypatch.setattr(provenance.metadata, "version", not_installed) + assert software_version() == "unknown" + record: dict = {} + stamp(record, tool=CAMERA_CALIBRATION) + assert record[PROVENANCE_KEY]["producer"]["version"] == "unknown" + + +def test_an_install_states_from_when_the_file_stands_and_what_it_replaced_in_a_copy_of_the_record(): + record: dict = {"K": [1]} + stamp(record, tool=CAMERA_CALIBRATION, grade="acceptable", install_rule="rule") + before = copy.deepcopy(record) + replaced = {"sha256": "f" * 64, "calibrated_at": "2026-01-01T08:00:00+00:00"} + written = with_validity(record, valid_from="2026-01-02T09:00:00+00:00", supersedes=replaced) + # The caller's record is left as it was: it may be installed again, or held against the file. + assert record == before and written is not record + statement = written[PROVENANCE_KEY] + assert statement["validity"] == {"valid_from": "2026-01-02T09:00:00+00:00", "supersedes": replaced} + assert statement["validity"]["supersedes"] is not replaced + assert (statement["grade"], statement["install_rule"], written["K"]) == ("acceptable", "rule", [1]) + # Installed again from what was written, the statement is replaced, not added to. + again = with_validity(written, valid_from="2026-01-03T09:00:00+00:00", supersedes=None) + assert again[PROVENANCE_KEY]["validity"] == {"valid_from": "2026-01-03T09:00:00+00:00", "supersedes": None} + # Without what the install stated, the file's content is the record it was installed from. + assert without_validity(written) == without_validity(again) == before + + +@pytest.mark.parametrize("left_by_another_tool", [None, "v2", ["a"], 7]) +def test_a_file_another_tool_made_gains_a_statement_that_holds_only_its_validity(left_by_another_tool): + record = copy.deepcopy(OLDER) + if left_by_another_tool is not None: + record[PROVENANCE_KEY] = left_by_another_tool + written = with_validity(record, valid_from="2026-01-02T09:00:00+00:00", supersedes=None) + assert written[PROVENANCE_KEY] == {"validity": {"valid_from": "2026-01-02T09:00:00+00:00", "supersedes": None}} + assert SCHEMA_VERSION_KEY not in written + # A statement that held nothing but the validity goes with it; anything else under the key stays. + if left_by_another_tool is None: + assert without_validity(written) == OLDER + assert without_validity(record) == record + + +def test_a_file_from_before_these_keys_reads_as_stating_nothing(): + assert read(OLDER) == NOTHING_STATED + assert layout_problem(OLDER, "head_camera_intrinsics.json") is None + + +def test_what_a_stamped_file_states_is_read_back(): + record = copy.deepcopy(OLDER) + stamp(record, tool=CAMERA_CALIBRATION, grade="excellent", install_rule="rule") + record = with_validity(record, valid_from="2026-01-02T09:00:00+00:00", supersedes=None) + assert read(record) == { + SCHEMA_VERSION_KEY: 1, + "software": "egocap", + "version": metadata.version("egocap"), + "tool": "camera_calibration", + "grade": "excellent", + "install_rule": "rule", + "valid_from": "2026-01-02T09:00:00+00:00", + } + + +@pytest.mark.parametrize( + "edited", + [ + {SCHEMA_VERSION_KEY: "one", PROVENANCE_KEY: "none"}, + {SCHEMA_VERSION_KEY: True, PROVENANCE_KEY: ["producer"]}, + {SCHEMA_VERSION_KEY: 1.5, PROVENANCE_KEY: {"producer": "egocap", "grade": 3, "validity": "always"}}, + {SCHEMA_VERSION_KEY: float("nan")}, + {SCHEMA_VERSION_KEY: float("inf")}, + {SCHEMA_VERSION_KEY: "-2"}, + {SCHEMA_VERSION_KEY: [2]}, + # Text that is no whole number, however much of it looks like one. + {SCHEMA_VERSION_KEY: "2.5"}, + {SCHEMA_VERSION_KEY: "1e-3"}, + {SCHEMA_VERSION_KEY: "2 0"}, + {SCHEMA_VERSION_KEY: "0x2"}, + {SCHEMA_VERSION_KEY: "1_0"}, + {SCHEMA_VERSION_KEY: "nan"}, + {SCHEMA_VERSION_KEY: "Infinity"}, + {SCHEMA_VERSION_KEY: "\uff12"}, + {SCHEMA_VERSION_KEY: "."}, + {SCHEMA_VERSION_KEY: "e5"}, + {SCHEMA_VERSION_KEY: ""}, + {PROVENANCE_KEY: {"producer": {"software": 1, "version": None, "tool": []}, "install_rule": {}}}, + {PROVENANCE_KEY: {"validity": {"valid_from": 20260102}}}, + ], +) +def test_keys_edited_by_hand_into_anything_else_read_as_stating_nothing_and_never_raise(edited): + assert read(edited) == NOTHING_STATED + assert layout_problem(edited, "x.json") is None + + +@pytest.mark.parametrize( + ("written", "layout"), + [ + ("2", 2), + (" 2 ", 2), + (2.0, 2), + (float("2e0"), 2), + ("1", 1), + (1.0, 1), + ("0", 0), + ("12", 12), + # The same numbers as text with a fraction part of zero, a sign, leading zeros or an exponent. + ("2.0", 2), + (" 2.000 ", 2), + ("2.", 2), + ("+2", 2), + ("002", 2), + ("2e0", 2), + ("0.2E1", 2), + ("20e-1", 2), + ("1.0", 1), + ("0.0", 0), + ], +) +def test_a_layout_number_written_as_text_or_as_a_whole_float_is_that_number(written, layout): + # Another tool, or a hand, writes a number its own way; a newer layout must not read as an older one for it. + record = {SCHEMA_VERSION_KEY: written} + assert read(record)[SCHEMA_VERSION_KEY] == layout + refused = layout_problem(record, "head_camera_extrinsics.json") + assert (refused is None) == (layout <= SCHEMA_VERSION) + if refused is not None: + assert refused.startswith(f"head_camera_extrinsics.json is written in layout {layout}, ") + + +@pytest.mark.parametrize("version", [0, 1, -3]) +def test_a_layout_this_build_writes_or_an_older_one_is_read(version): + assert layout_problem({SCHEMA_VERSION_KEY: version}, "head_camera_intrinsics.json") is None + + +def test_only_a_layout_newer_than_this_build_writes_is_refused_with_what_to_do(): + assert layout_problem({SCHEMA_VERSION_KEY: SCHEMA_VERSION + 1}, "head_camera_intrinsics.json") == ( + "head_camera_intrinsics.json is written in layout 2, and this software reads up to layout 1: " + "update the software, or calibrate again with this one" + ) + + +@pytest.mark.parametrize( + "written", + [ + "9" * 5000, + "9" * 100_000, + "1" + "0" * 5000 + ".0", + "1e400", + # An exponent of twenty nines: no number type holds it. + "1e" + "9" * 20, + "0.1e" + "9" * 20, + 10**4000, + 10**6000, + 1e300, + ], + ids=[ + "5000 digits", + "100000 digits", + "5001 digits and a fraction of zero", + "an exponent of 400", + "an exponent no number type holds", + "the same with a fraction", + "a whole number of 4001 digits", + "a whole number too long to print", + "a float of 301 digits", + ], +) +def test_a_layout_number_of_any_length_is_refused_in_a_sentence_of_bounded_length_and_never_raises(written): + record = {SCHEMA_VERSION_KEY: written} + # Read as a number no build will reach, small enough to send anywhere. + assert read(record)[SCHEMA_VERSION_KEY] == provenance.LAYOUT_CEILING == 1_000_000 + assert layout_problem(record, "head_camera_extrinsics.json") == ( + "head_camera_extrinsics.json is written in a layout far newer than any this software knows, and this " + "software reads up to layout 1: update the software, or calibrate again with this one" + ) + assert provenance.newer_layout(record) == "a layout far newer than any this software knows" + + +def test_a_layout_just_under_the_ceiling_is_still_named_by_its_number_and_one_this_build_reads_is_not_newer(): + assert provenance.newer_layout({SCHEMA_VERSION_KEY: "999999"}) == "layout 999999" + assert provenance.newer_layout({SCHEMA_VERSION_KEY: 2}) == "layout 2" + for readable in (1, 0, "1.0", None, "two", "0e" + "9" * 20, "1e-" + "9" * 20): + assert provenance.newer_layout({SCHEMA_VERSION_KEY: readable}) is None diff --git a/examples/egocap/tests/recording/unit/test_calibration_station_store.py b/examples/egocap/tests/recording/unit/test_calibration_station_store.py index 78297723dd..b3904e3ab7 100644 --- a/examples/egocap/tests/recording/unit/test_calibration_station_store.py +++ b/examples/egocap/tests/recording/unit/test_calibration_station_store.py @@ -22,7 +22,7 @@ import pytest from egocap.calibration import files as calibration_files -from egocap.calibration import station_store +from egocap.calibration import provenance, station_store from egocap.calibration.files import ( HEAD_EXTRINSICS, HEAD_INTRINSICS, @@ -112,6 +112,11 @@ def nested_too_deep(content): return json.dumps(content).replace(json.dumps(TOO_DEEP), NESTED) +def as_given(content): + # An installed or archived file as the record it was installed from: without what the install stated. + return provenance.without_validity(json.loads(content)) + + def archived(directory, name): # Every archived copy of the file, by its path under the history, with what it holds. history = directory / HISTORY_DIR @@ -150,11 +155,17 @@ def test_a_calibration_is_installed_archived_and_noted_in_the_ledger(tmp_path): f"{HISTORY_DIR}/2026-03-04/091507_{HEAD_INTRINSICS}", ] # The live file is one a recorder can load, and the archive is the same content. - assert load_intrinsics(directory / HEAD_INTRINSICS).record == INTRINSICS - assert ( - json.loads((directory / HISTORY_DIR / "2026-03-04" / f"091507_{HEAD_INTRINSICS}").read_text()) - == INTRINSICS - ) + installed_record = load_intrinsics(directory / HEAD_INTRINSICS).record + archive = directory / HISTORY_DIR / "2026-03-04" / f"091507_{HEAD_INTRINSICS}" + assert json.loads(archive.read_text()) == installed_record + # What was installed is the record given, with what only the install knows stated beside it: from when it + # is the station's calibration, and that it replaced nothing. + assert provenance.without_validity(installed_record) == INTRINSICS + assert installed_record["provenance"] == { + "validity": {"valid_from": "2026-03-04T09:15:07-08:00", "supersedes": None} + } + # The record handed in is the caller's, and is left as it was. + assert "provenance" not in INTRINSICS assert entry == { "date": "2026-03-04", "at": "2026-03-04T09:15:07-08:00", @@ -175,7 +186,8 @@ def test_what_an_install_writes_has_the_permissions_of_any_new_file(tmp_path): (directory / HEAD_INTRINSICS).chmod(0o600) (directory / LEDGER_NAME).chmod(0o600) evening = MORNING.replace(hour=18, minute=30, second=0) - install(directory, HEAD_INTRINSICS, INTRINSICS, kind="head_camera", operator="day shift", now=evening) + solved_again = {**INTRINSICS, "rms_calibrate_camera": 0.3} + install(directory, HEAD_INTRINSICS, solved_again, kind="head_camera", operator="day shift", now=evening) probe = directory / "probe" probe.write_text("") ordinary = stat.S_IMODE(probe.stat().st_mode) @@ -505,7 +517,7 @@ def test_a_ledger_read_but_nested_too_deep_to_write_back_still_gets_the_entry_of "operator": "day shift", "files": [HEAD_INTRINSICS], } - assert load_intrinsics(directory / HEAD_INTRINSICS).record == INTRINSICS + assert provenance.without_validity(load_intrinsics(directory / HEAD_INTRINSICS).record) == INTRINSICS # Every entry an install made is still there; what could not be written back is not. stored = json.loads((directory / LEDGER_NAME).read_text()) assert stored == {"headset": entry, "wrist": NIGHT_ENTRY, **left_of_it} @@ -786,7 +798,7 @@ def test_history_that_cannot_be_read_does_not_stand_in_for_a_copy(tmp_path): now=later, ) kept = tmp_path / HISTORY_DIR / "2026-03-06" / f"091507_replaced_{HEAD_INTRINSICS}" - assert json.loads(kept.read_text()) == INTRINSICS + assert as_given(kept.read_bytes()) == INTRINSICS @pytest.mark.parametrize("name", CALIBRATION_FILES) @@ -808,9 +820,216 @@ def test_a_file_placed_by_hand_is_kept_once_however_many_installs_follow_it(tmp_ } # The one kept copy is the hand-placed file, and each install still has its own. assert copies[f"2026-03-04/091507_replaced_{name}"] == by_hand - assert json.loads(copies[f"2026-03-04/091507_{name}"]) == {"turn": 0} - assert json.loads(copies[f"2026-03-04/091507-2_{name}"]) == {"turn": 1} - assert json.loads((tmp_path / name).read_text()) == {"turn": 3} + assert as_given(copies[f"2026-03-04/091507_{name}"]) == {"turn": 0} + assert as_given(copies[f"2026-03-04/091507-2_{name}"]) == {"turn": 1} + assert as_given((tmp_path / name).read_bytes()) == {"turn": 3} + + +def test_each_installed_file_names_the_file_it_replaced_by_the_hash_of_its_bytes(tmp_path): + def validity(path): + return json.loads(path.read_text())["provenance"]["validity"] + + def sha256(path): + return calibration_files.file_sha256(path) + + live = tmp_path / HEAD_INTRINSICS + install(tmp_path, HEAD_INTRINSICS, INTRINSICS, kind="headset", operator="day shift", now=MORNING) + assert validity(live) == {"valid_from": "2026-03-04T09:15:07-08:00", "supersedes": None} + first = sha256(live) + # The next one names the first by its bytes and by when it says it was made: a chain a reader of any + # session's copy can follow, though no installed file is ever rewritten. + later = MORNING + timedelta(hours=1) + solved_again = {**INTRINSICS, "rms_calibrate_camera": 0.3, "calibrated_at": "2026-03-04T10:14:00-08:00"} + install(tmp_path, HEAD_INTRINSICS, solved_again, kind="headset", operator="day shift", now=later) + assert validity(live) == { + "valid_from": "2026-03-04T10:15:07-08:00", + "supersedes": {"sha256": first, "calibrated_at": "2026-03-04T09:14:00-08:00"}, + } + assert sha256(tmp_path / HISTORY_DIR / "2026-03-04" / f"091507_{HEAD_INTRINSICS}") == first + # The archived copy of an install is the installed file, validity included. + assert (tmp_path / HISTORY_DIR / "2026-03-04" / f"101507_{HEAD_INTRINSICS}").read_bytes() == live.read_bytes() + + # A file placed by hand is named the same way, whatever it holds. Its time is carried only when it is a + # date and time: whatever else a hand wrote there would be copied into every later file and every session. + for by_hand, made in ( + (b'{"placed": "by hand"}', None), + (b"not json at all", None), + (b"[1, 2]", None), + (b'{"calibrated_at": "a\\nb"}', None), + (b'{"calibrated_at": "by someone on some machine, in a folder of theirs"}', None), + (b'{"calibrated_at": 7}', None), + (b'{"calibrated_at": "2026-02-01T08:00:00+00:00"}', "2026-02-01T08:00:00+00:00"), + # Carried in the one form every date here is written in, whatever form the file used. + (b'{"calibrated_at": "2026-02-01 08:00:00"}', "2026-02-01T08:00:00"), + ): + live.write_bytes(by_hand) + replaced = sha256(live) + later += timedelta(hours=1) + install(tmp_path, HEAD_INTRINSICS, INTRINSICS, kind="headset", operator="day shift", now=later) + assert validity(live)["supersedes"] == {"sha256": replaced, "calibrated_at": made} + + +@pytest.mark.parametrize( + ("stated", "carried"), + [ + ("2026-03-04T10:20:30+00:00", "2026-03-04T10:20:30+00:00"), + ("2026-03-04T10:20:30Z", "2026-03-04T10:20:30+00:00"), + ("2026-03-04 10:20:30", "2026-03-04T10:20:30"), + ("2026-03-04x10:20:30", "2026-03-04T10:20:30"), + ("20260304T102030", "2026-03-04T10:20:30"), + ("2026-03-04", "2026-03-04T00:00:00"), + ("2026-03-04T10:20:30." + "1234567890" * 3, "2026-03-04T10:20:30.123456"), + ("2026-03-04T10:20:30." + "7" * 100_000, "2026-03-04T10:20:30.777777"), + ("2026-03-04T10:20:30," + "7" * 80, "2026-03-04T10:20:30.777777"), + ("2026-03-04T10:20:30+05:30:15.123456", "2026-03-04T10:20:30+05:30:15.123456"), + ], + ids=[ + "as this store writes it", + "Z for the offset", + "a space between", + "another letter between", + "no separators", + "a date alone", + "a fraction of thirty digits", + "a fraction of a hundred thousand digits", + "a comma and eighty digits", + "an offset with seconds", + ], +) +def test_the_date_of_a_replaced_file_is_carried_in_one_bounded_form_whatever_form_the_file_wrote( + tmp_path, stated, carried +): + live = tmp_path / HEAD_INTRINSICS + live.write_text(json.dumps({"calibrated_at": stated})) + install(tmp_path, HEAD_INTRINSICS, INTRINSICS, kind="headset", operator="day shift", now=MORNING) + record = json.loads(live.read_text()) + assert record["provenance"]["validity"]["supersedes"]["calibrated_at"] == carried + # What is carried is copied into every later file and session: never longer than a date and time is. + assert len(carried) <= 42 and len(live.read_bytes()) < 2000 + + +def test_an_install_says_when_the_file_it_replaced_could_not_be_read(tmp_path): + def supersedes(): + return json.loads((tmp_path / HEAD_INTRINSICS).read_text())["provenance"]["validity"]["supersedes"] + + # Nothing was installed: nothing was replaced. + install(tmp_path, HEAD_INTRINSICS, INTRINSICS, kind="headset", operator="day shift", now=MORNING) + assert supersedes() is None + # A file that is there and cannot be read was replaced all the same, and the next file says so: it names + # no bytes, which is not the same as naming nothing. + live = tmp_path / HEAD_INTRINSICS + live.chmod(0) + try: + if os.access(live, os.R_OK): + pytest.skip("this account reads a file whatever its mode") + install(tmp_path, HEAD_INTRINSICS, {**INTRINSICS, "turn": 1}, kind="headset", operator="x", now=MORNING) + finally: + live.chmod(0o644) + assert supersedes() == {"sha256": None, "calibrated_at": None} + # A link that leads nowhere is such a file too. + live.unlink() + live.symlink_to(tmp_path / "nowhere.json") + install(tmp_path, HEAD_INTRINSICS, {**INTRINSICS, "turn": 2}, kind="headset", operator="x", now=MORNING) + assert supersedes() == {"sha256": None, "calibrated_at": None} and not live.is_symlink() + + +def test_installing_the_record_that_is_installed_leaves_the_file_as_it_is_and_only_notes_the_ledger(tmp_path): + solved = dict(INTRINSICS) + provenance.stamp(solved, tool=provenance.CAMERA_CALIBRATION, grade="excellent", install_rule="the rule") + install(tmp_path, HEAD_INTRINSICS, solved, kind="headset", operator="day shift", now=MORNING) + live = tmp_path / HEAD_INTRINSICS + first, history = live.read_bytes(), tree(tmp_path / HISTORY_DIR) + # The same solve installed again an hour later, by another operator: sessions hold the file's hash, and a + # file that supersedes its own earlier install would say a calibration changed when none did. + later = MORNING + timedelta(hours=1) + entry = install(tmp_path, HEAD_INTRINSICS, solved, kind="headset", operator="night shift", now=later) + assert live.read_bytes() == first + assert tree(tmp_path / HISTORY_DIR) == history + # The ledger says who installed it last and when, and that doing so changed nothing. + assert (entry["operator"], entry["at"]) == ("night shift", "2026-03-04T10:15:07-08:00") + assert entry["unchanged"] == [HEAD_INTRINSICS] + assert ledger(tmp_path)["headset"] == entry + # A record that differs in anything is another calibration, and goes in as one. + install( + tmp_path, HEAD_INTRINSICS, {**solved, "rms_calibrate_camera": 0.3}, kind="headset", operator="x", now=later + ) + assert live.read_bytes() != first + assert json.loads(live.read_text())["provenance"]["validity"]["supersedes"]["sha256"] == ( + calibration_files.file_sha256(tmp_path / HISTORY_DIR / "2026-03-04" / f"091507_{HEAD_INTRINSICS}") + ) + # A file placed by hand that happens to hold the record without any validity is not an install of it. + live.write_text(json.dumps(solved)) + install(tmp_path, HEAD_INTRINSICS, solved, kind="headset", operator="x", now=later + timedelta(hours=1)) + assert "validity" in json.loads(live.read_text())["provenance"] + + +def test_the_ledger_note_of_an_install_that_changed_nothing_says_so_and_is_no_calibration_done_that_day(tmp_path): + def valid_from() -> str: + return json.loads((tmp_path / HEAD_INTRINSICS).read_text())["provenance"]["validity"]["valid_from"] + + solved = dict(INTRINSICS) + provenance.stamp(solved, tool=provenance.CAMERA_CALIBRATION, grade="excellent", install_rule="the rule") + first = install(tmp_path, HEAD_INTRINSICS, solved, kind="headset", operator="alex", now=MORNING) + # A real install is noted as it always was, with no word of anything unchanged. + assert first == { + "date": "2026-03-04", + "at": "2026-03-04T09:15:07-08:00", + "operator": "alex", + "files": [HEAD_INTRINSICS], + } + assert done_today(tmp_path, "headset", date(2026, 3, 4)) is True + # The next day another operator presses Install on the same record. The note is made, names the file as + # left unchanged, and is not read as a calibration done that day; the file still stands from the first. + next_day = MORNING + timedelta(days=1, hours=2) + again = install(tmp_path, HEAD_INTRINSICS, solved, kind="headset", operator="blake", now=next_day) + assert again == { + "date": "2026-03-05", + "at": "2026-03-05T11:15:07-08:00", + "operator": "blake", + "files": [HEAD_INTRINSICS], + "unchanged": [HEAD_INTRINSICS], + } + assert ledger(tmp_path)["headset"] == again + assert valid_from() == "2026-03-04T09:15:07-08:00" + assert done_today(tmp_path, "headset", date(2026, 3, 5)) is False + # A second file the same operator really installs that day makes it a day's calibration; the first file is + # still named as unchanged. + position = install(tmp_path, HEAD_EXTRINSICS, EXTRINSICS, kind="headset", operator="blake", now=next_day) + assert (position["files"], position["unchanged"]) == ([HEAD_INTRINSICS, HEAD_EXTRINSICS], [HEAD_INTRINSICS]) + assert done_today(tmp_path, "headset", date(2026, 3, 5)) is True + # Once the first file is really replaced, nothing of the entry is unchanged, and the key is gone with it. + changed = {**solved, "rms_calibrate_camera": 0.3} + replaced = install(tmp_path, HEAD_INTRINSICS, changed, kind="headset", operator="blake", now=next_day) + assert replaced["files"] == [HEAD_EXTRINSICS, HEAD_INTRINSICS] and "unchanged" not in replaced + assert "unchanged" not in ledger(tmp_path)["headset"] + + +def test_what_a_hand_wrote_under_unchanged_is_shown_only_as_far_as_it_names_the_entrys_files(tmp_path): + entry = {"date": "2026-03-04", "operator": "alex", "files": [HEAD_INTRINSICS, HEAD_EXTRINSICS]} + for by_hand, shown in ( + ([HEAD_INTRINSICS, "notes.txt", 7], [HEAD_INTRINSICS]), + ([WRIST_OFFSETS], None), + ("all", None), + ([], None), + ): + (tmp_path / LEDGER_NAME).write_text(json.dumps({"headset": {**entry, "unchanged": by_hand}})) + assert ledger(tmp_path)["headset"].get("unchanged") == shown + # Only an entry whose every file was left unchanged is no calibration of that day. + assert done_today(tmp_path, "headset", date(2026, 3, 4)) is True + everything = {"headset": {**entry, "unchanged": [HEAD_EXTRINSICS, HEAD_INTRINSICS]}} + (tmp_path / LEDGER_NAME).write_text(json.dumps(everything)) + assert done_today(tmp_path, "headset", date(2026, 3, 4)) is False + + +def test_what_a_record_already_states_of_how_it_came_to_be_is_kept_beside_the_validity(tmp_path): + solved = dict(INTRINSICS) + provenance.stamp(solved, tool=provenance.CAMERA_CALIBRATION, grade="excellent", install_rule="the rule") + install(tmp_path, HEAD_INTRINSICS, solved, kind="headset", operator="day shift", now=MORNING) + stated = load_intrinsics(tmp_path / HEAD_INTRINSICS).record + assert stated["schema_version"] == 1 + assert sorted(stated["provenance"]) == ["grade", "install_rule", "producer", "validity"] + assert provenance.read(stated)["valid_from"] == "2026-03-04T09:15:07-08:00" + assert provenance.without_validity(stated) == solved and "validity" not in solved["provenance"] def test_a_file_placed_by_hand_between_two_installs_in_one_second_is_kept_beside_the_first_ones_copies(tmp_path): @@ -834,7 +1053,7 @@ def test_a_file_placed_by_hand_between_two_installs_in_one_second_is_kept_beside } assert copies[f"2026-03-04/091507_replaced_{WRIST_OFFSETS}"] == first assert copies[f"2026-03-04/091507-2_replaced_{WRIST_OFFSETS}"] == second - assert json.loads(copies[f"2026-03-04/091507_{WRIST_OFFSETS}"]) == {"turn": 0} + assert as_given(copies[f"2026-03-04/091507_{WRIST_OFFSETS}"]) == {"turn": 0} def test_many_installs_within_one_second_are_still_told_apart_in_the_order_they_were_made(tmp_path): @@ -850,7 +1069,7 @@ def test_many_installs_within_one_second_are_still_told_apart_in_the_order_they_ ) copies = archived(tmp_path, HEAD_EXTRINSICS) - assert json.loads(copies[f"2026-03-04/091507-11_{HEAD_EXTRINSICS}"]) == {"turn": 10} + assert as_given(copies[f"2026-03-04/091507-11_{HEAD_EXTRINSICS}"]) == {"turn": 10} # The eleventh is the newest of that second, not the one whose name sorts last: nothing is kept again. assert len(copies) == 12 and not [path for path in copies if "_replaced_" in path] @@ -885,7 +1104,7 @@ def test_a_copy_dropped_into_the_history_by_hand_costs_an_extra_kept_copy_and_ne now=later, ) kept = tmp_path / HISTORY_DIR / "2026-03-04" / f"101507_replaced_{HEAD_INTRINSICS}" - assert json.loads(kept.read_text()) == INTRINSICS + assert as_given(kept.read_bytes()) == INTRINSICS def test_the_kept_copy_of_a_replaced_file_is_on_disk_before_the_file_is_replaced(tmp_path, monkeypatch): diff --git a/examples/egocap/tests/recording/unit/test_calibration_wrist_offset.py b/examples/egocap/tests/recording/unit/test_calibration_wrist_offset.py index 936a72525b..a34f5ec908 100644 --- a/examples/egocap/tests/recording/unit/test_calibration_wrist_offset.py +++ b/examples/egocap/tests/recording/unit/test_calibration_wrist_offset.py @@ -10,6 +10,7 @@ import re import warnings from datetime import datetime, timedelta, timezone +from importlib import metadata import numpy as np import pytest @@ -442,7 +443,17 @@ def test_the_saved_record_has_the_shape_its_readers_depend_on(): "corr_right_deg", "left", "right", + # Added after every key readers outside this repository use, which are above and as they were. + "schema_version", + "provenance", ] + assert record["schema_version"] == 1 + assert record["provenance"] == { + "producer": {"software": "egocap", "version": metadata.version("egocap"), "tool": "wrist_offset_fit"}, + # A wrist-offset fit is not graded, and a caller that states no rule leaves none. + "grade": None, + "install_rule": None, + } written = datetime.fromisoformat(record["calibrated_at"]) assert written == now and written.utcoffset() is not None and written.microsecond == 0 assert record["n_samples"] == 40 and record["corr_left_deg"] == record["corr_right_deg"] == [0, -90, 0] @@ -461,6 +472,43 @@ def test_the_saved_record_has_the_shape_its_readers_depend_on(): assert np.allclose(record[side][f"hand_{side}_pico_translation"], translation) +def test_the_saved_record_states_the_rule_its_install_was_held_to_and_what_it_was_held_against(): + offsets = {"left": OFFSETS[1], "right": OFFSETS[2]} + fits = {"left": {"rms_px": 3.5, "clicks": 9, "frames": 4, "at_translation_limit": False}} + record = json.loads( + json.dumps(offsets_record(offsets, n_samples=4, install_rule="at least 8 clicks over 3 frames", fits=fits)) + ) + statement = record["provenance"] + assert (statement["grade"], statement["install_rule"]) == (None, "at least 8 clicks over 3 frames") + # A hand the caller names no fit for kept the offset it had: said as a null, never left out. + assert statement["evidence"] == {"left": fits["left"], "right": None} + # The offsets read back as they did before the file stated any of this. + for side in SIDES: + assert np.allclose(offsets_from_record(record)[side].trans_m, offsets[side].trans_m, atol=1e-9) + without = {key: value for key, value in record.items() if key not in ("schema_version", "provenance")} + for side in SIDES: + assert np.allclose(offsets_from_record(without)[side].trans_m, offsets[side].trans_m, atol=1e-9) + + +def test_wrist_offsets_written_in_a_newer_layout_are_refused_and_an_older_or_unstated_one_is_read(): + record = offsets_record({"left": OFFSETS[1], "right": OFFSETS[2]}, n_samples=4) + with pytest.raises(CalibrationFileError) as refused: + offsets_from_record({**record, "schema_version": 2}) + assert str(refused.value) == ( + "wrist_calibration_offsets.json is written in layout 2, and this software reads up to layout 1: " + "update the software, or calibrate again with this one" + ) + # A newer layout is one however the number was written. + for written in ("2", 2.0, "2.0"): + with pytest.raises(CalibrationFileError, match="is written in layout 2"): + offsets_from_record({**record, "schema_version": written}) + # A number of any length is refused in the sentence, and never raises. + with pytest.raises(CalibrationFileError, match="^wrist_calibration_offsets.json is written in a layout far"): + offsets_from_record({**record, "schema_version": "9" * 5000}) + for readable in (1, 0, "1", "two", None, True): + assert set(offsets_from_record({**record, "schema_version": readable})) == set(SIDES) + + def test_a_saved_record_says_its_poses_are_the_openxr_ones_and_one_without_the_stamp_is_another_sources(): record = json.loads(json.dumps(offsets_record({"left": OFFSETS[1], "right": OFFSETS[2]}, n_samples=12))) assert record[POSE_SOURCE_KEY] == OPENXR_POSES == "openxr" and POSE_SOURCE_KEY == "pose_source" 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 4c1406dc5d..421fb213dd 100644 --- a/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py +++ b/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py @@ -337,6 +337,21 @@ def test_count_trajectories_counts_valid_and_excluded(tmp_path): assert result[key]["timestamp"] == "2026-01-01-10-00-00" +def test_count_trajectories_reports_the_studio_the_session_states_and_its_folder_only_without_one(tmp_path): + episode = {0: {"episode_duration": 5.0, "recorded_at": "2026-01-01; 10-00-00"}} + key = "Kitchen/2026-01-01-10-00-00" + session = _build_session(tmp_path, "Kitchen", "2026-01-01-10-00-00", "station_01", episode) + assert count_trajectories(tmp_path, "2026-01-01")[key]["studio"] == "Kitchen" + # A label corrected after recording, in the session's config or on its root group, is the studio counted + # under; the session is still keyed by the folder it lies in, which a correction never moves. + (session / "config.yaml").write_text("meta:\n egocap_station_name: station_01\n studio: Larder\n") + assert count_trajectories(tmp_path, "2026-01-01")[key]["studio"] == "Larder" + _write_zarr_json(session, {"discarded_episode_indices": [], "studio": "Pantry"}) + counted = count_trajectories(tmp_path, "2026-01-01") + assert list(counted) == [key] and counted[key]["studio"] == "Pantry" + assert counted[key]["timestamp"] == "2026-01-01-10-00-00" + + def test_count_trajectories_track_language_false_skips_descriptions(tmp_path): _build_session( tmp_path, diff --git a/examples/egocap/tests/recording/unit/test_day_report.py b/examples/egocap/tests/recording/unit/test_day_report.py index 683981c422..5c9d9860d0 100644 --- a/examples/egocap/tests/recording/unit/test_day_report.py +++ b/examples/egocap/tests/recording/unit/test_day_report.py @@ -120,6 +120,8 @@ def test_totals_come_from_the_manifests_with_each_takes_real_disposition(tmp_pat "disposition": "flagged", "duration_seconds": 8.0, "task": "Pour water.", + # A recording that was never given a studio has none to report. + "studio": None, "task_details": "", "operator": "alex", "issues": ["sustained_freeze"], @@ -293,6 +295,52 @@ def test_a_task_corrected_after_recording_is_the_one_reported(tmp_path): assert tasks == ["Pour water.", "Place the cup on the shelf."] +def test_a_studio_corrected_after_recording_is_the_one_reported_for_a_session_and_for_a_routed_group(tmp_path): + session = _session(tmp_path) + _take(session, _manifest(0, "FINALIZED"), recorded_at=f"{DAY}; 08-20-00") + _take(session, _manifest(1, "FINALIZED"), recorded_at=f"{DAY}; 08-21-00") + _take(session, _manifest(2, "SEALED")) + + def studios() -> list[str | None]: + return [e["studio"] for e in build_day_report(tmp_path, DAY)["sessions"][0]["episodes"]] + + assert studios() == [None, None, None] + # The session's own label speaks for every take of it, the ones with no finalized episode included. + (session / "config.yaml").write_text("meta:\n egocap_station_name: Bench A\n studio: Pantry\n") + assert studios() == ["Pantry", "Pantry", "Pantry"] + # A take's own label is the take's. + attributes = {"recorded_at": f"{DAY}; 08-21-00", "studio": "Larder"} + (session / "episode_1" / "zarr.json").write_text(json.dumps({"attributes": attributes})) + assert studios() == ["Pantry", "Larder", "Pantry"] + for unusable in ("", " ", 7): + (session / "episode_1" / "zarr.json").write_text(json.dumps({"attributes": {"studio": unusable}})) + assert studios()[1] == "Pantry" + + # A routed take lies in a folder named after the studio it was recorded under. The group's own label is + # what is reported once it differs; the folder's studio only while the group states none. + other = "session_20260309-091500_def456" + routed_session = _session(tmp_path, other) + group = "Kitchen/2026-03-09-09-15-00" + assigned = {"group": group, "slot": 0} + _take(routed_session, _manifest(0, "FINALIZED", session=other, studio="Kitchen", assignment=assigned)) + _take(routed_session, _manifest(1, "CHECKED", session=other, studio="Kitchen")) + (tmp_path / group / "episode_0").mkdir(parents=True) + stamp = {ROUTE_ATTR: route_id(other, group)} + (tmp_path / group / "zarr.json").write_text(json.dumps({"attributes": stamp})) + (tmp_path / group / "episode_0" / "zarr.json").write_text( + json.dumps({"attributes": {"recorded_at": f"{DAY}; 09-20-00"}}) + ) + + def routed() -> list[str | None]: + return [e["studio"] for e in build_day_report(tmp_path, DAY)["sessions"][1]["episodes"]] + + assert routed() == ["Kitchen", "Kitchen"] + (tmp_path / group / "zarr.json").write_text(json.dumps({"attributes": {**stamp, "studio": "Pantry"}})) + # The take still to be routed keeps the studio it was recorded under, which is where it will be filed. + assert routed() == ["Pantry", "Kitchen"] + assert build_day_report(tmp_path, DAY)["sessions"][1]["episodes"][0]["location"] == f"{group}/episode_0" + + def test_an_unusable_recorded_at_falls_back_to_the_checkpoint_time(tmp_path): session = _session(tmp_path) _take(session, _manifest(0, "FINALIZED"), recorded_at="soon") diff --git a/examples/egocap/tests/recording/unit/test_episode_store.py b/examples/egocap/tests/recording/unit/test_episode_store.py index 4930c664a5..abd9b759a1 100644 --- a/examples/egocap/tests/recording/unit/test_episode_store.py +++ b/examples/egocap/tests/recording/unit/test_episode_store.py @@ -185,6 +185,39 @@ def test_manifest_round_trip_atomic_and_unsupported_version_reported(tmp_path: P assert len(problems) == 1 and "schema_version" in problems[0] +@pytest.mark.parametrize("content", ["[]", "null", "7", '"text"', "{", ""]) +def test_a_take_record_that_is_no_object_is_listed_as_unreadable_not_raised(tmp_path: Path, content: str) -> None: + """A record that is JSON and no object, or no JSON at all, must not fail the scan with an error of its own.""" + write_manifest(tmp_path, _manifest(1)) + manifest_path(tmp_path, 9).write_text(content) + found, problems = scan_manifests(tmp_path) + assert [m.episode_index for m in found] == [1] + assert len(problems) == 1 and problems[0].startswith("episode_9.json: ") + + +def test_a_take_record_or_a_sidecar_that_cannot_be_read_is_a_problem_and_never_no_take(tmp_path: Path) -> None: + """A sidecar that cannot be listed says nothing of the takes in it; read as empty, a waiting take is missed.""" + write_manifest(tmp_path, _manifest(1)) + write_manifest(tmp_path, _manifest(2)) + sidecar = tmp_path / ".recording" + record = manifest_path(tmp_path, 2) + record.chmod(0) + try: + if os.access(record, os.R_OK): + pytest.skip("this account reads a file whatever its mode") + found, problems = scan_manifests(tmp_path) + assert [m.episode_index for m in found] == [1] + # Said by the record's name alone: the report shows these lines, and a path is not an operator's to read. + assert problems == ["episode_2.json: cannot be opened: Permission denied"] + sidecar.chmod(0) + found, problems = scan_manifests(tmp_path) + assert found == [] and problems == [".recording: cannot be listed: Permission denied"] + finally: + sidecar.chmod(0o755) + record.chmod(0o644) + assert [m.episode_index for m in scan_manifests(tmp_path)[0]] == [1, 2] + + 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 diff --git a/examples/egocap/tests/recording/unit/test_route.py b/examples/egocap/tests/recording/unit/test_route.py index 941c3fdb62..ae938b55b9 100644 --- a/examples/egocap/tests/recording/unit/test_route.py +++ b/examples/egocap/tests/recording/unit/test_route.py @@ -14,6 +14,7 @@ import pytest from egocap.recording.episode_layout import ( + MANIFEST_DIR, ROUTE_ATTR, EpisodeManifest, final_dir, @@ -22,7 +23,7 @@ remove_owned_episode, route_id, ) -from egocap.recording.route import RoutingConfig, assign_output, refresh_group_totals, resolve_studio +from egocap.recording.route import RoutingConfig, assign_output, forget_group, refresh_group_totals, resolve_studio NOW = datetime.datetime(2026, 10, 20, 9, 30, 0) SESSION_ID = "session_1" @@ -432,3 +433,52 @@ def test_an_unrouted_manifest_still_uses_the_session_layout(tmp_path): manifest = _manifest(session) manifest.studio = manifest.assignment = None assert final_dir(session, manifest) == session / "episode_0" + + +def _bytes(root: Path) -> dict[str, bytes]: + return {str(path.relative_to(root)): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} + + +def test_a_group_whose_labels_were_corrected_is_forgotten_so_a_later_take_claims_a_fresh_one(tmp_path): + session = _session(tmp_path) + output = session.parent + group, _slot = _assign(session) + other, _slot = _assign(session, task="pour water") + routes_file = session / MANIFEST_DIR / "routes.json" + # A correction relabels the group's studio after its takes were filed. + stamp = json.loads((output / group / "zarr.json").read_text()) + stamp["attributes"]["studio"] = "Pantry" + (output / group / "zarr.json").write_text(json.dumps(stamp)) + # The session still sends a take of that studio and task to the group, which no longer says the same. + with pytest.raises(PermissionError, match="holds 'stack blocks' in 'Pantry', not 'stack blocks' in 'Kitchen'"): + _assign(session) + before = _bytes(output) + assert forget_group(session, group) is True + # Only the session's record of its routes changed: the group, its stamp and every other route are as they were. + after = _bytes(output) + assert [name for name in after if after[name] != before[name]] == [f"{SESSION_ID}/{MANIFEST_DIR}/routes.json"] + assert sorted(after) == sorted(before) + assert list(json.loads(routes_file.read_text()).values()) == [other] + # The next take of the same studio, task and day claims a group of its own, stamped as the take was recorded. + later = NOW + datetime.timedelta(minutes=5) + fresh, slot = _assign(session, now=later) + assert fresh != group and slot == 0 + assert (_attrs(output / fresh)["studio"], _attrs(output / group)["studio"]) == ("Kitchen", "Pantry") + # Forgetting a group the session never routed to, or one already forgotten, changes nothing. + recorded = routes_file.read_bytes() + assert forget_group(session, group) is False and forget_group(session, "Kitchen/never") is False + assert routes_file.read_bytes() == recorded + # A session that never routed anything has no record to change, and gains none. + bare = output / "session_bare" + bare.mkdir() + assert forget_group(bare, group) is False and not (bare / MANIFEST_DIR).exists() + + +def test_forgetting_a_group_fails_clearly_on_a_damaged_record_and_changes_nothing(tmp_path): + session = _session(tmp_path) + group, _slot = _assign(session) + routes_file = session / MANIFEST_DIR / "routes.json" + routes_file.write_text("not json") + with pytest.raises(ValueError, match="unreadable or not valid JSON"): + forget_group(session, group) + assert routes_file.read_text() == "not json" diff --git a/examples/egocap/tests/recording/unit/test_session_studio.py b/examples/egocap/tests/recording/unit/test_session_studio.py new file mode 100644 index 0000000000..86d56800e3 --- /dev/null +++ b/examples/egocap/tests/recording/unit/test_session_studio.py @@ -0,0 +1,83 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The studio a recorded session is labelled with: its own metadata first, its folder's name only without it.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from egocap.studio.session_studio import session_studio + + +def _session(root: Path, *, attributes: object = None, config: str | None = None) -> Path: + session = root / "Kitchen" / "2026-01-02-09-00-00" + session.mkdir(parents=True) + if attributes is not None: + (session / "zarr.json").write_text(json.dumps({"attributes": attributes, "node_type": "group"})) + if config is not None: + (session / "config.yaml").write_text(config) + return session + + +def test_the_root_groups_own_label_is_the_studio_whatever_the_folder_is_called(tmp_path): + session = _session(tmp_path, attributes={"studio": "Pantry"}, config="meta:\n studio: Larder\n") + assert session_studio(session, fallback="Kitchen") == "Pantry" + + +def test_a_session_without_a_root_group_is_known_by_its_config(tmp_path): + session = _session(tmp_path, config="meta:\n egocap_station_name: Bench A\n studio: Pantry\n") + assert session_studio(session, fallback="Kitchen") == "Pantry" + # A root group that states no studio leaves the config to say it. + stamped = _session( + tmp_path / "other", attributes={"task_description": "pour"}, config="meta: {studio: Pantry}" + ) + assert session_studio(stamped, fallback="Kitchen") == "Pantry" + + +def test_only_a_session_that_states_no_studio_is_known_by_its_folder(tmp_path): + assert session_studio(_session(tmp_path), fallback="Kitchen") == "Kitchen" + assert session_studio(tmp_path / "missing", fallback="Kitchen") == "Kitchen" + # With nothing to fall back on, a session that says nothing has no studio. + assert session_studio(tmp_path / "missing") is None + assert session_studio(tmp_path / "missing", fallback=" ") is None + + +def test_attributes_the_caller_already_read_are_not_read_again(tmp_path): + session = _session(tmp_path, attributes={"studio": "On disk"}) + assert session_studio(session, attributes={"studio": "Handed in"}) == "Handed in" + # Handed in and stating nothing, the config and then the folder are asked as usual. + assert session_studio(session, attributes={}, fallback="Kitchen") == "Kitchen" + + +@pytest.mark.parametrize( + ("attributes", "config"), + [ + ({"studio": ""}, None), + ({"studio": " "}, None), + ({"studio": 7}, None), + (["studio"], None), + (None, "meta: [studio]\n"), + (None, "- studio\n"), + (None, "meta:\n studio: 7\n"), + (None, "meta:\n studio: ''\n"), + (None, "meta: {studio: [\n"), + (None, b"\xff\xfe".decode("latin-1")), + ], +) +def test_metadata_that_states_no_usable_label_falls_back_instead_of_raising(tmp_path, attributes, config): + session = _session(tmp_path, attributes=attributes, config=config) + assert session_studio(session, fallback="Kitchen") == "Kitchen" + + +def test_unreadable_metadata_falls_back_instead_of_raising(tmp_path): + session = _session(tmp_path) + (session / "zarr.json").write_text("{not json") + (session / "config.yaml").write_bytes(b"\xff\xfe\x00meta") + assert session_studio(session, fallback="Kitchen") == "Kitchen" + (session / "zarr.json").write_text("[1, 2]") + assert session_studio(session, fallback="Kitchen") == "Kitchen" diff --git a/examples/egocap/tests/recording/unit/test_update_episode_task_description.py b/examples/egocap/tests/recording/unit/test_update_episode_task_description.py index 4be21c2ad0..2d9eca7806 100644 --- a/examples/egocap/tests/recording/unit/test_update_episode_task_description.py +++ b/examples/egocap/tests/recording/unit/test_update_episode_task_description.py @@ -2,18 +2,28 @@ # # SPDX-License-Identifier: Apache-2.0 +import json +import os +import stat from pathlib import Path import pytest import yaml import zarr +import egocap.data_processing.update_episode_task_description as relabel from egocap.data_processing.update_episode_task_description import ( MAX_EPISODE_SPAN, EpisodeRangeError, + RelabelError, + SessionConfigError, _parse_episode_arg, _update_session_config_yaml, + plan_session_studio, + remove_interrupted_writes, + stored_studio_name, update_episode_task_description, + update_session_studio, ) @@ -76,34 +86,43 @@ def test_update_session_config_yaml_no_meta_section_creates_one(tmp_path): assert data["meta"]["task_description"] == "x" -def test_update_session_config_yaml_non_dict_top_level_becomes_dict(tmp_path): +@pytest.mark.parametrize( + ("content", "refusal"), + [ + # Rewriting any of these would replace whatever the file holds with the label alone. + (b"- just\n- a\n- list\n", "config.yaml does not hold the session's settings"), + (b"just text\n", "config.yaml does not hold the session's settings"), + (b"meta: [a, list]\n", "config.yaml does not hold the session's settings"), + (b"meta: [unbalanced\n", "config.yaml cannot be read"), + (b"meta:\n egocap_station_name: Caf\xe9\n", "config.yaml cannot be read"), + ], +) +def test_a_config_that_is_not_the_sessions_settings_is_refused_and_left_as_it_is(tmp_path, content, refusal): cfg = tmp_path / "config.yaml" - cfg.write_text("- just\n- a\n- list\n", encoding="utf-8") - _update_session_config_yaml(tmp_path, task_description="x", task_name="", studio="") - data = yaml.safe_load(cfg.read_text(encoding="utf-8")) - assert data["meta"]["task_description"] == "x" + cfg.write_bytes(content) + with pytest.raises(SessionConfigError) as refused: + _update_session_config_yaml(tmp_path, task_description="x", task_name="", studio="Kitchen") + assert str(refused.value) == refusal + assert cfg.read_bytes() == content and sorted(path.name for path in tmp_path.iterdir()) == ["config.yaml"] -def test_update_session_config_yaml_malformed_yaml_swallowed(tmp_path): +def test_an_empty_config_is_given_a_meta_of_its_own(tmp_path): cfg = tmp_path / "config.yaml" - cfg.write_text("meta: [unbalanced\n", encoding="utf-8") - # Should not raise -- malformed config is a no-op, not a crash. - _update_session_config_yaml(tmp_path, task_description="x", task_name="", studio="") + cfg.write_text("", encoding="utf-8") + assert _update_session_config_yaml(tmp_path, task_description="x", task_name="", studio="") is True + assert yaml.safe_load(cfg.read_text(encoding="utf-8")) == {"meta": {"task_description": "x"}} -def test_update_session_config_yaml_unreadable_swallowed(tmp_path, monkeypatch): +def test_a_config_that_cannot_be_read_is_a_failure_and_never_passed_over(tmp_path, monkeypatch): cfg = tmp_path / "config.yaml" cfg.write_text("meta: {}\n", encoding="utf-8") - real_open = open - - def boom(p, *a, **k): - if str(p) == str(cfg): - raise OSError("permission denied") - return real_open(p, *a, **k) + def boom(self): + raise OSError("permission denied") - monkeypatch.setattr("builtins.open", boom) - _update_session_config_yaml(tmp_path, task_description="x", task_name="", studio="") + monkeypatch.setattr(Path, "read_bytes", boom) + with pytest.raises(SessionConfigError, match="^config.yaml cannot be read$"): + _update_session_config_yaml(tmp_path, task_description="x", task_name="", studio="") def _make_session(tmp_path: Path, n_episodes: int = 3) -> Path: @@ -227,6 +246,18 @@ def test_a_partial_correction_relabels_only_the_named_take_of_the_aligned_copy(t assert yaml.safe_load((aligned / "config.yaml").read_text(encoding="utf-8"))["meta"] == {} +def test_a_partial_correction_that_names_a_studio_gives_the_copy_the_studio_and_not_the_task(tmp_path): + session = tmp_path / "session" + _make_session(session, 2) + aligned = _make_aligned_copy(session) + update_episode_task_description(session, "0", task_description="pour cereal", studio="Kitchen") + store = zarr.open(str(aligned), mode="r") + # The studio is the whole session's; the task is the one take's, so the copy's own task stays unsaid. + assert store.attrs["studio"] == "Kitchen" and "task_description" not in store.attrs + take = store["episode_0"].attrs + assert (take["task_description"], take["studio"]) == ("pour cereal", "Kitchen") + + def _make_aligned_copy(session: Path) -> Path: aligned = session.with_name(f"{session.name}_aligned") store = zarr.open(str(aligned), mode="a") @@ -309,17 +340,37 @@ def test_a_failed_config_write_leaves_the_file_as_it_was_and_no_temporary_file(t def refuse(*_args, **_kwargs): raise yaml.YAMLError("cannot represent") - monkeypatch.setattr(yaml, "dump", refuse) - assert _update_session_config_yaml(tmp_path, task_description="after", task_name="", studio="") is False + monkeypatch.setattr(yaml, "safe_dump", refuse) + # A file that is there and was not rewritten is a failure, never "not updated" on a success. + with pytest.raises(yaml.YAMLError, match="cannot represent"): + _update_session_config_yaml(tmp_path, task_description="after", task_name="", studio="") assert cfg.read_text(encoding="utf-8") == "meta:\n task_description: before\n" assert sorted(path.name for path in tmp_path.iterdir()) == ["config.yaml"] -def test_the_config_is_replaced_whole_and_keeps_non_ascii_text(tmp_path): +def test_a_config_write_that_fails_on_the_disk_raises_and_leaves_the_file_and_no_temporary_file( + tmp_path, monkeypatch +): + cfg = tmp_path / "config.yaml" + cfg.write_text("meta:\n task_description: before\n", encoding="utf-8") + + def full(*_args, **_kwargs): + raise OSError(28, "No space left on device") + + monkeypatch.setattr(os, "replace", full) + with pytest.raises(OSError, match="No space left"): + _update_session_config_yaml(tmp_path, task_description="after", task_name="", studio="") + assert cfg.read_text(encoding="utf-8") == "meta:\n task_description: before\n" + assert sorted(path.name for path in tmp_path.iterdir()) == ["config.yaml"] + + +def test_the_config_is_replaced_whole_and_non_ascii_text_reads_back_as_it_was_given(tmp_path): cfg = tmp_path / "config.yaml" cfg.write_text("meta: {}\n", encoding="utf-8") assert _update_session_config_yaml(tmp_path, task_description="Café table", task_name="", studio="") is True - assert "Café table" in cfg.read_text(encoding="utf-8") + # Escaped in the file, as the recorder escapes it, and the same text once read. + assert cfg.read_bytes().isascii() + assert yaml.safe_load(cfg.read_bytes())["meta"]["task_description"] == "Café table" assert sorted(path.name for path in tmp_path.iterdir()) == ["config.yaml"] @@ -364,3 +415,840 @@ def test_a_linked_episode_is_not_followed_and_a_plain_directory_is_not_made_an_a assert (result.updated_episodes, result.missing_episodes) == (["episode_0"], ["episode_1"]) assert zarr.open_group(str(outside), mode="r").attrs["task_description"] == "untouched" assert list(aligned.iterdir()) == [] + + +# --- a studio correction in place -------------------------------------------------------------------------------- + + +def _tree(root: Path) -> dict[str, bytes]: + """Every file under ``root`` with its bytes, by path relative to it.""" + return {str(path.relative_to(root)): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} + + +def _recorded_session(root: Path, name: str = "session_a", takes: int = 2, aligned: bool = True) -> Path: + """A session as the recording service leaves it, with a pending take, recorded data and manifests, and + the time-aligned copy beside it.""" + session = root / name + for index in range(takes): + group = zarr.open_group(str(session / f"episode_{index}"), mode="w") + group.attrs.update({"task_description": "pour water", "episode_length": 10}) + group.create_array("pose", shape=(4,), dtype="f4")[:] = index + (session / f"episode_{index}" / "head.mp4").write_bytes(b"video bytes") + zarr.open_group(str(session / f"episode_{takes}.pending"), mode="w").attrs["task_description"] = "pour water" + (session / ".recording").mkdir() + (session / ".recording" / "episode_0.json").write_text('{"studio": "Kitchen", "task": "pour water"}') + (session / "config.yaml").write_text("meta:\n egocap_station_name: Bench A\n task_description: pour water\n") + if aligned: + copy = zarr.open_group(str(root / f"{name}_aligned"), mode="w") + copy.attrs["studio"] = "Kitchen" + copy.create_group("episode_0").attrs["studio"] = "Kitchen" + (root / f"{name}_aligned" / "config.yaml").write_text("meta:\n studio: Kitchen\n") + return session + + +def test_a_studio_name_is_stored_as_one_plain_segment(monkeypatch): + assert stored_studio_name(" Living room / annex ") == "Living_room_annex" + assert stored_studio_name(" ") == "" + # A studio the task library knows is stored in the library's own spelling. + monkeypatch.setattr("egocap.data_processing.update_episode_task_description.TASK_LIBRARY", {"Dining_Room": []}) + assert stored_studio_name("dining room") == "Dining_Room" + + +def test_a_studio_correction_relabels_the_whole_session_where_it_lies_and_touches_nothing_else(tmp_path): + session = _recorded_session(tmp_path) + before = _tree(tmp_path) + result = update_session_studio(session, " Living room ") + assert (result.zarr_root, result.studio_stored) == (session.resolve(), "Living_room") + assert (result.updated_episodes, result.config_yaml_updated) == (["episode_0", "episode_1"], True) + after = _tree(tmp_path) + # No file appeared, vanished or moved, and only label files differ: the two episodes' own metadata, the + # session's config, and the same three kinds of file in the aligned copy. + assert sorted(after) == sorted(before) + assert sorted(name for name in after if after[name] != before[name]) == [ + "session_a/config.yaml", + "session_a/episode_0/zarr.json", + "session_a/episode_1/zarr.json", + "session_a_aligned/config.yaml", + "session_a_aligned/episode_0/zarr.json", + "session_a_aligned/zarr.json", + ] + for index in (0, 1): + attrs = zarr.open_group(str(session / f"episode_{index}"), mode="r").attrs + assert (attrs["studio"], attrs["task_description"]) == ("Living_room", "pour water") + meta = yaml.safe_load((session / "config.yaml").read_text())["meta"] + assert meta == {"egocap_station_name": "Bench A", "task_description": "pour water", "studio": "Living_room"} + aligned = zarr.open_group(str(tmp_path / "session_a_aligned"), mode="r") + assert (aligned.attrs["studio"], aligned["episode_0"].attrs["studio"]) == ("Living_room", "Living_room") + assert yaml.safe_load((tmp_path / "session_a_aligned" / "config.yaml").read_text())["meta"]["studio"] == ( + "Living_room" + ) + # The session gained no root group, the pending take and the manifest keep what they were recorded with. + assert not (session / "zarr.json").exists() + assert "studio" not in zarr.open_group(str(session / "episode_2.pending"), mode="r").attrs + assert '"studio": "Kitchen"' in (session / ".recording" / "episode_0.json").read_text() + # Said again, it changes nothing. + update_session_studio(session, "Living room") + assert _tree(tmp_path) == after + + +def test_a_studio_correction_of_a_group_with_a_root_relabels_the_root_too(tmp_path): + group_dir = tmp_path / "Kitchen" / "2026-01-02-09-00-00" + store = zarr.open_group(str(group_dir), mode="w") + store.attrs.update({"studio": "Kitchen", "task_description": "pour water", "recording_route_id": "s|g"}) + for index in (0, 1): + store.create_group(f"episode_{index}").attrs["studio"] = "Kitchen" + store.create_group("notes") + result = update_session_studio(group_dir, "Pantry") + assert (result.updated_episodes, result.config_yaml_updated) == (["episode_0", "episode_1"], False) + relabelled = zarr.open_group(str(group_dir), mode="r") + assert relabelled.attrs["studio"] == "Pantry" and relabelled.attrs["task_description"] == "pour water" + assert relabelled.attrs["recording_route_id"] == "s|g" + assert [relabelled[f"episode_{index}"].attrs["studio"] for index in (0, 1)] == ["Pantry", "Pantry"] + # What is not an episode is not labelled, and the group stays where it was recorded. + assert "studio" not in relabelled["notes"].attrs + assert group_dir.is_dir() and not (tmp_path / "Pantry").exists() + assert not (tmp_path / "Kitchen" / "2026-01-02-09-00-00_aligned").exists() + + +def test_a_studio_correction_leaves_a_session_with_no_recorded_take_exactly_as_it_was(tmp_path): + session = _recorded_session(tmp_path, takes=0, aligned=False) + before = _tree(tmp_path) + result = update_session_studio(session, "Pantry") + assert (result.updated_episodes, result.config_yaml_updated) == ([], False) + assert _tree(tmp_path) == before + + +def test_a_studio_correction_labels_only_the_takes_the_aligned_copy_holds(tmp_path): + session = _recorded_session(tmp_path) + update_session_studio(session, "Pantry") + aligned = zarr.open_group(str(tmp_path / "session_a_aligned"), mode="r") + # Take 1 was never aligned: the copy is not given an episode it does not have. + assert sorted(aligned.group_keys()) == ["episode_0"] + + +@pytest.mark.parametrize("studio", ["", " "]) +def test_a_studio_correction_without_a_studio_is_refused_before_anything_is_read(tmp_path, studio): + with pytest.raises(ValueError, match="non-empty studio"): + update_session_studio(tmp_path / "missing", studio) + + +def test_a_studio_correction_of_a_missing_session_raises(tmp_path): + with pytest.raises(FileNotFoundError): + update_session_studio(tmp_path / "missing", "Pantry") + + +def _labels(root: Path, name: str = "session_a") -> dict[str, object]: + """The studio each label file under ``root`` carries, by file, with "-" for a file that carries none.""" + said: dict[str, object] = {} + for path in sorted(root.rglob("zarr.json")): + if ".pending" not in str(path) and "/pose/" not in str(path): + said[str(path.relative_to(root))] = ( + json.loads(path.read_bytes()).get("attributes", {}).get("studio", "-") + ) + for path in sorted(root.rglob("config.yaml")): + said[str(path.relative_to(root))] = (yaml.safe_load(path.read_bytes()).get("meta") or {}).get( + "studio", "-" + ) + return said + + +def _three_takes(root: Path) -> Path: + return _recorded_session(root, takes=3) + + +def test_one_episode_whose_folder_is_read_only_refuses_the_relabel_before_anything_is_written(tmp_path): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + os.chmod(session / "episode_1", 0o555) + try: + if os.access(session / "episode_1", os.W_OK): + pytest.skip("this account writes into a folder whatever its mode") + for _again in range(2): + with pytest.raises(RelabelError) as refused: + update_session_studio(session, "Pantry") + # It names the take, not a directory, and says what became of the session: nothing. + assert str(refused.value) == ( + "episode_1 cannot be rewritten (its folder is read-only), so nothing was changed" + ) + assert refused.value.left_changed == () + assert _tree(tmp_path) == before + finally: + os.chmod(session / "episode_1", 0o755) + # Once the folder can be written the same correction goes through, whole. + assert update_session_studio(session, "Pantry").updated_episodes == ["episode_0", "episode_1", "episode_2"] + assert set(_labels(tmp_path).values()) == {"Pantry"} + + +@pytest.mark.parametrize( + ("damage", "refusal"), + [ + (lambda path: path.write_text('{"attributes": {"recording_epi'), "episode_1 cannot be read"), + (lambda path: path.unlink(), "episode_1 is not a recorded take's metadata"), + (lambda path: path.write_text(""), "episode_1 cannot be read"), + ( + lambda path: path.write_text(json.dumps({"zarr_format": 3, "node_type": "array"})), + "episode_1 is not a recorded take's metadata", + ), + (lambda path: path.write_text("[1, 2]"), "episode_1 is not a recorded take's metadata"), + ( + lambda path: path.write_text(json.dumps({"node_type": "group", "attributes": [1]})), + "episode_1 is not a recorded take's metadata", + ), + ], + ids=["truncated", "missing", "empty", "an array", "a list", "attributes that are no mapping"], +) +def test_one_episode_whose_metadata_cannot_be_rewritten_refuses_the_relabel_with_nothing_changed( + tmp_path, damage, refusal +): + session = _three_takes(tmp_path) + damage(session / "episode_1" / "zarr.json") + before = _tree(tmp_path) + with pytest.raises(RelabelError, match=f"^{refusal}, so nothing was changed$"): + update_session_studio(session, "Pantry") + # The takes before it carry what they carried: the session is not left with two studios. + assert _tree(tmp_path) == before + + +@pytest.mark.parametrize( + ("holder", "content", "refusal"), + [ + ("session_a", b"meta: [unclosed\n", "config.yaml cannot be read"), + ("session_a", b"- numeric_sources\n", "config.yaml does not hold the session's settings"), + ( + "session_a_aligned", + b"meta:\n station: Caf\xe9\n", + "the time-aligned copy's config.yaml cannot be read", + ), + ], +) +def test_a_config_that_will_not_be_rewritten_refuses_the_relabel_with_nothing_changed( + tmp_path, holder, content, refusal +): + session = _three_takes(tmp_path) + (tmp_path / holder / "config.yaml").write_bytes(content) + before = _tree(tmp_path) + with pytest.raises(RelabelError, match=f"^{refusal}, so nothing was changed$"): + update_session_studio(session, "Pantry") + assert _tree(tmp_path) == before + + +def test_the_session_and_the_copy_are_checked_for_a_read_only_folder_and_an_unreadable_config( + tmp_path, monkeypatch +): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + monkeypatch.setattr(relabel, "_unwritable", lambda directory: directory.name == "session_a") + with pytest.raises(RelabelError, match=r"^config.yaml cannot be rewritten \(its folder is read-only\)"): + update_session_studio(session, "Pantry") + monkeypatch.undo() + real = Path.read_bytes + + def unreadable(self): + # Read once to be parsed, and gone when its bytes are taken to be put back later. + if self.name == "config.yaml" and unreadable.reads.setdefault(self, 0) == 1: + raise OSError("vanished") + if self.name == "config.yaml": + unreadable.reads[self] += 1 + return real(self) + + unreadable.reads = {} + monkeypatch.setattr(Path, "read_bytes", unreadable) + with pytest.raises(RelabelError, match="^config.yaml cannot be read, so nothing was changed$"): + update_session_studio(session, "Pantry") + monkeypatch.undo() + assert _tree(tmp_path) == before + + +#: The files a relabel of the three-take session rewrites, in the order it writes them: the session's episodes, +#: its config, then the copy's episode, own label and config. +WRITTEN = [ + "session_a/episode_0/zarr.json", + "session_a/episode_1/zarr.json", + "session_a/episode_2/zarr.json", + "session_a/config.yaml", + "session_a_aligned/episode_0/zarr.json", + "session_a_aligned/zarr.json", + "session_a_aligned/config.yaml", +] + + +@pytest.mark.parametrize("failing", range(len(WRITTEN))) +def test_a_write_that_fails_part_way_puts_back_every_label_already_written(tmp_path, monkeypatch, failing): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + writes: list[str] = [] + real = relabel._replace_file + + def fails_once(path: Path, content: bytes) -> None: + writes.append(str(path.relative_to(tmp_path))) + if len(writes) == failing + 1: + raise OSError(28, "No space left on device") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", fails_once) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + assert str(failed.value) == ( + "the labels could not all be written; those already written were put back, so nothing was changed" + ) + assert failed.value.left_changed == () + # Every file is what it was, byte for byte: the answer was a failure, and the session has one studio. + assert _tree(tmp_path) == before + # Written in one order up to the file that failed, then put back from the last written to the first. + assert writes == [*WRITTEN[: failing + 1], *reversed(WRITTEN[:failing])] + monkeypatch.undo() + # The fault gone, the same correction ends as an uninterrupted one does. + update_session_studio(session, "Pantry") + assert set(_labels(tmp_path).values()) == {"Pantry"} + + +def test_a_label_that_cannot_be_put_back_is_named_in_the_failure_and_the_rest_is_put_back(tmp_path, monkeypatch): + session = _three_takes(tmp_path) + before = _labels(tmp_path) + real = relabel._replace_file + seen: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + seen.append(path) + # The third take cannot be written, and after that neither can the first: it is not put back. + if path == session / "episode_2" / "zarr.json" or ( + path == session / "episode_0" / "zarr.json" and len(seen) > 3 + ): + raise OSError(5, "Input/output error") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + assert str(failed.value) == ( + "the labels could not all be written, and episode_0 could not be put back: it says Pantry now, and " + "the rest what they said before" + ) + assert failed.value.left_changed == ("episode_0",) + assert _labels(tmp_path) == {**before, "session_a/episode_0/zarr.json": "Pantry"} + + +def test_two_labels_that_cannot_be_put_back_are_both_named(tmp_path, monkeypatch): + session = _three_takes(tmp_path) + real = relabel._replace_file + wrote: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + wrote.append(path) + # Three takes are written, the session's config cannot be, and then nothing can. + if len(wrote) > 3: + raise OSError(5, "Input/output error") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + assert failed.value.left_changed == ("episode_2", "episode_1", "episode_0") + assert "episode_2, episode_1, episode_0 could not be put back: they say Pantry now" in str(failed.value) + + +def test_a_plan_is_checked_without_writing_and_writes_when_applied(tmp_path): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + plan = plan_session_studio(session, " pantry north ") + assert (plan.studio_stored, plan.episodes) == ("pantry_north", ["episode_0", "episode_1", "episode_2"]) + assert _tree(tmp_path) == before + result = plan.apply() + assert (result.studio_stored, result.config_yaml_updated) == ("pantry_north", True) + assert set(_labels(tmp_path).values()) == {"pantry_north"} + # A session with no recorded take gives a plan that changes nothing. + empty = tmp_path / "session_b" + (empty / "episode_0.pending").mkdir(parents=True) + (empty / "config.yaml").write_text("meta: {}\n") + nothing = plan_session_studio(empty, "Pantry") + assert (nothing.episodes, nothing.apply().updated_episodes) == ([], []) + assert (empty / "config.yaml").read_text() == "meta: {}\n" + + +def test_a_rewritten_file_keeps_the_permissions_of_the_file_it_replaces(tmp_path): + session = _three_takes(tmp_path) + modes = { + # As the recorder leaves a routed group's stamp, as somebody made a take read-only, and a config + # opened to a second account. + session / "episode_0" / "zarr.json": 0o600, + session / "episode_1" / "zarr.json": 0o440, + session / "config.yaml": 0o664, + tmp_path / "session_a_aligned" / "zarr.json": 0o640, + } + for path, mode in modes.items(): + os.chmod(path, mode) + previous = os.umask(0o022) + try: + update_session_studio(session, "Pantry") + # The task correction writes group metadata through the Zarr library, and keeps them the same. + update_episode_task_description(session, "0-2", task_description="wipe the table") + finally: + os.umask(previous) + assert {path: stat.S_IMODE(path.stat().st_mode) for path in modes} == modes + assert set(_labels(tmp_path).values()) == {"Pantry"} + + +def test_each_rewritten_file_and_its_folder_are_synced_as_the_recorder_syncs_them(tmp_path, monkeypatch): + session = _three_takes(tmp_path) + synced: list[str] = [] + real = os.fsync + + def recorded(fd: int) -> None: + synced.append("folder" if stat.S_ISDIR(os.fstat(fd).st_mode) else "file") + real(fd) + + monkeypatch.setattr(os, "fsync", recorded) + update_session_studio(session, "Pantry") + # Each file is synced before it takes its name, and its folder after. + assert synced == ["file", "folder"] * len(WRITTEN) + synced.clear() + update_episode_task_description(session, "0", task_description="wipe the table") + # The task correction writes the take's metadata through Zarr and syncs it and its folder afterwards, then + # config.yaml as above, and the same two in the copy. + assert synced == ["file", "folder"] * 4 + + +def test_stray_files_of_an_interrupted_correction_are_removed_and_nothing_else_is(tmp_path): + session = _three_takes(tmp_path) + kept = _tree(tmp_path) + strays = [ + session / "episode_0" / "zarr.3c9fa0c9aabb.partial", + session / "episode_1" / ".zarr.json.s2sswa6m.tmp", + session / ".config.yaml.s2sswa6m.tmp", + session / "episode_2" / "..zattrs.abcd1234.tmp", + tmp_path / "session_a_aligned" / ".config.yaml.x1.tmp", + tmp_path / "session_a_aligned" / "episode_0" / "zarr.0123.partial", + ] + for stray in strays: + stray.write_text("half a file") + # Left long ago: a staging file made within the last minute may still be a writer's. + os.utime(stray, (0, 0)) + # Named like a stray and not one: a folder, a link, a file somewhere a correction never writes, and a file + # whose name only resembles the pattern. + (session / "zarr.folder.partial").mkdir() + (session / "episode_0" / ".config.yaml.link.tmp").symlink_to(session / "config.yaml") + (session / "episode_3.pending" / "zarr.aa.partial").write_text("a take being written") + (session / ".recording" / ".config.yaml.kept.tmp").write_text("the recorder's own") + (session / "episode_0" / "pose" / "zarr.bb.partial").write_text("inside an array") + (session / "episode_0" / "notes.partial").write_text("an operator's file") + untouched = _tree(tmp_path) + removed = remove_interrupted_writes(session) + assert sorted(removed) == sorted(str(stray.relative_to(tmp_path)) for stray in strays) + left = _tree(tmp_path) + assert left == {name: data for name, data in untouched.items() if name not in removed} + assert all(left[name] == data for name, data in kept.items()) + assert (session / "zarr.folder.partial").is_dir() and ( + session / "episode_0" / ".config.yaml.link.tmp" + ).is_symlink() + # Nothing left to remove; a session with no aligned copy, and one whose copy is a link, are handled alike. + assert remove_interrupted_writes(session) == [] + alone = _recorded_session(tmp_path, "session_b", aligned=False) + (tmp_path / "session_b_aligned").symlink_to(tmp_path / "session_a_aligned") + (tmp_path / "session_a_aligned" / ".config.yaml.y2.tmp").write_text("not session_b's") + os.utime(tmp_path / "session_a_aligned" / ".config.yaml.y2.tmp", (0, 0)) + assert remove_interrupted_writes(alone) == [] + assert (tmp_path / "session_a_aligned" / ".config.yaml.y2.tmp").exists() + + +def _older_layout(root: Path) -> Path: + """A session in Zarr's format 2, one of whose takes has no attribute file, as a group with no attribute + of its own has none.""" + session = root / "session_v2" + group = zarr.open_group(str(session), mode="w", zarr_format=2) + group.attrs["studio"] = "Kitchen" + group.create_group("episode_0").attrs["task_description"] = "pour water" + group.create_group("episode_1") + (session / "episode_1" / ".zattrs").unlink(missing_ok=True) + return session + + +def test_a_session_in_the_older_zarr_layout_is_relabelled_in_its_own_attribute_files(tmp_path): + session = _older_layout(tmp_path) + result = update_session_studio(session, "Pantry") + assert result.updated_episodes == ["episode_0", "episode_1"] and result.config_yaml_updated is False + again = zarr.open_group(str(session), mode="r") + assert [again.attrs["studio"], again["episode_0"].attrs["studio"], again["episode_1"].attrs["studio"]] == [ + "Pantry" + ] * 3 + assert again["episode_0"].attrs["task_description"] == "pour water" + # A directory that is no group in either layout is not given attributes of one. + (session / "episode_0" / ".zgroup").unlink() + with pytest.raises( + RelabelError, match="^episode_0 is not a recorded take's metadata, so nothing was changed$" + ): + update_session_studio(session, "Kitchen") + + +def test_a_failed_relabel_of_the_older_layout_removes_the_attribute_file_it_created(tmp_path, monkeypatch): + session = _older_layout(tmp_path) + before = _tree(tmp_path) + assert "session_v2/episode_1/.zattrs" not in before + real = relabel._replace_file + + def the_sessions_own_fails(path: Path, content: bytes) -> None: + if path.parent == session: + raise OSError(28, "No space left on device") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", the_sessions_own_fails) + with pytest.raises(RelabelError, match="so nothing was changed$"): + update_session_studio(session, "Pantry") + assert _tree(tmp_path) == before + monkeypatch.undo() + # The task correction writes through Zarr, and keeps the permissions of a file only where there was one. + update_episode_task_description(session, "1", task_description="wipe the table") + assert zarr.open_group(str(session), mode="r")["episode_1"].attrs["task_description"] == "wipe the table" + + +def test_a_studio_typed_with_a_combining_accent_is_the_studio_typed_precomposed(): + assert stored_studio_name("Cafe\u0301") == stored_studio_name("Caf\u00e9") == "Caf\u00e9" + + +def test_a_task_correction_refuses_a_config_it_will_not_rewrite_before_it_writes_anything(tmp_path): + session = _three_takes(tmp_path) + (tmp_path / "session_a_aligned" / "config.yaml").write_text("- a list\n") + before = _tree(tmp_path) + # The file is named as the copy's, so the sentence says which of the two it is. + with pytest.raises( + SessionConfigError, match="^the time-aligned copy's config.yaml does not hold the session's settings$" + ): + update_episode_task_description(session, "0-2", task_description="wipe the table") + assert _tree(tmp_path) == before + (session / "config.yaml").write_text("meta: [unclosed\n") + with pytest.raises(SessionConfigError, match="^config.yaml cannot be read$"): + update_episode_task_description(session, "0", task_description="wipe the table") + + +def test_a_task_correction_says_when_it_changes_the_sessions_own_task_before_it_writes(tmp_path): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + seen: list[dict] = [] + # Some of the takes: the session's own task stays, and nobody is told. + part = update_episode_task_description( + session, "0-1", task_description="wipe the table", on_session_task_change=lambda: seen.append({}) + ) + assert (part.session_task_updated, seen) == (False, []) + # Every take: told once, before the first write, when nothing has changed yet. + session_b = _recorded_session(tmp_path, "session_b", takes=2, aligned=False) + untouched = _tree(session_b) + whole = update_episode_task_description( + session_b, + "0-9", + task_description="wipe the table", + on_session_task_change=lambda: seen.append(_tree(session_b)), + ) + assert whole.session_task_updated is True and seen == [untouched] + assert before != _tree(tmp_path) + + +# --- the task correction is checked whole, and put back, as the studio relabel is -------------------------------- + + +def _tasks(root: Path) -> dict[str, object]: + """The task each label file under ``root`` carries, by file, with "-" for a file that carries none.""" + said: dict[str, object] = {} + for path in sorted(root.rglob("zarr.json")): + if ".pending" not in str(path) and "/pose/" not in str(path): + attributes = json.loads(path.read_bytes()).get("attributes", {}) + said[str(path.relative_to(root))] = attributes.get("task_description", "-") + for path in sorted(root.rglob("config.yaml")): + meta = yaml.safe_load(path.read_bytes()).get("meta") or {} + said[str(path.relative_to(root))] = meta.get("task_description", "-") + return said + + +def test_a_take_the_task_correction_cannot_rewrite_refuses_it_whole_before_anything_is_written(tmp_path): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + told: list[int] = [] + os.chmod(session / "episode_1", 0o555) + try: + if os.access(session / "episode_1", os.W_OK): + pytest.skip("this account writes into a folder whatever its mode") + # The same on every repeat: the takes before the one that cannot be rewritten are never written first. + for _again in range(2): + with pytest.raises(RelabelError) as refused: + update_episode_task_description( + session, + "0-2", + task_description="wipe the table", + on_session_task_change=lambda: told.append(1), + ) + assert str(refused.value) == ( + "episode_1 cannot be rewritten (its folder is read-only), so nothing was changed" + ) + assert refused.value.left_changed == () + assert _tree(tmp_path) == before + finally: + os.chmod(session / "episode_1", 0o755) + # Refused before the first write, so nobody was told the session's own task would change. + assert told == [] + update_episode_task_description(session, "0-2", task_description="wipe the table") + assert set(_tasks(tmp_path).values()) == {"wipe the table"} + + +@pytest.mark.parametrize( + ("damaged", "refusal"), + [ + ("session_a/episode_2/zarr.json", "episode_2 cannot be read"), + ("session_a_aligned/episode_0/zarr.json", "the time-aligned copy's episode_0 cannot be read"), + ("session_a_aligned/zarr.json", "the time-aligned copy's own label cannot be read"), + ], +) +def test_a_take_whose_metadata_cannot_be_read_refuses_the_task_correction_with_nothing_changed( + tmp_path, damaged, refusal +): + session = _three_takes(tmp_path) + (tmp_path / damaged).write_text('{"attributes": {"task_descr') + before = _tree(tmp_path) + with pytest.raises(RelabelError, match=f"^{refusal}, so nothing was changed$"): + update_episode_task_description(session, "0-2", task_description="wipe the table") + assert _tree(tmp_path) == before + + +#: How many files a task correction of every take of the three-take session writes: three takes, the +#: session's config, then the copy's own label, its take and its config. +TASK_WRITES = 7 + + +@pytest.mark.parametrize("failing", range(TASK_WRITES)) +def test_a_task_correction_whose_write_fails_part_way_puts_back_what_it_wrote(tmp_path, monkeypatch, failing): + import zarr.storage._local as zarr_files + + session = _three_takes(tmp_path) + before = _tree(tmp_path) + writes: list[str] = [] + through_zarr, whole_file = zarr_files._put, relabel._replace_file + stopped = OSError(28, "No space left on device") + + def put(path, value, *args, **kwargs): + # A take's metadata goes through the Zarr library. + writes.append(str(Path(path).relative_to(tmp_path))) + if len(writes) == failing + 1: + raise stopped + return through_zarr(path, value, *args, **kwargs) + + def replace(path: Path, content: bytes) -> None: + # config.yaml is replaced whole, and so is every file that is put back. + writes.append(str(path.relative_to(tmp_path))) + if len(writes) == failing + 1: + raise stopped + whole_file(path, content) + + monkeypatch.setattr(zarr_files, "_put", put) + monkeypatch.setattr(relabel, "_replace_file", replace) + with pytest.raises(RelabelError) as failed: + update_episode_task_description(session, "0-2", task_description="wipe the table") + assert str(failed.value) == ( + "the labels could not all be written; those already written were put back, so nothing was changed" + ) + assert failed.value.left_changed == () + # The answer was a failure, and every take says the task it said: byte for byte. + assert _tree(tmp_path) == before + assert len(writes) >= failing + 1 + monkeypatch.undo() + update_episode_task_description(session, "0-2", task_description="wipe the table") + assert set(_tasks(tmp_path).values()) == {"wipe the table"} + + +def test_a_take_the_task_correction_could_not_put_back_is_named_and_the_rest_is_put_back(tmp_path, monkeypatch): + session = _three_takes(tmp_path) + before = _tasks(tmp_path) + real = relabel._replace_file + + def disk(path: Path, content: bytes) -> None: + # The session's config cannot be written, and after that neither can the first take: it is not put back. + if path.name == "config.yaml" or path.parent.name == "episode_0": + raise OSError(5, "Input/output error") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + with pytest.raises(RelabelError) as failed: + update_episode_task_description(session, "0-2", task_description="wipe the table") + assert str(failed.value) == ( + "the labels could not all be written, and episode_0 could not be put back: it carries the new task now, " + "and the rest what they said before" + ) + assert failed.value.left_changed == ("episode_0",) + assert _tasks(tmp_path) == {**before, "session_a/episode_0/zarr.json": "wipe the table"} + + +# --- the answer of a failed relabel is read from the disk -------------------------------------------------------- + + +@pytest.mark.parametrize("failing", range(len(WRITTEN))) +def test_a_write_that_fails_after_its_file_was_replaced_is_put_back_like_one_that_was_written( + tmp_path, monkeypatch, failing +): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + real = relabel._sync_directory + synced: list[Path] = [] + + def sync(directory: Path) -> None: + # The file has its new name by now: the write raises, and the label on the disk is the new one. + synced.append(directory) + if len(synced) == failing + 1: + raise OSError(5, "Input/output error") + real(directory) + + monkeypatch.setattr(relabel, "_sync_directory", sync) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + assert str(failed.value) == ( + "the labels could not all be written; those already written were put back, so nothing was changed" + ) + assert failed.value.left_changed == () + # "Nothing was changed" is what the disk says too, the file whose write raised included. + assert _tree(tmp_path) == before + assert set(_labels(tmp_path).values()) <= {"Kitchen", "-"} + + +def test_a_put_back_is_judged_by_what_the_file_holds_and_not_by_whether_it_raised(tmp_path, monkeypatch): + session = _three_takes(tmp_path) + before = _tree(tmp_path) + real_replace, real_sync = relabel._replace_file, relabel._sync_directory + replaced: list[Path] = [] + synced: list[Path] = [] + + def replace(path: Path, content: bytes) -> None: + replaced.append(path) + # The fifth file cannot be written at all. + if len(replaced) == 5: + raise OSError(28, "No space left on device") + real_replace(path, content) + + def sync(directory: Path) -> None: + synced.append(directory) + # Four writes were synced; the sync of the second file put back raises, after the file is back. + if len(synced) == 6: + raise OSError(5, "Input/output error") + real_sync(directory) + + monkeypatch.setattr(relabel, "_replace_file", replace) + monkeypatch.setattr(relabel, "_sync_directory", sync) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + # Every file holds what it held, so nothing is named as left changed. + assert _tree(tmp_path) == before + assert failed.value.left_changed == () + assert str(failed.value) == ( + "the labels could not all be written; those already written were put back, so nothing was changed" + ) + + +def test_a_label_that_cannot_be_read_after_a_failure_is_named_since_nothing_shows_it_was_put_back( + tmp_path, monkeypatch +): + session = _three_takes(tmp_path) + real_replace, real_read = relabel._replace_file, Path.read_bytes + failed_once: list[Path] = [] + + def replace(path: Path, content: bytes) -> None: + if path.name == "config.yaml" and not failed_once: + failed_once.append(path) + raise OSError(28, "No space left on device") + real_replace(path, content) + + def read(self: Path) -> bytes: + # Once the relabel has failed, the second take's metadata cannot be read any more. + if failed_once and self == session / "episode_1" / "zarr.json": + raise OSError(5, "Input/output error") + return real_read(self) + + monkeypatch.setattr(relabel, "_replace_file", replace) + monkeypatch.setattr(Path, "read_bytes", read) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + assert failed.value.left_changed == ("episode_1",) + + +def test_the_copys_own_label_is_called_that_when_it_cannot_be_put_back(tmp_path, monkeypatch): + session = _three_takes(tmp_path) + copy = tmp_path / "session_a_aligned" + real = relabel._replace_file + wrote: list[Path] = [] + + def disk(path: Path, content: bytes) -> None: + wrote.append(path) + # The copy's config cannot be written, and after that neither can the copy's own label. + if path == copy / "config.yaml" or (path == copy / "zarr.json" and len(wrote) > 6): + raise OSError(5, "Input/output error") + real(path, content) + + monkeypatch.setattr(relabel, "_replace_file", disk) + with pytest.raises(RelabelError) as failed: + update_session_studio(session, "Pantry") + assert failed.value.left_changed == ("the time-aligned copy's own label",) + assert str(failed.value) == ( + "the labels could not all be written, and the time-aligned copy's own label could not be put back: " + "it says Pantry now, and the rest what they said before" + ) + + +# --- staging files, and config.yaml as the recorder writes it ---------------------------------------------------- + + +def test_a_staging_file_younger_than_a_minute_is_left_for_the_writer_it_may_belong_to(tmp_path): + session = _three_takes(tmp_path) + copy = tmp_path / "session_a_aligned" + young = [copy / "zarr.0a1b2c3d.partial", session / "episode_0" / ".zarr.json.live.tmp"] + old = [copy / "episode_0" / "zarr.4e5f.partial", session / ".config.yaml.dead.tmp"] + for stray in (*young, *old): + stray.write_text("half a file") + now = 1_800_000_000.0 + for stray in young: + os.utime(stray, (now - 59, now - 59)) + for stray in old: + os.utime(stray, (now - 61, now - 61)) + # A writer outside this process's locks (an aligner run by hand) may be about to rename a young one. + removed = remove_interrupted_writes(session, now=now) + assert sorted(removed) == sorted(str(stray.relative_to(tmp_path)) for stray in old) + assert all(stray.exists() for stray in young) and not any(stray.exists() for stray in old) + # Asked again a minute later, they are strays like any other. + assert sorted(remove_interrupted_writes(session, now=now + 60)) == sorted( + str(stray.relative_to(tmp_path)) for stray in young + ) + + +def test_a_stray_that_cannot_be_removed_is_left_for_the_check_that_names_its_folder(tmp_path): + session = _three_takes(tmp_path) + stuck = session / "episode_1" / ".zarr.json.dead.tmp" + gone = session / "episode_0" / ".zarr.json.dead.tmp" + for stray in (stuck, gone): + stray.write_text("half a file") + os.utime(stray, (0, 0)) + os.chmod(session / "episode_1", 0o555) + try: + if os.access(session / "episode_1", os.W_OK): + pytest.skip("this account writes into a folder whatever its mode") + # Not raised: the relabel's own check says the folder is read-only, in a sentence. + assert remove_interrupted_writes(session) == ["session_a/episode_0/.zarr.json.dead.tmp"] + assert stuck.exists() + with pytest.raises(RelabelError, match="^episode_1 cannot be rewritten"): + update_session_studio(session, "Pantry") + finally: + os.chmod(session / "episode_1", 0o755) + + +def test_config_is_rewritten_as_the_recorder_writes_it_so_a_reader_of_any_locale_still_reads_it(tmp_path): + from egocap.recording.episode_layout import write_yaml_atomic + + session = _recorded_session(tmp_path, takes=1, aligned=False) + config = session / "config.yaml" + write_yaml_atomic(config, {"meta": {"egocap_station_name": "B\u00e4nk A", "task_description": "pour water"}}) + recorded = config.read_bytes() + assert recorded.isascii() and b"B\\xE4nk A" in recorded + update_session_studio(session, "Pantry") + update_episode_task_description(session, "0", task_description="Caf\u00e9 table") + written = config.read_bytes() + # Escaped as the recorder escapes it: the station's line is the line it was, in any locale's reading. + assert written.isascii() + assert written.splitlines()[:2] == recorded.splitlines()[:2] + meta = yaml.safe_load(written)["meta"] + assert meta == { + "egocap_station_name": "B\u00e4nk A", + "task_description": "Caf\u00e9 table", + "studio": "Pantry", + } + assert yaml.safe_load(config.read_text(encoding="latin-1"))["meta"]["egocap_station_name"] == "B\u00e4nk A" diff --git a/examples/egocap/tests/tools/test_calibrate_station.py b/examples/egocap/tests/tools/test_calibrate_station.py index 9d71a79533..105a09b383 100644 --- a/examples/egocap/tests/tools/test_calibrate_station.py +++ b/examples/egocap/tests/tools/test_calibrate_station.py @@ -22,7 +22,7 @@ import numpy as np import pytest -from egocap.calibration import station_store +from egocap.calibration import provenance, station_store from egocap.calibration.camera_pipeline import ( DEFAULT_LAG_SEARCH_S, EXTRINSICS_FILE, @@ -271,9 +271,30 @@ def test_install_writes_both_head_files_archives_them_and_stamps_the_ledger(head assert ( f"Installed: {HEAD_EXTRINSICS} in {calibration}, with the intrinsics it was solved under\n" in head_run.out ) - # What is installed is what the run solved and left for review, readable by the library's own loaders. - assert json.loads((calibration / HEAD_INTRINSICS).read_text()) == json.loads( - (head_run.review / INTRINSICS_FILE).read_text() + # What is installed is what the run solved and left for review, readable by the library's own loaders, + # with what only the install knows beside it: from when it stands, and that it replaced nothing. + installed = json.loads((calibration / HEAD_INTRINSICS).read_text()) + reviewed = json.loads((head_run.review / INTRINSICS_FILE).read_text()) + assert provenance.without_validity(installed) == reviewed + assert installed["provenance"]["validity"]["supersedes"] is None + # One moment for both files, which is the one the ledger notes. + at = station_store.ledger(calibration)["headset"]["at"] + assert installed["provenance"]["validity"]["valid_from"] == at + # Both files state the layout, what solved them, their grade and the rule they were installed under. + position = json.loads((calibration / HEAD_EXTRINSICS).read_text()) + for record, part in ((installed, "intrinsics"), (position, "extrinsics")): + stated = provenance.read(record) + assert (stated["schema_version"], stated["software"], stated["tool"]) == ( + 1, + "egocap", + "camera_calibration", + ) + assert stated["grade"] in ("excellent", "acceptable") + assert stated["valid_from"] == at + assert provenance.read(installed)["install_rule"].startswith("Intrinsics are installed only when excellent") + assert provenance.read(position)["install_rule"] == ( + "Extrinsics are installed unless graded bad, and only with the intrinsics they were solved with when " + "those may be installed." ) assert load_intrinsics(calibration / HEAD_INTRINSICS).image_size_wh == synthetic.SIZE assert load_headset_extrinsics(calibration / HEAD_EXTRINSICS).shape == (4, 4) From a34ceb32316e69127d3b40ab32546835cc692983 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Fri, 27 Nov 2026 15:02:04 -0800 Subject: [PATCH 2/2] egocap: label corrections and device requirements agree with the capture checks The end-of-day label corrections, a station's required tracking devices and the calibration follow-ups were built without the capture checks. This joins the two where each had settled the same thing, keeping one authority for each. The session lock. A correction took the recorder's lock class, which now writes a marker once a second for as long as it is held. A correction, refused or made, therefore left a recorder's marker in the session's lock file: the reader of takes left behind took the session for open, stopped listing its waiting takes and refused Recover and Discard for a watch time. A correction now asks the recording coordinator (hold_closed_session, which is OutputScan.held_closed): the session's marker unchanged between two looks a watch time apart, then its lock, held by SessionHold, which has no marker and writes nothing. A session a recorder has by its lock or by its marker is refused. What the reader knew of the session before the hold is what it knows after, so a correction is taken for a recorder only while it holds the lock. The lock file is opened without following a link and judged by what was opened. Takes that wait. takes_left_behind is the one rule for which takes wait, used by the page's list and by the correction's guard. A take whose discard was started still holds a correction; a take rejected with its data kept is settled and holds none; a folder that holds a record written for another session is refused in a sentence of its own; a take still to be set apart holds a correction of its session's quarantine folder. The refusal names the card that offers Recover and Discard. Take records. scan_session is the one reader of a session's records. A sidecar that cannot be listed is a problem, never an empty session, and such a session is not remembered as finished. Every line is in fixed words: no path, and nothing the system said. The day report reads a quarantined take's studio from the folder it was set apart in, which a correction of the session does not reach. The end-of-day dialog keeps focus when the last waiting take's card leaves it. Tests cover each place where the two meet: the hold and the rule in the recorder's own suites; corrections over the real coordinator against an open session, a waiting take and the page's two commands; a required device and an unreadable stations file refusing Record and a tool's take in one sentence; a tool's take held only by its own devices and kept unjudged; the aligner's two rules on one session; where a quarantined take, a corrected group and a recovered take end; the dialog with the card and both forms. Expectations that were sentences the other side replaced are compared with the new sentences, exactly. The READMEs, the design and the agent rules say the same. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/AGENTS.md | 6 + examples/egocap/DESIGN.md | 4 + examples/egocap/backend/README.md | 86 ++-- .../backend/egocap_web/day_report_routes.py | 122 ++--- .../backend/egocap_web/recording_session.py | 12 + examples/egocap/frontend/README.md | 7 +- .../egocap/frontend/src/WrapUpDialog.test.tsx | 93 +++- examples/egocap/frontend/src/WrapUpDialog.tsx | 6 + .../egocap/frontend/src/dayReportApi.test.ts | 2 +- examples/egocap/frontend/src/dayReportApi.ts | 3 +- examples/egocap/recording/README.md | 13 +- .../recording/egocap/analytics/day_report.py | 13 +- .../egocap/recording/episode_layout.py | 75 ++++ .../recording/recording_service/README.md | 12 +- .../recording/recording_service/__init__.py | 4 +- .../recording_service/output_scan.py | 95 +++- .../egocap/tests/backend/test_auto_align.py | 41 ++ .../tests/backend/test_calibration_routes.py | 155 +++++++ .../backend/test_day_report_real_recorder.py | 39 +- .../tests/backend/test_day_report_routes.py | 8 +- .../test_day_report_with_takes_waiting.py | 421 ++++++++++++++++++ .../unit/test_count_daily_trajectories.py | 16 + .../tests/recording/unit/test_day_report.py | 28 ++ .../recording/unit/test_episode_store.py | 13 +- .../unit/test_take_resolution_layout.py | 105 +++++ .../test_takes_left_behind.py | 196 ++++++++ 26 files changed, 1446 insertions(+), 129 deletions(-) create mode 100644 examples/egocap/tests/backend/test_day_report_with_takes_waiting.py diff --git a/examples/egocap/AGENTS.md b/examples/egocap/AGENTS.md index 8096f42591..6369bc5aba 100644 --- a/examples/egocap/AGENTS.md +++ b/examples/egocap/AGENTS.md @@ -92,6 +92,12 @@ before any file is written. An existing derived episode is refused, never replac labels its manifest froze. Never loosen `assign_output`'s check, and never write a manifest from a correction. A correction holds the recorder's own session lock for its checks and its writes, and one that really changes a routed group's studio or whole task drops the session's route to the group. +- Whether a recorder has a session open, and which of its takes wait, have one definition each, the recorder's: + `OutputScan.held_closed` (through the coordinator's `hold_closed_session`) and `takes_left_behind`. Anything + that writes into a closed session asks them, and holds the session with `SessionHold`, never `SessionLock`: + only a recorder writes a beat. +- A line or a refusal shown to an operator carries no path and nothing a parser, the interpreter or the system + said; `scan_session` is the one reader of a session's take records. - A correction of a session's studio or task that answers with a failure leaves the labels as they were, or names the ones it could not put back, and says so from what the disk holds. - A required device is judged on whether it delivers its data, from the capture session's own reason for its diff --git a/examples/egocap/DESIGN.md b/examples/egocap/DESIGN.md index e9d524753a..6d6e957b5e 100644 --- a/examples/egocap/DESIGN.md +++ b/examples/egocap/DESIGN.md @@ -96,6 +96,10 @@ other recorder on the same output, while a take of that session is being time-al correction of it is being written, while the session holds a take that was interrupted and is still to be filed by, or into, what is being corrected (the recorder files such a take by the labels it was recorded under), and for anything that is not a recorded session inside the recording output. +Whether a recorder has the session open, and which takes wait, are judged by the recorder's own +rules, the ones that list a waiting take with its two commands: the refusal over such a take names +that list, the correction holds the session without marking it as a recorder does, and the take can +be recovered or discarded right after. Either correction is all or nothing: it is checked whole before its first write, a write that still fails puts back what was written, and a correction that answers with a failure either left the session as it was or says, from what the disk holds, which labels it could not put back. A group diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index d597ff6c4f..d5793e5de8 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -233,7 +233,13 @@ The flow is station, devices, record, wrap-up ([`setup_service.py`](egocap_web/s shows exactly the rows it showed before requirements existed. - **A calibration take is held only by the devices its tool uses.** The head-camera tool's take uses the headset and the controllers, the glove tool's all five (`calibration_service.TOOL_DEVICES`); a required device the - tool does not use never holds that take, as the calibration item never does. + tool does not use never holds that take, as the calibration item never does. Being exempt from the capture + checks is a separate matter and changes nothing here: a tool's take is still held by its own devices, by a + station problem and by the recorder's readiness, in the same sentences as Record, and the device and + checks exemptions end with that take. +- **Where a hold is said.** What station setup holds a take for (a required device, a stations file that + cannot be read) is the reason the recording snapshot gives beside Record (`not_ready_reason`), the reason a + refused `start_episode` command carries and the `detail` of a tool's refused take: one sentence, composed here. - **A LiveKit camera passes only while its frames are seen arriving.** The backend is in the room only during a take or a live check of the head calibration, so it goes by what an operator's page reports of its preview (`POST /api/setup/livekit-preview`, [`livekit_sightings.py`](egocap_web/livekit_sightings.py)): frames arriving pass; no frames, an unpublished @@ -307,30 +313,57 @@ waiting to be aligned does not start in the middle of a correction. The lock is (device and inode), so two spellings of one directory, as another letter case is on a disk that folds case, are one lock; a time-aligned copy is refused as a target however its name is cased. -**The recorder's own lock.** A recorder owns a session by a lock on a file in the session's sidecar -(`egocap.recording.episode_layout.SessionLock`), and this backend's snapshot knows only its own recorder. A -correction therefore takes that lock too, without waiting, from before its checks to its last write, and answers -a held one with `this session is open in a recorder; end its batch there before correcting it`. No recorder can -open the session while a correction writes. The lock is taken only where the lock file already exists, which is -every session a recorder opened; nothing is created for a session that is gone or that no recorder ever locked. -For a routed group the session locked is the one its route stamp names. -A lock file that is not a regular file with one name (a link, a folder, a second name for a file elsewhere) is -refused with `this session's lock is not an ordinary file, so its labels are left as they are`, and is not -opened: taking the lock would write through it. +**The recorder's own lock, and its rule for an open session.** A recorder owns a session by a lock on a file in +the session's sidecar (`egocap.recording.episode_layout.SessionLock`) and, for a reader the lock does not reach, +by the beat it writes into that file once a second; this backend's snapshot knows only its own recorder. A +correction therefore asks the recording coordinator to hold the session closed +(`RecordingSessionCoordinator.hold_closed_session`, which is `OutputScan.held_closed`), from before its checks to +its last write. That is the one rule by which a take left behind is listed and resolved: the session's beat +unchanged between two looks a watch time (2.5 s) apart, then its lock, taken without waiting. A session a recorder +has by either sign answers `this session is open in a recorder; end its batch there before correcting it`. The +first correction of a session the coordinator has not looked at waits for the second look; one the coordinator +closed itself (New batch, or a take resolved from the page) waits for nothing. No recorder can open the session +while a correction writes. + +The correction's hold is not a recorder's (`episode_layout.SessionHold`): it has no beat and writes nothing to +the lock file, so the file keeps what its last recorder wrote. A correction, refused or made, is therefore never +taken for a recorder that has the session open: a take the session left behind stays listed, and Recover or +Discard is taken right after. A read of the output that meets the hold sees a lock that is taken, for exactly as +long as it is held. The lock is taken only where the lock file already exists, which is every session a recorder +opened; nothing is created for a session that is gone or that no recorder ever locked. For a routed group the +session held is the one its route stamp names. A lock file that is not a regular file with one name (a link, a +folder, a second name for a file elsewhere) is refused with `this session's lock is not an ordinary file, so its +labels are left as they are`: it is opened without following a link and judged by what was opened, and nothing +is taken through it. **A take still to be filed.** A correction of either label is refused while the session holds a take that is not -settled and whose later filing depends on what is being corrected. That is a take whose manifest carries a -studio and no assignment yet (`an interrupted take of this session must be recovered or discarded first: where -it is filed depends on the labels it was recorded under`): the recording service files it into the group of the -studio and task its manifest froze, and refuses a group whose labels no longer say the same -(`egocap.recording.route.assign_output`), so a correction made first would leave it unrecoverable. And it is a -take that already has its place in the group being corrected (`an interrupted take of this session must be -recovered or discarded first: it is still to be filed in this group`): filed afterwards, it would land in the -corrected group under the labels it was recorded with. An unsettled take recorded with routing off, which is -how this backend records, is filed by no label and holds no correction. While a take record cannot be read, or -the sidecar cannot be listed, both corrections are refused (`a take record of this session cannot be read, so -its labels are left as they are`): nothing shows that no take is waiting. A record that is JSON and no record, -and a session name that cannot be encoded, are refused in sentences like any other. +settled and whose later filing depends on what is being corrected. Which takes are not settled is the recorder's +rule (`recording_service.takes_left_behind`), the one that lists a take under *Takes waiting for a decision* +with Recover and Discard, and the refusal names that card. That is a take whose manifest carries a studio and no +assignment yet (`an interrupted take of this session must be recovered or discarded first, under Takes waiting +for a decision: where it is filed depends on the labels it was recorded under`): the recording service files it +into the group of the studio and task its manifest froze, and refuses a group whose labels no longer say the +same (`egocap.recording.route.assign_output`), so a correction made first would leave it unrecoverable. And it +is a take that is to be filed in the folder being corrected (`an interrupted take of this session must be +recovered or discarded first, under Takes waiting for a decision: it is still to be filed in this group`): one +that already has its place in the routed group, or, for a session's quarantine folder, one the capture checks +marked for it or have not judged yet. Filed afterwards, it would land in the corrected folder under the labels +it was recorded with. An unsettled take recorded with routing off, which is how this backend records, is filed +by no label and holds no correction of its session. A take whose discard was started and did not finish is not +settled, and holds a correction until it is discarded again. A take the integrity check rejected is settled, +also while its data is still on disk: it is never filed, and holds no correction. + +While a take record cannot be read, or the sidecar cannot be listed, both corrections are refused (`a take record +of this session cannot be read, so its labels are left as they are`): nothing shows that no take is waiting. A +session folder that holds a record written for another session was copied or renamed by hand; no command acts +on such a record, and neither does a correction (`a take record in this session's folder was written for another +session: the folder was copied or renamed by hand, so its labels are left as they are`). A record that is JSON +and no record, and a session name that cannot be encoded, are refused in sentences like any other. + +A session's quarantine folder (`_quarantine/`) carries the recording service's stamp, so it is accepted +as a target like a routed group, and a correction of the session itself does not reach it: a take set apart +keeps the labels of the folder it lies in, which is what the report shows for it. The page's forms offer the +places that hold kept or flagged takes only. **A corrected group stops being a destination.** When a correction will leave a routed group's own studio, or its own task, different from what it says now, the owning session's route to that group is dropped @@ -423,9 +456,10 @@ capture server, scripted stand-ins or synthetic data: that is killed part-way (the process, not a failed write) leaves two studios, or part of a task correction, with no reply and nothing that records it; no file is truncated, and the next correction of the session completes it. A time aligner run by hand is not excluded from a correction: only its staging files younger - than a minute are spared. Between the look at a session's lock file and the recorder's own opening of it, - which truncates, the file could be swapped for a link; closing that needs the recorder's lock class to open - without truncating. A take record of an unsupported layout is still reported with the record's full path. + than a minute are spared. Where the session's lock does not reach (another machine on a shared disk) a + correction excludes no recorder: it relies on the beat having been at rest for a watch time before it began. + A take that waits in another station's session is not listed on this station's page, though it holds a + correction of that session the same. - **Running this suite writes inside the checkout.** `tests/backend/test_recordings.py` builds the recordings page (`npm ci && npm run build` in `recordings_frontend/`, which reaches the npm registry and rewrites its git-ignored `node_modules` and `dist`), and `tests/backend/test_preview_routes.py` leaves two sessions under diff --git a/examples/egocap/backend/egocap_web/day_report_routes.py b/examples/egocap/backend/egocap_web/day_report_routes.py index 8494ee55b9..176a2004fe 100644 --- a/examples/egocap/backend/egocap_web/day_report_routes.py +++ b/examples/egocap/backend/egocap_web/day_report_routes.py @@ -14,7 +14,9 @@ time-aligned and while the session holds a take that is still to be filed by, or into, what is being corrected, and replaces each metadata file whole. It holds two locks from before its first check to its last write: this backend's own (session_locks.py), which the aligner and a second correction take, and the -recorder's lock on the session, so that no recorder opens the session meanwhile. It changes labels only; +recorder's lock on the session, so that no recorder opens the session meanwhile. Whether a recorder has the +session open, and which of its takes still wait, are the recorder's own rules (``OutputScan.held_closed``, +``takes_left_behind``): the ones that list a take on the page and resolve it there. It changes labels only; recorded video and tracking stay as captured, a take's manifest keeps what the take was recorded under, and nothing is ever moved: a studio correction relabels the session where it lies, whatever its folder is called. Either correction is all or nothing: it answers with a failure only with the session's labels as they were, @@ -29,7 +31,6 @@ import json import logging import re -import stat import time from collections.abc import Callable, Iterator from dataclasses import dataclass @@ -50,14 +51,16 @@ update_episode_task_description, ) from egocap.recording.episode_layout import ( + FINALIZATION_QUARANTINE, MANIFEST_DIR, ROUTE_ATTR, - UNRESOLVED_PHASES, - SessionLock, - scan_manifests, + LockFileNotPlain, + quarantine_group, + scan_session, write_json_atomic, ) from egocap.recording.route import ROUTES_FILE, forget_group +from recording_service import SessionOpen, takes_left_behind from .recording_command import MAX_TASK_DETAILS_CHARS, control_token_valid, interrupted_take from .request_body import read_authorized_json @@ -83,27 +86,30 @@ #: The studio names that are a folder's bookkeeping and never a studio a take was recorded in, as they compare #: once letter case and underscores are set aside. _RESERVED_STUDIOS = ("unmatched", "unknown") +#: Where the page offers Recover and Discard for a take that waits: the card of that title, which leads the +#: end-of-day dialog the corrections are made in. +_RESOLVE_IT = "must be recovered or discarded first, under Takes waiting for a decision" #: Why a correction is refused while one of the session's takes waits to be recovered or discarded. The #: recording service files such a take by the studio and task its manifest froze, and refuses to file it into a #: group whose labels no longer say the same, so a correction made first would leave the take unrecoverable. UNSETTLED_TAKE = ( - "an interrupted take of this session must be recovered or discarded first: " + f"an interrupted take of this session {_RESOLVE_IT}: " "where it is filed depends on the labels it was recorded under" ) -#: Why a correction of a routed group is refused while a take that already has its place in that group has not -#: been moved there. Recovered later, the take is filed into the group saying the labels it was recorded -#: under, and the corrected group would hold two. -STILL_TO_BE_FILED = ( - "an interrupted take of this session must be recovered or discarded first: " - "it is still to be filed in this group" -) +#: Why a correction of a routed group, or of a session's quarantine folder, is refused while a take that is +#: to be filed there has not been moved there. Recovered later, the take is filed saying the labels it was +#: recorded under, and the corrected folder would hold two. +STILL_TO_BE_FILED = f"an interrupted take of this session {_RESOLVE_IT}: it is still to be filed in this group" #: The same while a take's record cannot be read: nothing shows that no take is still waiting. UNREADABLE_TAKE = "a take record of this session cannot be read, so its labels are left as they are" -#: The file in a session's sidecar that a recorder locks for as long as it has the session open -#: (``episode_layout.SessionLock``). Looked for, never created: the lock is taken only where it exists. -_RECORDER_LOCK = "session.lock" +#: Why a correction is refused for a session directory that holds a record written for another session: the +#: directory is a copy or was renamed, and nothing acts on what it cannot vouch for. No command resolves it. +COPIED_SESSION = ( + "a take record in this session's folder was written for another session: the folder was copied or renamed " + "by hand, so its labels are left as they are" +) #: Why a correction is refused for a session whose lock file is a link, a folder or a file with a second name: -#: taking a recorder's lock opens that file for writing, and it would be written wherever it leads. +#: a recorder writes into that file, and nothing is taken through one that leads elsewhere. LOCK_NOT_A_FILE = "this session's lock is not an ordinary file, so its labels are left as they are" #: Why a correction is refused while a recorder holds the session: this backend's, or any other on the output. OPEN_IN_A_RECORDER = "this session is open in a recorder; end its batch there before correcting it" @@ -326,59 +332,61 @@ def _refuse_with_unsettled_take(owner: Path, target: Path) -> None: """Refuse a correction of either label of ``target`` while the session ``owner`` holds a take that is not settled and is still to be filed by, or into, what is being corrected. + Which takes wait is the recorder's rule (``takes_left_behind``), the one that lists them on the page with + Recover and Discard. A take the integrity check rejected is settled, also while its data is still on disk: + it is never filed, and holds no correction. + One that was recorded to be routed by its studio and has not been given its destination yet: reproduced against :func:`egocap.recording.route.assign_output`, once a routed group's studio or task differs from what such a take's manifest froze, filing the take into the group is refused, so it can no longer be recovered. The frozen values are the invariant; the labels wait for the take. - And one whose destination is the group being corrected: recovered later it is moved there saying the - labels it was recorded under, and the corrected group would hold two studios. A take recorded with - routing off is filed where it was recorded, by no label, and holds no correction. + And one whose destination is the folder being corrected, a routed group or the session's quarantine + folder: recovered later it is moved there saying the labels it was recorded under, and the corrected + folder would hold two studios. A take recorded with routing off is filed where it was recorded, by no + label, and holds no correction of its session. """ - manifests, problems = scan_manifests(owner) - waiting = [manifest for manifest in manifests if manifest.storage_phase in UNRESOLVED_PHASES] + scan = scan_session(owner) + waiting = [left.manifest for left in takes_left_behind(owner, scan) if not left.misplaced] if any(manifest.studio is not None and manifest.assignment is None for manifest in waiting): raise DayReportError(UNSETTLED_TAKE) group = _group_of(target) - placed = (manifest.assignment for manifest in waiting if isinstance(manifest.assignment, dict)) - if group is not None and any(assignment.get("group") == group for assignment in placed): + placed = [manifest.assignment.get("group") for manifest in waiting if isinstance(manifest.assignment, dict)] + # A take the checks have not judged yet may still be set aside, and one they marked for it will be. + if any(manifest.finalization in (None, FINALIZATION_QUARANTINE) for manifest in waiting): + placed.append(quarantine_group(owner.name)) + if group is not None and group in placed: raise DayReportError(STILL_TO_BE_FILED) - # A record that cannot be read, or a sidecar that cannot be listed, may be such a take. - if problems: + # A record written for another session is none of this session's takes, and no command acts on it. + if scan.misplaced: + raise DayReportError(COPIED_SESSION) + # A record that cannot be read, or a sidecar that cannot be listed, may be a take that waits. + if scan.problems: raise DayReportError(UNREADABLE_TAKE) @contextlib.contextmanager -def _closed_to_recorders(owner: Path) -> Iterator[None]: - """Hold the recorder's own lock on the session ``owner`` for the guard and the write, so that no recorder - opens it meanwhile, and refuse when one holds it now. Taken without waiting, and only where the file a - recorder locks is there: every session a recorder opened has one. A session that is gone, of a routed - group that outlived it, has no recorder to exclude, and nothing is created for a session no recorder - ever locked. - - Taking the lock opens its file for writing, so a lock file that is a link, a folder, or a file that has - another name somewhere refuses the correction: nothing is written through it.""" - lock: SessionLock | None = None - try: - # Looked at first, and not followed: taking the lock of a session that has no lock file would create - # one, and taking it through a link would empty the file the link leads to. - found = (owner / MANIFEST_DIR / _RECORDER_LOCK).lstat() - if not stat.S_ISREG(found.st_mode) or found.st_nlink != 1: - raise DayReportError(LOCK_NOT_A_FILE) - lock = SessionLock(owner) - except (FileNotFoundError, NotADirectoryError): - # No recorder ever opened this session, or it is gone: there is none to exclude. - pass - except BlockingIOError: - raise DayReportError(OPEN_IN_A_RECORDER) from None - except OSError: - # A sidecar that cannot be looked into cannot say which takes wait in it either. - raise DayReportError(UNREADABLE_TAKE) from None - try: +def _closed_to_recorders(coordinator: Any, owner: Path) -> Iterator[None]: + """Hold the session ``owner`` closed to every recorder for the guard and the write, and refuse when one has + it open now. + + Asked of the recording coordinator, so that "open" is one rule: the session's beat unchanged between two + looks, and its lock, which is held without a beat of its own (``hold_closed_session``). The first + correction of a session the coordinator has not watched waits for its second look. A session that is + gone, of a routed group that outlived it, has no recorder to exclude, and nothing is created for a session + no recorder ever locked. A lock file that is a link, a folder, or a file that has another name somewhere + refuses the correction.""" + with contextlib.ExitStack() as held: + try: + held.enter_context(coordinator.hold_closed_session(owner)) + except SessionOpen: + raise DayReportError(OPEN_IN_A_RECORDER) from None + except LockFileNotPlain: + raise DayReportError(LOCK_NOT_A_FILE) from None + except OSError: + # A sidecar that cannot be looked into cannot say which takes wait in it either. + raise DayReportError(UNREADABLE_TAKE) from None yield - finally: - if lock is not None: - lock.release() class _GroupRoute: @@ -451,7 +459,7 @@ def _corrected( a worker thread. ``kind`` checks the body's own fields and gives the write, which rewrites the labels of the confined session and says what it changed. ``snapshot`` is the recording coordinator's, taken on the event loop that owns its state, and ``locks`` is shared with the background aligner.""" - _context, _stations, _uptime, root = state + context, _stations, _uptime, root = state target = _confined_session(root, body.get("session")) _refuse_while_recording(snapshot, target) write = kind.prepare(body) @@ -462,7 +470,7 @@ def _corrected( try: owner = _owning_session(root, target) route = _GroupRoute(owner, target) - with _closed_to_recorders(owner): + with _closed_to_recorders(context.coordinator, owner): # Asked under both locks, immediately before the first write. _refuse_with_unsettled_take(owner, target) # What a correction that was killed part-way left behind goes before this one writes. diff --git a/examples/egocap/backend/egocap_web/recording_session.py b/examples/egocap/backend/egocap_web/recording_session.py index 2d43e120ba..4e1fe2fcc6 100644 --- a/examples/egocap/backend/egocap_web/recording_session.py +++ b/examples/egocap/backend/egocap_web/recording_session.py @@ -62,6 +62,7 @@ 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. +A correction of a closed session's labels asks the same looks through ``hold_closed_session``. """ from __future__ import annotations @@ -73,6 +74,7 @@ from dataclasses import dataclass, replace from enum import Enum from functools import partial +from pathlib import Path from typing import TYPE_CHECKING, Any, TypeVar from capture_server.client import CameraImage, CaptureFrame @@ -914,6 +916,16 @@ def pending_takes(self) -> tuple[PendingTake, ...]: + tuple(PendingTake(p, False, known) for p in earlier) ) + def hold_closed_session(self, session_path: Path) -> contextlib.AbstractContextManager[None]: + """Hold a session no recorder has open, for a writer that is not a recorder: a correction of its labels. + + The session is judged by the same looks at its beat as a take that is listed or resolved here, and its + lock is held for the block (see ``OutputScan.held_closed``). ``SessionOpen`` when a recorder has it. + The hold writes no beat, so a take the session left behind stays listed and can be resolved right + after. Blocking: entered and left in a worker thread. + """ + return self._output_scan.held_closed(session_path) + def recordings_disk_problem(self, exc: BaseException) -> str | None: """What the recordings disk refused, when ``exc`` failed on a file under the recording output. diff --git a/examples/egocap/frontend/README.md b/examples/egocap/frontend/README.md index 9ddc047965..a932fb095c 100644 --- a/examples/egocap/frontend/README.md +++ b/examples/egocap/frontend/README.md @@ -287,7 +287,8 @@ The page is built for an operator mid-take: the cameras fill it, and everything 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. + not count (one that cannot be read, or one of a session folder copied by hand) is a line over its session, and + so is a session whose records cannot be listed at all. - 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. @@ -298,6 +299,10 @@ The page is built for an operator mid-take: the cameras fill it, and everything changed (`left_changed`, carried by `CorrectionRefused` in `dayReportApi.ts`) the report is read again, so the table shows what the recording holds. A form that was sent is empty again, which disables its button: focus moves from the button to the form's first field, so it does not fall out of the dialog. + - A correction refused over a take that waits says so with the name of the card above (`... must be recovered or + discarded first, under Takes waiting for a decision: ...`). The take is resolved there and the correction sent + again; what was typed is kept. When the last waiting take is resolved its card leaves the dialog, and the focus + its button held is put on the dialog itself rather than falling to the page behind. - 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 diff --git a/examples/egocap/frontend/src/WrapUpDialog.test.tsx b/examples/egocap/frontend/src/WrapUpDialog.test.tsx index 59b6f484d5..66ea3387e7 100644 --- a/examples/egocap/frontend/src/WrapUpDialog.test.tsx +++ b/examples/egocap/frontend/src/WrapUpDialog.test.tsx @@ -734,8 +734,8 @@ describe("correcting a session's studio", () => { it("shows each take's studio once any take has one, and what the session is recorded as", async () => { renderDialog({}, fakeBackend(labelled(["Kitchen", "Kitchen", "Kitchen", null, null]))); const sessions = await region("Sessions"); - expect(within(sessions).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Outcome", "Time", "Task", "Studio", "Operator", "Issues"]); - expect(within(sessions).getAllByRole("row").slice(1).map((row) => row.querySelectorAll("td")[4].textContent)).toEqual(["Kitchen", "Kitchen", "Kitchen", "—", "—"]); + expect(within(sessions).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Outcome", "Time", "Task", "Studio", "Operator", "What was wrong"]); + expect(within(sessions).getAllByRole("row").slice(1).map((row) => row.querySelectorAll("td")[4].textContent)).toEqual(["Kitchen", "Kitchen", "Kitchen", "—", "—", "—"]); expect(within(await studioForm()).getByText(/^Recorded as Kitchen\. Only the label in the recording changes/)).toBeTruthy(); }); @@ -774,7 +774,7 @@ describe("correcting a session's studio", () => { it("shows the backend's reason for a refused correction, such as a take still waiting, and keeps what was typed", async () => { const backend = fakeBackend(); - const waiting = "an interrupted take of this session must be recovered or discarded first: where it is filed depends on the labels it was recorded under"; + const waiting = "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a decision: where it is filed depends on the labels it was recorded under"; backend.correctStudio = vi.fn(async () => { throw new SettingsHttpError(waiting); }); @@ -987,6 +987,93 @@ describe("keyboard focus in the end-of-day dialog", () => { }); }); +describe("a correction beside takes that wait", () => { + const OK: RecordingCommandResult = { outcome: "ok", reason: null }; + const WAITING = "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a decision: where it is filed depends on the labels it was recorded under"; + /** The fixture's day with a studio on every take of its session. */ + const labelled = (): DayReportReply => { + const [session] = DAY_REPORT_FIXTURE.report.sessions; + return { ...DAY_REPORT_FIXTURE, report: { ...DAY_REPORT_FIXTURE.report, sessions: [{ ...session, episodes: session.episodes.map((episode) => ({ ...episode, studio: "Kitchen" })) }] } }; + }; + /** One take an earlier session left behind, with the two commands. */ + const controls = (overrides: Partial = {}): PendingTakeControls => ({ takes: [earlierTake()], lastResult: null, blockedReason: null, recover: vi.fn(async () => OK), discard: vi.fn(async () => OK), ...overrides }); + /** The dialog with waiting takes over a labelled day, and a way to hand it the next snapshot's takes. */ + function renderBoth(pending: PendingTakeControls, backend = fakeBackend(labelled())) { + const props: WrapUpDialogProps = { open: true, onClose: vi.fn(), controlToken: "tok", backend, pending }; + const view = render(); + return { props, backend, update: (next: PendingTakeControls) => view.rerender() }; + } + + it("leads with the waiting takes and still shows each take's studio, its outcome tiles and both correction forms", async () => { + renderBoth(controls()); + const sessions = await region("Sessions"); + const body = document.querySelector(".settings-content-body") as HTMLElement; + expect(Array.from(body.children).slice(0, 4).map((card) => card.getAttribute("aria-label"))).toEqual(["Takes waiting for a decision", "Takes", "Station time", "Sessions"]); + expect(within(sessions).getAllByRole("columnheader").map((head) => head.textContent)).toEqual(["Take", "Outcome", "Time", "Task", "Studio", "Operator", "What was wrong"]); + expect(within(sessions).getByRole("group", { name: "Correct a task" })).toBeTruthy(); + expect(within(sessions).getByRole("group", { name: "Correct the studio" })).toBeTruthy(); + expect(within(await region("Takes waiting for a decision")).getAllByRole("button").map((button) => button.textContent)).toEqual(["Discard take 7", "Recover take 7"]); + }); + + it("reaches the waiting take a refused correction names by keyboard, resolves it there and corrects, with focus kept in the dialog", async () => { + const backend = fakeBackend(labelled()); + backend.correctStudio = vi + .fn() + .mockRejectedValueOnce(new CorrectionRefused(WAITING, [])) + .mockResolvedValue({ session: "s", studio: "Pantry", updated: ["episode_0"], config_updated: true }); + const pending = controls(); + const { update } = renderBoth(pending, backend); + const dialog = screen.getByRole("dialog", { name: "End of day" }); + const sessions = await region("Sessions"); + const form = within(sessions).getByRole("group", { name: "Correct the studio" }); + const studio = within(form).getByLabelText("Correct studio") as HTMLInputElement; + const send = within(form).getByRole("button", { name: "Correct studio" }) as HTMLButtonElement; + fireEvent.change(studio, { target: { value: "Pantry" } }); + send.focus(); + fireEvent.click(send); + // The refusal names the card that leads this dialog, and what was typed is kept for the next try. + const card = await region("Takes waiting for a decision"); + expect((await within(form).findByText(`Not corrected: ${WAITING}`)).textContent).toContain(card.getAttribute("aria-label")); + expect([studio.value, document.activeElement]).toEqual(["Pantry", send]); + + // Tab runs through the dialog's own controls and wraps inside it: the card's commands are among them, + // straight after Close, and the last control leads back to the first. + const close = within(dialog).getByRole("button", { name: "Close" }); + const discard = within(card).getByRole("button", { name: "Discard take 7" }); + close.focus(); + fireEvent.keyDown(close, { key: "Tab" }); + expect(document.activeElement).toBe(discard); + fireEvent.keyDown(discard, { key: "Tab", shiftKey: true }); + fireEvent.keyDown(document.activeElement as Element, { key: "Tab", shiftKey: true }); + const last = document.activeElement as HTMLElement; + expect(dialog.contains(last)).toBe(true); + fireEvent.keyDown(last, { key: "Tab" }); + expect(document.activeElement).toBe(close); + + // The question opens over the dialog, holds focus, and gives it back to the dialog once it is answered. + discard.focus(); + fireEvent.click(discard); + const question = screen.getByRole("alertdialog", { name: "Discard take 7?" }); + expect(question.contains(document.activeElement)).toBe(true); + send.focus(); + expect(question.contains(document.activeElement)).toBe(true); + fireEvent.click(within(question).getByRole("button", { name: "Discard take 7" })); + expect(pending.discard).toHaveBeenCalledWith(earlierTake()); + expect(screen.queryByRole("alertdialog")).toBeNull(); + // The next snapshot lists no take: the card goes, and focus is still inside the dialog. + await act(async () => update(controls({ takes: [] }))); + expect(screen.queryByRole("region", { name: "Takes waiting for a decision" })).toBeNull(); + expect(dialog.contains(document.activeElement)).toBe(true); + + // The same correction is now taken; the emptied form hands its focus to the field, not out of the dialog. + send.focus(); + fireEvent.click(send); + await within(form).findByText(/^Studio set to Pantry/); + expect(backend.correctStudio).toHaveBeenCalledTimes(2); + expect(document.activeElement).toBe(studio); + }); +}); + describe("takes waiting to be recovered or discarded", () => { const OK: RecordingCommandResult = { outcome: "ok", reason: null }; diff --git a/examples/egocap/frontend/src/WrapUpDialog.tsx b/examples/egocap/frontend/src/WrapUpDialog.tsx index 8e74c29a4b..a8226f828d 100644 --- a/examples/egocap/frontend/src/WrapUpDialog.tsx +++ b/examples/egocap/frontend/src/WrapUpDialog.tsx @@ -194,6 +194,12 @@ export function WrapUpDialog({ open, onClose, controlToken, backend = REAL_WRAP_ else closeButton.current?.focus(); }; }, [confirmingDiscard]); + // A control that holds focus can leave the dialog with its row: the last waiting take, once it is resolved, + // takes its card with it. Focus then falls to the page behind, so it is put back on the dialog itself. Run + // after the effect above, which has its own place for the focus of a control the question replaced. + useEffect(() => { + if (open && document.activeElement === document.body) dialogRef.current?.focus(); + }); useEffect(() => { if (!open || controlToken === null) return; diff --git a/examples/egocap/frontend/src/dayReportApi.test.ts b/examples/egocap/frontend/src/dayReportApi.test.ts index e5a88a515c..adeaa89eff 100644 --- a/examples/egocap/frontend/src/dayReportApi.test.ts +++ b/examples/egocap/frontend/src/dayReportApi.test.ts @@ -50,7 +50,7 @@ describe("the day report", () => { }); it("surfaces the backend's reason for a refused studio correction, and rejects a reply of the wrong shape", async () => { - const waiting = "an interrupted take of this session must be recovered or discarded first: where it is filed depends on the labels it was recorded under"; + const waiting = "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a decision: where it is filed depends on the labels it was recorded under"; stubFetch(400, { detail: waiting }); await expect(correctStudio("tok", { session: "s", studio: "Pantry" })).rejects.toThrow(new CorrectionRefused(waiting, [])); for (const body of [{ updated: [] }, { studio: "Pantry", updated: "episode_0" }, {}]) { diff --git a/examples/egocap/frontend/src/dayReportApi.ts b/examples/egocap/frontend/src/dayReportApi.ts index 8240b0d372..b979548da9 100644 --- a/examples/egocap/frontend/src/dayReportApi.ts +++ b/examples/egocap/frontend/src/dayReportApi.ts @@ -103,7 +103,8 @@ export interface ReportSession { by_disposition: Tally; episodes: ReportEpisode[]; /** 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). */ + * read, or one found in a session folder it was not written for (a folder copied or renamed by hand). A session + * whose records cannot be listed at all has one line that names no file. */ problems: string[]; } diff --git a/examples/egocap/recording/README.md b/examples/egocap/recording/README.md index 1499a13d22..0990adea0b 100644 --- a/examples/egocap/recording/README.md +++ b/examples/egocap/recording/README.md @@ -123,7 +123,10 @@ session directory. For as long as a session is held its lock file is rewritten a 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 +reader's 2.5 s, and a marker write that fails is tried again every second. `SessionHold` is the same +lock for a writer that is not a recorder (a correction of a closed session's labels): it keeps +recorders out, has no marker of its own and writes nothing, so the lock file keeps what its last +recorder wrote and a reader never takes the hold for a recorder once it is released. 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. @@ -222,9 +225,11 @@ calls `update_session_studio()`, and the rest is for offline callers: studio and task its manifest froze, and refuses a group whose labels differ. A caller that really changes a routed group's studio or whole task also calls `egocap.recording.route.forget_group()` under the session's lock, so a later take of that session claims a fresh group. - `episode_layout.scan_manifests()` reports a sidecar it cannot list, a record that is JSON and no - record, and a record that cannot be opened (by its name and the reason, with no path) as problems, - never as no take. + `episode_layout.scan_session()`, which `scan_manifests()` reads through, reports a sidecar it cannot + list, a record that is JSON and no record, a record that cannot be opened and a record written for + another session as problems, never as no take. Each line is in fixed words (`episode_3.json: the file + cannot be read`, `the take records cannot be listed`): the record's file name and nothing the parser + or the system said, with no path. ## Not yet verified on hardware diff --git a/examples/egocap/recording/egocap/analytics/day_report.py b/examples/egocap/recording/egocap/analytics/day_report.py index a074a3dd00..b2ebcfbf74 100644 --- a/examples/egocap/recording/egocap/analytics/day_report.py +++ b/examples/egocap/recording/egocap/analytics/day_report.py @@ -29,6 +29,7 @@ final_dir, manifest_path, quarantine_destination, + quarantine_group, scan_manifests, ) from egocap.studio.session_studio import session_studio @@ -133,13 +134,17 @@ def take_reasons(manifest: EpisodeManifest) -> tuple[list[str], list[str]]: def _studio(session_path: Path, manifest: EpisodeManifest, attributes: dict[str, Any]) -> str | None: - """The studio a take is labelled with: its finalized episode's own label, else the label of the session - or routed group that holds it, else the studio it was recorded under. None for a take with none of these, - which is every take of a recording that was never given a studio.""" + """The studio a take is labelled with: its finalized episode's own label, else the label of the session, + routed group or quarantine folder that holds it, else the studio it was recorded under. None for a take + with none of these, which is every take of a recording that was never given a studio.""" own = attributes.get("studio") if isinstance(own, str) and own.strip(): return own - group = manifest.assignment.get("group") if manifest.assignment is not None else None + if manifest.storage_phase == "QUARANTINED": + # Set apart, it lies in its session's quarantine folder, which a correction of the session leaves alone. + group = quarantine_group(manifest.session_id) + else: + group = manifest.assignment.get("group") if manifest.assignment is not None else None # A group's name comes from the manifest; one of another shape names no directory to read a label from. holder = session_path.parent / group if isinstance(group, str) and group else session_path return session_studio(holder, fallback=manifest.studio) diff --git a/examples/egocap/recording/egocap/recording/episode_layout.py b/examples/egocap/recording/egocap/recording/episode_layout.py index 191eee0058..4577141476 100644 --- a/examples/egocap/recording/egocap/recording/episode_layout.py +++ b/examples/egocap/recording/egocap/recording/episode_layout.py @@ -20,12 +20,14 @@ from __future__ import annotations +import errno import fcntl import json import logging import os import re import shutil +import stat import tempfile import threading import time @@ -724,6 +726,79 @@ def session_lock_is_free(session_path: Path) -> bool: handle.close() +class LockFileNotPlain(OSError): + """A session's lock file is a link, a folder, or a file that has a second name somewhere. + + A recorder writes its beat into that file, so nothing is taken through one that leads elsewhere. + """ + + +def _require_plain(found: os.stat_result) -> None: + """Refuse a lock file that is not a regular file with one name.""" + if not stat.S_ISREG(found.st_mode) or found.st_nlink != 1: + raise LockFileNotPlain("the session's lock is not an ordinary file") + + +def session_has_lock_file(session_path: Path) -> bool: + """Whether a recorder ever opened the session: every session one opened has a lock file. + + Looked at, never followed and never created. A session directory that is gone has none. + :class:`LockFileNotPlain` when something else than an ordinary file is there under the name. + """ + try: + found = os.lstat(session_path / MANIFEST_DIR / SESSION_LOCK_FILE) + except (FileNotFoundError, NotADirectoryError): + return False + _require_plain(found) + return True + + +class SessionHold: + """A closed session's lock held by a writer that is not a recorder, until explicitly released. + + For a correction of a session's labels: no recorder can open the session while it is held. Unlike + :class:`SessionLock` it has no beat and writes nothing, so the lock file keeps what its last recorder wrote: + a reader that watches the beat sees no recorder where there is none, and a recorder's beat is never + overwritten by one that is then refused. Where the lock does not reach, the hold excludes nobody; whether a + recorder there has the session open is the beat's to say, before the hold is taken. + """ + + def __init__(self, session_path: Path) -> None: + """Take the lock without waiting. + + ``BlockingIOError`` when a recorder holds the session, ``FileNotFoundError`` when it has no lock file + (nothing is created), :class:`LockFileNotPlain` when the file is not an ordinary one. + """ + path = session_path / MANIFEST_DIR / SESSION_LOCK_FILE + try: + # For writing, since a file server grants an exclusive lock only on such a descriptor; nothing is + # written. A link is not followed, and a name that is no file must not make the open wait. + self._descriptor: int | None = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError as exc: + if exc.errno in (errno.ELOOP, errno.EISDIR): + raise LockFileNotPlain("the session's lock is not an ordinary file") from None + raise + try: + # Judged on what was opened, so nothing can be put under the name between a look and the open. + _require_plain(os.fstat(self._descriptor)) + try: + fcntl.flock(self._descriptor, 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._descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException: + os.close(self._descriptor) + raise + + def release(self) -> None: + """Release the lock; safe to call twice.""" + if self._descriptor is not None: + # Closing the descriptor is what gives the lock up. + os.close(self._descriptor) + self._descriptor = None + + class SessionLock: """Exclusive ownership of one session directory, held until explicitly released. diff --git a/examples/egocap/recording/recording_service/README.md b/examples/egocap/recording/recording_service/README.md index 60dc20a20c..25f5af6591 100644 --- a/examples/egocap/recording/recording_service/README.md +++ b/examples/egocap/recording/recording_service/README.md @@ -252,8 +252,16 @@ unchanged. `OutputScan.judge(session)` answers the same for one session before a 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. +could not be read yet (a new session has its sidecar before its `config.yaml`), or whose records could not be +listed: it is looked at again. Without an `OutputScan` the call is a single look that asks each session's lock +and nothing else. + +Which takes wait is one rule, `takes_left_behind(session, scan)`, for this listing and for any other caller that +must know (a correction of a session's labels asks it). `OutputScan.held_closed(session)` is for such a caller, +a writer that is not a recorder: it judges the session as `judge` does, waiting for its own second look when the +session has not been watched, then holds the session's lock for the block with `SessionHold`, which writes no +beat. `SessionOpen` when a recorder has the session by its lock or its beat. What the scan knew of the session +before the hold is what it knows after, so the hold is taken for a recorder only while it lasts. Changing the capture policy or algorithm makes an in-flight take incompatible rather than re-judging it silently. Manifests written diff --git a/examples/egocap/recording/recording_service/__init__.py b/examples/egocap/recording/recording_service/__init__.py index bb3a480293..3d1cdfd3b6 100644 --- a/examples/egocap/recording/recording_service/__init__.py +++ b/examples/egocap/recording/recording_service/__init__.py @@ -41,7 +41,7 @@ VideoSample, VideoSourceSpec, ) -from .output_scan import OutputScan +from .output_scan import OutputScan, SessionOpen, takes_left_behind from .recording_service import RecordingService, storage_problem __all__ = [ @@ -70,6 +70,7 @@ "RoutingConfig", "ServiceConfig", "SessionInfo", + "SessionOpen", "SourceCounts", "StateError", "SubmissionResult", @@ -78,4 +79,5 @@ "VideoSample", "VideoSourceSpec", "storage_problem", + "takes_left_behind", ] diff --git a/examples/egocap/recording/recording_service/output_scan.py b/examples/egocap/recording/recording_service/output_scan.py index 4d309c5411..60d160ae10 100644 --- a/examples/egocap/recording/recording_service/output_scan.py +++ b/examples/egocap/recording/recording_service/output_scan.py @@ -13,7 +13,9 @@ 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. +Reading is read-only: it opens no session for writing, takes no lock for longer than a probe, and creates no +file. The one exception is :meth:`OutputScan.held_closed`, for a writer that is not a recorder (a correction of a +closed session's labels): it holds a session the same rule calls closed, and writes nothing to its lock file. """ from __future__ import annotations @@ -23,22 +25,27 @@ import stat import threading import time -from collections.abc import Callable, Collection +from collections.abc import Callable, Collection, Iterator +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from egocap.recording.episode_layout import ( BEAT_WATCH_SECONDS, MANIFEST_DIR, + RECORDS_UNLISTABLE, UNRESOLVED_PHASES, EpisodeManifest, + SessionHold, + SessionScan, frozen_station, scan_session, session_beat, + session_has_lock_file, session_lock_is_free, ) -__all__ = ["LeftBehind", "OutputScan"] +__all__ = ["LeftBehind", "OutputScan", "SessionOpen", "takes_left_behind"] logger = logging.getLogger("isaaccapture.egocap.output_scan") @@ -56,6 +63,30 @@ class LeftBehind: misplaced: bool = False +def takes_left_behind(session_path: Path, scan: SessionScan) -> list[LeftBehind]: + """The takes a session's records leave for someone to resolve: the one rule for which takes wait. + + A take that was not finished, whatever stopped it, and such a take's record found in a directory it was not + written for. A take the integrity check rejected is finished, also while its data is still on disk: it is + not one of these, and neither is a record that cannot be read, which ``scan.problems`` names. + """ + 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 + ] + return found + + +class SessionOpen(Exception): + """A recorder has the session open: its lock is held, or its beat changed between two looks.""" + + @dataclass class _Watch: """The last beat seen in a session's lock file and when this reader first saw that value.""" @@ -180,6 +211,48 @@ def note_closed(self, session_path: Path) -> None: with self._guard: self._watches[session_path.name] = _Watch(session_beat(session_path), float("-inf")) + @contextmanager + def held_closed(self, session_path: Path, sleep: Callable[[float], None] = time.sleep) -> Iterator[None]: + """Hold a session no recorder has open, for the block of a writer that is not a recorder. + + For a correction of a closed session's labels. The session is judged as before a take of it is resolved: + its beat unchanged between two looks a watch time apart (the second is waited for when this reader has + not watched the session), then its lock, held for the block. :class:`SessionOpen` when a recorder has + it by either sign; ``LockFileNotPlain`` for a lock file that is no ordinary file. + + The hold writes no beat, and what this reader knew of the session before it is what it knows after, so + a read that meets the hold takes it for a recorder only while it lasts. A session without a lock file + was never a recorder's: the block runs with nothing held. Blocking: call it off the event loop. + """ + # Every session a recorder opened has a lock file; one without was never anybody's to keep out. + if not session_has_lock_file(session_path): + yield + return + # The beat first: it is the only sign of a recorder the lock does not reach. + quiet, wait = self.judge(session_path) + if quiet is None: + sleep(wait) + quiet, _wait = self.judge(session_path) + if not quiet: + raise SessionOpen + with self._guard: + known = self._watches.get(session_path.name) + # Taken outside the block's own ``try``, so that only the hold's refusal is read as a recorder. + try: + hold = SessionHold(session_path) + except BlockingIOError: + raise SessionOpen from None + try: + yield + finally: + hold.release() + with self._guard: + met = self._watches.get(session_path.name) + # A read that met the hold started its watch over, as for a recorder. The beat is the one judged + # quiet before, so that judgment still stands; a beat that changed is a recorder's, and is kept. + if known is not None and met is not None and met.beat == known.beat: + self._watches[session_path.name] = known + 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) @@ -218,15 +291,7 @@ def _read_session(self, session_path: Path, names: frozenset[str]) -> tuple[list # 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 + found = takes_left_behind(session_path, scan) + # A session whose configuration could not be read is looked at again: it may still be written. So is + # one whose records could not be listed: nothing says that no take waits in it. + return found, read and not found and RECORDS_UNLISTABLE not in scan.problems diff --git a/examples/egocap/tests/backend/test_auto_align.py b/examples/egocap/tests/backend/test_auto_align.py index d1356c8c38..6875b2b64e 100644 --- a/examples/egocap/tests/backend/test_auto_align.py +++ b/examples/egocap/tests/backend/test_auto_align.py @@ -656,6 +656,47 @@ def recorded() -> dict[str, bytes]: assert recorded() == before +async def test_only_the_good_take_of_a_session_with_a_newer_file_is_tried_again_and_a_bad_one_is_never_aligned( + tmp_path, monkeypatch, caplog +): + """The real tool on a session whose stated lag is in a layout this build does not read, holding a good + take, one the capture checks flagged, and one they set apart.""" + out = tmp_path / "out" + session = out / "s1" + build_raw(session, timing=timing_under(0.02)) + state_a_lag(session) + stated = json.loads((session / HEAD_EXTRINSICS).read_text()) + (session / HEAD_EXTRINSICS).write_text(json.dumps({**stated, "schema_version": 2})) + write_manifest(session, make_manifest(session, session_id="s1", qc_decision="PASSED")) + write_manifest(session, make_manifest(session, 1, session_id="s1", qc_decision="FLAGGED_BAD")) + set_apart = dict(storage_phase="QUARANTINED", finalization=FINALIZATION_QUARANTINE, qc_decision="FLAGGED_BAD") + _write_session_manifest(out, "s1", 2, qualified=None, **set_apart) + copies = out / "s1_aligned" + caplog.set_level(logging.WARNING, logger=auto_align.logger.name) + + # Every start tries the good take alone: it is the only one handed to the tool, and the only one the log + # speaks of. It leaves no marker, since a newer file is no refusal of the take for what it is. + for _ in range(2): + caplog.clear() + assert await _one_start(out, lambda: len(caplog.records) > 0) == ["s1/episode_0"] + assert [record.getMessage().split(":")[0] for record in caplog.records] == [ + "s1 episode 0 was not time-aligned" + ] + assert not copies.exists() + + # With the software updated the good take is aligned. The takes the checks marked bad are not, and they are + # not marked as refused either: they were never the tool's to refuse. + newer = tmp_path / "newer_build" + newer.mkdir() + (newer / "sitecustomize.py").write_text(UPDATED_BUILD) + monkeypatch.setenv("PYTHONPATH", f"{newer}{os.pathsep}{os.environ.get('PYTHONPATH', '')}") + assert await _one_start(out, (copies / "episode_0").is_dir) == ["s1/episode_0"] + assert sorted(entry.name for entry in copies.iterdir() if entry.name.startswith((".", "episode_"))) == [ + "episode_0" + ] + assert AutoAligner(out, INDEX).scan() == [] + + async def test_an_unreadable_manifest_leaves_no_marker_and_a_later_scan_queues_the_episode_again(tmp_path): session = tmp_path / "out" / "s1" build_raw(session) diff --git a/examples/egocap/tests/backend/test_calibration_routes.py b/examples/egocap/tests/backend/test_calibration_routes.py index c036b47965..5517df5c34 100644 --- a/examples/egocap/tests/backend/test_calibration_routes.py +++ b/examples/egocap/tests/backend/test_calibration_routes.py @@ -840,6 +840,161 @@ def page(action: str, **payload) -> dict: server.stop() +def test_the_real_application_holds_a_tools_take_only_for_the_devices_it_records_with_and_keeps_it_unjudged( + monkeypatch, unused_tcp_port, tmp_path +): + """The real application against the real CaptureServer in its mock mode, whose cameras withhold frames for a + while. The mock reports a headset and two controllers and no glove, and the station in use requires one.""" + 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() + (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) + monkeypatch.delenv("EGOCAP_CAPTURE_PLUGINS", raising=False) + output = tmp_path / "recordings" + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: output) + start = capture_server_support.start_capture_server + stalled = functools.partial(start, camera_faults={"camera_stall"}) + monkeypatch.setattr(capture_server_support, "start_capture_server", stalled) + 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.") + fields = { + "name": "Bench A", + "camera_roles": {"ego": "head_human_camera"}, + "required_devices": ["headset", "glove_left"], + } + bench = client.post("/api/stations", json=fields, headers=auth).json()["stations"][-1]["id"] + client.post("/api/stations/select", json={"id": bench}, headers=auth) + missing = "Left glove: not reported by the capture session; this station requires it" + _poll_until_sync(lambda: client.get("/api/setup").json()["blocked_reason"] == missing) + + 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) + + # An ordinary take is held by any device the station requires, in the station's own sentence: it is + # the reason the recording page shows beside Record, and the reason the command is refused with. + assert context.snapshot()["not_ready_reason"] == missing + refused = page("start_episode") + assert (refused["outcome"], refused["reason"]) == ("rejected", missing) + # The glove tool records with the gloves, so its take waits for them like an ordinary one. + glove = client.post(f"{ROOT}/recording", json=GLOVE_TAKE, headers=auth) + assert (glove.status_code, glove.json()) == (409, {"detail": missing}) + assert not output.exists() or not any(output.glob("session_*")) + + # The headset tool records no glove: its take starts, and it is not judged by the capture checks, + # which would have rejected it for the frames its camera withheld. + started = client.post(f"{ROOT}/recording", json={**CAMERA_TAKE, "mode": "intrinsic"}, 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"]) + session, episode = kept["episode_id"].split("/") + record = json.loads((output / session / ".recording" / f"{episode}.json").read_text()) + assert record["capture_checks_exempt"] is True and record["task"] == "Calibration: head camera" + # The exemption and the tool's devices were that take's alone: Record is still held for the glove. + assert context.snapshot()["not_ready_reason"] == missing + again = page("start_episode") + assert (again["outcome"], again["reason"]) == ("rejected", missing) + # With the requirement cleared the same capture, recorded from the page, is judged and rejected. + client.put(f"/api/stations/{bench}", json={"required_devices": []}, headers=auth) + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + judged = page("start_episode") + assert judged["outcome"] == "ok", judged["reason"] + time.sleep(FAULT_TAKE_SECONDS) + result = page("stop_episode", episode_id=judged["snapshot"]["current_episode_id"])["snapshot"][ + "last_result" + ] + assert (result["outcome"], result["qc_decision"], result["media_removed"]) == ( + "rejected", + "REJECTED_CAMERA", + True, + ) + finally: + server.stop() + + +def test_the_real_application_refuses_every_take_in_the_stations_own_words_while_its_stations_file_is_unreadable( + monkeypatch, unused_tcp_port, tmp_path +): + """The real application against the real CaptureServer in its mock mode, started over a stations file that + this build cannot read.""" + 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") + 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(tmp_path / "calibration")) + monkeypatch.delenv("EGOCAP_OPERATOR_SETTINGS_FILE", raising=False) + output = tmp_path / "recordings" + monkeypatch.setattr(app_module, "_recording_output_root", lambda data_dir: output) + (output / ".egocap").mkdir(parents=True) + (output / ".egocap" / "stations.json").write_text("{ not a registry", encoding="utf-8") + server = _ServerThread(unused_tcp_port) + unreadable = "Saved stations are unreadable. Adding a station replaces them" + 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) + # The page's reason beside Record, the refused command and a tool's refused take say the one sentence. + snapshot = context.snapshot() + assert (snapshot["ready_to_record"], snapshot["not_ready_reason"]) == (False, unreadable) + + def record() -> dict: + """Record, as the page sends it for the batch it shows.""" + command = parse_recording_command( + { + "request_id": "r1", + "action": "start_episode", + "payload": {"batch_id": context.batch_id}, + "operator_token": "sam", + "control_token": context.control_token, + } + ) + return client.portal.call(handle_recording_command, command, context) + + refused = record() + assert (refused["outcome"], refused["reason"]) == ("rejected", unreadable) + tool = client.post(f"{ROOT}/recording", json={**CAMERA_TAKE, "mode": "intrinsic"}, headers=auth) + assert (tool.status_code, tool.json()) == (409, {"detail": unreadable}) + assert not any(output.glob("session_*")) + # Adding a station replaces the file, and with that station in use a take starts. + fields = {"name": "Bench A", "camera_roles": {"ego": "head_human_camera"}} + bench = client.post("/api/stations", json=fields, headers=auth).json()["stations"][-1]["id"] + client.post("/api/stations/select", json={"id": bench}, headers=auth) + _poll_until_sync(lambda: context.snapshot()["ready_to_record"] is True) + started = record() + assert (started["outcome"], started["reason"]) == ("ok", None) + finally: + server.stop() + + GLOVE_ROUTES = [ ("post", "/glove/session", {"take": None, "samples": 40}), ("get", "/glove/session", None), diff --git a/examples/egocap/tests/backend/test_day_report_real_recorder.py b/examples/egocap/tests/backend/test_day_report_real_recorder.py index 37bc7e0490..93df0b371e 100644 --- a/examples/egocap/tests/backend/test_day_report_real_recorder.py +++ b/examples/egocap/tests/backend/test_day_report_real_recorder.py @@ -35,6 +35,7 @@ FieldSpec, NumericSample, NumericSourceSpec, + OutputScan, QcConfig, RecordingService, RoutingConfig, @@ -48,8 +49,8 @@ ROUTED = RoutingConfig(session_studio="Kitchen") OPEN_IN_A_RECORDER = "this session is open in a recorder; end its batch there before correcting it" UNSETTLED_TAKE = ( - "an interrupted take of this session must be recovered or discarded first: " - "where it is filed depends on the labels it was recorded under" + "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a " + "decision: where it is filed depends on the labels it was recorded under" ) @@ -118,7 +119,11 @@ def _client(root: Path) -> TestClient: """The report's routes for a backend that has no session of its own open.""" small = FastAPI() small.include_router(day_report_routes.router) - idle = SimpleNamespace(snapshot=lambda: SimpleNamespace(service=None, active_operation=None)) + idle = SimpleNamespace( + snapshot=lambda: SimpleNamespace(service=None, active_operation=None), + # The coordinator's own rule for a session no recorder has open, as a reader that looks once: the lock. + hold_closed_session=lambda session: OutputScan(watch_seconds=0.0).held_closed(session), + ) small.state.recording_context = SimpleNamespace(control_token=TOKEN, coordinator=idle) small.state.station_service = SimpleNamespace(label=lambda: "Bench A") small.state.station_uptime = UptimeLog(root.parent / "station_status") @@ -691,8 +696,8 @@ def no_room(path: Path, data: object) -> None: # --- a take that already has its place in the group ------------------------------------------------------------ STILL_TO_BE_FILED = ( - "an interrupted take of this session must be recovered or discarded first: " - "it is still to be filed in this group" + "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a " + "decision: it is still to be filed in this group" ) @@ -741,5 +746,25 @@ async def test_the_report_names_a_take_record_it_cannot_open_and_never_its_path( record.chmod(0o600) assert report.status_code == 200 (listed,) = report.json()["report"]["sessions"] - assert listed["problems"] == ["episode_0.json: cannot be opened: Permission denied"] - assert str(tmp_path) not in report.text + # In the recorder's own fixed words: nothing the system said about the file is repeated. + assert listed["problems"] == ["episode_0.json: the file cannot be read"] + assert str(tmp_path) not in report.text and "Permission denied" not in report.text + + +async def test_the_report_says_in_fixed_words_that_a_sessions_records_cannot_be_listed(tmp_path): + root = tmp_path / "recordings" + session_id, session = await _recorded(root, None) + sidecar = session / ".recording" + sidecar.chmod(0o300) # its files can be opened by name, and it cannot be listed + try: + if os.access(sidecar, os.R_OK): + pytest.skip("this account lists a directory whatever its mode") + report = _client(root).get("/api/day-report", headers=AUTH) + finally: + sidecar.chmod(0o755) + assert report.status_code == 200 + (listed,) = report.json()["report"]["sessions"] + # One line for the session, and no take of it counted: read as an empty session, a waiting take is missed. + assert (listed["session_id"], listed["episodes"]) == (session_id, []) + assert listed["problems"] == ["the take records cannot be listed"] + assert str(tmp_path) not in report.text and "Permission denied" not in report.text diff --git a/examples/egocap/tests/backend/test_day_report_routes.py b/examples/egocap/tests/backend/test_day_report_routes.py index 0d1c62d84b..750251d65b 100644 --- a/examples/egocap/tests/backend/test_day_report_routes.py +++ b/examples/egocap/tests/backend/test_day_report_routes.py @@ -29,7 +29,7 @@ from egocap_web import day_report_routes from egocap_web.session_locks import ALIGNER, SessionLocks from egocap_web.station_uptime import DOWN, READY, RECORDING, UptimeLog -from recording_service import RecordingPhase +from recording_service import OutputScan, RecordingPhase TOKEN = "t" * 43 AUTH = {"X-Control-Token": TOKEN} @@ -46,6 +46,8 @@ def __init__(self, root: Path): self.episode_id: str | None = None self.operation: str | None = None self.interrupted = False + # The coordinator's own rule for a session no recorder has open, as a reader that looks once: the lock. + self.hold_closed_session = lambda session: OutputScan(watch_seconds=0.0).held_closed(session) def snapshot(self): if self.session_id is None: @@ -775,8 +777,8 @@ def test_a_correction_would_strand_a_take_still_to_be_filed_so_it_is_refused_unt refused = asked(client, holder) assert (refused.status_code, refused.json()["detail"]) == ( 400, - "an interrupted take of this session must be recovered or discarded first: " - "where it is filed depends on the labels it was recorded under", + "an interrupted take of this session must be recovered or discarded first, under Takes waiting for " + "a decision: where it is filed depends on the labels it was recorded under", ) assert _tree(root) == before assert _file_the_waiting_take(session, group) == (group, 1) diff --git a/examples/egocap/tests/backend/test_day_report_with_takes_waiting.py b/examples/egocap/tests/backend/test_day_report_with_takes_waiting.py new file mode 100644 index 0000000000..718fd09a3b --- /dev/null +++ b/examples/egocap/tests/backend/test_day_report_with_takes_waiting.py @@ -0,0 +1,421 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A correction of a recorded session's labels, beside the recorder's own rules for an open session and for a +take that waits. + +The end-of-day routes run over the real coordinator and the real recording service, and the takes that wait are +resolved by the recording page's own commands, so "open" and "waits" are here what the page lists and acts on. +Takes are built in the test (see qc_takes.py). Where a refusal must change nothing, the whole output is compared +byte for byte, the session's lock file included. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import datetime +import json +import shutil +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +import recording_service.recording_service as service_module +from egocap.recording import episode_layout +from egocap.recording.episode_layout import ROUTE_ATTR, read_manifest, route_id +from egocap.recording.route import assign_output, claim_quarantine_group +from egocap_web import day_report_routes +from egocap_web.recording_command import RecordingContext +from egocap_web.recording_session import RecordingSessionCoordinator +from egocap_web.session_locks import SessionLocks +from egocap_web.station_uptime import UptimeLog +from recording_service import RoutingConfig +from tests.backend.qc_takes import ALWAYS_READY, STATION, config_factory, offer, take_frames +from tests.backend.test_takes_left_behind_wire import TOKEN, _context, _lose_capture, _rows, _send, _take + +AUTH = {"X-Control-Token": TOKEN} +#: Takes are routed by the session's studio into a group under that studio's folder. +ROUTED = RoutingConfig(session_studio="Kitchen") +#: How far apart the coordinator's two looks at a beat are here, and how often a recorder beats: the production +#: values are 2.5 s and 1 s. +WATCH, BEAT = 0.25, 0.02 +#: A take the capture checks mark bad, which this station sets apart: nothing tracked moves. +NOTHING_MOVES = dict(frozen_head=True, frozen_hands=True) +OPEN_IN_A_RECORDER = "this session is open in a recorder; end its batch there before correcting it" +TAKE_WAITS = ( + "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a " + "decision: where it is filed depends on the labels it was recorded under" +) +TO_BE_FILED_HERE = ( + "an interrupted take of this session must be recovered or discarded first, under Takes waiting for a " + "decision: it is still to be filed in this group" +) +COPIED = ( + "a take record in this session's folder was written for another session: the folder was copied or renamed " + "by hand, so its labels are left as they are" +) + + +def _factory(root: Path, routed: bool): + """The application's recording configuration, with takes routed by studio when ``routed``.""" + plain = config_factory(root) + return (lambda: dataclasses.replace(plain(), routing=ROUTED)) if routed else plain + + +async def _station(root: Path, *, routed: bool = False, watch: float = WATCH) -> RecordingContext: + """A backend's recorder over ``root``: the real coordinator, with a task set and its commands. Like a + backend at its start, it has read the output once.""" + coordinator = RecordingSessionCoordinator( + _factory(root, routed), queue_capacity=8192, readiness_check=ALWAYS_READY, watch_seconds=watch + ) + await coordinator.refresh_pending() + return _context(coordinator) + + +def _page(root: Path, context: RecordingContext) -> TestClient: + """The end-of-day routes of the backend whose recorder is ``context``.""" + small = FastAPI() + small.include_router(day_report_routes.router) + small.state.recording_context = context + small.state.station_service = SimpleNamespace(label=lambda: STATION) + small.state.station_uptime = UptimeLog(root.parent / "station_status") + small.state.recording_output_root = root + small.state.session_locks = SessionLocks() + return TestClient(small) + + +def _studio(client: TestClient, **body): + return client.post("/api/day-report/studio", json=body, headers=AUTH) + + +def _task(client: TestClient, **body): + return client.post("/api/day-report/correct", json=body, headers=AUTH) + + +def _files(root: Path) -> dict[str, bytes]: + """Every file under ``root`` with its bytes, lock files included.""" + return {str(path.relative_to(root)): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} + + +def _labels(directory: Path) -> dict: + return json.loads((directory / "zarr.json").read_text())["attributes"] + + +def _dies(*args, **kwargs): + raise OSError("the recorder stopped here") + + +async def _interrupted(context: RecordingContext, monkeypatch, step: str, frames=None) -> str: + """Record a take whose recorder stops at ``step``, after its checks: the id of the take left waiting.""" + with monkeypatch.context() as stopped: + stopped.setattr(service_module, step, _dies) + snapshot = await _take(context, frames) + assert snapshot["last_result"]["outcome"] == "interrupted" + return snapshot["last_result"]["episode_id"] + + +async def _new_batch(context: RecordingContext) -> dict: + """End the batch, which closes the session, and read what it left behind; the page's snapshot.""" + assert (await _send(context, "new_batch"))["outcome"] == "ok" + await context.coordinator.refresh_pending() + return context.snapshot() + + +@pytest.fixture +async def closing(): + """Close every recorder a test made, whatever became of the test.""" + made: list[RecordingContext] = [] + yield made.append + for context in made: + await context.coordinator.close(final=True) + + +# --- a take that waits --------------------------------------------------------------------------------------- + + +async def test_a_correction_is_held_by_a_take_the_page_lists_and_taken_once_that_take_is_discarded_there( + tmp_path, closing +): + root = tmp_path / "out" + context = await _station(root, routed=True) + closing(context) + kept = await _take(context) + group = Path(kept["last_result"]["location"]).parent.as_posix() + started = await _send(context, "start_episode") + waiting = started["snapshot"]["current_episode_id"] + offer(context.coordinator, take_frames(seconds=1.0)) + await _lose_capture(context) + session = waiting.split("/")[0] + assert waiting in _rows(await _new_batch(context)) + record = read_manifest(root / session / ".recording" / "episode_1.json") + assert (record.storage_phase, record.studio, record.assignment) == ("WRITING", "Kitchen", None) + + client = _page(root, context) + before = _files(root) + for holder in (group, session): + for refused in ( + _studio(client, session=holder, studio="Pantry"), + _task(client, session=holder, episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": TAKE_WAITS}) + # Nothing was written, the session's lock file included: the correction left no sign of a recorder. + assert _files(root) == before + # So the take is still listed, and the command the sentence names is taken at once. + assert waiting in _rows(context.snapshot()) + await context.coordinator.refresh_pending() + assert waiting in _rows(context.snapshot()) + discarded = await _send(context, "discard_pending", episode_id=waiting) + assert (discarded["outcome"], discarded["reason"]) == ("ok", None) + assert discarded["snapshot"]["last_result"]["outcome"] == "discarded" + assert discarded["snapshot"]["pending_takes"] == [] + # With nothing left waiting the correction is taken. + corrected = _studio(client, session=group, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0"]) + assert _labels(root / group)["studio"] == "Pantry" + + +async def test_a_take_whose_discard_was_started_and_did_not_finish_still_holds_the_correction( + tmp_path, closing, monkeypatch +): + root = tmp_path / "out" + context = await _station(root, routed=True) + closing(context) + kept = await _take(context) + group = Path(kept["last_result"]["location"]).parent.as_posix() + waiting = await _interrupted(context, monkeypatch, "assign_output") + await _new_batch(context) + with monkeypatch.context() as failing: + failing.setattr( + episode_layout.shutil, "rmtree", lambda *a, **k: (_ for _ in ()).throw(OSError("device error")) + ) + half = await _send(context, "discard_pending", episode_id=waiting) + assert half["outcome"] == "ok" and half["snapshot"]["last_result"]["outcome"] == "interrupted" + session = waiting.split("/")[0] + assert read_manifest(root / session / ".recording" / "episode_1.json").discard_requested + client = _page(root, context) + refused = _studio(client, session=group, studio="Pantry") + assert (refused.status_code, refused.json()) == (400, {"detail": TAKE_WAITS}) + # Discarded again, as its row on the page says, it is gone and the correction is taken. + again = await _send(context, "discard_pending", episode_id=waiting) + assert again["outcome"] == "ok" and again["snapshot"]["last_result"]["outcome"] == "discarded" + assert _studio(client, session=group, studio="Pantry").status_code == 200 + + +async def test_a_correction_of_a_session_whose_waiting_take_it_does_not_concern_leaves_that_take_resolvable( + tmp_path, closing, monkeypatch +): + root = tmp_path / "out" + context = await _station(root) # routing off: a take is filed in its session, by no label + closing(context) + kept = await _take(context) + session = kept["last_result"]["location"].split("/")[0] + waiting = await _interrupted(context, monkeypatch, "finalize_episode_dir") + assert waiting in _rows(await _new_batch(context)) + lock_file = root / session / ".recording" / "session.lock" + left = lock_file.read_bytes() + client = _page(root, context) + corrected = _studio(client, session=session, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0"]) + relabelled = _task(client, session=session, episodes="0", task="Wash the cup.") + assert (relabelled.status_code, relabelled.json()["updated"]) == (200, ["episode_0"]) + # The corrections held the session's lock and wrote no beat: the lock file is as its recorder left it. + assert lock_file.read_bytes() == left + # So neither is taken for a recorder that has the session open: the take is listed and recovered at once. + await context.coordinator.refresh_pending() + assert waiting in _rows(context.snapshot()) + recovered = await _send(context, "recover_pending", episode_id=waiting) + assert (recovered["outcome"], recovered["reason"]) == ("ok", None) + result = recovered["snapshot"]["last_result"] + assert (result["outcome"], result["location"]) == ("kept", f"{session}/episode_1") + + +async def test_a_take_rejected_with_its_data_kept_holds_no_correction_and_a_copied_folder_is_left_alone( + tmp_path, closing +): + root = tmp_path / "out" + context = await _station(root, routed=True) + closing(context) + kept = await _take(context) + group = Path(kept["last_result"]["location"]).parent.as_posix() + # No camera frame: the integrity check rejects the take and leaves its data on disk. + tracking_only = [frame for frame in take_frames() if not hasattr(frame, "jpeg")] + rejected = await _take(context, tracking_only) + assert rejected["last_result"]["outcome"] == "rejected_data_kept" + session = rejected["last_result"]["episode_id"].split("/")[0] + # Once its session is closed nothing lists it, and it is never filed: no label waits for it. + assert (await _new_batch(context))["pending_takes"] == [] + client = _page(root, context) + corrected = _studio(client, session=group, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0"]) + assert (root / session / "episode_1.pending").is_dir() + + # A copy of the session's folder holds records written for the session it is a copy of. Nothing acts on + # them, a correction included, and the sentence says what the folder is. + shutil.copytree(root / session, root / f"{session}_copy") + before = _files(root) + for refused in ( + _studio(client, session=f"{session}_copy", studio="Larder"), + _task(client, session=f"{session}_copy", episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": COPIED}) + assert _files(root) == before and str(root) not in COPIED + + +# --- a session a recorder has open --------------------------------------------------------------------------- + + +async def test_a_session_another_recorder_has_open_is_not_corrected_and_its_beat_is_not_touched( + tmp_path, closing, monkeypatch +): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) + root = tmp_path / "out" + theirs, ours = await _station(root), await _station(root) + closing(theirs), closing(ours) + kept = await _take(theirs) + session = kept["last_result"]["location"].split("/")[0] + client = _page(root, ours) + before = _files(root) + for refused in ( + _studio(client, session=session, studio="Pantry"), + _task(client, session=session, episodes="0", task="Wash the cup."), + ): + assert (refused.status_code, refused.json()) == (400, {"detail": OPEN_IN_A_RECORDER}) + # The recorder's own beat is still the last thing written to its lock file. + assert _files(root) == before + assert (await _take(theirs))["last_result"]["outcome"] == "kept" + assert (await _send(theirs, "new_batch"))["outcome"] == "ok" + await asyncio.sleep(WATCH) + corrected = _studio(client, session=session, studio="Pantry") + # Its beat changed since this backend last looked, so it is judged again after a watch time at rest. + if corrected.status_code == 400: + assert corrected.json() == {"detail": OPEN_IN_A_RECORDER} + await asyncio.sleep(WATCH) + corrected = _studio(client, session=session, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1"]) + + +async def test_where_the_lock_does_not_reach_a_session_that_beats_is_not_corrected(tmp_path, closing, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", BEAT) + root = tmp_path / "out" + theirs = await _station(root) # on another machine that shares the recordings + closing(theirs) + kept = await _take(theirs) + session = kept["last_result"]["location"].split("/")[0] + ours = await _station(root) + closing(ours) + client = _page(root, ours) + labels = _labels(root / session / "episode_0") + with monkeypatch.context() as shared_disk: + # A lock taken on one machine is not seen on the other: every lock is granted. + shared_disk.setattr(episode_layout.fcntl, "flock", lambda *_: None) + started = asyncio.get_running_loop().time() + refused = _studio(client, session=session, studio="Pantry") + waited = asyncio.get_running_loop().time() - started + assert (refused.status_code, refused.json()) == (400, {"detail": OPEN_IN_A_RECORDER}) + # Told by its beat, between two looks a watch time apart; nothing was written. + assert waited >= WATCH and _labels(root / session / "episode_0") == labels + assert (await _take(theirs))["last_result"]["outcome"] == "kept" + + +async def test_the_first_correction_of_a_session_this_backend_has_not_watched_waits_for_its_second_look( + tmp_path, closing +): + root = tmp_path / "out" + recorded = await _station(root, watch=0.0) + closing(recorded) + kept = await _take(recorded) + session = kept["last_result"]["location"].split("/")[0] + await recorded.coordinator.close(final=True) + # A backend started later knows nothing of the session yet. + ours = await _station(root) + closing(ours) + client = _page(root, ours) + loop = asyncio.get_running_loop() + started = loop.time() + assert _studio(client, session=session, studio="Pantry").status_code == 200 + first = loop.time() - started + started = loop.time() + assert _task(client, session=session, episodes="0", task="Wash the cup.").status_code == 200 + # Watched and at rest from then on, the next correction waits for nothing. + assert first >= WATCH > loop.time() - started + + +# --- where each take ends ------------------------------------------------------------------------------------ + + +async def test_a_quarantined_take_a_corrected_group_and_a_recovered_take_each_end_where_they_belong( + tmp_path, closing, monkeypatch +): + root = tmp_path / "out" + context = await _station(root, routed=True) + closing(context) + kept = await _take(context) + group = Path(kept["last_result"]["location"]).parent.as_posix() + bad = await _take(context, take_frames(**NOTHING_MOVES)) + session = bad["last_result"]["episode_id"].split("/")[0] + assert (bad["last_result"]["outcome"], bad["last_result"]["location"]) == ( + "quarantined", + f"_quarantine/{session}/episode_1", + ) + waiting = await _interrupted(context, monkeypatch, "assign_output") + await _new_batch(context) + client = _page(root, context) + assert _studio(client, session=group, studio="Pantry").json() == {"detail": TAKE_WAITS} + # Recovered from the page, the waiting take is filed in the group it was recorded for, in the next slot. + recovered = await _send(context, "recover_pending", episode_id=waiting) + assert recovered["outcome"] == "ok", recovered["reason"] + result = recovered["snapshot"]["last_result"] + assert (result["outcome"], result["location"]) == ("kept", f"{group}/episode_1") + # Corrected, the group says the new studio, keeps its folder and stops being a destination; the quarantine + # folder and the take in it are as they were. + quarantine = root / "_quarantine" / session + set_apart = _files(quarantine) + corrected = _studio(client, session=group, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1"]) + assert _labels(root / group)["studio"] == "Pantry" and (root / group / "episode_1").is_dir() + assert json.loads((root / session / ".recording" / "routes.json").read_text()) == {} + assert _files(quarantine) == set_apart + # The report lists each take where it is, with the studio that place says. + report = client.get("/api/day-report", headers=AUTH).json()["report"] + (listed,) = [entry for entry in report["sessions"] if entry["session_id"] == session] + assert [(take["disposition"], take["location"], take["studio"]) for take in listed["episodes"]] == [ + ("kept", f"{group}/episode_0", "Pantry"), + ("quarantined", f"_quarantine/{session}/episode_1", "Kitchen"), + ("kept", f"{group}/episode_1", "Pantry"), + ] + # What a recorder that reopens the session does for its next takes: a kept take claims a group of its own, + # since the corrected one no longer says what the take is recorded under, and a take marked bad joins the + # one already set apart, in the folder the session claimed before its routes were rewritten. + later = datetime.datetime.now() + datetime.timedelta(minutes=1) + fresh, slot = assign_output(root / session, session, "Kitchen", "pour water", "alex", [], later) + assert fresh != group and slot == 0 and _labels(root / fresh)[ROUTE_ATTR] == route_id(session, fresh) + assert claim_quarantine_group(root / session, session) == quarantine and _files(quarantine) == set_apart + + +async def test_a_take_still_to_be_set_apart_holds_a_correction_of_its_sessions_quarantine_folder( + tmp_path, closing, monkeypatch +): + root = tmp_path / "out" + context = await _station(root) # routing off + closing(context) + bad = await _take(context, take_frames(**NOTHING_MOVES)) + session = bad["last_result"]["episode_id"].split("/")[0] + folder = f"_quarantine/{session}" + assert bad["last_result"]["location"] == f"{folder}/episode_0" + waiting = await _interrupted(context, monkeypatch, "finalize_episode_dir", take_frames(**NOTHING_MOVES)) + assert read_manifest(root / session / ".recording" / "episode_1.json").finalization == "QUARANTINE" + await _new_batch(context) + client = _page(root, context) + before = _files(root) + refused = _studio(client, session=folder, studio="Pantry") + assert (refused.status_code, refused.json()) == (400, {"detail": TO_BE_FILED_HERE}) + assert _files(root) == before + recovered = await _send(context, "recover_pending", episode_id=waiting) + assert recovered["snapshot"]["last_result"]["location"] == f"{folder}/episode_1" + corrected = _studio(client, session=folder, studio="Pantry") + assert (corrected.status_code, corrected.json()["updated"]) == (200, ["episode_0", "episode_1"]) 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 421fb213dd..5dd2e3dc11 100644 --- a/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py +++ b/examples/egocap/tests/recording/unit/test_count_daily_trajectories.py @@ -422,6 +422,22 @@ def test_every_take_of_a_folder_stamped_as_quarantine_is_excluded_even_before_it assert breakdown == {"total_seconds": 4.0, "valid_seconds": 0.0, "excluded_seconds": 4.0} +def test_a_quarantine_folder_is_counted_where_it_lies_under_the_studio_its_own_settings_state(tmp_path): + """The folder is keyed by where its data is; the studio is the one it states, as for any session.""" + 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"}) + key = "_quarantine/session_20260101-100000_abc123" + # With no studio stated the folder is known by the name of the folder it lies in. + assert count_trajectories(tmp_path, "2026-01-01")[key]["studio"] == "_quarantine" + # The copy of its session's settings the recorder gives the folder states the studio it was recorded in. + (folder / "config.yaml").write_text("meta:\n egocap_station_name: station_01\n studio: Kitchen\n") + counted = count_trajectories(tmp_path, "2026-01-01") + assert list(counted) == [key] and counted[key]["studio"] == "Kitchen" + assert (counted[key]["valid"], counted[key]["excluded"]) == (0, 1) + + 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" diff --git a/examples/egocap/tests/recording/unit/test_day_report.py b/examples/egocap/tests/recording/unit/test_day_report.py index 5c9d9860d0..523d3982ea 100644 --- a/examples/egocap/tests/recording/unit/test_day_report.py +++ b/examples/egocap/tests/recording/unit/test_day_report.py @@ -341,6 +341,34 @@ def routed() -> list[str | None]: assert build_day_report(tmp_path, DAY)["sessions"][1]["episodes"][0]["location"] == f"{group}/episode_0" +def test_a_quarantined_take_reports_the_studio_of_the_folder_it_was_set_apart_in(tmp_path): + session = _session(tmp_path) + (session / "config.yaml").write_text("meta:\n egocap_station_name: Bench A\n studio: Kitchen\n") + _take(session, _manifest(0, "FINALIZED"), recorded_at=f"{DAY}; 08-20-00") + _take(session, _manifest(1, "QUARANTINED", qc_decision="FLAGGED_BAD", finalization="QUARANTINE")) + # Checked and marked for quarantine, and interrupted before it was moved there: still in its session. + _take(session, _manifest(2, "CHECKED", qc_decision="FLAGGED_BAD", finalization="QUARANTINE")) + folder = tmp_path / "_quarantine" / SESSION + (folder / "episode_1").mkdir(parents=True) + (folder / "zarr.json").write_text( + json.dumps({"attributes": {ROUTE_ATTR: route_id(SESSION, f"_quarantine/{SESSION}")}}) + ) + (folder / "episode_1" / "zarr.json").write_text( + json.dumps({"attributes": {"recorded_at": f"{DAY}; 08-21-00"}}) + ) + # The folder carries the copy of the session's settings the recorder gave it when the take was set apart. + (folder / "config.yaml").write_text("meta:\n egocap_station_name: Bench A\n studio: Kitchen\n") + + def studios() -> list[str | None]: + return [e["studio"] for e in build_day_report(tmp_path, DAY)["sessions"][0]["episodes"]] + + assert studios() == ["Kitchen", "Kitchen", "Kitchen"] + # A correction of the session relabels the session where it lies. The quarantine folder is another folder, + # and the take in it goes on saying what that folder says; the one still waiting is the session's. + (session / "config.yaml").write_text("meta:\n egocap_station_name: Bench A\n studio: Pantry\n") + assert studios() == ["Pantry", "Kitchen", "Pantry"] + + def test_an_unusable_recorded_at_falls_back_to_the_checkpoint_time(tmp_path): session = _session(tmp_path) _take(session, _manifest(0, "FINALIZED"), recorded_at="soon") diff --git a/examples/egocap/tests/recording/unit/test_episode_store.py b/examples/egocap/tests/recording/unit/test_episode_store.py index abd9b759a1..0b7b331211 100644 --- a/examples/egocap/tests/recording/unit/test_episode_store.py +++ b/examples/egocap/tests/recording/unit/test_episode_store.py @@ -188,15 +188,19 @@ def test_manifest_round_trip_atomic_and_unsupported_version_reported(tmp_path: P @pytest.mark.parametrize("content", ["[]", "null", "7", '"text"', "{", ""]) def test_a_take_record_that_is_no_object_is_listed_as_unreadable_not_raised(tmp_path: Path, content: str) -> None: """A record that is JSON and no object, or no JSON at all, must not fail the scan with an error of its own.""" + 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)) manifest_path(tmp_path, 9).write_text(content) found, problems = scan_manifests(tmp_path) assert [m.episode_index for m in found] == [1] - assert len(problems) == 1 and problems[0].startswith("episode_9.json: ") + assert problems == ["episode_9.json: not a take record"] def test_a_take_record_or_a_sidecar_that_cannot_be_read_is_a_problem_and_never_no_take(tmp_path: Path) -> None: """A sidecar that cannot be listed says nothing of the takes in it; read as empty, a waiting take is missed.""" + 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)) write_manifest(tmp_path, _manifest(2)) sidecar = tmp_path / ".recording" @@ -207,11 +211,12 @@ def test_a_take_record_or_a_sidecar_that_cannot_be_read_is_a_problem_and_never_n pytest.skip("this account reads a file whatever its mode") found, problems = scan_manifests(tmp_path) assert [m.episode_index for m in found] == [1] - # Said by the record's name alone: the report shows these lines, and a path is not an operator's to read. - assert problems == ["episode_2.json: cannot be opened: Permission denied"] + # Said by the record's name alone and in fixed words: the report shows these lines, and neither a path + # nor what the system said is an operator's to read. + assert problems == ["episode_2.json: the file cannot be read"] sidecar.chmod(0) found, problems = scan_manifests(tmp_path) - assert found == [] and problems == [".recording: cannot be listed: Permission denied"] + assert found == [] and problems == ["the take records cannot be listed"] finally: sidecar.chmod(0o755) record.chmod(0o644) diff --git a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py index f21e65d15c..ab7b8e8649 100644 --- a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py +++ b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py @@ -28,6 +28,7 @@ QUARANTINE_DIR, ROUTE_ATTR, EpisodeManifest, + SessionHold, SessionLock, final_dir, finalize_episode_dir, @@ -714,6 +715,110 @@ def test_a_recorder_is_still_turned_away_by_another_recorder_that_keeps_the_lock owner.release() +# --- a writer that is not a recorder holds a closed session without a beat ---------------------- + + +def test_a_hold_keeps_recorders_out_and_leaves_the_last_recorders_beat_as_it_was(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout.time, "sleep", lambda seconds: None) + session = _session(tmp_path) + recorder = SessionLock(session) + recorder.release() + lock_file = session / ".recording" / "session.lock" + left, written = lock_file.read_bytes(), lock_file.stat().st_mtime_ns + assert episode_layout.session_has_lock_file(session) + hold = SessionHold(session) + # No recorder opens the session meanwhile, and a reader's probe finds it taken. + with pytest.raises(BlockingIOError): + SessionLock(session) + assert not episode_layout.session_lock_is_free(session) + # Nothing was written: no beat of the hold's own, and the refused recorder wrote none either. + assert _beating(session) == [] + assert episode_layout.session_beat(session) == (left, written) + hold.release() + hold.release() # a second release is nothing + assert episode_layout.session_lock_is_free(session) + assert (lock_file.read_bytes(), lock_file.stat().st_mtime_ns) == (left, written) + again = SessionLock(session) + again.release() + + +def test_a_hold_is_refused_while_a_recorder_has_the_session_and_does_not_touch_its_beat(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) + monkeypatch.setattr(episode_layout.time, "sleep", lambda seconds: None) + session = _session(tmp_path) + recorder = SessionLock(session) + beat = episode_layout.session_beat(session) + with pytest.raises(BlockingIOError): + SessionHold(session) + assert episode_layout.session_beat(session) == beat + recorder.release() + + +def test_a_hold_is_not_turned_away_by_a_reader_that_held_the_lock_for_an_instant(tmp_path, monkeypatch): + session = _session(tmp_path) + SessionLock(session).release() + probe = open(session / ".recording" / "session.lock") # 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) + hold = SessionHold(session) + assert waited == [episode_layout._PROBE_GRACE_SECONDS] + hold.release() + + +def test_a_session_no_recorder_ever_opened_has_no_lock_to_hold_and_none_is_made(tmp_path): + session = _session(tmp_path) + assert not episode_layout.session_has_lock_file(session) + with pytest.raises(FileNotFoundError): + SessionHold(session) + assert list((session / ".recording").iterdir()) == [] + # A session that is gone, or whose sidecar is no directory, has none either. + assert not episode_layout.session_has_lock_file(tmp_path / "out" / "gone") + (tmp_path / "out" / "flat").mkdir() + (tmp_path / "out" / "flat" / ".recording").write_text("not a directory") + assert not episode_layout.session_has_lock_file(tmp_path / "out" / "flat") + + +@pytest.mark.parametrize("shape", ["a link out", "a second name", "a folder", "a pipe"]) +def test_a_lock_file_that_is_no_ordinary_file_is_refused_and_nothing_is_done_through_it(tmp_path, shape): + session = _session(tmp_path) + lock_file = session / ".recording" / "session.lock" + outside = tmp_path / "outside.txt" + outside.write_text("kept") + if shape == "a link out": + lock_file.symlink_to(outside) + elif shape == "a second name": + os.link(outside, lock_file) + elif shape == "a folder": + lock_file.mkdir() + else: + os.mkfifo(lock_file) + with pytest.raises(episode_layout.LockFileNotPlain): + episode_layout.session_has_lock_file(session) + with pytest.raises(episode_layout.LockFileNotPlain): + SessionHold(session) + assert outside.read_text() == "kept" + + +def test_a_lock_file_that_cannot_be_opened_fails_as_the_system_said(tmp_path, monkeypatch): + session = _session(tmp_path) + SessionLock(session).release() + + def denied(path, flags, *args, **kwargs): + raise PermissionError(errno.EACCES, "Permission denied", str(path)) + + monkeypatch.setattr(episode_layout.os, "open", denied) + with pytest.raises(PermissionError) as raised: + SessionHold(session) + assert not isinstance(raised.value, episode_layout.LockFileNotPlain) + + # --- a failed write is given the name of the file it was writing ------------------------------- diff --git a/examples/egocap/tests/recording_service/test_takes_left_behind.py b/examples/egocap/tests/recording_service/test_takes_left_behind.py index fc2329dad8..a15e63f131 100644 --- a/examples/egocap/tests/recording_service/test_takes_left_behind.py +++ b/examples/egocap/tests/recording_service/test_takes_left_behind.py @@ -315,6 +315,202 @@ async def test_one_look_with_no_memory_asks_the_lock_alone(tmp_path, own, fast_b await other.discard_episode(episode.episode_id) +# --- a writer that is not a recorder holds a session the same rule calls closed --------------- + + +def _held(reader: "_Reader", session_path: Path): + """The reader's hold on a session, with a wait that moves the reader's own clock; the waits it made.""" + waits: list[float] = [] + + def wait(seconds: float) -> None: + waits.append(seconds) + reader.now += seconds + + return reader.scan.held_closed(session_path, sleep=wait), waits + + +async def test_a_closed_session_is_held_without_a_beat_and_its_take_stays_listed(tmp_path, own): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root) + assert reader.look() == [] and reader.look(WATCH) == [left.episode_id] + before = tree(root) + hold, waits = _held(reader, session.session_path) + with hold: + # No recorder opens the session meanwhile, and nothing was written to say one has it. + with pytest.raises(StateError, match="owned by another recorder"): + await RecordingService(_config(root)).open_session(session.session_id) + assert tree(root) == before + # A read of the output that meets the hold sees a lock that is taken, and lists nothing of the session. + assert reader.look() == [] + # The session was watched and quiet, so the hold waited for nothing; released, it is quiet as before: its + # take is listed by the very next read and can be resolved at once. + assert waits == [] and tree(root) == before + assert reader.look() == [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) + assert (await reopened.discard_pending(left.episode_id)).disposition is Disposition.DISCARDED + + +async def test_a_session_the_reader_has_not_watched_is_held_after_its_second_look(tmp_path): + root = tmp_path / "out" + session, _left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root) + hold, waits = _held(reader, session.session_path) + with hold: + assert waits == [WATCH] + assert not episode_layout.session_lock_is_free(session.session_path) + assert episode_layout.session_lock_is_free(session.session_path) + + +async def test_a_session_a_recorder_has_open_is_not_held_and_its_beat_is_left_alone(tmp_path, own): + root = tmp_path / "out" + other = own(RecordingService(_config(root))) + session = await other.open_session() + assert (await record(other)).disposition is Disposition.KEPT + reader = _Reader(root, watch=0.0) # one look: the lock alone says it + ran = [] + with pytest.raises(output_scan.SessionOpen): + with reader.scan.held_closed(session.session_path): + ran.append("the block") + assert ran == [] + # Refused, it wrote nothing into the lock file: the recorder's own beat is the only one there. + token = session_beat(session.session_path)[0].split()[0] + assert (await record(other)).disposition is Disposition.KEPT + assert session_beat(session.session_path)[0].split()[0] == token + + +async def test_where_the_lock_does_not_reach_a_session_that_beats_is_not_held( + tmp_path, own, fast_beat, lock_does_not_reach +): + root = tmp_path / "out" + other = own(RecordingService(_config(root))) # on another machine: its lock is not seen here + session = await other.open_session() + reader = _Reader(root) + waits: list[float] = [] + + def wait_for_a_beat(seconds: float) -> None: + waits.append(seconds) + reader.now += seconds + _next_beat(session.session_path) + + ran = [] + with pytest.raises(output_scan.SessionOpen): + with reader.scan.held_closed(session.session_path, sleep=wait_for_a_beat): + ran.append("the block") + # Judged by two looks a watch time apart, as a take of the session would be before it is resolved. + assert ran == [] and waits == [WATCH] + await other.close() + # At rest again for a watch time, it is held. + assert reader.scan.judge(session.session_path)[0] is not True + reader.now += WATCH + with reader.scan.held_closed(session.session_path, sleep=wait_for_a_beat): + ran.append("the block") + assert ran == ["the block"] + + +async def test_a_recorder_that_took_the_session_during_a_hold_is_seen_by_its_beat_afterwards( + tmp_path, own, fast_beat, lock_does_not_reach +): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root) + assert reader.look() == [] and reader.look(WATCH) == [left.episode_id] + hold, _waits = _held(reader, session.session_path) + with hold: + other = own(RecordingService(_config(root))) # where the lock does not reach, it is not kept out + await other.open_session(session.session_id) + assert reader.look() == [] + # What the reader knew before the hold is not put back over a beat that changed: the session is open. + _next_beat(session.session_path) + assert reader.look() == [] and reader.scan.judge(session.session_path)[0] is not True + + +def test_a_session_no_recorder_ever_locked_has_nothing_to_hold_and_nothing_is_made(tmp_path): + session = tmp_path / "out" / "session_by_hand" + (session / ".recording").mkdir(parents=True) + reader = _Reader(tmp_path / "out") + hold, waits = _held(reader, session) + ran = [] + with hold: + ran.append("the block") + assert ran == ["the block"] and waits == [] + assert list((session / ".recording").iterdir()) == [] + # The same for a session that is gone. + with reader.scan.held_closed(tmp_path / "out" / "gone"): + ran.append("the block") + assert len(ran) == 2 and not (tmp_path / "out" / "gone").exists() + + +async def test_a_failure_inside_the_hold_releases_it_and_is_passed_on(tmp_path): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + reader = _Reader(root, watch=0.0) + assert reader.look() == [left.episode_id] + with pytest.raises(BlockingIOError, match="the block's own"): + with reader.scan.held_closed(session.session_path): + # Not taken for a held lock: only the hold's own refusal says a recorder has the session. + raise BlockingIOError("the block's own") + assert episode_layout.session_lock_is_free(session.session_path) + assert reader.look() == [left.episode_id] + + +# --- which takes wait: one rule --------------------------------------------------------------- + + +async def test_the_takes_that_wait_are_the_unfinished_ones_whatever_else_the_session_holds( + tmp_path, own, monkeypatch +): + 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 + interrupted = await _interrupted_take(service) + await service.close() + path = session.session_path + waiting = output_scan.takes_left_behind(path, episode_layout.scan_session(path)) + # The take rejected for integrity is finished, though its data is still on disk: it is not one of them. + assert (path / "episode_1.pending").is_dir() + assert [(left.manifest.episode_id, left.misplaced) for left in waiting] == [(interrupted.episode_id, False)] + # A discard that was started and did not finish leaves the take waiting, marked. + reopened = own(RecordingService(_config(root))) + await reopened.open_session(session.session_id) + with monkeypatch.context() as patched: + patched.setattr( + episode_layout.shutil, "rmtree", lambda *a, **k: (_ for _ in ()).throw(OSError("device error")) + ) + assert ( + await reopened.discard_pending(interrupted.episode_id) + ).disposition is Disposition.RECOVERY_REQUIRED + await reopened.close() + (marked,) = output_scan.takes_left_behind(path, episode_layout.scan_session(path)) + assert marked.manifest.discard_requested and marked.manifest.episode_id == interrupted.episode_id + # In a copy of the directory the same record is listed as one nothing may act on. + shutil.copytree(path, root / "a_copy") + copied = output_scan.takes_left_behind(root / "a_copy", episode_layout.scan_session(root / "a_copy")) + assert [(left.manifest.episode_id, left.misplaced) for left in copied] == [(interrupted.episode_id, True)] + + +async def test_a_session_whose_sidecar_cannot_be_listed_is_never_remembered_as_finished(tmp_path): + root = tmp_path / "out" + session, left = await _left_by_a_recorder_that_is_gone(root) + sidecar = session.session_path / ".recording" + reader = _Reader(root, watch=0.0) + sidecar.chmod(0o300) # its files can be opened by name, and it cannot be listed + try: + if os.access(sidecar, os.R_OK): + pytest.skip("this account lists a directory whatever its mode") + assert episode_layout.scan_session(session.session_path).problems == ("the take records cannot be listed",) + assert reader.look() == [] and reader.look() == [] + finally: + sidecar.chmod(0o755) + # Nothing was concluded from the listing that failed: the take is found once the sidecar can be listed. + assert reader.look() == [left.episode_id] + + # --- probe before judging: nothing is concluded from a session that is being opened -----------