Skip to content

Latest commit

 

History

History
383 lines (316 loc) · 26.2 KB

sources.md

File metadata and controls

383 lines (316 loc) · 26.2 KB

Sources

A source records where a project's assets came from. Register an image or point-cloud directory before ingesting its files. A video import records the clip metadata and extraction settings reported by the client, then uploads the decoded frames; a server-side video ingest does the same with metadata it probed and a decoder it ran itself. Labeled dataset imports can also record ordered sequences for tracks.

Two doors, one per kind

Use SourceService.register_images to register an IMAGE_DIRECTORY source.

sources = SourceService(workspace)

stills = sources.register_images(project.id, Path("~/captures/2026-07").expanduser())

VideoImportService.start creates a VIDEO source and opens the session for uploading its frames. Use SourceService.get, .list, and require_source to read any source kind. See video import sessions.

register_point_clouds(project.id, directory, frame=ScanFrame.LIDAR_FLU) is the door to a POINT_CLOUD_DIRECTORY source - see Point-cloud directories and their frame.

An IMAGE_SEQUENCE source has no registration at all. An import whose dataset orders stills, such as an OpenLane segment, a MOTChallenge sequence or a CVAT video task, writes one per sequence inside its own transaction through SourceService.add_image_sequence_in, with the sequence's frame occurrences, so tracks can observe them. Like a video import, every run writes a new one, under a fresh image-sequence-import:<uuid4> locator that names no path, and nothing ingests from it.

A POINT_CLOUD_SEQUENCE source is the same for scans: an import whose dataset orders its scans, such as a nuScenes scene, writes one per sequence through SourceService.add_point_cloud_sequence_in, under a point-cloud-sequence-import:<uuid4> locator. It declares no frame and takes no calibration (CALIBRATION_NOT_APPLICABLE): each scan stays an asset of the point-cloud directory at the import root, whose declared frame its labels are read in.

register_images checks that the directory exists and is a directory, and stops there. What is in it is read at ingest, because a count taken at registration would be stale by the time anything used it.

What a source records

Field Meaning
kind image_directory, point_cloud_directory, video, image_sequence or point_cloud_sequence - a SourceKind
locator identifies the origin; only the two directory kinds promise it is a path this process can open
display_name what somebody asked this source to be called, or None for nobody said
registered_at timezone-aware UTC, the first registration
capture_params opaque operator-supplied provenance; nothing branches on it
video a VideoProvenance, present exactly when kind is video
calibration the camera behind its frames, or None - see Camera calibration. Never on a point-cloud directory or sequence
frame the axis convention a point-cloud directory's scans are written in, present exactly when kind is point_cloud_directory

locator is the domain's name for what used to be unconditionally path, and the rename is the point: a directory's locator is a canonical filesystem path, canonical_path-normalized, and this process may open it. A VIDEO source's locator is video-import:<uuid4> - a token naming that import and nothing else, opaque to every reader but VideoImportService itself, and unique per import so two clients declaring "the same" clip are still two sources rather than one row racing to be first. Nothing downstream is entitled to treat it as a path; the underlying database column is still named path and unchanged, because the rename is a domain-level promise, not a schema migration.

display_name exists because not every locator has a readable last segment: an HTTP upload of stills is staged under a content-addressed directory, so its basename is a 64-character digest, and a video import's locator is a bare token with no segment a person would recognize at all - while a directory named at a terminal, or a clip somebody titled before starting the import, carries something a person chose. Like capture_params it is outside the identity key — renaming must not fork one origin into two — and unlike registered_at a stated value does refresh the stored one, because a label is curation rather than provenance. Source.name is the one spelling of the resolution: the stated name, else the locator's last segment, and it is what both wire projections publish.

VideoProvenance is what a client's decoder read off the container - width, height, the source fps, duration, codec - plus the cut a decomposition will run at: extraction_fps, the clip ranges extraction reads (empty meaning the whole clip), and scale_percent, the percent of the native size frames are stored at (100 meaning unscaled). Ranges are stored canonically — clamped to the clip, sorted, overlaps and touches merged, a full cover collapsing to the empty selection — so two spellings of one selection cannot fork a source. The declared metadata is kept whole rather than re-spelled field by field, because metadata.fps is the rate the file was shot at and extraction_fps is the rate we chose to cut it at, and re-declaring the first beside the second is how the two come to be confused. metadata.fps is null for a variable-frame-rate clip, which has no single rate it was shot at; the extraction rate is never put there to fill the gap.

An exact-count cut (server ingest only) stores extraction_fps as null and sample_counts, one count per range, instead. Its ranges are kept sorted and disjoint but never clamped or merged, and its positions are numbered at each range's own spacing with the gaps left in place; see ingest.md.

Two more fields ride beside that cut, and they are about the decomposition rather than the clip: policy_version names which spelling of the sampling rules — the grid, the rotation handling, the scale rounding — produced these frames, and materializer names what actually decoded them (a string like "mediabunny/1.56.1", or None for a source registered before either field existed). Frame bytes are not reproducible across decoders the way a JPEG's bytes are reproducible across machines - two browsers can disagree over one container - so neither field promises a clip will decode the same way twice; they say which policy was in force and what drew the frames, so a future change to either is legible in the data instead of an unexplained difference between two batches.

The video/kind pairing is an invariant, enforced on construction and on assignment - Source is the only model in the domain with validate_assignment on, because a model_validator does not re-run when you assign to a field. Reading it goes through source.require_video(), which raises WorkspaceCorrupt rather than handing back a None that every caller would have to assert away.

Decomposition parameters live on the source, not on the job

A source can be ingested more than once, and the promise is that the same source yields the same assets. That promise only means something if the parameters are part of what "the same source" is - put them on the ingest job and two runs of one source could legitimately disagree, leaving idempotency with nothing to be measured against.

The consequence is deliberate: one clip registered at 1 fps and again at 5 fps — or at 100% and again at 50% — is two sources over one file, not one source with a history.

Storing frames at a smaller size

A video import declares an optional scale_percent when it starts, and the client's own materializer is what applies it: every frame it posts already comes out at max(1, (native * percent + 50) // 100) per dimension - scaledDimension in @visionset/media, the same integer formula VideoProvenance.stored_width/stored_height compute from the record. The server does not resize anything; it only checks that a staged frame's declared size, decoded, matches what the source says every frame of this import should be. Image directories always store stills at their decoded size — an image batch mixes resolutions, and export is where a uniform size is made.

This is not the export-time resize: pre-processing recipes bring every exported image to one model input size at export. The import-time scale exists to cut upload and storage cost for clips nobody needs at native resolution, and it is permanent — the assets are the smaller pixels. Starting another import of the same clip at a different scale is a second source.

Image-directory registration is idempotent; a video import never merges

register_images's match key is (kind, locator) within a project: registering the same directory twice returns the same Source rather than a second one, so that once ingest gives asset.source_id a target, "which source did this asset come from?" has one answer. capture_params is deliberately left out of that key — fragmenting one directory into two sources because an operator typed a different lens note would defeat the point — and differing params are written onto the matched source instead.

A video import has no equivalent merge, on purpose. VideoImportService.start always creates a new source, because its locator is a fresh video-import:<uuid4> every time - there is no "already-known clip" to match against, since the server never has the bytes to compare. Two imports of what a person considers the same file are two sources, exactly as two registrations of one clip at different rates or ranges already were before this change; asset-level content addressing is what actually deduplicates identical frames, and it does that regardless of how many sources point at them.

The unique index underneath register_images still carries video's old columns - uq_source_project_kind_path_fps_ranges_scale, over (project_id, kind, path, coalesce(json_extract(video, '$.extraction_fps'), 0), coalesce(json_extract(video, '$.ranges'), ''), coalesce(json_extract(video, '$.scale_percent'), 0)) - because the stored rows still carry them and dropping a column is a migration nobody has asked for. For an image_directory row those terms are always the same three zeros, so the index does what it always did: it is the backstop under two concurrent registrations of one folder, which the module docstring for SourceService calls dead weight for the one writer left there. For a video row every locator is already unique, so the same index can never fire for one - the guarantee it existed to give video sources is now given structurally, by the locator itself, rather than by this constraint.

The gap this left, and how it was closed

The idempotency check above shipped without a backstop, which docs/content/persistence.md calls a wish: two concurrent registrations of one folder could both pass the pre-check and both insert. It was tolerable only because nothing referenced a source, so a duplicate was inert - and ingest ended that, by giving asset.source_id a target and letting the winner of a race decide an asset's recorded origin. The index above went in with it, coalesced rather than left to compare NULLs, because SQLite treats NULLs in a unique index as distinct - an image directory, whose video is NULL, would otherwise never collide with itself, which is most of what the index is for.

The two layers do what they do everywhere else in this store. The pre-check is what produces a friendly answer; the index is the guarantee. A caller that loses the race sees a raw ConstraintViolated, and the remedy is to call the same method again, which finds the winner's row and returns it. A caller that instead waits out the store's busy_timeout sees WorkspaceBusy, and the remedy is the same.

Paths are canonicalized once, and only for a directory

canonical_path is str(Path.resolve(strict=True)): absolute, symlinks followed, so ./data, ../project/data and /abs/data are one source. It applies to register_images alone - a video import's locator is an opaque token the server minted itself, never a path anyone supplied, so there is nothing to resolve. Two things canonical_path does not do:

  • It does not normalize case. On a case-insensitive filesystem - macOS by default, Windows always - /Data and /data are one directory and would register as two sources. Lower-casing would be wrong on Linux, where they are genuinely two.
  • It does not look at the content. Two hard links to one inode read as two origins. What the bytes are is asked at ingest, where the answer is a content hash.

strict=True means an origin that is not on disk is a FileNotFoundError, and a file offered where a directory was wanted is a NotADirectoryError. Both are about the machine rather than the workspace, so both stay outside the VisionSetError tree.

Over HTTP, a directory is an upload; a clip is never one

SourceService registers a directory by path, and an HTTP client has bytes rather than a path. So the REST API's POST /projects/{id}/sources/images takes multipart - one files part per image plus an optional name - writes the parts under <workspace>/uploads/, and registers what it wrote. There is no route that accepts a server-side path: it would hand every token holder an arbitrary-directory read, and the two surfaces that legitimately hold real paths, the CLI and MCP, call the SDK in-process and never go through HTTP.

The staging directory is named by a digest of the whole part set - sha-256 over the sorted name:sha256 lines - which is what makes register_images's idempotency survive the trip. The same files under the same names stage to the same path, so a repeated upload returns the same Source instead of a second one over a second copy on disk. Different bytes, or the same bytes under a different filename, are a different offer and stage apart.

That upload-only choice has a quiet dividend: because the server just wrote the file, the FileNotFoundError and NotADirectoryError above are unreachable from HTTP. Neither is a VisionSetError, so neither has an entry in the API's error table - and neither needs one.

A client never sees locator. SourceOut publishes the source's name and nothing about the machine - which for a VIDEO source is doubly true, since there was never a machine path to begin with. A video source is never registered through sources.py at all: it comes into being by POST /projects/{id}/video-imports, a JSON body of declared metadata and no bytes, or by POST /projects/{id}/video-ingests, which takes an uploaded clip and decodes it as a background job; both are documented in ingest.md.

Declaring a source is not validating it

That was true of register_video's probe, and it is still true of what replaced it. A clip whose tail has been truncated still has a readable header, so a client's own probe reports a plausible duration and VideoImportService.start records it without complaint - the server has no way to know otherwise, since it never sees the bytes. The damage, if there is any, surfaces later and per frame: each one is decoded by ImageProcessor as it is staged, and a frame that will not decode, or that decodes to something other than its own declared size, is refused there. Anything that treats a successful start as proof a clip will fully materialize is wrong, on the same terms the old registration warning stated it.

Camera calibration

A 3D label is read against the camera that took its image, so a source can carry a Calibration and an asset can override it - the rule is Three-dimensional labels are calibrated image labels. A polyline_3d or cuboid_3d label (see annotations) is refused on an asset with no effective calibration.

Part Meaning
intrinsics fx, fy, cx, cy, skew (default 0) in pixels, and the width x height they were measured at
extrinsics required: a row-major 3x3 rotation and a translation in metres, taking the sensor frame into the rig's: p_rig = R p_sensor + t. The rotation must be proper - orthonormal with determinant +1, to 1e-4
distortion optional: plumb_bob, OpenCV's radial-tangential k1, k2, p1, p2, k3 (default 0)

The sensor frame is OpenCV's: x right, y down, z forward along the optical axis, in metres.

An asset's effective calibration is its own override, else its source's, else none. The override exists because an imported asset has no source_id, so it is the only way a calibration reaches one; it is curation rather than provenance, and replaceable until a 3D label is drawn against it.

Calibration is not identity. It is outside the origin index like capture_params, and register_images takes none: registering the same directory again returns the same source with its calibration untouched, so a re-registration cannot re-interpret labels already drawn against it. CalibrationService is the one writer, and REST, the CLI and MCP each reach it through set, get and clear.

Refusal When
CALIBRATION_RESOLUTION_MISMATCH (422) the intrinsics were measured at a size other than an asset they would apply to - for a source, any of its assets with no override of its own, or a clip's stored frame size; for clearing an asset's override, the source calibration it would fall back to. An asset of unknown size takes any
CALIBRATION_IN_USE (409) a change would re-read an asset's 3D labels against another calibration, or leave them with none. Clearing: a source's, while an inheriting asset holds them, or an asset's override when its source has none to fall back to, or a different one. Replacing with a different calibration is refused the same way, because those labels were drawn against the stored one: a source's, while an asset inheriting it (one with no override of its own) holds 3D labels, and an asset's override - compared with the calibration in effect for it, its override or else its source's - while that asset holds them, so a first override other than the inherited calibration is refused too. Setting the identical calibration again is not a replacement and changes nothing; a first calibration where none applied, an override equal to the inherited one, and a change no 3D label depends on are accepted

An asset ingested after its source was calibrated is not measured against it at ingest. The check runs when a calibration is stated, and again wherever a 3D label is read against one - a write, an import, a publish - so an asset that joined a calibrated source at another size refuses its first 3D label with CALIBRATION_RESOLUTION_MISMATCH rather than being read with the wrong focal lengths.

Point-cloud directories and their frame

A point-cloud directory holds single PCD or PLY scans, each ingested as one point_cloud asset (see media.md). A scan has no intrinsics, so its labels are read against the frame its source declares, not a calibration - the rule is the same decision record. Nothing is normalised on ingest: a coordinate is stored in exactly the axes the sensor wrote.

ScanFrame Axes Up
lidar_flu x forward, y left, z up +z
camera_rdf x right, y down, z forward (a depth camera's optical frame) -y
lidar_rfu x right, y forward, z up (nuScenes' LIDAR_TOP) +z

A cuboid_3d on a scan is a centre and a size in the frame's own units and a yaw about its up axis, counter-clockwise seen from above. The thumbnail is drawn from above along the same axis, forward up the picture.

Registration is idempotent on the directory, like register_images, and a point-cloud directory is a different source from an image directory at the same path. Registering it again with another frame replaces the declaration, unless one of its scans holds a 3D label: then it is refused with CALIBRATION_IN_USE (409), because the label would be re-read in other axes. The check runs under the store's write lock, the one every label write takes before it checks the frame, so a cuboid cannot land between the check and the change. The same transaction drops the previews of the source's scans, which were drawn in the old frame, and the next thumbnail backfill draws them in the new one; until then a scan's thumbnail is THUMBNAIL_NOT_CACHED. A scan's thumbnail is served for revalidation rather than as immutable, so a browser picks up the redrawn one at the same URL. An import of scans, such as kitti or nuscenes, writes or reuses the point-cloud source at its directory in the dataset's frame, and never re-declares one: a source there in another frame refuses the import with CALIBRATION_IN_USE, even while none of its scans holds a label - unlike registering the directory again, which replaces the frame in that case. Stating a camera calibration for a point-cloud directory, or for a scan, is refused with CALIBRATION_NOT_APPLICABLE (409).

Every surface registers one. The SDK and visionset ingest DIR --point-clouds FRAME take a directory on this machine, and so does the MCP ingest tool given a frame. REST takes the scans as an upload, POST /projects/{project_id}/sources/point-clouds with a required frame form field, and stages them the way it stages images, so uploading the same files again returns the same source. A missing or unknown frame is VALIDATION_ERROR (422). The browser's ingest screen uses the same route for .pcd and .ply files - see ingest.md.

Declaring a capture group

Frames from one clip, one scene or one capture session are correlated: split one asset at a time, validation ends up holding near-copies of training frames. A split recipe with group_by keeps every asset sharing a group_label in one fold - see releases.md - and an ingest is where you say which assets belong together. One ingest call is one capture group: put each clip, scene or session in its own directory and ingest each with its own label.

ingest.ingest(clip_a.id, group_label="drive-2026-07-01-a")
ingest.ingest(clip_b.id, group_label="drive-2026-07-01-b")
Surface How
SDK IngestService.ingest(source_id, group_label=...), or enqueue(..., group_label=...)
CLI visionset ingest DIR --project P --group-label NAME
MCP the ingest tool's group_label argument
REST group_label in the body of POST /sources/{source_id}/ingest-jobs
Clip import (SDK, REST) VideoImportService.start(..., group_label=...), or group_label in the body of POST /projects/{project_id}/video-imports; every frame the commit creates takes it, with the same first-label-wins rule. The browser's clip screen has no field for it yet

The label is normalized the way a name is: surrounding whitespace is stripped, and one that is blank, longer than 255 characters or holding a control character or line break is refused with INVALID_NAME (422) before the run's job row exists; over REST, one longer than 255 characters is VALIDATION_ERROR (422). It is stored on the ingest job too, so a queued run, or a failed one resumed, writes the label the caller asked for. Assets, the ingest job and every asset listing carry group_label, null for none. It also applies to a point-cloud directory, whose scans take it the same way.

The first label wins. A label is provenance, like source_id: it is written on an asset when the run creates it and never rewritten. An asset the project already held - the same bytes ingested before, under another label or under none - keeps what it arrived with and still joins this run's batch. The run reports how many such assets keep a label other than the one it declared, as kept_other_label from the CLI's --json, the MCP tool and IngestResult; the REST job does not count them. A file repeated inside the run is one asset and takes the run's label.

What the system cannot infer for you:

  • Correlated frames that nobody labelled. An asset ingested with no label is a unit of its own in a grouped split, so frames of one clip ingested without group_label can land in every fold. The split report's partial_group_labels and no_group_labels warnings say how many assets were cut alone.
  • Near-duplicates. A resized or re-encoded copy, or a burst of nearly identical frames, has different bytes and is a different asset. Only exact bytes are recognized as the same asset.
  • Two labels for one scene. Two directories of one place are one group only if they carry one label.

A label cannot be changed after ingest: there is no relabel or regroup operation yet, and ingesting the same bytes again under another label does not move them. To regroup existing assets, ingest them into a fresh project with the labels you want. A browser video import and a labeled dataset import do not take a declared label; an import can carry the one its format names - see import.md.

What is deliberately not here yet

  • No delete. A source disappears with its project's cascade and no sooner. The question ingest raised does now have an answer, though: an asset outlives the receipt it came from. Deleting a source must not take the asset, its annotations, its dataset membership or the releases naming it, so a future SourceService.delete clears asset.source_id rather than cascading through it
  • and it has to do that itself, because that column is deliberately not a foreign key (see adapters/_tables.py for why, and what it costs).
  • No event. Registering a source announces nothing. IngestCompleted is the event this area emits, and the ingest pipeline owns it.
  • No editing a capture group. group_label is written once, at an asset's first arrival - see Declaring a capture group.
  • No remote kinds. SourceKind has four members and grows by a deliberate kernel change with a service method behind it - see the enum's own docstring for why it is an enum where DatasetChange.operation is a plain str.