1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! The [`Stage`] trait — the core user-implementable perception contract.
//!
//! Stages are the primary extension point for adding perception capabilities
//! to the pipeline. Each stage processes one frame at a time and produces
//! structured output.
//!
//! # Design intent: one trait, composed pipelines
//!
//! The library uses a **single** `Stage` trait for all stage types —
//! detection, tracking, classification, scene analysis, etc.
//! The abstraction stays minimal, and specialization happens by
//! convention (which fields a stage populates), not by type hierarchy.
//!
//! Instead, the pipeline _composes_ stages linearly: earlier stages write
//! fields into [`StageOutput`] that later stages read from
//! [`StageContext::artifacts`]. Specialization happens by convention (which
//! fields a stage populates), not by type hierarchy.
//!
//! # Supported model patterns
//!
//! The single-trait design naturally supports several model architectures:
//!
//! - **Classical detector → tracker**: a `FrameAnalysis` stage produces
//! detections, then an `Association` stage consumes them and produces tracks.
//! - **Joint detection+tracking**: a single `FrameAnalysis` stage sets both
//! `detections` and `tracks` in its [`StageOutput`]. No separate tracker
//! stage is needed.
//! - **Direct track emitter**: a stage produces `tracks` without intermediate
//! detections. Set `detection_id` to `None` on each `TrackObservation`.
//! - **Richer observations**: per-observation metadata (embeddings, features,
//! model-specific scores) is stored in `TrackObservation::metadata`.
//! Per-track metadata goes in [`Track::metadata`]. Per-frame shared data
//! goes in [`StageOutput::artifacts`].
//!
//! # What a stage should do
//!
//! - Process a single frame and return structured results.
//! - Read upstream artifacts from [`StageContext::artifacts`].
//! - Read temporal history from [`StageContext::temporal`].
//! - Populate only the [`StageOutput`] fields it owns.
//! - Remain stateless across feeds — internal state is per-feed.
//!
//! # What a stage should NOT do
//!
//! - Block on network I/O (manage async bridges internally).
//! - Mutate shared global state.
//! - Produce side-channel output bypassing [`StageOutput`].
//! - Depend on stage execution order beyond what upstream artifacts provide.
//! - Accumulate unbounded internal state (use the temporal store instead).
use cratePerceptionArtifacts;
use crateDetectionSet;
use crateSceneFeature;
use crateDerivedSignal;
use crateTemporalAccess;
use crateTrack;
use TypedMetadata;
use StageError;
use ;
use StageMetrics;
use FrameEnvelope;
use ;
/// Optional category hint for a perception stage.
///
/// Does not affect execution order or behavior — the pipeline executor
/// treats all stages uniformly. Categories serve as:
///
/// - **Documentation** — makes pipeline composition self-describing.
/// - **Metrics grouping** — category-aware dashboards and provenance.
/// - **Composition validation** — pipeline builders can warn about
/// unusual orderings (e.g., a tracker before a detector).
///
/// A stage may produce **any combination** of output fields regardless of
/// its declared category. Categories describe the stage's *primary role*,
/// not a hard constraint on what it can output. For example, a joint
/// detection+tracking model that reads pixels and produces both detections
/// and tracks in one forward pass is best categorized as `FrameAnalysis`.
///
/// Stages report their category via [`Stage::category()`], which defaults
/// to [`StageCategory::Custom`].
/// Declares what artifact types a stage produces and consumes.
///
/// Used by [`StagePipeline::validate()`](crate::StagePipeline::validate) to
/// detect unsatisfied dependencies (e.g., a tracker that consumes detections
/// placed before the detector that produces them).
///
/// Stages report capabilities via [`Stage::capabilities()`]. The default
/// implementation returns `None`, meaning the stage opts out of validation.
///
/// # Validated fields
///
/// The validator checks:
/// - `consumes_detections` / `produces_detections`
/// - `consumes_tracks` / `produces_tracks`
///
/// The remaining fields (`consumes_temporal`, `produces_signals`,
/// `produces_scene_features`) are informational — available
/// for external tooling but not enforced by the built-in validator.
///
/// # Example
///
/// ```
/// use nv_perception::StageCapabilities;
///
/// let caps = StageCapabilities::new()
/// .consumes_detections()
/// .produces_tracks();
/// ```
/// Context provided to every stage invocation.
///
/// Contains the current frame, accumulated artifacts from prior stages,
/// read-only view and temporal snapshots, and stage-level metrics.
///
/// All references are valid for the duration of the `process()` call.
/// Output returned by a stage's `process()` method.
///
/// Each field is optional — a stage only sets the fields it produces.
/// The pipeline executor merges this into the [`PerceptionArtifacts`] accumulator.
///
/// # Joint-model and direct-track-emitter patterns
///
/// A stage is not limited to producing a single artifact type. Common
/// patterns beyond classical detection:
///
/// - **Joint det+track model**: set both `detections` and `tracks` in a
/// single `StageOutput`. The executor merges both into the accumulator.
/// Tracks produced this way can carry per-observation metadata via
/// [`TrackObservation::metadata`](crate::TrackObservation::metadata).
/// - **Direct track emitter**: set only `tracks` (leave `detections` as
/// `None`). No intermediate `DetectionSet` is required. Set
/// `TrackObservation::detection_id` to `None` since there are no
/// upstream detections to reference.
/// - **Richer observations**: stages that produce typed artifacts
/// (embeddings, feature maps, attention weights) can store them in
/// [`TrackObservation::metadata`](crate::TrackObservation::metadata)
/// (per-observation) or [`Track::metadata`](crate::Track::metadata)
/// (per-track), or pass them as `artifacts` (per-frame typed metadata)
/// for downstream stage consumption.
/// Incremental builder for [`StageOutput`].
///
/// Created via [`StageOutput::build()`]. Each setter returns `self` for chaining.
/// The core user-implementable perception trait.
///
/// This is the **only** extension point for adding perception logic to the
/// pipeline. Stages run in a fixed linear order; each stage sees the
/// accumulated [`PerceptionArtifacts`] from all
/// prior stages.
///
/// All methods take `&mut self`. The executor holds exclusive ownership of each
/// stage on the feed's dedicated OS thread — stages are never shared across
/// threads or called concurrently within a feed.
///
/// Requires `Send + 'static` (moved onto the feed thread at startup).
/// Does **not** require `Sync` — stages do not need to be shareable.
///
/// # Lifecycle
///
/// 1. `on_start()` — called once when the feed starts.
/// 2. `process()` — called once per frame, in order.
/// 3. `on_view_epoch_change()` — called when the camera view changes significantly.
/// 4. `on_stop()` — called once when the feed stops.
///
/// # Error handling
///
/// - `process()` returning `Err(StageError)` drops that frame and emits a health event.
/// The feed continues processing subsequent frames.
/// - `on_start()` returning `Err` prevents the feed from starting.
/// - A panic in `process()` is caught; the feed restarts per its restart policy.
///
/// # Supported model patterns
///
/// The library supports multiple perception model patterns through the
/// same `Stage` trait. A stage may produce *any combination* of output
/// fields — the pipeline does not enforce a single pattern.
///
/// | Pattern | Reads | Writes | Category |
/// |---|---|---|---|
/// | Classical detector | frame pixels | `detections` | `FrameAnalysis` |
/// | Classical tracker | `detections`, temporal | `tracks` | `Association` |
/// | Joint det+track model | frame pixels, temporal | `detections` + `tracks` | `FrameAnalysis` |
/// | Direct track emitter | frame pixels | `tracks` (skip detections) | `FrameAnalysis` |
/// | Classifier / enricher | `detections` or `tracks` | `artifacts` (typed metadata) | `Custom` |
/// | Scene analysis | frame pixels, temporal | `scene_features`, `signals` | `TemporalAnalysis` |
///
/// These are conventions, not enforced constraints. A stage may read and write
/// any combination of fields.