Multimodal Training Data Ingestion and Curation Pipeline
Easy · ML System Design · Software Engineer · Technical Screen
Prompt
Architect a backend platform that receives, vets, and archives multimodal machine learning demonstrations submitted by a large fleet of client devices and operator stations.
Every uploaded submission bundles bulky visual assets (video streams or still photographs), time-indexed action trajectories, ground-truth task annotations, and hardware/session metadata. Before any submission enters a training corpus, an automated curation pipeline must run checks to:
- Identify misoriented or visually defective media, such as camera feeds or photographs captured upside down.
- Catch both byte-exact re-uploads and near-duplicate video clips or action trajectories.
- Screen out spam, adversarial noise, and low-effort or unusable recordings.
- Organize approved submissions in durable storage optimized for high-throughput downstream model training.
Scope & Expectations
- Define the ingestion APIs, resumable transfer flow for large media blobs, operational metadata schema, and training-ready storage layout.
- Detail the asynchronous validation pipeline, horizontal scaling strategy, fault-tolerance and retry guarantees, and end-to-end observability.
- Explain concrete mechanisms for visual defect and orientation checks, exact and near-duplicate trajectory detection, and submission quality scoring.
- Describe how to measure, alert on, and counteract representation skew and collection bias across the curated training dataset.
Step-by-step walkthrough
Clarify requirements and scope
In robotics and embodied AI, each training record — called an episode — bundles multi-camera video, high-frequency robot joint commands, task labels, and hardware metadata. Recording a two-minute episode takes real human operator and robot time. That creates a two-sided risk: an overly aggressive filter silently destroys expensive demonstrations, while a weak filter lets broken cameras, duplicate uploads, or farmed spam poison downstream model training. Our system must accept large uploads reliably, run validation asynchronously, and keep every filtering decision auditable and reversible.
Functional requirements
- Multimodal ingestion: Devices submit episodes bundling multi-stream video or still imagery, high-rate joint trajectories (commanded targets alongside measured states), task outcomes (activity ID, pass/fail flag), and session context (hardware model, firmware build, operator ID, facility, calibration profile).
- Automated curation checks:
- Flag inverted, out-of-focus, blacked-out, stalled, clock-skewed, or unreadable visual streams.
- Catch byte-identical uploads as well as perceptually or kinematically similar trajectories.
- Screen out farmed noise, idle padding, and substandard demonstrations.
- High-throughput training storage: Pack approved episodes into sequential archives that distributed GPU jobs can stream at line rate, backed by immutable dataset manifests.
- Transparency and slice balance: Surface submission states and actionable rejection codes to uploaders, while tracking and correcting representation skew across operators, facilities, tasks, and lighting conditions.
Non-functional requirements
- Zero loss after completion: Uploads must resume cleanly across flaky Wi-Fi, and once acknowledged as complete, no episode may be silently lost.
- Turnaround latency: Produce an accept/reject/review decision within 30 minutes for 95% of uploads so operators get timely feedback.
- Reversibility: Filters and ML quality models will evolve. Raw data and per-stage scores must be versioned so decisions can be recomputed without re-uploading media.
- Horizontal scalability and fairness: Scale smoothly with fleet size and isolate noisy clients so one uploader's burst cannot stall everyone else.
Assumptions for sizing
- Clients: 1,000 robots and teleoperation stations (mix of in-house fleets and external contractors paid per accepted hour), each recording ~6 hours per day.
- Episode shape: Average 2 minutes (120 seconds) with 3 cameras at 720p, 30 frames per second (fps), H.264 encoded at 4 Mbit/s per camera, plus 30 robot joints logged at 50 Hz. Some uploads are single-image records.
- Duplicates: Performing the same task twice (such as folding two towels) is valuable training diversity; uploading the same recording twice or replaying recorded motor commands to farm payouts is a duplicate.
Back-of-the-envelope numbers
Walking through the arithmetic step by step exposes where the real bottlenecks sit:
Fleet & episode rate Active fleet 1,000 devices x 6 recorded hours/day (21,600 s/day) Episodes per device 360 min / 2 min per episode = 180 episodes/device/day Fleet episodes 1,000 x 180 = 180,000 episodes/day (~65.7M episodes/year) Arrival rate 180,000 / 86,400 s = ~2.1 episodes/s average Shift-end upload bursts (3x) = ~6.3 episodes/s peak Episode size & bandwidth Video bitrate 3 cameras x 4 Mbit/s = 12 Mbit/s = 1.5 MB/s (since 8 bits = 1 byte) Video per episode 1.5 MB/s x 120 s = 180 MB total (~60 MB per camera file) Actions per episode 50 Hz x 30 joints x 2 floats (command + state) x 4 B x 120 s = 1.44 MB (<1%) Daily fleet volume 1,000 devices x 1.5 MB/s x 21,600 s = 32.4 TB/day Ingress throughput 32.4 TB / 86,400 s = 375 MB/s average (~3 Gbit/s) 3x shift-end peak = ~1.13 GB/s (~9 Gbit/s) Storage footprint Annual raw media 32.4 TB/day x 365 = ~11.8 PB/year Accepted (~70%) 0.70 x 11.8 PB = ~8.3 PB/year kept long-term Rejected (~30%) Kept 30 days for appeals/retraining: 0.30 x 32.4 TB x 30 = ~292 TB Compute & indexing Keyframe sample 1 frame/s x 3 cameras x 120 s = 360 frames/episode Sync check clip 4 s of head camera at full 30 fps = 120 frames/episode Total decoded 480 frames/episode -> 1,000 frames/s avg (3,000 frames/s peak) Full decode avoided 3 cameras x 30 fps x 120 s = 10,800 frames/episode (22,500 frames/s avg) Sampling + sync clip decodes 22.5x fewer frames than full video decode Near-dup vectors 65.7M episodes/year x 128-byte int8 vector = ~8.4 GB/year (~14 GB in RAM) Human review budget 3,000 episodes/day (~1.7% of traffic, ~50 reviewer-hours/day at 1 min each): 900/day (0.5%) random audit + 2,100/day uncertain borderline episodesThree design decisions follow immediately from these numbers:
- Media bytes never pass through API servers. Routing 1.13 GB/s of video through backend instances wastes network and memory; clients upload media directly to cloud object storage.
- Video decoding dominates compute, not neural network inference. Requiring clients to encode a keyframe (also called an I-frame, a self-contained video frame that can be decoded on its own without reading surrounding frames) once per second lets workers decode 22.5× fewer frames than a full decode.
- Human review capacity is fixed (~3,000 episodes/day). Automated filter thresholds must be tuned so borderline episodes fit inside that daily review budget.
API and resumable upload flow
Every device authenticates with mutual TLS (mTLS) or a per-device API key and is subject to daily episode and byte quotas. To handle 180 MB uploads over spotty Wi-Fi, we combine three building blocks:
- An idempotency key is a unique client-generated token attached to a request so retrying the exact same call returns the original result instead of creating duplicate records.
- A multipart upload splits a large file into independent chunks (here 16 MiB each) so a dropped connection only retries one chunk instead of restarting a 60 MB file from zero.
- A presigned URL is a temporary, cryptographically signed link generated by the API that grants a client permission to upload a specific chunk directly to object storage for a limited time (such as 1 hour).
1. Register episode manifest POST /v1/episodes Idempotency-Key: <client_id>:<local_episode_uuid> Body: { device_id, operator_id, site_id, recorded_at, duration_s: 120, labels: { task: "fold_towel", success: true }, metadata: { robot_model, firmware, calibration_id, keyframe_interval_s: 1 }, files: [ { name: "cam_head.mp4", kind: "video", size: 62914560, sha256: "..." }, { name: "cam_wrist_l.mp4", kind: "video", size: 58720256, sha256: "..." }, { name: "cam_wrist_r.mp4", kind: "video", size: 59768832, sha256: "..." }, { name: "actions.parquet", kind: "actions", size: 1450000, sha256: "..." } ] } -> 201 Created { episode_id, uploads: [ { name, part_size: 16777216, part_urls: ["https://..."] } ] } (Repeating the same Idempotency-Key returns the existing episode_id and URLs for missing parts.) 2. Upload media chunks directly to object storage (bypassing API servers) PUT <presigned_part_url> (16 MiB chunks uploaded in parallel; returns per-part ETag checksum) 3. Commit upload and enqueue validation POST /v1/episodes/{episode_id}:complete Body: { files: [ { name: "cam_head.mp4", parts: [ { part_number: 1, etag: "..." }, ... ] } ] } -> 202 Accepted { status: "QUEUED" } 4. Poll status and contributor quality feedback GET /v1/episodes/{episode_id} -> { status, reasons: [...], decided_at, filter_versions } GET /v1/clients/{client_id}/quality -> { rolling_accept_rate, top_rejection_reasons } 5. Build versioned training dataset (internal ML platform call) POST /v1/datasets { filters, slice_caps, sampling_weights } -> { dataset_id, manifest_uri }The handoff contract is strict: the client keeps its local files on disk until
:completereturns202 Accepted. During:complete, the API verifies that every declared file exists in object storage with the expected byte size, transitions the episode fromUPLOADINGtoQUEUED, and hands ownership to the backend (QUEUED -> PROCESSING -> ACCEPTED | REJECTED | NEEDS_REVIEW, orFAILEDif worker retries exhaust). Single-image uploads use the exact same flow with a single part.Data model and storage layout
Different parts of the system read data in completely different ways, so we separate operational state, raw media, analytical metadata, and packed training data:
- Object storage (such as Amazon S3 or Google Cloud Storage) is a flat, durable blob store ideal for large immutable media files, but slow if ML jobs make millions of tiny random reads.
- Apache Parquet is a columnar file format that stores values of the same column together for fast analytical scans, and Apache Iceberg is a table format layered over Parquet files in object storage that provides SQL queries, atomic snapshots, and schema evolution.
- Training shards (such as ~1 GB TAR/WebDataset archives) pack hundreds of accepted episodes sequentially so GPU training nodes stream large contiguous blocks at full network speed.
1. Object storage (immutable raw uploads) Key: episodes/<yyyy>/<mm>/<dd>/<episode_id>/<filename> - Written once; accepting or rejecting never copies or moves the 180 MB media. - Lifecycle rule aborts incomplete multipart uploads after 7 days. - Daily cleanup job deletes rejected media 30 days after decided_at (using decided_at rather than upload time prevents immediately deleting an old episode newly rejected by a backfill). - Accepted raw media transitions to cheaper infrequent-access storage after 90 days. 2. Postgres (operational state & idempotency) - episode(episode_id PK [UUIDv7], client_id, device_id, idempotency_key UNIQUE, status, recorded_at, labels jsonb, metadata jsonb, created_at, decided_at) - file(episode_id, name, kind, size_bytes, sha256, object_key, PRIMARY KEY (episode_id, name)) - stage_result(episode_id, stage, stage_version, status, outputs jsonb, attempts, updated_at, PRIMARY KEY (episode_id, stage, stage_version)) - content_hash(sha256 PRIMARY KEY, first_episode_id) - client(client_id PK, trust_tier, reputation_score, quota_bytes_per_day) 3. Similarity indexes (partitioned by (robot_model, task)) - Action & video vector index: 128-dim int8 embeddings per episode (~8.4 GB/year per modality) - Keyframe hash tables: 12 head-camera 64-bit perceptual hashes per episode (1 every 10 s), indexed in four 16-bit band lookup tables for fast candidate retrieval 4. Analytics catalog (Iceberg over Parquet) - One wide row per episode: metadata, labels, all stage scores, filter_versions, decision, rejection_reasons, dedup_cluster_id, and bias slice attributes 5. Packed training datasets (object storage) - datasets/<dataset_id>/shard-{00000..09999}.tar (~1 GB sequential shards) + manifest.jsonNotice two subtle schema choices in Postgres:
stage_resultincludesstage_versionin its primary key. Running a v2 orientation classifier alongside v1 simply inserts a second row without overwriting v1's score, making every filter upgrade reversible and easy to compare.- UUIDv7 for
episode_id. A UUIDv7 is a globally unique 128-bit ID whose leading bits encode a millisecond timestamp, keeping new inserts clustered at the end of B-tree indexes and lettingstage_result(~460M rows/year across 7 stages) be range-partitioned roughly by month onepisode_idwhile keepingepisode(idempotency_key)andcontent_hash(sha256)globally unique in unpartitioned tables (~66M rows/year).
High-level architecture
To guarantee no completed episode is ever stranded in Postgres without a validation job, the ingest API uses the transactional outbox pattern — writing both the
episodestatus update and anoutboxqueue message inside a single ACID database transaction, which a lightweight relay process forwards to the job queue.Robots, Teleop Rigs, Contractor Stations | 1. POST /v1/episodes | 3. POST /v1/episodes/{id}:complete v v [ API Gateway: mTLS auth, per-client rate & byte quotas ] | | | 2. Parallel PUT (16 MiB parts) v | [ Stateless Ingest API ] ---> [ Operational Postgres ] | | (episode + outbox tx, v | 4. Outbox relay stage_result, hashes) [ Object Storage: Raw Media ] v ^ ^ [ Stage Job Queues (SQS-style) ] | | Stream keyframes & files | | +-------------------------- [ Filtering Workers ] ------------------+ Stage 1: Integrity (CPU + I/O) Stage 2: Metadata & kinematics rules (CPU) Stage 3: Exact hash dedup (Postgres lookup) Stage 4: Frame quality & orientation (CPU decode + GPU) Stage 5: Action/video near-dup (GPU + ANN/DTW) Stage 6: Spam/quality GBDT scorer (CPU) Stage 7: Policy decision & routing | \ v v [ Iceberg Data Catalog ] [ Human Review Tool ] | | (audit + borderline) v v | [ Bias & Drift Reports ] [ Dataset Builder ] <+ | v [ ~1 GB Training Shards ] --> [ GPU Training ]Asynchronous filtering pipeline
Validation runs as a staged funnel ordered from cheapest to most expensive, stopping immediately on any hard failure so corrupted uploads or obvious spam never burn GPU cycles:
Stage Checks performed Typical cost 1. Integrity Verify whole-file SHA-256 against manifest, container ~1-2 s streaming I/O headers parse, video duration matches actions, 1 s keyframe interval present 2. Fast rules Registered device, timestamp not in future, duration < 10 ms CPU >= 5 s, task label in taxonomy, joint values finite (no NaN/Inf), within physical joint limits, non-zero motion variance 3. Exact dedup Lookup file SHA-256s and quantized action-sequence ~2 ms DB lookup SHA-256 in content_hash table 4. Frame checks Decode 360 keyframes + 120 sync frames; check black, ~1-3 s CPU + batched GPU blur, frozen feed, camera orientation, video-action lag 5. Near-dup Keyframe perceptual-hash band lookup + action ANN ~50-100 ms CPU search + Dynamic Time Warping (DTW) residual check 6. Quality score Gradient-boosted tree scoring all features + client < 5 ms CPU reputation history 7. Decision Apply precision/review-budget thresholds -> ACCEPTED, < 5 ms DB + event emit REJECTED (with reason code), or NEEDS_REVIEWWhy per-stage job queues instead of Kafka partitions for worker execution? Episode durations and retry behavior vary wildly — a 10-minute episode or a malformed MP4 that crashes
ffmpegtakes far longer than a 20-second clip. In a partition-ordered log like Apache Kafka, one stuck message blocks every newer message in that partition unless you build side-queues. An SQS-style job queue gives each message an independent visibility timeout (a lease window during which a worker hides the message from other workers; if the worker crashes before acknowledging completion, the message automatically reappears for retry) and routes poison messages that fail 5 times to a dead-letter queue (DLQ) (a holding queue for repeatedly failing jobs so engineers can inspect them without blocking healthy traffic). Once Stage 7 reaches a verdict, we do publish anepisode.decidedevent to an event stream to populate the Iceberg catalog and real-time dashboards.Idempotent stages: Queue delivery is at-least-once, meaning a worker retry can run the same stage twice. Every worker writes its output via
INSERT INTO stage_result ... ON CONFLICT (episode_id, stage, stage_version) DO UPDATEand advances the episode state with a guarded compare-and-swap (UPDATE episode SET status = next_stage WHERE episode_id = $1 AND status = current_stage), making duplicate execution harmless.Deep dive: inverted camera feeds, media defects, and quality scoring
1. Upside-down and invalid frames
Whether an image is "upside down" depends on physical camera mounting:
- Static images: Check the EXIF orientation tag first (camera metadata stored in image headers indicating whether the sensor was rotated 90°, 180°, or 270°). Missing or misapplied EXIF tags cause most "upside-down" image bugs without any hardware issue.
- Fixed head/scene cameras: Gravity stays aligned with the frame. We run a lightweight 4-way orientation CNN (
0°, 90°, 180°, 270°) across the 120 sampled keyframes and take a majority vote. Training labels are free (self-supervised): take verified upright frames from each robot environment, rotate them randomly by0°, 90°, 180°, 270°, and train the CNN to predict the applied rotation. If>80%of keyframes predict the same non-zero angle at>0.90confidence, we flag the stream. Better yet, if a camera was mounted upside down (180°across the whole episode), we do not discard the expensive demonstration — we recordtransform: rotate_180in metadata for the dataset builder and alert the site technician to remount the camera. - Rotating wrist cameras: A gripper camera legitimately turns upside down while pouring or grasping! Running a naive horizon detector would falsely reject valid grasps. Instead, we compute the expected camera roll from the robot's joint angles (forward kinematics) and camera calibration matrix, and only flag the stream if the visual orientation consistently disagrees with the physical joint pose.
On those exact same decoded keyframes, fast CPU statistics catch other media defects: - Blank or blown-out frames: Mean pixel luminance near 0 (lens cap on) or 255 (saturated sensor). - Blurry or smudged lens: Variance of the Laplacian (a fast edge-detection filter whose variance drops near zero when sharp edges disappear). - Frozen camera stream: Identical consecutive perceptual hashes while robot joints are moving. - Audio/video-to-action clock drift: Keyframes 1 second apart are too coarse to spot a 100 ms timestamp offset, so Stage 4 decodes one 4-second head-camera window at full 30 fps (120 frames, 33 ms spacing) and cross-correlates visual optical-flow magnitude against robot joint speed. A lag exceeding 100 ms rejects the episode for misaligned clocks.
2. Adversarial spam and low-effort demonstrations
Paid external contractors may wave the robot arms aimlessly, leave the robot idle for 110 of 120 seconds, or label failed attempts as
success: true. We frame quality filtering as a supervised ML ranking problem:- Problem framing: Output a calibrated quality probability
q in [0, 1]mapped to three actions:REJECT(q < T_low),NEEDS_REVIEW(T_low <= q < T_high), orACCEPT(q >= T_high), combined with deterministic hard-reject rules. - Unbiased labels via random audit: If humans only label episodes in the
NEEDS_REVIEWband, our training and test sets suffer severe selection bias. We route a uniform 0.5% random audit sample (~900 episodes/day) from all incoming episodes (including ones the model wanted to auto-accept or auto-reject) to human reviewers. Offline metrics are computed strictly on this unbiased audit set. - Features & model: Gradient-boosted decision trees (GBDT) (an ensemble of small decision trees that excels on tabular features with thousands of labels and provides clear feature attributions) trained on: idle-time fraction, end-effector path length, motion smoothness (jerk, the rate of change of acceleration), frame sharpness/brightness stats, nearest-neighbor action similarity, episode duration, and contributor features (rolling audited acceptance rate, upload burstiness).
- Thresholds & offline metrics: Set
T_lowso auto-reject precision is ≥ 95% on the random audit set (protecting good demonstrations), then setT_highso theNEEDS_REVIEWband uses the remaining ~2,100 reviews/day. Track precision, recall, false-rejection rate, and false-acceptance rate per data slice (site, lighting bucket, robot model). - Serving: Stage 4 batches keyframes across episodes onto GPUs (2–4 data-center GPUs easily handle 3,000 frames/s peak for a small 224×224 CNN), while Stage 6 runs GBDT inference in
<5 mson CPU, logging exact model versions instage_result.
Deep dive: exact and near-duplicate detection
"Duplicate" actually covers five distinct scenarios that need different detectors and policies:
Scenario Detection method System action 1. Network timeout retry Idempotency-Key match in Postgres Return existing episode_id 2. Exact same file re-uploaded Whole-file SHA-256 in content_hash Auto-reject (EXACT_DUP) 3. Video re-encoded, resized, or trimmed Keyframe 64-bit perceptual hashes Auto-reject (VIDEO_DUP) 4. Recorded motor actions replayed / noised Action vector ANN + DTW residual check Review or reject (REPLAY) 5. Same task demonstrated again by a human High-level path match, human residual Accept + assign cluster_idNear-duplicate video: Each sampled head-camera keyframe is converted to a 64-bit perceptual hash (such as
dHash, which downscales an image to a tiny 9×8 grayscale grid and sets 64 bits based on whether adjacent pixels brighten or darken — staying within 0–3 bit flips across re-encoding or resizing). Indexing all 120 head-camera frames across 65.7M annual episodes would create ~8 billion entries, so we index 1 frame every 10 seconds (12 hashes/episode) and query with all 120 frames of a new episode (guaranteeing a query frame lands within 0.5 seconds of an indexed frame even if the clip was trimmed).To avoid scanning millions of hashes linearly, we split each 64-bit indexed hash into four 16-bit bands, maintaining 4 hash tables per
(robot_model, task)partition. By the pigeonhole principle, if two 64-bit hashes differ in at most 3 bits, at least one of the 4 bands must have zero differing bits and collide in that band's lookup table. In a large partition of 10M indexed hashes (~830k episodes), each of the2^16 = 65,536buckets holds10,000,000 / 65,536 ≈ 153entries. Querying 4 bands across 120 frames inspects120 × 4 × 153 ≈ 73,00064-bit integers via single-instruction XOR + bit-count (popcount), finishing in<1 msin RAM. Any candidate episode with multiple frame hits is verified against its full 120-hash sequence (~1 KB instage_result): if most frames match in order at a constant time offset, it is a re-encoded copy.Near-duplicate actions: How do we separate a fraudster replaying recorded commands from an honest operator folding a towel a second time?
- Canonicalize: Trim leading/trailing idle seconds, resample the 50 Hz actions to 10 Hz (
1,200steps for a 2-minute episode), and normalize each joint's physical range to[0, 1]. - Exact replay hash: Quantize values to 1% bins and SHA-256 hash the sequence; identical hashes mean identical motor commands (impossible for human hands).
- Candidate search via ANN: Downsample the episode to 64 evenly spaced steps (
64 × 30 joints = 1,920floats), project to a 128-dimint8vector, and query an Approximate Nearest Neighbor (ANN) index (a graph or clustered vector structure that finds top-k closest vectors in milliseconds without scanning every vector) within the same(robot_model, task)partition for the top 10 neighbors. - Verify with Dynamic Time Warping (DTW): DTW aligns two time-series sequences even if one was executed slightly faster or slower. Running DTW on the 10 Hz sequence (
1,200steps) with a±10%(±120-step) warp band evaluates1,200 × 241 ≈ 290,000cells per candidate (<100 mstotal for 10 candidates). After alignment, we inspect the residual error:- Residual near the hardware sensor-noise floor, or tiny uncorrelated step-to-step white noise added synthetically -> replayed trajectory (
REJECTorNEEDS_REVIEW). - Smooth, low-frequency variation centimeter-scale above sensor noise -> genuine human demonstration (
ACCEPT, tagging a shareddedup_cluster_idso the dataset builder can cap repetitive clusters).
- Residual near the hardware sensor-noise floor, or tiny uncorrelated step-to-step white noise added synthetically -> replayed trajectory (
- Canonicalize: Trim leading/trailing idle seconds, resample the 50 Hz actions to 10 Hz (
Deep dive: measuring dataset skew, rebalancing slices, and filter A/B tests
Real-world robot datasets accumulate bias from two directions: skewed collection (a few fast operators produce half the hours, bright daytime labs dominate, operators delete failed grasps so models never learn recovery behaviors) and skewed filtering (a quality model trained mostly on bright labs accidentally rejects dim home kitchens as "low quality").
Bias detection
- Slice coverage matrix: Every episode in the Iceberg catalog carries structured slice tags:
operator_id,site_id,robot_model,firmware,task,lighting_bucket(from mean frame luminance),time_of_day, andsuccess. Dashboards compare accepted hours per slice against target quotas set by ML researchers. - Contributor concentration: Track the effective number of contributors,
N_eff = 1 / sum(p_i^2), wherep_iis operatori's fraction of accepted hours. If 100 operators upload data equally (p_i = 0.01),N_eff = 100; if a few operators dominate,N_effdrops to 12 and triggers a concentration warning. - Filter fairness alerts: Monitor rejection rates per slice. If a slice with
>= 200episodes is rejected at> 2xthe fleet average, check the random audit set for that slice: a high audited false-rejection rate proves the filter itself is biased against that environment, whereas a low false-rejection rate points to a real hardware or operator problem at that site. - Unsupervised visual coverage: Run monthly k-means clustering over accepted video embeddings to spot visual environments shrinking over time.
Bias mitigation (fix at dataset build time, never by deleting valid uploads)
- Rebalance in the dataset builder: Keep all valid episodes in storage, and enforce diversity when building training shards — capping any single operator at
<= 5%of a dataset, capping singlededup_cluster_idgroups, and applying inverse-propensity sampling weights to under-represented lighting or object slices. - Collection bounties & failure incentives: Publish live collection targets (such as higher contractor payouts for low-light kitchen tasks) and explicitly pay for honest
success: falserecovery episodes so operators stop hiding mistakes. - Unbiasing filters: Up-weight rare slices in GBDT training or calibrate per-slice rejection thresholds using the audit set.
Evaluating filter upgrades via Dataset A/B tests
Because raw media and versioned
stage_resultrows are preserved, we do not need to split live uploads randomly: 1. Offline audit check: Verify v2 beats v1 on overall and per-slice false-rejection rate on the random audit set. 2. Shadow mode: Run v2 alongside v1 on 100% of live uploads for 1–2 weeks without changing live verdicts; have humans label a sample of episodes where v1 and v2 disagree. 3. Paired Dataset A/B test: BuildDataset_A(episodes accepted by v1) andDataset_B(episodes accepted by v2) over the exact same two-week window, train the identical downstream robot policy recipe on both, and compare task success rates in simulation and real-robot evaluations.- Slice coverage matrix: Every episode in the Iceberg catalog carries structured slice tags:
Scaling, reliability, observability, and trade-offs
Scaling and bottlenecks
- Ingest API & storage prefixes: At 6.3 episodes/s peak, the stateless API handles
<30lightweight metadata calls/s. With 16 MiB chunks, 1.13 GB/s peak equals~70chunkPUTs/s directly to object storage — well below cloud object storage limits (such as S3's 3,500PUT/s per key prefix). - Decoupled CPU and GPU worker pools: Video decoding runs on CPU pools while orientation/embedding inference runs batched on GPU pools, each autoscaling on the age of the oldest queued message toward our 30-minute p95 turnaround target. Per-client concurrency limits prevent one partner's 10× upload dump from starving other devices.
Failure modes and recovery
- Stuck jobs & GPU outages: Failed tasks retry with exponential backoff up to 5 times before landing in the DLQ (
FAILEDstatus + alert), and a periodic reaper re-enqueues any episode stuck inPROCESSINGfor>2 hours. If the GPU pool goes down for 4 hours, uploads continue uninterrupted while2.1 ep/s × 14,400 s = ~30,000episodes queue safely; once GPUs return (provisioned for 3× peak =6.3 ep/s), net drain is6.3 - 2.1 = 4.2 ep/s, clearing the backlog in~2 hours. - Storage durability: Postgres runs with a synchronous cross-zone standby; object storage replicates across availability zones automatically.
Observability
- System health: End-to-end decision latency (
p50/p95), queue age per stage, DLQ depth, GPU batch utilization, and compute cost per accepted training hour. - Data health: Acceptance rate sliced by client, site, and firmware version; feature/score drift measured via the Population Stability Index (PSI) (a single number quantifying how much a score distribution has shifted relative to a 4-week baseline); and human-reviewer overturn rate. For example, if a new robot firmware update accidentally flips a wrist camera feed, an alert on orientation-rejection spikes for that firmware version pages engineers within an hour.
Summary of key trade-offs
- Direct presigned multipart uploads vs. API proxy: Keeps 1.13 GB/s off API servers and makes uploads resumable in 16 MiB increments, at the cost of a 3-step upload protocol and orphan-upload cleanup.
- Keyframe-only decoding vs. full video decoding: Cuts decoding compute by 22.5×, trading slightly larger video files (1-second keyframe interval) and not inspecting sub-second visual glitches outside the sync window.
- Reject junk vs. tag-and-rebalance bias: Hard defects and replays are rejected, while valid repeats and over-represented operators are retained and rebalanced in the dataset builder — preserving raw data at the cost of a smarter dataset-packing stage.
- 30-day rejected retention +
0.5%random audit vs. immediate deletion: Costs ~292 TB of temporary storage and ~900 human reviews/day, buying unbiased filter metrics, contributor appeals, negative training examples, and paired dataset A/B tests.
- Ingest API & storage prefixes: At 6.3 episodes/s peak, the stateless API handles
Intuition & how it works
Think of this system like a film studio's intake facility receiving thousands of raw footage reels from camera crews around the world. Instead of squeezing heavy 180 MB film canisters through the receptionist's small front window and forcing couriers to wait in line while editors inspect every frame, the receptionist checks the courier's badge, records a manifest slip, and hands back temporary locker keys (presigned URLs, which are short-lived signed links letting a client upload chunks straight into cloud object storage). Once the courier confirms all chunks are locked away, an assembly line of background inspectors checks the footage from cheapest to most expensive — verifying file checksums in milliseconds before ever waking up a GPU to inspect camera angles or trajectory duplicates — and writes every verdict on the tracking slip without moving or deleting the master tape.
The naive approach — uploading videos directly through backend web servers and running validation models synchronously inside the HTTP upload request — breaks down immediately at scale. At a 1.13 GB/s shift-end peak, proxying video bytes saturates API server memory and network cards, and any slow GPU check or flaky Wi-Fi drop times out the entire 180 MB upload. Worse, decoding every frame of 30 fps video (22,500 frames/s fleet-wide) wastes massive compute on nearly identical consecutive frames, and deleting rejected or repetitive uploads right away makes filter bugs impossible to undo.
Here is how three concrete 2-minute episodes move through our pipeline:
1. Ep-101 (corrupted upload): A station uploads three 60 MB videos in 16 MiB chunks and calls :complete (202 QUEUED). Stage 1 (Integrity) streams the bytes, sees cam_head.mp4's SHA-256 checksum mismatches the manifest, marks REJECTED (CORRUPT_MEDIA) in 2 seconds, and never touches a GPU.
2. Ep-102 (valid rotating wrist camera): Passes integrity, joint-limit rules, and exact hash lookup in milliseconds. Stage 4 decodes 1 keyframe/second (plus a 4-second 30 fps sync clip); the wrist camera looks upside down mid-grasp, but matches the expected roll from the robot's joint angles, so Stages 5–7 score it 0.94 and mark ACCEPTED, later packing it into a 1 GB training shard.
3. Ep-103 (contractor action replay): Has fresh video so file and frame hashes look new, but Stage 5 projects its joint trajectory into an Approximate Nearest Neighbor (ANN) vector index (a fast search structure for finding similar embeddings), retrieves Ep-102, aligns both 10 Hz sequences with Dynamic Time Warping (DTW) (an algorithm that aligns two time series across slight speed changes), sees the difference is tiny synthetic white noise rather than natural human variation, and flags REJECTED (ACTION_REPLAY).
Key trade-offs
- Direct presigned multipart uploads vs. streaming media through API servers. Direct 16 MiB chunked uploads keep 1.13 GB/s of video off application servers and let interrupted uploads resume from the last chunk. The trade-off is a three-step client protocol (
create -> PUT parts -> complete) and background cleanup for abandoned uploads. - Asynchronous staged job queues vs. synchronous validation. Returning
202 Acceptedonce bytes are durable decouples upload reliability from heavy ML inference and lets cheap CPU checks filter out junk before GPU stages run. Clients wait minutes rather than milliseconds for a final verdict, requiring status endpoints and clear rejection codes. - Per-message job queues vs. partitioned logs for worker execution. A queue with a visibility timeout (a per-task processing lease that automatically retries crashed tasks) isolates slow or poison episodes so they never block neighbors, whereas a partition-ordered log like Kafka stalls an entire partition behind one slow video. Event logs remain ideal for downstream
episode.decidedevents consumed by analytics. - Keyframe-only decoding vs. full 30 fps decoding. Requiring a 1-second keyframe (a self-contained video frame decodable without prior frames) plus one 4-second 30 fps sync clip cuts decoded frames by 22.5×, trading slightly higher video bitrate and missing sub-second glitches outside the sync window.
- Hard-reject defects vs. tag-and-rebalance bias and valid repeats. Corrupted files and replayed trajectories are rejected, while genuine task repeats and over-represented operators are accepted with cluster and slice tags so the dataset builder enforces diversity later. Keeping valid data preserves flexibility for different training runs at the cost of a smarter dataset-packing pipeline.
- Strict auto-reject precision (
≥ 95%) + random audit (0.5%) vs. human review cost. High auto-reject precision protects expensive robot demonstrations, while routing ~900 random episodes/day to humans provides the only unbiased ground truth for filter accuracy and fairness — consuming ~30% of the 3,000/day review budget. - Retaining rejected media for 30 days and versioned
stage_resultrows vs. immediate deletion. Roughly 292 TB of rolling storage pays for contributor appeals, retraining spam classifiers on negative examples, reversible filter backfills, and paired dataset A/B tests.
Common mistakes
- Streaming 180 MB videos through backend web servers in a single request, causing server OOMs and forcing clients on spotty Wi-Fi to restart entire uploads from byte zero.
- Treating all similar trajectories as duplicates — or missing motor replays. Two humans folding a towel naturally follow similar paths and should both be kept; conversely, replaying recorded joint commands on a real robot creates brand-new camera footage, which only action-trajectory alignment (DTW residual analysis) catches.
- Running a generic "is this image upside down?" classifier on wrist cameras, which legitimately invert whenever the robot rotates its gripper, instead of comparing visual orientation against physical joint kinematics.
- Evaluating and retraining the quality model only on borderline
NEEDS_REVIEWepisodes, which creates severe selection bias because the model never sees its own false rejections or false acceptances without a uniform random audit sample. - Trying to fix dataset bias by deleting valid uploads from prolific operators at ingestion, throwing away useful data instead of tagging slices and rebalancing weights or caps in the dataset builder.
- Skipping stage idempotency, forgetting that at-least-once queues will occasionally run the same worker stage twice and corrupt statuses unless writes upsert on
(episode_id, stage, stage_version). - Monitoring only infrastructure metrics (CPU, queue latency) and ignoring data-distribution drift, missing cases like a firmware update that flips a camera stream and silently spikes orientation rejections while every server looks healthy.
Follow-up questions
- How would you redact personally identifiable visual details like faces, badges, or monitors before records enter training sets? Insert a dedicated anonymization worker stage ahead of
ACCEPTEDstatus that runs face, badge/plate, and screen detectors over sampled keyframes (widening to full-rate frame windows around hits) and writes a blurred derivative video used exclusively for training shards. Unredacted originals are either isolated in a short-TTL compliance bucket with strict audit logging or purged immediately according to the facility's consent policy stored onepisode. Because both the Iceberg catalog and shard manifests recordepisode_idlineage, subsequent deletion requests can remove specific recordings cleanly from raw buckets and future dataset versions. - When an improved orientation or quality classifier ships months later, how do you re-evaluate historical uploads without disrupting live traffic? Register the upgraded classifier under a new
stage_versionand launch a rate-limited batch job that selects candidate episodes from the Iceberg catalog (for instance, recent orientation rejections within the 30-day retention window plus an accepted baseline sample) and pushes them onto a dedicated low-priority backfill queue isolated from the live 30-minute SLA workers. Backfill workers append new(episode_id, stage, stage_version)score rows without overwriting historical scores and re-run policy thresholds with zero client re-uploads. Long-term accepted media can be rescored anytime, while rejected raw videos older than 30 days are intentionally out of scope once purged. - What system and incentive controls stop paid external contributors from reverse-engineering and gaming the automated quality scorer? Return only coarse, human-fixable rejection categories (such as
CAMERA_BLURRYorHIGH_IDLE_TIME) rather than raw model probabilities or feature cutoffs. Hold contractor payouts inside a settlement window until uniform random audits and batch trajectory-cluster checks finish, enabling clawbacks on replayed or padded sessions. Track a rolling contributor trust score in Postgres that automatically raises human-audit sampling rates on newly onboarded accounts or sudden volume spikes, and continuously retrain the GBDT scorer on fresh audited labels as adversarial patterns shift.
Follow-up questions
- How would you redact personally identifiable visual details like faces, badges, or monitors before records enter training sets?
- When an improved orientation or quality classifier ships months later, how do you re-evaluate historical uploads without disrupting live traffic?
- What system and incentive controls stop paid external contributors from reverse-engineering and gaming the automated quality scorer?
Similar questions
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models
- Hybrid Talent Search and Ranking Architecture
- Local Document RAG CLI and Streaming Service with Mistral
- Greenfield Recommendation Engine and Grounded Discovery Assistant