Skip to content

Python API

The Python API is the boundary the GUI and CLI drive. This reference is generated from the docstrings.

Experiment and recording

detail.api.experiment.Experiment

Source code in detail/api/experiment.py
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
class Experiment:
    def __init__(self, experiment_dir: Path | str) -> None:
        self._dir = Path(experiment_dir)

    @classmethod
    def create(cls, name: str, parent_dir: Path | str | None = None) -> "Experiment":
        """Create the experiment directory structure and config.yaml.

        ``parent_dir`` defaults to the managed workspace root (the ``default``
        storage location, §2) — the GUI never picks a folder.
        """
        if parent_dir is None:
            parent_dir = locations.experiments_root()
        return cls(experiment_store.create_experiment(parent_dir, name))

    @classmethod
    def open(cls, experiment_dir: Path | str) -> "Experiment":
        """Open an existing experiment (validates config.yaml)."""
        experiment_store.read_config(experiment_dir)
        return cls(experiment_dir)

    @classmethod
    def list_all(cls) -> list["Experiment"]:
        """All experiments in the managed workspace (storage ``default`` root, §2)."""
        return [cls(p) for p in locations.list_experiment_dirs()]

    @classmethod
    def import_archive(
        cls,
        archive: Path | str,
        *,
        replace: bool = False,
        name: str | None = None,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> "Experiment":
        """Import an exported experiment bundle into the managed workspace (§15).
        Creates it, or replaces a same-id experiment when ``replace`` is True; ``name``
        overrides the target id (import as a separate copy).

        Args:
            progress: ``(stage, fraction, detail)`` callback — ``reading`` →
                ``extracting`` → ``verifying`` → ``placing``. A callback that raises stops
                the import with nothing placed.

        A recording whose video is referenced in place is looked for where the exporting machine
        had it, and its video root registered here when a video there matches (#916);
        `referenced_video_missing` lists what was not found.

        Raises:
            ValueError: Malformed/corrupt archive or unsupported schema_version.
            FileExistsError: Target id exists and ``replace`` is False.
        """
        dest = export_store.import_experiment(
            archive,
            locations.experiments_root(),
            replace=replace,
            name=name,
            progress=progress,
        )
        return cls(dest)

    @staticmethod
    def replace_losses(
        archive: Path | str, *, name: str | None = None
    ) -> "export_store.ReplaceLosses | None":
        """What importing ``archive`` with ``replace=True`` would delete and not bring back, or
        ``None`` when there is no experiment to replace.

        The same answer an import without ``replace`` carries on its refusal
        (`export_store.ExperimentExistsError.losses`); `replace_warning` words it. Walks the
        existing experiment, so a surface calls it off the UI thread.

        Raises:
            ValueError: ``archive`` is not a DETAIL export, or ``name`` is not a bare name.
        """
        manifest = export_store.read_manifest(archive)
        dest = export_store.import_target(locations.experiments_root(), manifest, name)
        if not dest.exists():
            return None
        return export_store.replace_losses(manifest, dest)

    def export(
        self,
        dest: Path | str | None = None,
        *,
        include_video: bool = False,
        include_datasets: bool = False,
        gzip: bool = False,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> Path:
        """Pack this experiment into a single portable archive (§15). Slim by default
        (outputs + metadata + models; no source video / datasets) — pass
        ``include_video`` / ``include_datasets`` for a full transfer. Returns the
        archive path (default ``<workspace>/<id>.segproj.tar``).

        ``progress`` is a ``(stage, fraction, detail)`` callback — ``scanning`` →
        ``checking`` → ``hashing`` → ``packing``. The GUI does not call this directly: its
        Export runs the catalogue's ``bundle`` target as an export run (`run_export`), so the
        export is listed under Active processes and survives the window closing."""
        if dest is None:
            dest = self._dir.parent / f"{self._dir.name}.segproj.tar"
        return export_store.export_experiment(
            self._dir,
            dest,
            include_video=include_video,
            include_datasets=include_datasets,
            gzip=gzip,
            progress=progress,
        )

    @property
    def dir(self) -> Path:
        return self._dir

    @property
    def name(self) -> str:
        """Experiment display name (from config.yaml; decoupled from the folder)."""
        return experiment_store.read_config(self._dir)["name"]

    @property
    def description(self) -> str:
        """Experiment description (empty string if unset)."""
        return experiment_store.read_config(self._dir).get("description", "")

    @property
    def modified_at(self) -> float:
        """Unix mtime of the most recent experiment-level change.

        The max mtime across config.yaml, ``recordings/`` and ``runs/`` — a cheap
        proxy for "last activity" without walking the whole tree.
        """
        candidates = [
            self._dir / "config.yaml",
            self._dir / "recordings",
            self._dir / "runs",
        ]
        return max((p.stat().st_mtime for p in candidates if p.exists()), default=0.0)

    def preview_image(self, width: int = PREVIEW_WIDTH) -> Path | None:
        """A cached still identifying this experiment, or ``None`` if one can't be made.

        The frame comes from the **middle** of the first recording whose video is on this
        machine: the opening frames are often a blank lead-in and the last ones an empty
        arena, so a midpoint is the one place likely to show the animal. It is written once
        to ``<experiment>/preview.jpg`` and regenerated only when older than
        ``modified_at``, so listing a workspace costs a file read rather than a decode per
        experiment.

        Never raises. ``None`` means there is nothing to show — no recordings, no video, a
        referenced video that isn't on this machine (§5 reference-in-place), or a cache that
        couldn't be written (read-only media) — and the caller renders a placeholder.
        """
        import cv2

        path = self._dir / PREVIEW_FILENAME
        with contextlib.suppress(OSError):
            if path.is_file() and path.stat().st_mtime >= self.modified_at:
                return path
        frame = self._middle_frame()
        if frame is None:
            return None
        height = max(int(frame.shape[0] * width / max(frame.shape[1], 1)), 1)
        thumb = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
        try:
            cv2.imwrite(str(path), rgb_to_bgr(thumb))  # get_frame returns RGB
        except (OSError, cv2.error):
            return None
        return path if path.is_file() else None

    def _middle_frame(self):
        """The midpoint frame of the first recording with usable video, else ``None``."""
        for recording in self.recordings:
            if not recording.video_available:
                continue
            counts = recording.part_frame_counts
            total = sum(counts)
            if total <= 0:
                continue
            target = total // 2
            for part_index, count in enumerate(counts):
                if target < count:
                    with contextlib.suppress(IndexError, ValueError, OSError):
                        return recording.get_frame(part_index, target)
                    break
                target -= count
        return None

    def set_metadata(
        self, name: str | None = None, description: str | None = None
    ) -> None:
        """Edit experiment identity (name / description) in config.yaml.

        Only the given fields change; the experiment directory is not renamed.

        Raises:
            ValueError: If ``name`` is given but empty.
        """
        experiment_store.set_metadata(self._dir, name=name, description=description)

    # --- notes (§15) -------------------------------------------------------- #
    def notes(self, kind: str, entry_id: str = "") -> str:
        """The user's notes on one entry, or ``""`` when it has none.

        ``kind`` is one of ``storage.notes.KINDS`` (``experiment``, ``recording``, ``run``,
        ``analysis_run``, ``dataset``, ``model``, ``distill``, ``export_run``,
        ``comparison``); ``experiment`` takes no ``entry_id``.

        Raises:
            ValueError: If ``kind`` is not an entry kind, or the id is missing or extra.
            FileNotFoundError: If there is no such entry.
        """
        return notes_store.read_notes(notes_store.entry_dir(self._dir, kind, entry_id))

    def set_notes(self, kind: str, entry_id: str, text: str) -> None:
        """Replace the user's notes on one entry; empty ``text`` clears them.

        Safe while the entry's run is still going: the notes are a file of their own
        (``notes.md``), never a field in a record a worker is rewriting.

        Raises:
            ValueError: If ``kind`` is not an entry kind, or the id is missing or extra.
            FileNotFoundError: If there is no such entry.
        """
        notes_store.write_notes(notes_store.entry_dir(self._dir, kind, entry_id), text)

    @property
    def recording_ids(self) -> list[str]:
        """The recording ids in id order — the listing, without the records.

        :attr:`recordings` builds a :class:`Recording` per id, and each one reads its
        ``recording.yaml`` to learn its name. A caller that only needs *how many* there
        are, or which ids exist, pays a file read per recording for a number it could
        have had from the directory listing.
        """
        return experiment_store.discover_recordings(self._dir)

    @property
    def recordings(self) -> list[Recording]:
        return [Recording(self._dir, sid) for sid in self.recording_ids]

    def create_recording(
        self, recording_id: str, metadata: dict[str, str] | None = None
    ) -> Recording:
        """Create a recording **at a chosen id** (identity only — video/streams are
        optional, added later) and seed its ``metadata.csv`` row (§11).

        The id is the caller's, which is what a script or a test wants. An *application*
        adding a recording a user is naming should call :meth:`add_recording` instead —
        it mints the id and leaves the name to the user.
        """
        recording_store.create_recording(
            self._dir, recording_id=recording_id, name=recording_id
        )
        metadata_store.upsert_row(self._dir, recording_id, metadata)
        return Recording(self._dir, recording_id)

    def add_recording(
        self, name: str, metadata: dict[str, str] | None = None
    ) -> Recording:
        """Add a recording the user has *named*: the tool mints the id, the name is theirs.

        ``name`` is normally the video's filename — a good starting label and a terrible
        identity, since the file gets moved, renamed, or joined by a second part. The id
        is opaque and permanent (``recording_000``); the name is editable and unique, and
        is what every surface displays.

        A name already taken is **suffixed** (``m27_day3`` → ``m27_day3_2``) rather than
        refused: the caller here is the tool, importing a folder where two files can
        legitimately share a name, and failing the import over a label would be absurd.
        A name a *user* types goes through :meth:`Recording.set_name`, which refuses.
        """
        recording_id = experiment_store.next_recording_id(self._dir)
        recording_store.create_recording(
            self._dir, recording_id=recording_id, name=self.unique_name(name)
        )
        metadata_store.upsert_row(self._dir, recording_id, metadata)
        return Recording(self._dir, recording_id)

    def missing_previews(self, recording_ids: list[str] | None = None) -> list:
        """Preview builds missing on this machine across ``recording_ids`` (default: every
        recording), proxies before masks within each recording (§3 *Video preview cache*).
        One stat per part once this machine's cache knows the file."""
        from detail.api import previews

        tasks = []
        for recording_id in recording_ids or self.recording_ids:
            recording = self.get_recording(recording_id)
            tasks.extend(previews.recording_tasks(recording.dir, recording_id))
        return tasks

    def build_previews(
        self,
        recording_ids: list[str] | None = None,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> "previews.PreviewBuildReport":
        """Build every missing preview for ``recording_ids`` (default: all) under one bar;
        returns a ``previews.PreviewBuildReport`` (built count, and each failure with why).
        The bar is weighed by video length across the whole batch, and its phase line names
        the recording, part and build in hand."""
        from detail.api import previews

        return previews.build_tasks(
            self.dir,
            self.missing_previews(recording_ids),
            self.recording_names(),
            progress,
        )

    def recording_names(self) -> dict[str, str]:
        """``{recording_id: name}`` for every recording — the display map.

        The name is the handle on every surface, so this is read per page build. It rides
        the mtime-cached ``recording_store.read_recording``, the same read the recordings
        table already makes several of per row (no new I/O class — the UI-thread rule).
        """
        return {r.id: r.name for r in self.recordings}

    def unique_name(self, name: str, *, exclude: str | None = None) -> str:
        """``name``, or the first free ``name_2`` / ``name_3`` … variant.

        ``exclude`` skips one recording's own name, so renaming a recording to what it is
        already called is not a collision with itself.
        """
        taken = {n for rid, n in self.recording_names().items() if rid != exclude}
        if name not in taken:
            return name
        suffix = 2
        while f"{name}_{suffix}" in taken:
            suffix += 1
        return f"{name}_{suffix}"

    def get_recording(self, recording_id: str) -> Recording:
        return Recording(self._dir, recording_id)

    def video_not_packed(self) -> str | None:
        """Why a bundle with ``include_video`` would pack no video, or ``None`` when it would
        pack some (`no_video_packed_reasons`). Walks the experiment the way the export does, so
        a surface calls it off the UI thread."""
        if export_store.packs_video(self._dir):
            return None
        return no_video_packed_reasons(self._dir)

    def referenced_video_missing(self) -> list[str]:
        """Ids of recordings whose video is referenced in place and is not on this machine.

        What is left after an import has looked where the exporting machine kept the video:
        locating one file of such a recording (`Recording.relink_video_part`) registers its
        folder, and every recording whose video is in that folder finds it too. A stat per part,
        so a surface calls this off the UI thread.
        """
        return [
            recording_id
            for recording_id in export_store.referenced_video_recordings(self._dir)
            if not self.get_recording(recording_id).video_available
        ]

    def resolve_recording(self, ref: str) -> Recording:
        """A recording by id **or** name — what a user types is the name (§11).

        An exact id wins, so a recording perversely *named* another's id can still be
        reached by its own id. Then a unique name. Anything else raises rather than
        guessing.

        Raises:
            KeyError: no recording matches, or the name is ambiguous (only possible in an
                experiment whose names predate the uniqueness rule).
        """
        names = self.recording_names()
        if ref in names:
            return Recording(self._dir, ref)
        matches = [rid for rid, name in names.items() if name == ref]
        if len(matches) == 1:
            return Recording(self._dir, matches[0])
        if not matches:
            raise KeyError(
                f"no recording {ref!r} in this experiment — "
                f"known: {', '.join(sorted(names.values())) or '(none)'}"
            )
        raise KeyError(f"{ref!r} is the name of several recordings: {sorted(matches)}")

    # --- spatial-setup propagation (§10, #342) ------------------------------ #
    # Push one recording's spatial setup onto a chosen set of others — the batch form of
    # the per-recording `import_*_from` pulls, run the other way (issue #342 — the
    # one-recording-at-a-time pulls, batched). The four categories are one table in `api.spatial_categories`,
    # which also owns the two rules that make this safe: a copy never replaces, and a
    # definition's keyframe motion and active window do not survive the trip.

    def propagate_spatial(
        self,
        category_key: str,
        source: str,
        *,
        targets: list[str] | None = None,
        names: list[str] | None = None,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> spatial_categories.PropagationResult:
        """Copy ``category_key`` from ``source`` onto ``targets`` (default: every other
        recording), never replacing what a target already has.

        A target that already holds this category is **skipped and reported**, not
        overwritten — the operation has no undo and spans many recordings, so a
        correction is a deliberate delete on the recording that needs it. So is a target
        the category does not fit — a calibration onto a video of another shape, which is
        another rig. A target that refuses for any other reason is skipped too rather than
        aborting the batch, the same contract as ``apply_stream_preset``.

        Returns:
            A ``PropagationResult`` — the recordings that took it, the ones that did not
            and why, and what the trip changed about the definitions themselves.

        Raises:
            KeyError: ``source`` (or a ref in ``targets``) matches no recording.
            ValueError: unknown ``category_key``, or ``source`` has nothing to copy —
                checked before any recording is touched (Tenet 10).
        """
        cat = spatial_categories.category(category_key)
        src = self.resolve_recording(source)
        if not cat.has_data(src):
            raise ValueError(
                f"recording {src.name!r} has no {cat.label.lower()} to copy"
            )
        dests = self._propagate_targets(src, targets)
        stage = f"copying {cat.label.lower()}"
        total = len(dests)
        copied: list[str] = []
        skipped: list[tuple[str, str]] = []
        flattened: list[str] = []
        refused: list[tuple[str, str, str]] = []
        for index, dest in enumerate(dests):
            detail = f"{dest.name} ({index + 1}/{total})"
            if progress is not None:
                progress(stage, index / total, detail)
            reason = cat.occupied(dest) or cat.unfit(src, dest)
            if reason is not None:
                skipped.append((dest.id, reason))
            else:
                try:
                    added, dest_flattened, dest_refused = cat.give(src, dest, names)
                except (ValueError, FileNotFoundError, KeyError, OSError) as exc:
                    skipped.append((dest.id, str(exc)))
                else:
                    # Accumulated per target and tagged with it. Assigning them here kept
                    # only the last target's notes, so a refusal on any other recording was
                    # reported as "see the notes below" with no notes (#35 finding 12).
                    flattened += [n for n in dest_flattened if n not in flattened]
                    refused += [(dest.id, name, why) for name, why in dest_refused]
                    # Only a target that actually received something counts as copied. A
                    # set-shaped kind can have every one of its names refused, which is
                    # not a failure and not a copy.
                    (copied if added else skipped).append(
                        dest.id
                        if added
                        else (
                            dest.id,
                            "nothing new to add — everything offered was refused",
                        )
                    )
            if progress is not None:
                progress(stage, (index + 1) / total, detail)
        return spatial_categories.PropagationResult(
            copied=copied, skipped=skipped, flattened=flattened, refused=refused
        )

    def _propagate_targets(
        self, src: Recording, targets: list[str] | None
    ) -> list[Recording]:
        """``targets`` resolved to recordings, defaulting to every other recording; the
        source is excluded defensively even if named explicitly."""
        if targets is None:
            return [r for r in self.recordings if r.id != src.id]
        return [r for ref in targets if (r := self.resolve_recording(ref)).id != src.id]

    def propagate_field_of_view(
        self, source: str, **kwargs
    ) -> spatial_categories.PropagationResult:
        """Copy ``source``'s field of view onto recordings that have none (Section 10).
        See ``propagate_spatial``."""
        return self.propagate_spatial("fov", source, **kwargs)

    def propagate_calibration(
        self, source: str, **kwargs
    ) -> spatial_categories.PropagationResult:
        """Copy ``source``'s distance calibration onto recordings that have none
        (Section 10). See ``propagate_spatial``."""
        return self.propagate_spatial("calibration", source, **kwargs)

    def propagate_rois(
        self, source: str, **kwargs
    ) -> spatial_categories.PropagationResult:
        """Copy ``source``'s regions of interest onto recordings that have none
        (Section 10). See ``propagate_spatial``."""
        return self.propagate_spatial("roi", source, **kwargs)

    def propagate_points(
        self, source: str, **kwargs
    ) -> spatial_categories.PropagationResult:
        """Copy ``source``'s points of interest onto recordings that have none
        (Section 10). See ``propagate_spatial``."""
        return self.propagate_spatial("point", source, **kwargs)

    def import_behavior_labels(
        self,
        manifest_path: Path | str,
        *,
        name: str = "behavior",
        importer: str = "behavior_csv",
        progress: Callable[[int, int, str, float, str], None] | None = None,
    ) -> list[tuple[str, str]]:
        """Batch-import behavior ground-truth labels onto existing recordings (Section 3).

        Loads + validates the labels manifest (all problems reported upfront,
        Tenet 10), then adds each recording's file as a ``behavior``-role stream named
        ``name`` (default ``"behavior"``), each resolved against its own timestamp
        map. Every file in one batch uses the same ``importer`` (``behavior_csv`` or
        ``boris``). ``progress(index, total, recording_id, fraction, status)`` reports
        per recording. Returns the skipped recordings as ``[(recording_id, error), ...]``.

        Raises:
            FileNotFoundError: If the manifest file is absent.
            ValueError: If the manifest is malformed or references an unknown recording
                or missing file (nothing is imported).
        """
        from detail.api import imports as imports_mod
        from detail.storage import labels_manifest as labels_store

        manifest = labels_store.load_labels_manifest(manifest_path)
        mapping = labels_store.resolve_labels_manifest(
            manifest_path, manifest, experiment_store.discover_recordings(self._dir)
        )
        return imports_mod.import_label_batch(
            self, mapping, name=name, importer=importer, on_progress=progress
        )

    # --- heading definitions (§14 egocentric alignment) ----------------------- #
    def heading_definitions(self) -> list[dict]:
        """Saved heading definitions, oldest first: ``{name, front, back}`` (``[]`` if none)."""
        return heading_store.list_definitions(self._dir)

    def get_heading_definition(self, name: str) -> dict:
        """Raises: ValueError if no definition named ``name`` exists."""
        return heading_store.get_definition(self._dir, name)

    def save_heading_definition(
        self, name: str, front: list[str], back: list[str], *, overwrite: bool = False
    ) -> dict:
        """Save a heading definition: the points whose mean is the front and the points whose
        mean is the back. Checked against a skeleton when a run uses it, not here.

        Raises:
            ValueError: An invalid name or definition, or the name exists and ``overwrite``
                is False.
        """
        return heading_store.save_definition(
            self._dir, name, front, back, overwrite=overwrite
        )

    def delete_heading_definition(self, name: str) -> None:
        """Raises: ValueError if no definition named ``name`` exists."""
        heading_store.delete_definition(self._dir, name)

    def export_heading_definition(self, name: str, out_path: Path | str) -> None:
        """Write a saved definition to a standalone, shareable YAML file.

        Raises:
            ValueError: No definition named ``name`` exists.
        """
        heading_store.export_definition(self._dir, name, out_path)

    def import_heading_definition(
        self, in_path: Path | str, *, name: str | None = None, overwrite: bool = False
    ) -> str:
        """Import a definition from a standalone file; returns the name it was saved under.

        Raises:
            FileNotFoundError: ``in_path`` does not exist.
            ValueError: A malformed file, the wrong schema version, or (without
                ``overwrite``) the name already exists.
        """
        return heading_store.import_definition(
            self._dir, in_path, name=name, overwrite=overwrite
        )

    # --- stream presets (§3) ------------------------------------------------ #
    def list_stream_presets(self) -> list[dict]:
        """Saved importer setups for this experiment, oldest first (``[]`` if none)."""
        return stream_presets.list_presets(self._dir)

    def get_stream_preset(self, name: str) -> dict:
        """Raises: ValueError if no preset named ``name`` exists."""
        return stream_presets.get_preset(self._dir, name)

    def save_stream_preset(
        self,
        name: str,
        importer: str,
        config: dict | None,
        *,
        offset_ns: int | None = None,
        overwrite: bool = False,
    ) -> None:
        """Save an importer + its config for reuse on this experiment's other recordings.

        Raises:
            ValueError: An invalid name, or the name exists and ``overwrite`` is False.
        """
        stream_presets.save_preset(
            self._dir, name, importer, config, offset_ns=offset_ns, overwrite=overwrite
        )

    def check_new_stream_preset_name(self, name: str) -> None:
        """Refuse a name :meth:`save_stream_preset` would refuse without ``overwrite``, so a
        caller that saves after other work can refuse before doing it.

        Raises:
            ValueError: An invalid name, or a preset by that name exists.
        """
        stream_presets.check_new_name(self._dir, name)

    def delete_stream_preset(self, name: str) -> None:
        """Raises: ValueError if no preset named ``name`` exists."""
        stream_presets.delete_preset(self._dir, name)

    def export_stream_preset(self, name: str, out_path: Path | str) -> None:
        """Write a saved preset to a standalone, shareable YAML file.

        Raises:
            ValueError: No preset named ``name`` exists.
        """
        stream_presets.export_preset(self._dir, name, out_path)

    def import_stream_preset(
        self,
        in_path: Path | str,
        *,
        name: str | None = None,
        overwrite: bool = False,
    ) -> str:
        """Import a preset from a standalone file; returns the name it was saved under.

        Raises:
            FileNotFoundError: ``in_path`` does not exist.
            ValueError: A malformed file, the wrong schema version, or (without
                ``overwrite``) the name already exists.
        """
        return stream_presets.import_preset(
            self._dir, in_path, name=name, overwrite=overwrite
        )

    def apply_stream_preset(
        self,
        preset: str,
        sources: list[tuple[str, Path | str, int | None]],
        *,
        name: str,
        by_video: bool = False,
        progress: Callable[[int, int, str, float, str], None] | None = None,
    ) -> list[tuple[str, str]]:
        """Import one stream per recording from a saved preset (Section 3).

        The batch shape for a mapping worked out once. ``sources`` is
        ``[(recording_ref, file, offset_ns | None), ...]`` — **one row per recording, with
        its own file and its own offset**, because those are exactly what a preset cannot
        carry: each video and logger pair has its own skew, so one number applied to sixty
        recordings is one recording's answer given to all of them.

        A recording that fails is recorded and skipped, so one unreadable file never sinks
        the batch — the same contract as ``import_behavior_labels``.

        Args:
            name: The stream name to give each import (the same on every recording).
            by_video: Each ``recording_ref`` is a **video file name**, matched by the same
                rule as a metadata import's file key (base name, any case, extension
                optional) — the key a table made alongside the recordings carries (#330).
                ``False``: an id or a name.
            progress: ``progress(index, total, recording_id, fraction, status)``.

        Returns:
            The skipped recordings as ``[(recording_ref, error), ...]``.

        Raises:
            ValueError: If ``preset`` names nothing saved (nothing is imported).
        """
        self.get_stream_preset(preset)  # fail before touching any recording (Tenet 10)
        total = len(sources)
        skipped: list[tuple[str, str]] = []
        if by_video:
            names = self.recording_names()
            matches = self._video_file_matches(ref for ref, _, _ in sources)
        for index, (ref, path, offset_ns) in enumerate(sources):
            if progress is not None:
                progress(index, total, ref, 0.0, "importing")
            error = (
                _match_error("video file", ref, matches[ref], names)
                if by_video
                else None
            )
            if error is None:
                try:
                    recording = (
                        self.get_recording(matches[ref][0])
                        if by_video
                        else self.resolve_recording(ref)
                    )
                    recording.add_stream_from_preset(
                        name, path, preset, offset_ns=offset_ns
                    )
                except (ValueError, FileNotFoundError, KeyError, OSError) as exc:
                    error = str(exc)
            if error is not None:
                skipped.append((ref, error))
            if progress is not None:
                progress(index, total, ref, 1.0, "done" if error is None else "skipped")
        return skipped

    # --- grouping variables (§11) ------------------------------------------- #
    @property
    def recording_metadata(self) -> dict[str, dict[str, str]]:
        """The cohort metadata table: ``{recording_id: {column: value}}`` (§11)."""
        return metadata_store.read_metadata(self._dir)

    @property
    def metadata_columns(self) -> list[str]:
        """User-defined grouping-variable columns (excluding ``recording_id``)."""
        return metadata_store.columns(self._dir)

    def set_recording_metadata(self, recording_id: str, values: dict[str, str]) -> None:
        """Set/merge a recording's grouping variables; new columns are added (§11)."""
        metadata_store.upsert_row(self._dir, recording_id, values)

    def add_metadata_column(self, name: str) -> None:
        """Add an empty grouping-variable column to the cohort table (§11)."""
        metadata_store.add_column(self._dir, name)

    def delete_metadata_column(self, name: str) -> None:
        """Remove a grouping-variable column and its values from every recording (§11).
        Idempotent; ``recording_id`` cannot be deleted."""
        metadata_store.delete_column(self._dir, name)

    def set_metadata_table(
        self, columns: list[str], rows: dict[str, dict[str, str]]
    ) -> None:
        """Replace the whole cohort table (§11): ``columns`` in order, ``rows`` keyed by
        recording id. Commits a fully edited table — added/deleted columns and cell edits
        together — in one write; the bulk counterpart to :meth:`set_recording_metadata`.
        """
        metadata_store.write_metadata(self._dir, columns, rows)

    def metadata_csv_key(self, path: Path | str) -> tuple[str | None, list[str]]:
        """``(key_column, header)`` for a metadata CSV: the column an import would key on
        by default — ``None`` when none is recognised — and every column it has, so a
        surface can ask which one holds the video file name (#330).

        Raises:
            FileNotFoundError: If the file is absent.
            ValueError: An empty file, or an empty or duplicate column header.
        """
        header = metadata_store.read_import_header(path)
        return metadata_store.detect_key_column(header), header

    def import_metadata_csv(
        self,
        path: Path | str,
        *,
        dry_run: bool = False,
        key_column: str | None = None,
    ) -> tuple[list[str], list[str], int]:
        """Bulk-apply recording grouping variables from a CSV (§11): merge-only,
        blank cells skipped, a row matching no recording rejected. Validates the whole
        file first — on **any** error nothing is applied (Tenet 10).

        Each row is matched to a recording by its **key column**: ``recording_id``, the
        recording's ``name``, or its **video file name** — the key a sheet prepared before
        import actually carries, since the id is minted at import and the name is right
        only once every recording has been renamed (#330). A video file name is the base
        name, any case, extension optional, and matches any of the recording's video parts.

        Args:
            key_column: The column to key on. ``None`` detects it — ``recording_id``, then
                ``name``, then a video file name column
                (``metadata_store.VIDEO_KEY_HEADERS``). A column named here that is not
                the id or the name is matched as a video file name.

        A name or file key is resolved to its id here and never *sets* anything: renaming
        is ``Recording.set_name``, which enforces uniqueness.

        Returns ``(errors, warnings, recordings_updated)``.
        """
        try:
            kind, columns, rows = metadata_store.load_import_csv(path, key_column)
        except (FileNotFoundError, ValueError) as exc:
            return [str(exc)], [], 0
        if kind != metadata_store.RECORDING_KEY:
            rows, errors = self._rekey_import_rows(kind, rows)
            if errors:
                return errors, [], 0
        errors, warnings = metadata_store.validate_import(
            columns, rows, [s.id for s in self.recordings]
        )
        if errors or dry_run:
            return errors, warnings, 0
        applied = metadata_store.apply_import(self._dir, columns, rows)
        return errors, warnings, applied

    def _rekey_import_rows(self, kind: str, rows: list) -> tuple[list, list[str]]:
        """Re-key name- or file-addressed import rows onto recording ids.

        Returns the re-keyed rows and one error per row that matched no recording, matched
        several, or matched a recording another row already did — all of them, in the
        user's own terms, rather than the first (Tenet 10).
        """
        names = self.recording_names()
        values = [value for value, _ in rows]
        if kind == metadata_store.NAME_KEY:
            ids_by_name = {name: rid for rid, name in names.items()}
            matches = {v: [ids_by_name[v]] if v in ids_by_name else [] for v in values}
            what = "recording name"
        else:
            matches = self._video_file_matches(values)
            what = "video file"
        rekeyed, errors = [], []
        first_value_by_id: dict[str, str] = {}
        for value, cells in rows:
            if not value:
                errors.append(f"a row has an empty {what}")
                continue
            error = _match_error(what, value, matches[value], names)
            if error:
                errors.append(error)
                continue
            recording_id = matches[value][0]
            if recording_id in first_value_by_id:
                errors.append(
                    f"{what}s {first_value_by_id[recording_id]!r} and {value!r} both "
                    f"match recording {names[recording_id]!r} — one row per recording"
                )
                continue
            first_value_by_id[recording_id] = value
            rekeyed.append((recording_id, cells))
        return rekeyed, errors

    def _video_file_matches(self, values: Iterable[str]) -> dict[str, list[str]]:
        """``{value: [recording_id, ...]}`` — the recordings whose video each value names.

        The one matching rule for a video-file key, wherever a table carries one (#330):
        the **base name** of the value (a pasted path is fine), **any case**, **extension
        optional** — ``M27.MP4``, ``m27`` and ``D:\\raw\\m27.mp4`` all name ``m27.mp4`` —
        matched against every video part of every recording. An empty list is no match;
        more than one is an ambiguity the caller refuses rather than resolves.
        """
        by_file: dict[str, set[str]] = {}
        by_stem: dict[str, set[str]] = {}
        with read_cache.pinned():
            for recording in self.recordings:
                for source in recording.video_sources:
                    if not source:
                        continue
                    file_name = _video_file_key(source)
                    by_file.setdefault(file_name, set()).add(recording.id)
                    stem = os.path.splitext(file_name)[0]
                    by_stem.setdefault(stem, set()).add(recording.id)
        out = {}
        for value in values:
            key = _video_file_key(value)
            out[value] = sorted(by_file.get(key) or by_stem.get(key) or ())
        return out

    def export_metadata_csv(self, path: Path | str) -> None:
        """Write the current grouping variables to ``path`` as a fill-in CSV template
        (§11) — ``recording_id``, ``name``, ``file``, then every column, one row per
        recording.

        ``name`` and ``file`` (the first video part's file name, as the table shows it)
        ride along so the sheet is legible — an id alone tells a person filling it in
        nothing — and so the filled sheet can be keyed back on any of the three. Neither
        is a stored value: editing one here renames nothing.
        """
        with read_cache.pinned():
            files = {
                recording.id: next(
                    (_base_name(s) for s in recording.video_sources if s), ""
                )
                for recording in self.recordings
            }
        metadata_store.export_metadata(
            self._dir, path, names=self.recording_names(), files=files
        )

    #: How an import's own status vocabulary maps onto the shared run one. An import is
    #: ``queued`` before it starts and ``importing`` while it runs — the two states every other
    #: family calls ``pending`` and ``running``, in a dialect only this one speaks. Translating
    #: here rather than teaching every reader the dialect is what lets one listing, one quit
    #: guard and one "is it still going" predicate cover a family that keeps its status on a
    #: recording instead of in a run record. ``ready`` reads as ``complete``: on a local disk an
    #: import is usually over within a second of being asked for, so a listing that dropped
    #: finished ones showed nothing to a user who had just imported 533 MB of video.
    _IMPORT_RUN_STATUS = {
        "queued": JobStatus.PENDING.value,
        "importing": JobStatus.RUNNING.value,
        "ready": JobStatus.COMPLETE.value,
        "failed": JobStatus.FAILED.value,
        "cancelled": JobStatus.CANCELLED.value,
    }

    @property
    def import_runs(self) -> list[dict]:
        """Every recording that was imported, shaped like a run record (§3).

        An import is the one long operation this app runs that is *not* a run: it writes no run
        record, and its state lives on the recording as ``import_status``. This is the adapter
        that lets it be listed, counted and cancelled beside the families that do — the shape
        ``api.active.RUN_KINDS`` reads, carrying the recording id a surface needs to open it and
        the name a surface should show instead of that id (§11).

        ``created_at`` is the recording's own, which is the right answer rather than a
        convenient one: ``create_shell`` mints the recording synchronously when the import is
        submitted, so it is the moment the import was asked for.

        Read under a pin because every :class:`Recording` property is its own ``recording.yaml``
        read and this wants three of them per recording — and the quit guard asks this question
        **on the UI thread**, where the difference is one round trip per recording instead of
        three (`storage/read_cache.py`).
        """
        runs: list[dict] = []
        with read_cache.pinned():
            for recording in self.recordings:
                record = recording_store.read_recording(recording.dir)
                # The key, not `Recording.import_status`, which defaults a missing one to
                # "ready". Only an import writes it: a recording made before the field existed,
                # or given video by `recording add-video`, never went through one.
                status = self._IMPORT_RUN_STATUS.get(record.get("import_status"))
                if status is None:
                    continue
                # A shell created with metadata only is `ready` the moment it exists and carried
                # nothing in — calling it a finished import would list every such recording.
                imported_something = (record.get("video") or {}).get(
                    "files"
                ) or record.get("streams")
                if status == JobStatus.COMPLETE.value and not imported_something:
                    continue
                runs.append(
                    {
                        "id": recording.id,
                        "name": recording.name,
                        "status": status,
                        "created_at": record.get("created_at", ""),
                    }
                )
        return runs

    def cancel_import(self, recording_id: str) -> None:
        """Mark a recording's unfinished import cancelled. A no-op once it is terminal.

        This records a decision; it does not reach into a worker. An import runs on a thread
        owned by whichever app has this experiment open (`gui/import_queue.py`), so there is no
        cross-process handle to pull — and on the path that matters, quitting, the worker dies
        with the process regardless. What the caller gets is the difference between a record
        that says ``cancelled`` and one left at ``queued`` for the next open to call ``failed``:
        the same outcome, one of them blaming the user for it.

        Raises:
            FileNotFoundError: If the recording doesn't exist.
        """
        recording = self.get_recording(recording_id)
        if recording.import_status not in ("queued", "importing"):
            return
        recording_store.set_import_status(recording.dir, "cancelled")

    def reconcile_imports(self) -> None:
        """Flip orphaned import statuses (``queued`` / ``importing`` left by a
        crash or close, with no active queue) to ``failed`` so they're visible +
        deletable, not stuck. Called on experiment open before the import queue starts
        (the in-memory queue can't resume — §3)."""
        for recording in self.recordings:
            if recording.import_status in ("queued", "importing"):
                recording_store.set_import_status(recording.dir, "failed")

    def reconcile_runs(self) -> None:
        """Fold each still-active processing run's real on-disk status back into its
        record on experiment open (§15). A run's coordinator + workers are detached and
        may outlive the app, but a crashed/SIGKILLed run can read ``running`` forever.
        Evidence-based (see :meth:`_reconcile_run`). Mirrors :meth:`reconcile_imports`.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        for record in runs_store.list_runs(self._dir):
            self._reconcile_run(record)

    def reconcile_recording_runs(self) -> int:
        """Adopt each per-recording run's real status into its ``recording.yaml`` (§15).

        ``_RecordedRun.wait()`` is what copies a job's terminal status into the recording, and
        a one-recording run has no coordinator to call it: a Ctrl-C, a closed terminal, or a
        script that never waits left the entry ``pending`` forever, the recording refused a
        second run, and tracking refused it as "not complete" (issue #28, finding 5). This is
        the backstop, run wherever an experiment is opened — the GUI and every CLI command.

        Driven from ``PROCESSING_MODULES`` (every per-recording module's ``runs_key``), so a
        new module is covered the day it registers. Cost: one ``recording.yaml`` read per
        recording, and one ``job.json`` read only per entry still marked active — never per
        run. An entry whose job is still active is left alone while its worker lives; one with
        no run dir yet is a launch in progress and is left alone too. Returns how many entries
        changed.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        return sum(
            self._reconcile_one_recording(recording_id)
            for recording_id in experiment_store.discover_recordings(self._dir)
        )

    def _reconcile_one_recording(self, recording_id: str) -> int:
        """:meth:`reconcile_recording_runs` for one recording; how many entries changed."""
        modules = {}
        for module in PROCESSING_MODULES.values():
            if not getattr(module, "batch", False):
                modules.setdefault(module.runs_key, module)
        rdir = experiment_store.recording_path(self._dir, recording_id)
        try:
            data = recording_store.read_recording(rdir)
        except (
            Exception
        ):  # noqa: BLE001 — one unreadable recording must not stop the rest
            return 0
        changed = 0
        for runs_key, module in modules.items():
            for entry in data.get(runs_key) or []:
                if entry.get("status") not in ACTIVE_STATUSES:
                    continue
                status = self._recording_run_evidence(rdir, module, entry.get("id"))
                if status is None:
                    continue
                with contextlib.suppress(FileNotFoundError, ValueError, KeyError):
                    self.get_recording(recording_id)._set_run_status(
                        runs_key, entry["id"], status
                    )
                    changed += 1
        return changed

    @staticmethod
    def _recording_run_evidence(rdir: Path, module, run_id: str | None) -> str | None:
        """The status a per-recording run's ``job.json`` says it ended with, or ``None``
        when there is nothing to adopt yet (no run dir, or a worker still working)."""
        if not run_id:
            return None
        out_dir = rdir / module.output_path(run_id).rstrip("/")
        if not (out_dir / rundir.JOB_FILENAME).is_file():
            return None
        try:
            status = rundir.read_status(out_dir).value
        except (FileNotFoundError, KeyError, ValueError):
            return None
        if status not in ACTIVE_STATUSES:
            return status
        if worker_alive(out_dir):
            return None
        reason = "worker exited without completing (reconciled on open)"
        with contextlib.suppress(Exception):
            rundir.set_status(out_dir, JobStatus.FAILED, error=reason)
        return JobStatus.FAILED.value

    def _reconcile_run(self, record: dict) -> bool:
        """Reconcile one run record against on-disk evidence; returns True if changed.
        The **coordinator pid** is the liveness authority: alive → leave running; gone
        → adopt each recording's terminal ``job.json`` status, keep an individually-alive
        recording worker running, fail recordings the coordinator never launched, and roll
        up. This is the SIGKILL backstop that guarantees a terminal status."""
        if record.get("status") not in ACTIVE_STATUSES:
            return False
        module = PROCESSING_MODULES.get(record.get("module_id"))
        if module is None:
            return False
        run_id = record["id"]
        pid = runs_store.read_coordinator_pid(self._dir, run_id)
        if pid is None:
            return False  # pid not recorded yet — just launched, leave running
        if coordinator_alive(runs_store.run_dir(self._dir, run_id), pid):
            return False  # the coordinator is driving it
        per_recording = dict(record.get("per_recording") or {})
        changed = False
        for sid, entry in per_recording.items():
            stage_run_id = entry.get("run_id")
            if entry.get("status") not in ACTIVE_STATUSES:
                continue
            if stage_run_id is None:
                # Never launched — `retry_run` seeds its pending recordings this way, so a
                # retry whose coordinator died first left the run `running` for good.
                entry["status"] = JobStatus.FAILED.value
                entry["error"] = "interrupted: coordinator gone before launch"
                changed = True
                continue
            sess_run_dir = experiment_store.recording_path(
                self._dir, sid
            ) / module.output_path(stage_run_id)
            try:
                status = rundir.read_status(sess_run_dir).value
            except (FileNotFoundError, KeyError, ValueError):
                status = None
            if status is None or status in ACTIVE_STATUSES:
                if status is not None and worker_alive(sess_run_dir):
                    continue  # a detached recording worker still finishing — leave it
                status = JobStatus.FAILED.value
                entry["error"] = "interrupted: coordinator gone (reconciled on open)"
            entry["status"] = status
            changed = True
            with contextlib.suppress(FileNotFoundError, ValueError, KeyError):
                self.get_recording(sid)._set_run_status(
                    module.runs_key, stage_run_id, status
                )
        before = len(per_recording)
        new_status = roll_up_run_status(
            record.get("recording_ids") or [],
            per_recording,  # a recording the coordinator never launched → failed
            cancelled=False,
            unlaunched=(
                JobStatus.FAILED.value,
                "interrupted: coordinator gone before launch",
            ),
        )
        changed = changed or len(per_recording) != before
        record["per_recording"] = per_recording
        if new_status != record.get("status"):
            record["status"] = new_status
            changed = True
        if changed:
            runs_store.write_run(self._dir, run_id, record)
        return changed

    def delete_recording(self, recording_id: str) -> None:
        """Delete a recording and everything it owns — its imported video, runs
        (detection / tracking / embedding / downsampling), arenas, and masks.

        A processing run merely *indexes* per-recording runs (its outputs live in
        the recordings, Tenet 5), so the recording is pruned from every processing
        run's ``per_recording`` map and an emptied run record is removed — not
        blocked. Nothing outside a recording is computed from a whole recording
        today; a future cross-recording analysis would register as a dependent.

        **Refused while a run is using the recording** (issue #28, finding 6): a processing
        run that lists it, a run of its own still going, or an analysis, distill, dataset or
        export run reading it. Deleting under a live worker orphaned it — the worker re-created
        the folder within seconds — and wiped the run record the coordinator was still writing,
        so the other recordings never ran. Every family is reconciled first, so a run that is
        only *recorded* as running (its process long gone) does not block the delete.

        The recording leaves both of a run record's fields, ``per_recording`` **and**
        ``recording_ids`` (finding 10): a deleted id left in the plan made ``process retry``
        fail reading its ``recording.yaml`` and ``process list`` count it.

        Raises:
            FileNotFoundError: If no such recording exists.
            ValueError: If a run is still using the recording — it names each one.
        """
        sdir = experiment_store.recording_path(self._dir, recording_id)
        if not sdir.is_dir():
            raise FileNotFoundError(f"recording {recording_id!r} not found")
        blockers = self._active_runs_reading(recording_id)
        if blockers:
            raise ValueError(
                f"cannot delete recording {recording_id!r} while a run is using it — "
                "cancel it or let it finish first:\n" + "\n".join(blockers)
            )
        shutil.rmtree(sdir)
        metadata_store.remove_row(
            self._dir, recording_id
        )  # prune its grouping vars (§11)
        for record in runs_store.list_runs(self._dir):
            per = record.get("per_recording", {})
            planned = list(record.get("recording_ids") or [])
            if recording_id not in per and recording_id not in planned:
                continue
            per.pop(recording_id, None)
            record["recording_ids"] = [sid for sid in planned if sid != recording_id]
            if per or record["recording_ids"]:
                record["per_recording"] = per
                runs_store.write_run(self._dir, record["id"], record)
            else:
                runs_store.delete_run(self._dir, record["id"])

    def _active_runs_reading(self, recording_id: str) -> list[str]:
        """One line per run still using ``recording_id`` — empty when it may be deleted.

        Reconciles first (processing runs, single-job runs, distill runs and this recording's
        own runs), so only a run whose process is really alive can block.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        self.reconcile_runs()
        self.reconcile_job_runs()
        self._reconcile_one_recording(recording_id)
        lines = []
        processing = {r["id"]: r for r in runs_store.list_runs(self._dir)}
        for run_id, record in processing.items():
            if record.get("status") in ACTIVE_STATUSES and (
                recording_id in (record.get("recording_ids") or [])
                or recording_id in (record.get("per_recording") or {})
            ):
                lines.append(f"  processing run {run_id!r} ({record.get('module_id')})")
        data = recording_store.read_recording(
            experiment_store.recording_path(self._dir, recording_id)
        )
        for module in PROCESSING_MODULES.values():
            if getattr(module, "batch", False):
                continue
            for entry in data.get(module.runs_key) or []:
                if entry.get("status") in ACTIVE_STATUSES:
                    line = f"  {module.module_id} run {entry.get('id')!r} on this recording"
                    if line not in lines:
                        lines.append(line)
        analysis = {}
        for ref in self.analysis_runs:
            analysis[ref.id] = ref
            if ref.status in ACTIVE_STATUSES and recording_id in ref.recording_ids:
                lines.append(f"  analysis run {ref.id!r} ({ref.module_id})")
        for record in self.distill_runs:  # reconciled by the property
            sources = (record.get("config") or {}).get("source_recording_ids") or []
            if record.get("status") in ACTIVE_STATUSES and recording_id in sources:
                lines.append(f"  distill run {record.get('id')!r}")

        def reads(kind: str, subject_id: str) -> bool:
            if kind == "recording":
                return subject_id == recording_id
            if kind == "run" and subject_id in processing:
                return recording_id in (
                    processing[subject_id].get("recording_ids") or []
                )
            if kind == "analysis_run" and subject_id in analysis:
                return recording_id in analysis[subject_id].recording_ids
            return False

        for ref in self.export_runs:
            if ref.status in ACTIVE_STATUSES and reads(
                ref.subject_kind, ref.subject_id
            ):
                lines.append(f"  export run {ref.id!r}")
        for ref in self.datasets:
            if ref.status not in ACTIVE_STATUSES:
                continue
            ddir = datasets_store.dataset_dir(self._dir, ref.id)
            with contextlib.suppress(Exception):
                source = datasets_store.read_dataset_yaml(ddir).get("source") or {}
                if reads("run", source.get("run_id", "")):
                    lines.append(f"  dataset run {ref.id!r}")
        return lines

    def delete(self) -> None:
        """Delete the whole experiment directory — every recording, run, model, and
        dataset it owns. Nothing outside an experiment depends on it, so this is
        never blocked (the cohesive delete strategy, gui_design §1.1). The
        ``Experiment`` instance is dead afterwards.

        Raises:
            FileNotFoundError: If the experiment directory no longer exists.
        """
        if not self._dir.is_dir():
            raise FileNotFoundError(f"experiment not found: {self._dir}")
        shutil.rmtree(self._dir)

    # --- Processing runs over a recording selection (§15) --------------------- #
    def run_processing(
        self,
        module_id: str,
        recording_ids: list[str],
        config: dict,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> "AttachedRun":
        """Run a processing module over a selection of recordings.

        Validates every selected recording up front (Tenet 10), reserves the run
        record, then spawns a **detached coordinator** (``executor/coordinator.py``)
        that sequences the per-recording ``Recording.run`` calls and publishes aggregate
        progress. Returns an :class:`AttachedRun` polling that progress — so the run
        survives the app closing and any process can reattach (§15). Per-recording
        outputs land in each recording (Tenet 5).

        ``progress`` takes the standard ``(stage, fraction, detail)`` callback and names
        each recording as the up-front checks reach it: over a large selection they read
        every recording's outputs, which is minutes, not a moment.

        Raises:
            ValueError: For an unknown ``module_id``, an empty selection, or any
                recording that fails the module's pre-run validation.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        module = PROCESSING_MODULES.get(module_id)
        if module is None:
            raise ValueError(
                f"unknown module_id {module_id!r}; "
                f"available: {sorted(PROCESSING_MODULES)}"
            )
        # The same recording named twice (a name and its id, say) would run twice: the second
        # run's id replaces the first in `per_recording`, leaving an output no run indexes and
        # a batch marked failed though both runs completed (issue #28, finding 7). Here, not in
        # a surface, so the CLI, the GUI and a script all get it. Order is kept.
        recording_ids = list(dict.fromkeys(recording_ids))
        if not recording_ids:
            raise ValueError("recording_ids must be non-empty")
        if module.batch:
            # A batch module validates the whole subset once and its cross-recording step
            # needs the normalized config in the record (there is no per-recording
            # re-validation by the coordinator).
            config = module.validate_batch(self._dir, recording_ids, dict(config))
        else:
            # Values that must agree across the selection (embedding's shared canvas)
            # are resolved once, here, and enrich the stored config — a per-recording
            # validate cannot see the other recordings (§6.5).
            shared = _RecordingSteps(
                self._dir, progress, "Resolving shared settings", len(recording_ids)
            )
            config = module.resolve_shared_config(
                self._dir, recording_ids, dict(config), on_recording=shared
            )
            shared.finish()
            checks = _RecordingSteps(
                self._dir, progress, "Validating", len(recording_ids)
            )
            for sid in recording_ids:
                checks(sid)
                sdir = experiment_store.recording_path(self._dir, sid)
                sdata = recording_store.read_recording(sdir)
                # Resolve the batch spec per recording before fail-fast validation (§6.5);
                # the stored run-record config keeps the spec so the coordinator re-resolves.
                module.validate(
                    sdir, sdata, module.resolve_upstream_spec(sdir, sdata, dict(config))
                )
            checks.finish()
        config = _with_model_defaults(module, config)
        # Allocate and reserve under one lock: `next_run_id` is max+1 over a directory scan,
        # so two launches racing between the scan and the write both take the same id and the
        # loser's atomic replace fails on a tmp file the winner already consumed.
        # Reserve before spawning so the run is discoverable + a coordinator that starts and
        # then dies reconciles to failed (not stuck running).
        with runs_store.runs_lock(self._dir):
            run_id = runs_store.next_run_id(self._dir)
            runs_store.write_run(
                self._dir,
                run_id,
                {
                    "id": run_id,
                    "module_id": module_id,
                    "recording_ids": recording_ids,
                    "config": _jsonable(config),
                    "per_recording": {},
                    "status": "running",
                    "created_at": utc_timestamp(),
                },
            )
        try:
            pid = spawn_coordinator(
                runs_store.run_dir(self._dir, run_id), tuple(_PIPELINE_RUNNERS)
            )
        except (
            Exception
        ) as exc:  # noqa: BLE001 — re-raised; must not leave a stuck record
            # The coordinator never launched (e.g. Popen OSError). Without a recorded
            # pid, reconcile can't tell this from a just-launched run, so mark the
            # reserved record failed here rather than leave it stuck "running".
            self._fail_run_record(run_id, f"coordinator failed to launch: {exc}")
            raise
        runs_store.set_coordinator_pid(self._dir, run_id, pid)
        return self.attach_run(run_id)

    def retry_run(
        self,
        run_id: str,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> "AttachedRun":
        """Re-run a terminal processing run's incomplete recordings, into the same record.

        Gap-fills rather than minting a new run: each recording already owns its own stage
        run id in ``per_recording``, so the record is a map with holes in it. The re-spawned
        coordinator seeds those results and drives only what isn't ``complete``, and the
        run rolls up to ``complete`` once every recording is (§15). Retried recordings get a
        *fresh* stage run id from ``Recording.run``, so nothing appends into a half-written
        zarr — a recording is re-run whole, not resumed mid-way (§7 resume is not built).

        Covers ``failed`` and ``cancelled`` runs alike: the set is every recording that
        isn't complete, including ones the coordinator never launched.

        ``progress`` takes the ``(stage, fraction, detail)`` callback and names each
        recording as it is re-validated, as :meth:`run_processing` does.

        Returns:
            An :class:`AttachedRun` streaming the re-spawned coordinator.

        Raises:
            FileNotFoundError: If the run record does not exist.
            ValueError: If the run is still running, its module is unknown, every recording
                is already complete, or any incomplete recording no longer validates.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        record = runs_store.read_run(self._dir, run_id)
        # A SIGKILLed coordinator leaves the record "running" forever and no CLI path
        # calls reconcile, so gating on a terminal status would reject a run that is
        # genuinely retryable. Reconcile mutates + persists in place.
        self._reconcile_run(record)
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(
                f"processing run {run_id!r} is still running — cancel it before retrying"
            )
        module_id = record.get("module_id")
        module = PROCESSING_MODULES.get(module_id)
        if module is None:
            raise ValueError(
                f"unknown module_id {module_id!r} for run {run_id!r}; "
                f"available: {sorted(PROCESSING_MODULES)}"
            )
        per_recording = dict(record.get("per_recording") or {})
        pending = [
            sid
            for sid in record.get("recording_ids") or []
            if per_recording.get(sid, {}).get("status") != JobStatus.COMPLETE.value
        ]
        if not pending:
            raise ValueError(
                f"processing run {run_id!r}: every recording is complete — nothing to retry"
            )
        # The record stores _jsonable(config); restore the typed values before validating,
        # whose checks read compute.backend / prompt.targets as objects (cf. __init__).
        config = _typed_config(record.get("config") or {})
        errors = self._validate_retry_recordings(module, pending, config, progress)
        if errors:
            detail = "; ".join(f"{sid}: {err}" for sid, err in errors.items())
            raise ValueError(f"cannot retry run {run_id!r} — {detail}")
        for sid in pending:
            per_recording[sid] = {"run_id": None, "status": JobStatus.PENDING.value}
        record["per_recording"] = per_recording
        record["status"] = "running"
        record.pop("error", None)
        runs_store.write_run(self._dir, run_id, record)
        # A cancelled run's sentinel outlives its coordinator; leave it and the fresh one
        # stops on its first recording and re-records cancelled (cf. resume_training).
        runs_store.clear_cancel(self._dir, run_id)
        # Seed the aggregate bar so a client reattaching before the coordinator's first
        # emit sees the real standing, not the finished run's stale recordings_done.
        runs_store.write_progress(
            self._dir,
            run_id,
            processing_progress_to_dict(
                ProcessingProgress(
                    len(record["recording_ids"]) - len(pending),
                    len(record["recording_ids"]),
                    pending[0],
                    None,
                    0.0,
                    len(record["recording_ids"]) - len(pending),
                )
            ),
        )
        try:
            pid = spawn_coordinator(
                runs_store.run_dir(self._dir, run_id), tuple(_PIPELINE_RUNNERS)
            )
        except (
            Exception
        ) as exc:  # noqa: BLE001 — re-raised; must not leave it "running"
            self._fail_run_record(run_id, f"coordinator failed to launch: {exc}")
            raise
        runs_store.set_coordinator_pid(self._dir, run_id, pid)
        return self.attach_run(run_id)

    def _validate_retry_recordings(
        self,
        module,
        recording_ids: list[str],
        config: dict,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> dict[str, str]:
        """``{recording_id: reason}`` for every recording that no longer validates.

        Collects instead of raising on the first: a retry names *every* broken recording so
        the user fixes them in one pass. Broad except is the aggregation boundary — every
        reason is re-raised by the caller, nothing is swallowed.
        """
        errors: dict[str, str] = {}
        if module.batch:
            # A batch run has no per-recording validate; re-validate the whole subset once.
            try:
                module.validate_batch(self._dir, recording_ids, dict(config))
            except Exception as exc:  # noqa: BLE001 — aggregation boundary
                errors[recording_ids[0]] = f"{type(exc).__name__}: {exc}"
            return errors
        checks = _RecordingSteps(self._dir, progress, "Validating", len(recording_ids))
        for sid in recording_ids:
            checks(sid)
            sdir = experiment_store.recording_path(self._dir, sid)
            try:
                sdata = recording_store.read_recording(sdir)
                module.validate(
                    sdir, sdata, module.resolve_upstream_spec(sdir, sdata, dict(config))
                )
            except (
                Exception
            ) as exc:  # noqa: BLE001 — aggregation boundary; see docstring
                errors[sid] = f"{type(exc).__name__}: {exc}"
        checks.finish()
        return errors

    def _fail_run_record(self, run_id: str, error: str) -> None:
        record = runs_store.read_run(self._dir, run_id)
        record["status"] = "failed"
        record.setdefault("error", error)
        runs_store.write_run(self._dir, run_id, record)

    def attach_run(self, run_id: str) -> "AttachedRun":
        """Reattach to a processing run by id — a live one streams its coordinator's
        progress, a terminal one returns at once. Works after an app restart because
        the coordinator + workers are detached and progress is on disk (§15)."""
        return AttachedRun(self, run_id)

    def attach_active_run(self, run_id: str) -> "AttachedRun | None":
        """An :class:`AttachedRun` when the run is still active (for a live reattach
        after reopen), else ``None`` — so the GUI shows a progress bar for a run that
        is still going and a static record for a finished one."""
        with contextlib.suppress(FileNotFoundError):
            if runs_store.read_run(self._dir, run_id).get("status") in ACTIVE_STATUSES:
                return self.attach_run(run_id)
        return None

    # --- Distill runs (label → train, one durable run — §12) ------------------ #
    def _sampling_recordings(self, source_recording_ids: list[str] | None) -> list[str]:
        """The recordings a labeling sample draws from: the ones named, or every one with video.

        "None given" means *all of them that have something to sample*. It meant every
        recording, so one metadata-only recording — which Add recordings allows — refused the
        whole job naming itself, and the GUI's "none = all" could not be used at all (#35).
        Recordings that were *named* are taken as named, so a named one with no video is still
        refused, by name, by the check that follows.
        """
        if source_recording_ids:
            # Order-keeping de-duplication, as `run_processing` does (issue #28, finding 7).
            return list(dict.fromkeys(source_recording_ids))
        with read_cache.pinned():
            recordings = self.recordings
            return [r.id for r in recordings if r.video_parts]

    def distill(
        self,
        name: str,
        classes: list[LabelingClass],
        n_frames: int,
        *,
        source_recording_ids: list[str] | None = None,
        sampling: str = "stratified",
        logit_threshold: float = 0.5,
        min_contour_area: int = 100,
        val_split: float = 0.15,
        background_share: float = LabelingConfig.model_fields[
            "background_share"
        ].default,
        negative_prompt: str | None = None,
        label_model_id: str = "sam3",
        label_model_variant: str | None = None,
        label_compute: ComputeTarget | None = None,
        base_model: str = "yolo11s-seg.pt",
        trainer_id: str = "ultralytics_yolo",
        hyperparams: dict | None = None,
        train_compute: ComputeTarget | None = None,
    ) -> "AttachedDistillRun":
        """Distill a fast detector in one durable run (§12): label a frame sample with a
        prompt-capable model, then train a closed-set YOLO on those labels.
        ``negative_prompt`` names something in the video that is not the subject (a tether's
        cable): it is labelled as a class of its own so the student learns it apart, and the
        trained model never reports it (§12 *Negative prompt*).

        Validates the union of the labeling and training pre-flight up front (Tenet 10),
        reserves the run record, then spawns a **detached distill coordinator** that
        sequences the two stages and publishes folded progress. Returns an
        :class:`AttachedDistillRun` — the run survives the app closing and any process can
        reattach. The trained model lands in ``models/<id>/`` (usable in this experiment at
        once); promote it with :meth:`promote_model` for cross-experiment reuse.

        Raises:
            ValueError: no/duplicate classes, a non-prompt-capable label model, a recording
                without video, ``n_frames`` above the frames available, the label model not
                ready, an unknown/unready trainer, an unsupported train backend, or invalid
                hyperparameters; or a ``negative_prompt`` that is also one of the classes.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        recording_ids = self._sampling_recordings(source_recording_ids)
        if not classes:
            raise ValueError("labeling needs at least one class (a name + text prompt)")
        # The label stage adds the negative class itself (label_dataset); the clash is refused
        # here too, so a bad combination fails before the run exists (Tenet 10).
        with_negative_prompt(classes, negative_prompt)
        prompts = [c.prompt for c in classes]
        if len(set(prompts)) != len(prompts):
            raise ValueError(
                "two classes share a text prompt; prompts must be distinct"
            )
        capable = api_models.prompt_capable_models()
        if label_model_id not in capable:
            raise ValueError(
                f"model {label_model_id!r} cannot label — labeling needs a prompt-capable "
                f"model; choose one of {capable}"
            )
        lab_cfg = LabelingConfig.model_validate(
            {
                "model_id": label_model_id,
                "model_variant": label_model_variant,
                "n_frames": n_frames,
                "sampling": sampling,
                "logit_threshold": logit_threshold,
                "min_contour_area": min_contour_area,
                "val_split": val_split,
                "background_share": background_share,
                "negative_prompt": negative_prompt,
            }
        )
        trainer_cls = TRAINERS.get(trainer_id)
        if trainer_cls is None:
            raise ValueError(
                f"unknown trainer_id {trainer_id!r}; available: {sorted(TRAINERS)}"
            )
        trainer = trainer_cls()
        if not trainer.is_ready():
            raise ValueError(
                f"trainer {trainer_id!r} is not ready (install its backend)"
            )
        train_compute = train_compute or default_compute(trainer.supported_backends)
        if train_compute.backend not in trainer.supported_backends:
            raise ValueError(
                f"trainer {trainer_id!r} does not support backend "
                f"{train_compute.backend!r}; supports {trainer.supported_backends}"
            )
        if train_compute.backend == "cuda" and train_compute.device_indices:
            check_cuda_indices(train_compute.device_indices)
        hyperparams = trainer.validate_hyperparams(hyperparams or {})
        # Enforce the run-level composition + a non-empty name before the recording sweep.
        DistillConfig.model_validate(
            {
                "name": name,
                "base_model": base_model,
                "trainer_id": trainer_id,
                "labeling": lab_cfg.model_dump(),
                "training": hyperparams,
            }
        )
        if not recording_ids:
            raise ValueError("labeling needs at least one source recording with video")
        available = 0
        for sid in recording_ids:
            recording = self.get_recording(sid)  # raises if the recording is unknown
            data = recording_store.read_recording(recording.dir)
            files = data.get("video", {}).get("files", [])
            if not files:
                raise ValueError(
                    f"recording {recording.name!r} has no video to sample; choose "
                    "recordings that have video, or leave the choice empty to use all of them"
                )
            available += sum(
                len(recording_store.load_active_timestamps(recording.dir, data, i))
                for i in range(len(files))
            )
        if lab_cfg.n_frames > available:
            raise ValueError(
                f"n_frames={lab_cfg.n_frames} exceeds the {available} frames available "
                "across the selected recordings"
            )
        access = self.check_model_access(lab_cfg.model_id)
        if not access.ready:
            raise ValueError(f"{lab_cfg.model_id} is not ready — {access.message}")
        label_compute = label_compute or default_compute(
            api_models.supported_backends(lab_cfg.model_id)
        )
        run_id = distill_store.next_distill_id(self._dir)
        config = {
            "name": name,
            "base_model": base_model,
            "trainer_id": trainer_id,
            "classes": [c.to_dict() for c in classes],
            "source_recording_ids": recording_ids,
            "labeling": lab_cfg.model_dump(),
            "training": hyperparams,
            "label_compute": label_compute.to_dict(),
            "train_compute": train_compute.to_dict(),
        }
        # Reserve before spawning so the run is discoverable and a coordinator that dies on
        # launch reconciles to failed (not stuck running).
        distill_store.write_run(
            self._dir,
            run_id,
            {
                "id": run_id,
                "name": name,
                "status": "running",
                "created_at": utc_timestamp(),
                "config": config,
                "stages": {
                    "label": {"status": "pending", "dataset_id": None},
                    "train": {"status": "pending", "model_id": None},
                },
                "resume": False,
            },
        )
        try:
            pid = spawn_coordinator(
                distill_store.run_dir(self._dir, run_id),
                tuple(_PIPELINE_RUNNERS),
                entrypoint="detail.executor.distill_coordinator",
            )
        except (
            Exception
        ) as exc:  # noqa: BLE001 — re-raised; must not leave it "running"
            self._fail_distill_record(run_id, f"coordinator failed to launch: {exc}")
            raise
        distill_store.set_coordinator_pid(self._dir, run_id, pid)
        return self.attach_distill_run(run_id)

    def resume_distill(self, run_id: str) -> "AttachedDistillRun":
        """Resume a terminal (failed / cancelled) distill run into the same record: reuse a
        complete labeled dataset, resume a partial model, and re-spawn the coordinator.

        Raises:
            FileNotFoundError: If the run record does not exist.
            ValueError: If the run is still running or already complete.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        record = distill_store.read_run(self._dir, run_id)
        # A SIGKILLed coordinator reads "running" forever; reconcile mutates + persists.
        self._reconcile_distill_run(record)
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(
                f"distill run {run_id!r} is still running — cancel it before resuming"
            )
        stages = record.get("stages") or {}
        final = stages.get(distill_final_stage(record)) or {}
        if final.get("status") == JobStatus.COMPLETE.value:
            raise ValueError(
                f"distill run {run_id!r} is already complete — nothing to resume"
            )
        record["status"] = "running"
        record["resume"] = True
        record.pop("error", None)
        distill_store.write_run(self._dir, run_id, record)
        # A cancelled run's sentinel outlives its coordinator; clear it so the fresh one
        # doesn't stop on its first stage (cf. retry_run / resume_training).
        distill_store.clear_cancel(self._dir, run_id)
        try:
            pid = spawn_coordinator(
                distill_store.run_dir(self._dir, run_id),
                tuple(_PIPELINE_RUNNERS),
                entrypoint="detail.executor.distill_coordinator",
            )
        except (
            Exception
        ) as exc:  # noqa: BLE001 — re-raised; must not leave it "running"
            self._fail_distill_record(run_id, f"coordinator failed to launch: {exc}")
            raise
        distill_store.set_coordinator_pid(self._dir, run_id, pid)
        return self.attach_distill_run(run_id)

    def cancel_distill(self, run_id: str) -> None:
        """Stop an active distill run: kill the coordinator, cancel the live stage worker,
        and record the run's real status (``complete`` if training actually finished,
        else ``cancelled``). No-op once terminal. Raises FileNotFoundError if absent."""
        record = distill_store.read_run(self._dir, run_id)
        if record.get("status") not in ACTIVE_STATUSES:
            return
        distill_store.request_cancel(self._dir, run_id)
        kill_coordinator(
            distill_store.run_dir(self._dir, run_id),
            distill_store.read_coordinator_pid(self._dir, run_id),
        )
        stages = dict(record.get("stages") or {})
        for name in distill_stage_names(record):
            stage = dict(stages.get(name) or {})
            if stage.get("status") in ACTIVE_STATUSES:
                _, run_dir = self._distill_stage_status(name, stage)
                if run_dir is not None:
                    cancel_run_dir(run_dir)
                    try:
                        stage["status"] = rundir.read_status(run_dir).value
                    except (FileNotFoundError, KeyError, ValueError):
                        stage["status"] = "cancelled"
                else:
                    stage["status"] = "cancelled"
                stages[name] = stage
        record["stages"] = stages
        final_status = (stages.get(distill_final_stage(record)) or {}).get("status")
        record["status"] = (
            "complete" if final_status == JobStatus.COMPLETE.value else "cancelled"
        )
        distill_store.write_run(self._dir, run_id, record)

    def delete_distill(self, run_id: str) -> None:
        """Delete a distill run's index record only (``distill/<id>/``). The produced
        dataset, trained model, and any promoted global model are independent artifacts
        with their own lifecycles and are left intact — delete them explicitly.

        Refused while the run is active (reconciled first, so a dead coordinator does not
        block): deleting the record under a live coordinator is the processing-run case of
        issue #28, finding 6 — the coordinator re-writes a record nothing lists any more.

        Raises:
            FileNotFoundError: If the run record does not exist.
            ValueError: If the run is still active.
        """
        record = self.distill_run_record(
            run_id
        )  # reconciled; FileNotFoundError if absent
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(
                f"distill run {run_id!r} is still active — cancel it first"
            )
        distill_store.delete_run(self._dir, run_id)

    def attach_distill_run(self, run_id: str) -> "AttachedDistillRun":
        """Reattach to a distill run by id — a live one streams its coordinator's progress,
        a terminal one returns at once (§12)."""
        return AttachedDistillRun(self, run_id)

    def attach_active_distill_run(self, run_id: str) -> "AttachedDistillRun | None":
        """An :class:`AttachedDistillRun` when the run is still active, else ``None`` — so
        the GUI shows a live bar for a running distill and a static record for a done one.
        """
        with contextlib.suppress(FileNotFoundError):
            if (
                distill_store.read_run(self._dir, run_id).get("status")
                in ACTIVE_STATUSES
            ):
                return self.attach_distill_run(run_id)
        return None

    @property
    def distill_runs(self) -> list[dict]:
        """All distill-run records (§12), reconciled to their real on-disk status."""
        self.reconcile_distill_runs()
        return distill_store.list_runs(self._dir)

    def distill_run_record(self, run_id: str) -> dict:
        """The full ``distill.yaml`` for one run, reconciled (Tenet 2).

        Raises:
            FileNotFoundError: If the run record does not exist.
        """
        record = distill_store.read_run(self._dir, run_id)
        if self._reconcile_distill_run(record):
            record = distill_store.read_run(self._dir, run_id)
        return record

    def reconcile_distill_runs(self) -> None:
        """Fold each still-active distill run's real on-disk status back into its record on
        experiment open (§12) — the SIGKILL backstop, mirroring :meth:`reconcile_runs`.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        for record in distill_store.list_runs(self._dir):
            self._reconcile_distill_run(record)

    def _distill_stage_status(
        self, name: str, stage: dict
    ) -> tuple[str | None, Path | None]:
        """The stage's on-disk ``job.json`` status + its run dir (``datasets/<id>/`` for
        label, ``models/<id>/`` for train), or ``(None, None)`` if it never produced one.
        The register stage runs inside the coordinator and has neither.
        """
        if name == "register":
            return None, None
        art_id = stage.get("dataset_id") if name == "label" else stage.get("model_id")
        if art_id is None:
            return None, None
        run_dir = (
            datasets_store.dataset_dir(self._dir, art_id)
            if name == "label"
            else models_store.model_dir(self._dir, art_id)
        )
        try:
            return rundir.read_status(run_dir).value, run_dir
        except (FileNotFoundError, KeyError, ValueError):
            return None, run_dir

    def _reconcile_distill_run(self, record: dict) -> bool:
        """Reconcile one distill record against on-disk evidence; returns True if changed.
        The **coordinator pid** is the liveness authority: alive → leave running; gone →
        adopt each stage's terminal ``job.json`` status, keep an individually-alive stage
        worker running, fail an active stage with no live worker, and roll up (complete only
        when training is)."""
        if record.get("status") not in ACTIVE_STATUSES:
            return False
        run_id = record["id"]
        pid = distill_store.read_coordinator_pid(self._dir, run_id)
        if pid is None:
            return False  # pid not recorded yet — just launched, leave running
        if coordinator_alive(distill_store.run_dir(self._dir, run_id), pid):
            return False  # the coordinator is driving it
        stages = dict(record.get("stages") or {})
        changed = False
        alive = False
        for name in distill_stage_names(record):
            stage = dict(stages.get(name) or {})
            if stage.get("status") not in ACTIVE_STATUSES:
                stages[name] = stage
                continue
            status, run_dir = self._distill_stage_status(name, stage)
            if status is None or status in ACTIVE_STATUSES:
                if run_dir is not None and status is not None and worker_alive(run_dir):
                    alive = True  # a detached stage worker still finishing — leave it
                    stages[name] = stage
                    continue
                stage["status"] = JobStatus.FAILED.value
                stage.setdefault(
                    "error", "interrupted: coordinator gone (reconciled on open)"
                )
            else:
                stage["status"] = status
            changed = True
            stages[name] = stage
        record["stages"] = stages
        final = stages.get(distill_final_stage(record)) or {}
        if alive:
            new_status = "running"
        elif final.get("status") == JobStatus.COMPLETE.value:
            new_status = "complete"
        else:
            new_status = "failed"
        if new_status != record.get("status"):
            record["status"] = new_status
            changed = True
        if changed:
            distill_store.write_run(self._dir, run_id, record)
        return changed

    def _fail_distill_record(self, run_id: str, error: str) -> None:
        record = distill_store.read_run(self._dir, run_id)
        record["status"] = "failed"
        record.setdefault("error", error)
        distill_store.write_run(self._dir, run_id, record)

    def promote_model(self, model_id: str, name: str | None = None) -> str:
        """Promote a completed trained model into the machine-global catalog so it can be
        selected in *any* experiment (§12) — the on-demand step after a distill. The global
        model records its provenance (this experiment + the source dataset + base model +
        metrics), and its weights are copied so it stays self-contained. Returns the assigned
        global model id.

        Raises:
            FileNotFoundError: If the model (or its weights file) does not exist.
            ValueError: If the model is not complete or the derived global id collides.
        """
        import_runner_modules(
            _PIPELINE_RUNNERS
        )  # populate registries for id validation
        return distilled_store.register_distilled_model(
            self._dir,
            model_id,
            source_experiment_name=self.name,
            source_experiment_id=self._dir.name,
            name=name,
        )

    @property
    def processing_runs(self) -> list[dict]:
        """Experiment-level processing-run records — the runs index (§15)."""
        return runs_store.list_runs(self._dir)

    # --- Training datasets (§12) -------------------------------------------- #
    @property
    def datasets(self) -> list[DatasetRef]:
        """Training datasets in the experiment (scans ``datasets/``)."""
        refs = []
        for rec in dirscan.read_each(
            datasets_store.discover_datasets(self._dir),
            lambda d: datasets_store.read_dataset_yaml(
                datasets_store.dataset_dir(self._dir, d)
            ),
        ):
            refs.append(
                DatasetRef(
                    id=rec["id"],
                    name=rec.get("name", ""),
                    status=rec.get("status", "unknown"),
                    n_train=rec.get("n_train", 0),
                    n_val=rec.get("n_val", 0),
                    created_at=rec.get("created_at", ""),
                )
            )
        return refs

    def dataset_record(self, dataset_id: str) -> dict:
        """The full ``dataset.yaml`` for one dataset (for detail views — Tenet 2)."""
        return datasets_store.read_dataset_yaml(
            datasets_store.dataset_dir(self._dir, dataset_id)
        )

    def generate_dataset(
        self,
        name: str,
        source_run_id: str,
        frame_selection: dict | None = None,
        val_split: float = 0.15,
        min_contour_area: int = 100,
    ) -> DatasetRun:
        """Export a YOLO training dataset from a completed detection/tracking run
        (§12). No new inference — reuses the run's masks. Returns a run handle.

        Raises:
            FileNotFoundError: If the source run record is absent.
            ValueError: If the source run is not a complete detection/tracking run.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        record = runs_store.read_run(self._dir, source_run_id)  # raises if missing
        if record.get("module_id") not in ("detection", "tracking"):
            raise ValueError(
                f"dataset source must be a detection or tracking run, got "
                f"{record.get('module_id')!r}"
            )
        if record.get("status") != "complete":
            raise ValueError(
                f"source run {source_run_id!r} is {record.get('status')!r}, "
                "not complete"
            )
        dataset_id = datasets_store.next_dataset_id(self._dir)
        job = DatasetExportJob(
            job_id=dataset_id,
            dataset_id=dataset_id,
            name=name,
            source_run_id=source_run_id,
            frame_selection=frame_selection or {"mode": "all"},
            val_split=val_split,
            min_contour_area=min_contour_area,
            created_at=utc_timestamp(),
        )
        # An initial record so the dataset is discoverable while it runs, written
        # *before* submit so the runner's completion write (full record) is always
        # last — never clobbered by this one (the worker can finish fast).
        ddir = datasets_store.dataset_dir(self._dir, dataset_id)
        ddir.mkdir(parents=True, exist_ok=True)
        datasets_store.write_dataset_yaml(
            ddir,
            {
                "id": dataset_id,
                "name": name,
                "source": {"kind": "run_export", "run_id": source_run_id},
                "status": "running",
            },
        )
        executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
        executor.submit(job)  # run_dir = datasets/<id>/; writes job.json there
        return DatasetRun(ExecutorRunHandle(executor, dataset_id), self, dataset_id)

    def label_dataset(
        self,
        name: str,
        classes: list[LabelingClass],
        n_frames: int,
        source_recording_ids: list[str] | None = None,
        logit_threshold: float = 0.5,
        min_contour_area: int = 100,
        val_split: float = 0.15,
        compute: ComputeTarget | None = None,
        sampling: str = "stratified",
        model_id: str = "sam3",
        model_variant: str | None = None,
        background_share: float = LabelingConfig.model_fields[
            "background_share"
        ].default,
        negative_prompt: str | None = None,
    ) -> DatasetRun:
        """Build a YOLO dataset by running a prompt-capable model on a sample of frames (§12) —
        the distill-into-YOLO source, no existing detection run needed. ``model_id`` picks which
        prompt-capable model labels (``sam3`` by default), ``model_variant`` its size
        (``None`` = the model's default). ``n_frames`` is sampled proportionally to recording
        length; ``sampling`` picks how frames are drawn within each video (``"stratified"`` spreads
        them evenly across time, ``"uniform"`` is fully random). ``source_recording_ids=None`` uses
        every recording. Frames where the model found none of the classes are kept with an
        empty label, up to ``background_share`` of the dataset. ``negative_prompt`` adds a class
        for something that is not the subject (a tether's cable), labelled so a detector trained
        on the dataset learns it apart and never reports it (§12 *Negative prompt*). Returns a
        run handle.

        The flat scalar parameters (``model_id``, ``model_variant``, ``n_frames``, ``sampling``,
        ``logit_threshold``, ``min_contour_area``, ``val_split``, ``background_share``,
        ``negative_prompt``) are
        validated by
        :class:`LabelingConfig`; the checks below need recording data and stay here.

        Raises:
            ValueError: no classes, duplicate class prompts, a scalar out of its model bounds
                (bad ``sampling`` / ``val_split`` / ``n_frames`` / thresholds), a model that is not
                prompt-capable, a recording without video, ``n_frames`` above the frames available,
                the chosen model not ready, or a ``negative_prompt`` that is also one of the
                classes.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        recording_ids = self._sampling_recordings(source_recording_ids)
        compute = compute or default_compute(api_models.supported_backends(model_id))
        if not classes:
            raise ValueError("labeling needs at least one class (a name + text prompt)")
        prompts = [c.prompt for c in classes]
        if len(set(prompts)) != len(prompts):
            raise ValueError(
                "two classes share a text prompt; prompts must be distinct"
            )
        capable = api_models.prompt_capable_models()
        if model_id not in capable:
            raise ValueError(
                f"model {model_id!r} cannot label — labeling needs a prompt-capable model; "
                f"choose one of {capable}"
            )
        cfg = LabelingConfig.model_validate(
            {
                "model_id": model_id,
                "model_variant": model_variant,
                "n_frames": n_frames,
                "sampling": sampling,
                "logit_threshold": logit_threshold,
                "min_contour_area": min_contour_area,
                "val_split": val_split,
                "background_share": background_share,
                "negative_prompt": negative_prompt,
            }
        )
        # The negative prompt is labelled as one more class, recorded by name (Tenet 9).
        labelled, negative_classes = with_negative_prompt(classes, cfg.negative_prompt)
        if not recording_ids:
            raise ValueError("labeling needs at least one source recording with video")
        available = 0
        for sid in recording_ids:
            recording = self.get_recording(sid)  # raises if the recording is unknown
            data = recording_store.read_recording(recording.dir)
            files = data.get("video", {}).get("files", [])
            if not files:
                raise ValueError(
                    f"recording {recording.name!r} has no video to sample; choose "
                    "recordings that have video, or leave the choice empty to use all of them"
                )
            # Frame count from the PTS timestamp map (Tenet 8 / CLAUDE.md frame-count rule), not
            # cv2's CAP_PROP_FRAME_COUNT estimate — so the n_frames check matches what's sampleable.
            available += sum(
                len(recording_store.load_active_timestamps(recording.dir, data, i))
                for i in range(len(files))
            )
        if cfg.n_frames > available:
            raise ValueError(
                f"n_frames={cfg.n_frames} exceeds the {available} frames available across "
                "the selected recordings"
            )
        status = self.check_model_access(cfg.model_id)
        if not status.ready:
            raise ValueError(f"{cfg.model_id} is not ready — {status.message}")

        dataset_id = datasets_store.next_dataset_id(self._dir)
        job = LabelingJob(
            job_id=dataset_id,
            dataset_id=dataset_id,
            name=name,
            source_recording_ids=recording_ids,
            classes=labelled,
            n_frames=cfg.n_frames,
            logit_threshold=cfg.logit_threshold,
            min_contour_area=cfg.min_contour_area,
            val_split=cfg.val_split,
            background_share=cfg.background_share,
            compute=compute,
            created_at=utc_timestamp(),
            sampling=cfg.sampling,
            model_id=cfg.model_id,
            model_variant=cfg.model_variant,
            negative_classes=negative_classes,
        )
        ddir = datasets_store.dataset_dir(self._dir, dataset_id)
        ddir.mkdir(parents=True, exist_ok=True)
        datasets_store.write_dataset_yaml(
            ddir,
            {
                "id": dataset_id,
                "name": name,
                "source": {"kind": "labeling", "model": cfg.model_id},
                "status": "running",
            },
        )
        executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
        executor.submit(job)
        return DatasetRun(ExecutorRunHandle(executor, dataset_id), self, dataset_id)

    # --- Keypoints (§26): one-line methods delegating to api/keypoints.py -------- #
    # Each keypoint PR (2 example sets, 4 detect) adds its
    # methods here as one-liners that import `detail.api.keypoints` locally and forward
    # to it — the shape `query_run` has — so three PRs never edit one region's body.
    # -- keypoints (§26): PR 8 -- distill keypoints (api/keypoint_distill.py)
    def keypoint_dataset(
        self, name: str, detect_runs=None, n_frames: int | None = None, **options
    ) -> "DatasetRun":
        """Build a YOLO-pose dataset (§12 *Distill keypoints*, the label stage on its own).
        The teacher is ``detect_runs`` (finished keypoint detect runs: recording names or ids,
        each with a run id or ``None`` for the only one; ``tracking=`` may name the tracking
        run each recording's poses are assigned to, else the one on the detect run's
        detection run) or the patch method (``example_set=``, ``tracking=``, ``model_id=``,
        ``label_compute=``); the other options are ``KeypointDatasetConfig``'s. Returns a
        ``DatasetRun``."""
        from detail.api import keypoint_distill as _kd

        return _kd.keypoint_dataset(self, name, detect_runs, n_frames, **options)

    def test_keypoints(self, detect_runs=None, **options):
        """Test a keypoint teacher on about a dozen frames drawn the way a distill would, with
        the held-out check against the example clicks; writes nothing (§12, *Test
        cut-off…*). Takes ``distill_keypoints``'s teacher keywords plus ``n_frames`` and
        ``seed``. Returns a ``TeacherTest``."""
        from detail.api import keypoint_distill as _kd

        return _kd.keypoint_test(self, detect_runs, **options)

    def distill_keypoints(
        self, name: str, detect_runs=None, n_frames: int | None = None, **options
    ) -> "AttachedDistillRun":
        """Distill a teacher into a fast YOLO-pose student in one durable run (label →
        train → register). The teacher is ``detect_runs`` or the patch method
        (``example_set=`` + ``tracking=``), as :meth:`keypoint_dataset` takes it. Options:
        ``KeypointDatasetConfig``'s fields plus ``base_model`` (a ``-pose`` checkpoint),
        ``trainer_id``, ``hyperparams``, ``train_compute`` and ``label_compute``. Returns an
        :class:`AttachedDistillRun`."""
        from detail.api import keypoint_distill as _kd

        return _kd.distill_keypoints(self, name, detect_runs, n_frames, **options)

    # -- keypoints (§26): PR 2 -- example sets
    def example_sets(self, purpose: str | None = "example") -> list:
        """This experiment's example sets of one purpose (``None`` for all), id order."""
        from detail.api import keypoints as _keypoints

        return _keypoints.example_sets(self, purpose)

    def example_set(self, set_id: str):
        """One example set; ``FileNotFoundError`` names the sets that exist."""
        from detail.api import keypoints as _keypoints

        return _keypoints.example_set(self, set_id)

    def create_example_set(self, name: str, skeleton, *, purpose: str = "example"):
        """A new, empty example set holding a copy of ``skeleton``."""
        from detail.api import keypoints as _keypoints

        return _keypoints.create_example_set(self, name, skeleton, purpose=purpose)

    def sample_example_frames(self, set_id: str, sources, n_frames: int = 5, **options):
        """Copy tracked frames into an example set (``varied`` or ``spread``); see
        ``api.keypoints.sample_example_frames`` for the options."""
        from detail.api import keypoints as _keypoints

        return _keypoints.sample_example_frames(
            self, set_id, sources, n_frames, **options
        )

    def add_example_frame(
        self, set_id, recording, tracking_run_id, part_id, frame_idx, track_id
    ):
        """Copy one navigated-to frame into an example set."""
        from detail.api import keypoints as _keypoints

        return _keypoints.add_example_frame(
            self, set_id, recording, tracking_run_id, part_id, frame_idx, track_id
        )

    def set_example_marks(self, set_id: str, frame_index: int, marks):
        """Replace one frame's marks and write the set atomically."""
        from detail.api import keypoints as _keypoints

        return _keypoints.set_example_marks(self, set_id, frame_index, marks)

    def remove_example_frame(self, set_id: str, frame_index: int):
        """Drop one frame from an example set (its PNG stays)."""
        from detail.api import keypoints as _keypoints

        return _keypoints.remove_example_frame(self, set_id, frame_index)

    def example_frame_image(self, set_id: str, frame_index: int):
        """One example frame's picture as RGB uint8."""
        from detail.api import keypoints as _keypoints

        return _keypoints.example_frame_image(self, set_id, frame_index)

    def update_example_set(self, set_id: str, *, name=None, skeleton=None):
        """Rename an example set, and/or change its skeleton until its first mark."""
        from detail.api import keypoints as _keypoints

        return _keypoints.update_example_set(self, set_id, name=name, skeleton=skeleton)

    def duplicate_example_set(self, set_id: str, *, name=None):
        """A new, empty set holding a copy of this set's skeleton."""
        from detail.api import keypoints as _keypoints

        return _keypoints.duplicate_example_set(self, set_id, name=name)

    def export_example_set(self, set_id: str, out_dir):
        """Write a set (``examples.yaml`` + its frame images) to a folder."""
        from detail.api import keypoints as _keypoints

        return _keypoints.export_example_set(self, set_id, out_dir)

    def example_set_runs(self, set_id: str) -> list:
        """``(recording_id, run_id)`` of the keypoint detect runs that list a set."""
        from detail.api import keypoints as _keypoints

        return _keypoints.example_set_runs(self, set_id)

    def import_example_set(self, yaml_path):
        """Read a prepared example set (YAML + images beside it) in under a fresh id."""
        from detail.api import keypoints as _keypoints

        return _keypoints.import_example_set(self, yaml_path)

    def delete_example_set(self, set_id: str) -> None:
        """Delete an example set no keypoint run lists."""
        from detail.api import keypoints as _keypoints

        _keypoints.delete_example_set(self, set_id)

    # --- Trained models (§12) ---------------------------------------------- #
    @property
    def models(self) -> list[ModelRef]:
        """Trained models in the experiment (scans ``models/``)."""
        refs = []
        for rec in dirscan.read_each(
            models_store.discover_models(self._dir),
            lambda m: models_store.read_model_yaml(
                models_store.model_dir(self._dir, m)
            ),
        ):
            refs.append(
                ModelRef(
                    id=rec["id"],
                    name=rec.get("name", ""),
                    status=rec.get("status", "unknown"),
                    trainer_id=rec.get("trainer_id", ""),
                    dataset_id=rec.get("dataset_id", ""),
                    created_at=rec.get("created_at", ""),
                    role="keypoints" if rec.get("task") == "pose" else "detection",
                )
            )
        return refs

    def model_names(self) -> dict[str, str]:
        """``{model_id: name}`` for every model this experiment can name — its own trained
        models plus the machine-global imported ones (§5/§12). The model twin of
        :meth:`recording_names`.

        Records key on the model **id**, which is permanent; the **name** is what people
        read (§11). A label built from this falls back to the id for anything absent — a
        built-in model, whose id *is* its name, or a model deleted since the run. Cost is
        O(models), not O(recordings), so it is cheap enough to build per page render.
        """
        names = {m.id: m.name for m in self.models if m.name}
        names.update({m.id: m.name for m in self.imported_models if m.name})
        return names

    def model_record(self, model_id: str) -> dict:
        """The full ``model.yaml`` for one trained model (for detail views — Tenet 2)."""
        return models_store.read_model_yaml(models_store.model_dir(self._dir, model_id))

    def model_metric_history(self, model_id: str) -> list[dict[str, float]]:
        """Per-epoch metrics for a trained model, oldest first; ``[]`` if it has none yet.

        The series behind `model_record`'s summary. `final_metrics` answers *how good is this
        model*; someone deciding whether to stop training early is asking the other question —
        *is it still getting better* — and one number cannot tell a run that has been improving
        for an hour from one that plateaued forty epochs ago.

        Readable while the run is live, because it comes off the trainer's own on-disk record
        rather than progress events — so it is whole on a page opened after the run began, and a
        model that trained overnight has its curve in the morning.

        Returns ``[]`` rather than raising when the trainer is not installed on this machine:
        reading a finished run's record must not require the backend that produced it (a model
        trained elsewhere and imported has no Ultralytics here), and a missing curve is the
        honest rendering of a history we cannot read.
        """
        record = self.model_record(model_id)  # FileNotFoundError if the model is gone
        # The registry's entrypoint, not a hope that something earlier in this process ran it:
        # `train_model` does, but a GUI that opens an existing model — or watches a distill whose
        # training runs in its detached coordinator — never trains here, found `TRAINERS` empty,
        # and drew no curve at all. The test session imports every registry up front, so the
        # suite could not see it.
        import_trainers()
        trainer_cls = TRAINERS.get(record.get("trainer_id", ""))
        if trainer_cls is None:
            return []
        return trainer_cls().metric_history(models_store.model_dir(self._dir, model_id))

    def train_model(
        self,
        name: str,
        dataset_id: str,
        trainer_id: str,
        base_model: str,
        hyperparams: dict | None = None,
        compute: ComputeTarget | None = None,
    ) -> ModelRun:
        """Train a custom detection model from a dataset (§12). Returns a handle.

        Raises:
            FileNotFoundError: If the dataset does not exist.
            ValueError: If the dataset is not complete, the trainer is unknown or
                not ready, the backend is unsupported, or hyperparams are invalid.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        ddir = datasets_store.dataset_dir(self._dir, dataset_id)
        if not (ddir / datasets_store.DATASET_FILENAME).is_file():
            raise FileNotFoundError(f"dataset {dataset_id!r} not found")
        if datasets_store.read_dataset_yaml(ddir).get("status") != "complete":
            raise ValueError(f"dataset {dataset_id!r} is not complete")
        trainer_cls = TRAINERS.get(trainer_id)
        if trainer_cls is None:
            raise ValueError(
                f"unknown trainer_id {trainer_id!r}; available: {sorted(TRAINERS)}"
            )
        trainer = trainer_cls()
        if not trainer.is_ready():
            raise ValueError(
                f"trainer {trainer_id!r} is not ready (install its backend)"
            )
        compute = compute or default_compute(trainer.supported_backends)
        if compute.backend not in trainer.supported_backends:
            raise ValueError(
                f"trainer {trainer_id!r} does not support backend "
                f"{compute.backend!r}; supports {trainer.supported_backends}"
            )
        if compute.backend == "cuda" and compute.device_indices:
            check_cuda_indices(compute.device_indices)
        hyperparams = trainer.validate_hyperparams(hyperparams or {})
        # A base checkpoint that cannot learn the dataset's labels (a -seg base on a pose
        # dataset, or the reverse) fails here, before anything is downloaded or written.
        check_base = getattr(trainer, "check_base_model", None)
        if check_base is not None:
            check_base(base_model, ddir)
        model_id = models_store.next_model_id(self._dir)
        job = TrainingJob(
            job_id=model_id,
            model_id=model_id,
            dataset_id=dataset_id,
            trainer_id=trainer_id,
            base_model=base_model,
            hyperparams=hyperparams,
            compute=compute,
            created_at=utc_timestamp(),
        )
        # Initial record (before submit) carrying the name + lineage; the runner
        # fills in classes/weights/metrics/status on completion.
        mdir = models_store.model_dir(self._dir, model_id)
        mdir.mkdir(parents=True, exist_ok=True)
        models_store.write_model_yaml(
            mdir,
            {
                "id": model_id,
                "name": name,
                "trainer_id": trainer_id,
                "dataset_id": dataset_id,
                "base_model": base_model,
                # Resolved (defaults filled) before the run starts: the live training curve
                # and `train status` read the epoch count from here.
                "hyperparams": dict(hyperparams),
                "status": "running",
            },
        )
        executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
        executor.submit(job)  # run_dir = models/<id>/; writes job.json there
        return ModelRun(ExecutorRunHandle(executor, model_id), self, model_id)

    def resume_training(self, model_id: str) -> ModelRun:
        """Resume a training that was killed or crashed mid-run (cancelled / failed) from
        its last checkpoint instead of restarting from epoch 0 (§12). Re-submits the original
        job; the runner picks up ``run/weights/last.pt``. Returns a handle.

        A ``partial`` model is refused: it stopped cleanly, so its checkpoint was finalized
        and holds nothing to resume (:data:`RESUMABLE_TRAINING_STATUSES`).

        Raises:
            FileNotFoundError: If the model does not exist.
            ValueError: If the model finished (complete / partial) or is running, its
                recorded training job is missing/unreadable, its trainer is unknown, or it has
                no checkpoint to resume from.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        mdir = models_store.model_dir(self._dir, model_id)
        record = models_store.read_model_yaml(mdir)  # FileNotFoundError if absent
        status = record.get("status")
        if status == "partial":
            raise ValueError(
                f"model {model_id!r} stopped cleanly, so its training is finished and its "
                "checkpoint holds nothing to resume. Its best weights are usable as they are; "
                "train a new model to train further."
            )
        if status not in RESUMABLE_TRAINING_STATUSES:
            raise ValueError(
                f"model {model_id!r} is {status!r}; only a cancelled or failed training "
                "can be resumed"
            )
        try:
            job = rundir.read_job(
                mdir
            )  # the original TrainingJob (run_dir = models/<id>/)
        except (FileNotFoundError, KeyError, ValueError) as exc:
            raise ValueError(
                f"model {model_id!r} has no recorded training job to resume ({exc})"
            ) from exc
        trainer_cls = TRAINERS.get(job.trainer_id)
        if trainer_cls is None:
            raise ValueError(
                f"unknown trainer_id {job.trainer_id!r} for model {model_id!r}"
            )
        if trainer_cls().checkpoint_path(mdir) is None:
            raise ValueError(
                f"model {model_id!r} has no checkpoint to resume from — train it first"
            )
        live = live_process_pid(mdir)
        if live is not None:
            raise ValueError(
                f"model {model_id!r} still has a training process running (pid {live}) — "
                "cancel it in DETAIL before resuming. A force-kill of the trainer alone "
                "leaves the worker above it alive and holding the GPU."
            )
        models_store.set_model_status(mdir, "running")
        # A cancelled/partial run left a `cancel` marker in the run dir; clear it or the resumed
        # worker's cancel watcher sees it and immediately re-cancels (cf. api/annotation.py).
        rundir.clear_cancel(mdir)
        executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
        executor.submit(job)  # same run dir: last.pt is present, so the runner resumes
        return ModelRun(ExecutorRunHandle(executor, model_id), self, model_id)

    def delete_dataset(self, dataset_id: str) -> None:
        """Delete a training dataset (images + labels + ``dataset.yaml``).

        Blocked only while *active* work would lose its inputs (gui_design §1.1):
        the dataset's own export, or a model still training from it. A *completed*
        model is self-contained (it copied its weights), so its lineage reference
        is left to dangle — it does not block.

        Raises:
            FileNotFoundError: If no such dataset exists.
            ValueError: If the dataset's export or a model training from it is active.
        """
        record = datasets_store.read_dataset_yaml(  # FileNotFoundError if absent
            datasets_store.dataset_dir(self._dir, dataset_id)
        )
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(
                f"dataset {dataset_id!r} is still being generated — wait for it"
            )
        blockers = [
            m.id
            for m in self.models
            if m.dataset_id == dataset_id and m.status in ACTIVE_STATUSES
        ]
        if blockers:
            raise ValueError(
                f"cannot delete dataset {dataset_id!r} — a model is training from "
                f"it: {', '.join(blockers)}"
            )
        datasets_store.delete_dataset(self._dir, dataset_id)

    def delete_model(self, model_id: str) -> None:
        """Delete a trained model (``model.yaml`` + trainer run + weights).

        Blocked only while *active* work would lose its inputs (gui_design §1.1):
        the model's own training, or a detection run still using it. A *completed*
        detection run keeps its own masks, so its lineage reference is left to
        dangle — it does not block.

        Raises:
            FileNotFoundError: If no such model exists.
            ValueError: If the model's training or a detection run using it is active.
        """
        record = models_store.read_model_yaml(  # FileNotFoundError if absent
            models_store.model_dir(self._dir, model_id)
        )
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(f"model {model_id!r} is still training — wait for it")
        blockers = [
            run["id"]
            for run in self.processing_runs
            if run.get("module_id") == "detection"
            and run.get("status") in ACTIVE_STATUSES
            and run.get("config", {}).get("weights_source") == "trained"
            and run.get("config", {}).get("model_id") == model_id
        ]
        if blockers:
            raise ValueError(
                f"cannot delete model {model_id!r} — a detection run is using it: "
                f"{', '.join(blockers)}"
            )
        models_store.delete_model(self._dir, model_id)

    def delete_run(self, run_id: str) -> None:
        """Delete a processing run: its per-recording outputs (zarr stores +
        recording.yaml entries) and the experiment-level run record.

        Refuses if any per-recording output is still depended on by a downstream
        run (e.g. tracking built on this detection) — delete those first. Nothing
        is removed until the whole run is clear to delete (Tenet 10).

        Raises:
            FileNotFoundError: If no such run record exists.
            ValueError: If the run is still active, or a downstream run depends on it.
        """
        record = runs_store.read_run(self._dir, run_id)
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(f"run {run_id!r} is still active — wait for it to finish")
        module_id = record["module_id"]
        per_recording = record.get("per_recording", {})

        blockers = []
        for recording_id, info in per_recording.items():
            stage_run_id = info.get("run_id")
            if stage_run_id is None:
                continue
            recording = self.get_recording(recording_id)
            for dep_module, dep_run_id in recording.run_dependents(
                module_id, stage_run_id
            ):
                blockers.append(
                    f"  {recording_id}: {dep_module} run {dep_run_id!r} depends on "
                    f"{stage_run_id!r}"
                )
        if blockers:
            raise ValueError(
                f"cannot delete run {run_id!r} — delete its dependents first:\n"
                + "\n".join(blockers)
            )

        active = self._active_analysis_blockers(module_id, per_recording)
        if active:
            raise ValueError(
                f"cannot delete run {run_id!r} — an analysis run is still reading it:\n"
                + "\n".join(active)
            )

        for recording_id, info in per_recording.items():
            stage_run_id = info.get("run_id")
            if stage_run_id is not None:
                self.get_recording(recording_id).delete_run(module_id, stage_run_id)
        runs_store.delete_run(self._dir, run_id)

    def _active_analysis_blockers(
        self, module_id: str, per_recording: dict
    ) -> list[str]:
        """Active analysis runs that consume one of this run's per-recording stage runs.

        A *completed* analysis run copied its derived values into its own CSVs, so it
        never blocks (it dangles, like a dataset's source) — only an **active** run,
        mid-read of the source, does. Location export consumes tracking runs; future
        analysis modules consuming other stages would extend the field check here.
        """
        if module_id != "tracking":
            return []
        stage_ids = {info.get("run_id") for info in per_recording.values()}
        recordings = set(per_recording)
        blockers = []
        for ref in self.analysis_runs:
            if ref.status not in ACTIVE_STATUSES:
                continue
            rec = self.analysis_record(ref.id)
            if rec.get("tracking_run_id") in stage_ids and (
                set(rec.get("recording_ids", [])) & recordings
            ):
                blockers.append(f"  active analysis run {ref.id!r} is using it")
        return blockers

    def cancel_run(self, run_id: str) -> None:
        """Stop an active processing run: signal a live orchestrator (the on-disk
        cancel sentinel — works even after the app restarted), cancel each in-flight
        per-recording worker, and record each recording's real on-disk status. A recording
        the coordinator never launched is listed as ``cancelled`` (not run), so ``process
        retry`` picks it up. The run record becomes ``cancelled`` unless every *planned*
        recording actually completed (then ``complete`` — e.g. a worker that finished after
        the GUI was closed, so its results aren't hidden); see :func:`roll_up_run_status`.
        No-op once terminal.

        Raises:
            FileNotFoundError: If no such run record exists.
        """
        record = runs_store.read_run(self._dir, run_id)
        if record.get("status") not in ACTIVE_STATUSES:
            return
        runs_store.request_cancel(
            self._dir, run_id
        )  # cooperative stop for the coordinator
        # Kill the coordinator so it can't launch the next recording before it notices
        # the flag; its own finalize and this record write both converge on cancelled.
        kill_coordinator(
            runs_store.run_dir(self._dir, run_id),
            runs_store.read_coordinator_pid(self._dir, run_id),
        )
        module_id = record["module_id"]
        per_recording = record.get("per_recording", {})
        for recording_id, info in per_recording.items():
            if info.get("status") not in ACTIVE_STATUSES:
                continue  # a recording that already finished keeps its real status
            stage_run_id = info.get("run_id")
            if stage_run_id is not None:
                info["status"] = self.get_recording(recording_id).cancel_run(
                    module_id, stage_run_id
                )
            else:
                info["status"] = "cancelled"
        # Over the plan: a recording the coordinator never launched is listed as not run
        # (cancelled), so the run reads cancelled and `process retry` picks it up.
        record["status"] = roll_up_run_status(
            record.get("recording_ids") or [],
            per_recording,
            cancelled=True,
            unlaunched=(
                JobStatus.CANCELLED.value,
                "not run: the run was cancelled first",
            ),
        )
        record["per_recording"] = per_recording
        runs_store.write_run(self._dir, run_id, record)

    def cancel_model(self, model_id: str) -> None:
        """Stop an active model-training run (kill its worker), then record its real
        on-disk status — ``cancelled`` if killed, but ``complete`` if the worker
        actually finished (so a done run isn't mislabeled). No-op once terminal.
        Raises FileNotFoundError if the model doesn't exist."""
        mdir = models_store.model_dir(self._dir, model_id)
        record = models_store.read_model_yaml(mdir)  # FileNotFoundError if absent
        if record.get("status") not in ACTIVE_STATUSES:
            return
        cancel_run_dir(mdir)  # models/<id>/ is the run dir (job.json lives there)
        models_store.set_model_status(mdir, rundir.read_status(mdir).value)

    def stop_model(self, model_id: str) -> None:
        """Ask a training run to stop at its next epoch and **keep what it has**.

        The counterpart to :meth:`cancel_model`, and the reason the two exist separately: cancel
        force-kills after three seconds, which on a run whose epochs take minutes means the
        worker dies mid-epoch and never writes ``weights.best`` or ``metrics`` into the record.
        The checkpoint file is on disk and nothing references it.

        This only asks. The run stops at its next epoch boundary, runs its own completion path,
        and records the best weights it reached — which is what *"the metrics look good, stop
        here"* has to mean to be worth offering. The record's status stays as the worker leaves
        it (``complete``), because the run did finish, early.

        No-op once terminal. Raises FileNotFoundError if the model does not exist.
        """
        mdir = models_store.model_dir(self._dir, model_id)
        record = models_store.read_model_yaml(mdir)  # FileNotFoundError if absent
        if record.get("status") not in ACTIVE_STATUSES:
            return
        request_stop(mdir)

    def cancel_dataset(self, dataset_id: str) -> None:
        """Stop an active dataset-export run (kill its worker), then record its real
        on-disk status (``cancelled`` if killed, ``complete`` if it finished). No-op
        once terminal. Raises FileNotFoundError if the dataset doesn't exist."""
        ddir = datasets_store.dataset_dir(self._dir, dataset_id)
        record = datasets_store.read_dataset_yaml(ddir)  # FileNotFoundError if absent
        if record.get("status") not in ACTIVE_STATUSES:
            return
        cancel_run_dir(ddir)
        datasets_store.set_dataset_status(ddir, rundir.read_status(ddir).value)

    # --- Reattach to a single-job run (§12/§16) ------------------------------ #
    # The four single-job run kinds differ only in where their record lives, so one table
    # drives every attach. Each entry is (run_dir, read_record, set_status); the run dir is
    # also the executor's, holding the job.json AttachedJobRun polls.
    _JOB_RUN_KINDS = {
        "analysis": (
            analysis_store.analysis_dir,
            analysis_store.read_analysis_yaml,
            analysis_store.set_analysis_status,
            analysis_store.discover_analyses,
        ),
        "dataset": (
            datasets_store.dataset_dir,
            datasets_store.read_dataset_yaml,
            datasets_store.set_dataset_status,
            datasets_store.discover_datasets,
        ),
        "model": (
            models_store.model_dir,
            models_store.read_model_yaml,
            models_store.set_model_status,
            models_store.discover_models,
        ),
        # `export_runs_store`, not `export_store` — the latter is the experiment *bundle*
        # (`storage/export.py`). Three different things want the word "export" in this package
        # and the run store is the newest of them, so it is the one that qualifies its name.
        "export": (
            export_runs_store.export_dir,
            export_runs_store.read_export_yaml,
            export_runs_store.set_export_status,
            export_runs_store.discover_exports,
        ),
    }

    def attach_job_run(self, kind: str, run_id: str) -> AttachedJobRun:
        """Reattach to a single-job run — a live one streams its worker's progress, a
        terminal one returns at once. Works from any process, after an app restart
        included: the worker is detached and its progress is on disk.

        ``kind`` is a key of ``_JOB_RUN_KINDS``. The typed wrappers below are what callers
        use; this is the shared body.

        **The runner modules are imported first, and that is not optional.** A progress event is
        rebuilt from ``job.json`` by tag, and every tag outside `core/dataclasses.py` — every
        analysis module's, and the export's — is registered as a side effect of importing the
        module that defines it. Reattaching without that raises ``unknown progress event type``
        the moment the first event is read. No test saw it because ``conftest``'s autouse
        ``_isolate_registries`` imports every runner into every test, so the registry is full in
        the suite and empty in a bare ``detail analysis attach``.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        run_dir_for, read_record, set_status, _discover = self._JOB_RUN_KINDS[kind]
        run_dir = run_dir_for(self._dir, run_id)

        def finalize(rdir: Path, status: str) -> None:
            # On success the runner writes the full record, with its own detail;
            # `reconciled_status` is what decides when the envelope overrides it.
            adopted = reconciled_status(read_record(rdir).get("status"), status)
            if adopted is not None:
                set_status(rdir, adopted, rundir.read_envelope(rdir).get("error"))

        return AttachedJobRun(run_dir, run_id, finalize)

    def attach_active_job_run(self, kind: str, run_id: str) -> AttachedJobRun | None:
        """An :class:`AttachedJobRun` when that run is still active, else ``None`` — so the
        GUI shows a live bar for a running one and a static record for a finished one. The
        single-job twin of :meth:`attach_active_run`."""
        if self.job_run_active(kind, run_id):
            return self.attach_job_run(kind, run_id)
        return None

    def job_run_active(self, kind: str, run_id: str) -> bool:
        """Whether that run's job is still working, whatever its record already claims.

        The record is usually enough. An **authored** run (§21) is the exception: its runner
        writes ``open`` before the work that ends the job, so for that stretch the record says
        "ready to interpret" while the job is still writing what interpreting reads. Believed,
        the run page built the workspace mid-fit and its tabs read an artifact that did not
        exist yet ("no behavior_output.yaml"). So an authored status is checked against the job
        envelope, which is the one place that knows the job has not finished.
        """
        run_dir_for, read_record, _set, _discover = self._JOB_RUN_KINDS[kind]
        run_dir = run_dir_for(self._dir, run_id)
        try:
            status = read_record(run_dir).get("status")
        except FileNotFoundError:
            return False
        if status in ACTIVE_STATUSES:
            return True
        if status not in AUTHORED_STATUSES:
            return False
        try:
            return rundir.read_status(run_dir).value in ACTIVE_STATUSES
        except (FileNotFoundError, KeyError, ValueError):
            return False

    def analysis_job_active(self, run_id: str) -> bool:
        """:meth:`job_run_active` for an analysis run."""
        return self.job_run_active("analysis", run_id)

    def attach_analysis_run(self, run_id: str) -> AttachedJobRun:
        """Reattach to an analysis run by id (§16)."""
        return self.attach_job_run("analysis", run_id)

    def attach_active_analysis_run(self, run_id: str) -> AttachedJobRun | None:
        """A handle for a still-active analysis run, else ``None`` (§16)."""
        return self.attach_active_job_run("analysis", run_id)

    def attach_dataset_run(self, dataset_id: str) -> AttachedJobRun:
        """Reattach to a dataset-export run by id (§12)."""
        return self.attach_job_run("dataset", dataset_id)

    def attach_active_dataset_run(self, dataset_id: str) -> AttachedJobRun | None:
        """A handle for a still-active dataset export, else ``None`` (§12)."""
        return self.attach_active_job_run("dataset", dataset_id)

    def attach_model_run(self, model_id: str) -> AttachedJobRun:
        """Reattach to a training run by id (§12)."""
        return self.attach_job_run("model", model_id)

    def attach_active_model_run(self, model_id: str) -> AttachedJobRun | None:
        """A handle for a still-active training run, else ``None`` (§12)."""
        return self.attach_active_job_run("model", model_id)

    def attach_export_run(self, run_id: str) -> AttachedJobRun:
        """Reattach to an export run by id (#354)."""
        return self.attach_job_run("export", run_id)

    def attach_active_export_run(self, run_id: str) -> AttachedJobRun | None:
        """A handle for a still-active export, else ``None`` (#354)."""
        return self.attach_active_job_run("export", run_id)

    # --- Analysis runs (§16) ------------------------------------------------ #

    def reconcile_job_runs(self) -> None:
        """Fold every still-active single-job run's real on-disk status back into its record
        on experiment open — the SIGKILL backstop for analysis, dataset, model and export
        runs alike (§12/§16), beside :meth:`reconcile_runs` for processing runs.

        Driven by ``_JOB_RUN_KINDS``, so a fifth kind inherits the backstop by adding a
        table entry. Without it a killed worker leaves a record reading ``running`` forever,
        which also cannot be deleted — every delete method refuses an active record.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        for kind, (_dir_for, _read, _set, discover) in self._JOB_RUN_KINDS.items():
            for run_id in discover(self._dir):
                self._reconcile_job_run(kind, run_id)

    def _reconcile_job_run(self, kind: str, run_id: str) -> bool:
        """Reconcile one single-job record against on-disk evidence; True if changed.

        The job envelope is the authority: ``reconciled_status`` says when its terminal
        status overrides the record's, and a record whose job is still nominally active but
        whose worker pid is gone is failed. A record with no envelope at all is left alone —
        that job was reserved but never submitted.

        Deliberately **not** gated on the record being ``pending`` / ``running``. An authored
        run (§21) writes ``open`` mid-job, so gating on an active record skipped exactly the
        runs that write a terminal-looking status before the work that justifies it — which is
        how a failed pose-clustering run went on reporting ``open`` through every surface.
        """
        run_dir_for, read_record, set_status, _discover = self._JOB_RUN_KINDS[kind]
        run_dir = run_dir_for(self._dir, run_id)
        try:
            record = read_record(run_dir)
        except (FileNotFoundError, ValueError, yaml.YAMLError):
            # **A record we cannot parse is one we cannot reconcile**, and that is all it is.
            # This runs on every experiment open, so an exception here does not fail a run — it
            # makes the *experiment* impossible to open, and there is no way back to the record
            # from inside the app to fix it. One malformed file, written by a half-finished
            # write, a hand-edit, or a version that stored something this one cannot read, took
            # the whole project down.
            #
            # The isolation holds the read and nothing else (CLAUDE.md): the reconciliation
            # below is a verdict on the run, and must not be skipped for any reason except that
            # there is no record to pass a verdict on.
            return False
        record_status = record.get("status")
        try:
            status = rundir.read_status(run_dir)
        except (FileNotFoundError, KeyError, ValueError):
            return False
        adopted = reconciled_status(record_status, status.value)
        if adopted is not None:
            set_status(run_dir, adopted, rundir.read_envelope(run_dir).get("error"))
            return True
        if status.value not in ACTIVE_STATUSES:
            return False
        # The envelope still says the job is running. That is only believable while the
        # record is one the job is still writing — active, or an authored run mid-projection.
        if record_status not in ACTIVE_STATUSES + AUTHORED_STATUSES:
            return False
        pid = rundir.read_pid(run_dir)
        if pid is not None and not pid_alive(pid):
            reason = "worker exited without completing"
            rundir.set_status(run_dir, JobStatus.FAILED, error=reason)
            set_status(run_dir, JobStatus.FAILED.value, reason)
            return True
        return False

    def reconcile_analysis_runs(self) -> None:
        """The analysis slice of :meth:`reconcile_job_runs` — kept because callers name it,
        and because a caller that only touched analysis should not sweep every kind."""
        import_runner_modules(_PIPELINE_RUNNERS)
        for run_id in analysis_store.discover_analyses(self._dir):
            self._reconcile_job_run("analysis", run_id)

    def reconcile_analysis_run(self, run_id: str) -> bool:
        """Reconcile one analysis run against its job envelope; ``True`` if the record moved.

        One ``job.json`` read, so a surface can afford it on the way into a run's page rather
        than trusting a record last reconciled when the experiment was opened. That gap is
        real: a run that fails *during* a session keeps its optimistic record until something
        sweeps, and the surface that shows it is exactly the one about to offer its results.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        return self._reconcile_job_run("analysis", run_id)

    @property
    def analysis_runs(self) -> list[AnalysisRunRef]:
        """Analysis runs in the experiment (scans ``analysis/``)."""
        refs = []
        for rec in dirscan.read_each(
            analysis_store.discover_analyses(self._dir),
            lambda r: analysis_store.read_analysis_yaml(
                analysis_store.analysis_dir(self._dir, r)
            ),
        ):
            refs.append(
                AnalysisRunRef(
                    id=rec["id"],
                    module_id=rec.get("module_id", ""),
                    recording_ids=rec.get("recording_ids", []),
                    status=rec.get("status", "unknown"),
                    created_at=rec.get("created_at", ""),
                )
            )
        return refs

    # --- Export runs (#354) -------------------------------------------------- #

    @property
    def export_runs(self) -> list["ExportRunRef"]:
        """Every export run in the experiment (scans ``exports/``)."""
        refs = []
        for record in dirscan.read_each(
            export_runs_store.discover_exports(self._dir),
            lambda r: export_runs_store.read_export_yaml(
                export_runs_store.export_dir(self._dir, r)
            ),
        ):
            refs.append(
                ExportRunRef(
                    id=record["id"],
                    subject_kind=record.get("subject_kind", ""),
                    subject_id=record.get("subject_id", ""),
                    target_ids=list(record.get("target_ids") or []),
                    status=record.get("status", "unknown"),
                    created_at=record.get("created_at", ""),
                    folder=record.get("folder", ""),
                    destination=dict(record.get("destination") or {}),
                )
            )
        return refs

    def export_record(self, run_id: str) -> dict:
        """The full record for one export run (for detail views)."""
        return export_runs_store.read_export_yaml(
            export_runs_store.export_dir(self._dir, run_id)
        )

    def run_export(
        self,
        subject_kind: str,
        subject_id: str,
        target_ids: Sequence[str],
        parent: Path | str,
        *,
        scope=None,
        **options,
    ) -> "ExportRun":
        """Export ``target_ids`` from a subject into a new folder under ``parent``, as a run.

        **One request is one run**, however many targets it covers: they share a destination
        folder and a manifest because that is what was asked for once. The targets become the
        run's units.

        ``parent`` is resolved to a machine-local alias (`storage/roots.py`) before it reaches
        the job: everything in a job lands in the run record via ``runners.job_params``, a record
        is ``.yaml``, and an absolute path in one would make ``experiment.export`` refuse this
        experiment permanently (Tenet 6).

        The folder name is minted here rather than in the worker so a surface can say where the
        files are going before the run starts.

        Raises:
            ExportError: if a target is unknown, cannot run for this subject, or the request is
                one ``exporters.check_request`` refuses (a target twice, a scope a target does
                not take, a cluster or frame range the subject does not have).
            ValueError: if ``options["theme"]`` is not a chart theme (``light`` / ``dark``).
        """
        from detail.api import exporters
        from detail.pipeline.export_run import EXPORT_ROOTS_KEY
        from detail.storage import roots

        import_runner_modules(_PIPELINE_RUNNERS)
        subject = exporters.ExportSubject(subject_kind, self._dir, subject_id)
        targets = [exporters.target(subject_kind, t) for t in target_ids]
        for target in targets:
            reason = exporters.unavailable_reason(target, subject)
            if reason is not None:
                raise exporters.ExportError(
                    f"cannot export {target.label.lower()}: {reason}"
                )
        self._check_export_recordings(subject, scope)
        exporters.check_request(subject, targets, scope)
        if options.get("theme") is not None:
            from detail.core.chart_theme import theme as chart_theme

            # Refused here, where the caller can see it, rather than in the worker minutes later
            # as a failed run.
            chart_theme(options["theme"])

        parent = Path(parent).expanduser()
        parent.mkdir(parents=True, exist_ok=True)
        alias = roots.resolve_or_register(EXPORT_ROOTS_KEY, parent)
        rel = parent.resolve().relative_to(
            roots.root(EXPORT_ROOTS_KEY, alias).resolve()
        )

        run_id = export_runs_store.reserve_export_id(self._dir)
        job = ExportJob(
            job_id=run_id,
            subject_kind=subject_kind,
            subject_id=subject_id,
            target_ids=[t.id for t in targets],
            destination={"root": alias, "rel": rel.as_posix()},
            folder=exporters.folder_name(subject),
            created_at=utc_timestamp(),
            scope=_scope_dict(scope),
            options=dict(options),
        )
        # Written before submit so the run is discoverable while it runs, and so the runner's
        # completion write is always last — the worker can finish before this returns.
        rdir = export_runs_store.export_dir(self._dir, run_id)
        export_runs_store.write_export_yaml(
            rdir,
            {
                "id": run_id,
                "subject_kind": subject_kind,
                "subject_id": subject_id,
                "target_ids": [t.id for t in targets],
                "folder": job.folder,
                "destination": dict(job.destination),
                "params": job_params(job),
                "status": "running",
                "created_at": job.created_at,
            },
        )
        executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
        executor.submit(job)
        return ExportRun(ExecutorRunHandle(executor, run_id), self, run_id)

    def _check_export_recordings(self, subject, scope) -> None:
        """Refuse a recordings scope that names something this export does not span.

        Refused here, where the caller can see it, rather than writing an empty folder: a
        misspelt id on a large run would otherwise read as "nothing to write". Only a run
        or analysis run has a set of recordings to choose between; for anything else the one
        thing a scope may name is the subject's own recording.
        """
        from detail.api import exporters

        if scope is None or not scope.recording_ids:
            return
        if subject.kind in ("run", "analysis_run"):
            known = set(exporters.recordings_of(subject))
            unknown = [r for r in scope.recording_ids if r not in known]
            if unknown:
                raise exporters.ExportError(
                    f"{', '.join(unknown)} is not one of the recordings in this "
                    f"{subject.kind.replace('_', ' ')} ({len(known)}: "
                    f"{', '.join(sorted(known)[:6])}{', ...' if len(known) > 6 else ''})"
                )
            return
        if subject.kind == "recording" and set(scope.recording_ids) <= {subject.id}:
            return
        raise exporters.ExportError(
            f"a {subject.kind.replace('_', ' ')} export has no recordings to choose between; "
            "choose recordings when exporting a run or an analysis run"
        )

    def estimate_export(
        self,
        subject_kind: str,
        subject_id: str,
        target_ids: Sequence[str],
        parent: Path | str | None = None,
        *,
        scope=None,
        **options,
    ):
        """How big an export would be and how long it would take, without writing it.

        The same arguments as :meth:`run_export`, and the answer is what the Export dialog and
        ``detail export run`` show before they start: an :class:`exporters.ExportEstimate`, one
        entry per target plus the free space on ``parent``'s drive. A video target times a few
        dozen frames on this machine to answer (about a second); everything else reads sizes and
        row counts from disk.

        Raises:
            ExportError: if a target is unknown, ``scope`` names a recording the export does
                not span, or the request is one ``exporters.check_request`` refuses.
        """
        from detail.api import exporters

        subject = exporters.ExportSubject(subject_kind, self._dir, subject_id)
        targets = [exporters.target(subject_kind, t) for t in target_ids]
        scope = scope or exporters.ExportScope()
        self._check_export_recordings(subject, scope)
        exporters.check_request(subject, targets, scope)
        return exporters.estimate(
            subject, targets, scope=scope, parent=parent, **options
        )

    def cancel_export(self, run_id: str) -> None:
        """Stop an active export run. No-op once terminal.

        Raises:
            FileNotFoundError: If the run doesn't exist.
        """
        rdir = export_runs_store.export_dir(self._dir, run_id)
        record = export_runs_store.read_export_yaml(rdir)
        if record.get("status") not in ACTIVE_STATUSES:
            return
        cancel_run_dir(rdir)
        export_runs_store.set_export_status(rdir, rundir.read_status(rdir).value)

    def delete_export(self, run_id: str) -> None:
        """Delete an export run's record. Blocked while it is still active.

        Deletes the record, never the exported files: those are in the user's own folder,
        outside the experiment, and forgetting a run is not a request to delete its output.
        """
        record = export_runs_store.read_export_yaml(
            export_runs_store.export_dir(self._dir, run_id)
        )
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(
                f"export run {run_id!r} is still {record.get('status')}; cancel it first"
            )
        export_runs_store.delete_export(self._dir, run_id)

    def analysis_record(self, run_id: str) -> dict:
        """The full ``analysis.yaml`` for one analysis run (for detail views)."""
        return analysis_store.read_analysis_yaml(
            analysis_store.analysis_dir(self._dir, run_id)
        )

    def analysis_run_dir(self, run_id: str) -> Path:
        """The on-disk output directory for an analysis run (``analysis/<run_id>/``)
        — for opening it in a file manager."""
        return analysis_store.analysis_dir(self._dir, run_id)

    def location_plots(self, run_id: str) -> "LocationPlots":
        """Plots of a completed location-export run (DESIGN_PLAN §16 "Location plots"): its
        animals' paths, occupancy, speed and body, drawn from the run's own CSVs.

        Returns:
            A ``LocationPlots``: ``build(view)`` for a ``PlotSpec``, ``export(view, stem)``
            for files.

        Raises:
            ValueError: The run is not a location export, or has no completed recording.
        """
        from detail.api.location_plots import LocationPlots

        return LocationPlots(self, run_id)

    def run_analysis(self, module_id: str, config: dict) -> AnalysisRun:
        """Launch an experiment-scoped analysis run (§16): one module over a selection
        of recordings, producing artifacts in ``analysis/<run_id>/``. A single
        executor job (not a per-recording fan-out). Returns a run handle.

        Raises:
            ValueError: If the module is unknown or config validation fails.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        module = ANALYSIS_MODULES.get(module_id)
        if module is None:
            raise ValueError(f"unknown analysis module: {module_id!r}")
        config = module.validate(self._dir, dict(config))
        run_id = analysis_store.reserve_analysis_id(self._dir)
        job = module.build_job(run_id, config)
        # An initial record so the run is discoverable while it runs, written
        # *before* submit so the runner's completion write (full record) is always
        # last — never clobbered by this one (the worker can finish fast).
        adir = analysis_store.analysis_dir(self._dir, run_id)
        adir.mkdir(parents=True, exist_ok=True)
        analysis_store.write_analysis_yaml(
            adir,
            {
                "id": run_id,
                "module_id": module_id,
                "recording_ids": config.get("source_recording_ids", []),
                "status": "running",
                "created_at": utc_timestamp(),
            },
        )
        executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
        executor.submit(job)  # run_dir = analysis/<run_id>/; writes job.json there
        return AnalysisRun(ExecutorRunHandle(executor, run_id), self, run_id)

    def run_comparison(self, config, *, progress=None, stop_check=None):
        """Run a §24 comparison — group statistics across recording metadata — and save it."""
        from detail.api.comparison import run_comparison

        return run_comparison(self, config, progress=progress, stop_check=stop_check)

    def get_comparison(self, comparison_id: str):
        """Handle for an existing comparison in this experiment."""
        from detail.api.comparison import Comparison

        return Comparison(self, comparison_id)

    def measures(self, run_id: str):
        """The §23 measures of one analysis run's behavior artifact (§19)."""
        from detail.api.measures import Measures

        return Measures(self, run_id)

    @property
    def comparisons(self) -> list:
        """All saved comparisons in this experiment."""
        from detail.api.comparison import Comparison
        from detail.storage import comparisons as comparisons_store

        return [
            Comparison(self, cid)
            for cid in comparisons_store.discover_comparisons(self._dir)
        ]

    #: Which handle an authored module's runs are reached through (§21). One table rather than a
    #: copy per caller: the GUI, the CLI and the comparison path all need it, and three parallel
    #: dicts is how the fourth authored module gets forgotten by one of them.
    _AUTHORED_RUN_ACCESSORS = {
        "temporal_clustering": "temporal_clustering_run",
        "query": "query_run",
    }

    def authored_run(self, run_id: str):
        """The §21 handle for an authored run, or ``None`` if this run is not one.

        A computed run (a location export, an eval) has no authored state and pins nothing, so it
        has no handle of this kind — the caller shows no snapshot surface rather than an empty one.
        """
        try:
            record = self.analysis_record(run_id)
        except (FileNotFoundError, KeyError):
            return None
        accessor = self._AUTHORED_RUN_ACCESSORS.get(record.get("module_id"))
        if accessor is None:
            return None
        try:
            return getattr(self, accessor)(run_id)
        except (KeyError, ValueError, FileNotFoundError):
            return None

    def comparisons_using(self, run_id: str) -> dict[str, list[str]]:
        """``{snapshot_id: [comparison_id, ...]}`` for one analysis run's pinned artifacts.

        **Derived, never stored.** A snapshot records why it was taken but not what consumed it:
        an export has no stable identifier to keep (its path lies outside the experiment, and an
        absolute path in an experiment file is a hard rule), and a comparison id does not exist
        until after the pin. So the link is read back off the consumers, which is also the §21 rule
        that a fact checkable from the store gets no second writer.

        One pass over ``comparisons/``, which holds tens of records in a real experiment rather
        than thousands. Records written before ``source_snapshot`` existed carry none and are
        skipped rather than guessed at.
        """
        from detail.storage import comparisons as comparisons_store

        out: dict[str, list[str]] = {}
        for cid in comparisons_store.discover_comparisons(self._dir):
            try:
                record = comparisons_store.read_comparison_yaml(
                    comparisons_store.comparison_dir(self._dir, cid)
                )
            except dirscan.UNREADABLE_RECORD_ERRORS:
                continue  # a half-written or foreign folder is not a comparison
            if not isinstance(record, dict) or record.get("source_run_id") != run_id:
                continue
            snapshot = record.get("source_snapshot")
            if snapshot:
                out.setdefault(str(snapshot), []).append(cid)
        return out

    def delete_comparison(self, comparison_id: str) -> None:
        """Delete a comparison and everything it wrote, exports included.

        Raises:
            FileNotFoundError: no comparison with that id.
        """
        from detail.storage import comparisons as comparisons_store

        if comparison_id not in comparisons_store.discover_comparisons(self._dir):
            raise FileNotFoundError(
                f"no comparison {comparison_id!r} in {self._dir}; "
                f"have {comparisons_store.discover_comparisons(self._dir)}"
            )
        comparisons_store.delete_comparison(self._dir, comparison_id)

    def query_run(self, run_id: str):
        """Reopen an existing §20 Query run as a ``QueryRun`` handle (no active search job) —
        for calibrating a cutoff, naming a behavior, or exporting the artifact.

        The way a searched run is reached to be calibrated: the search leaves the run ``open``
        rather than ``complete``, and the whole of calibration happens through this handle.
        """
        from detail.api.query import QueryRun

        self._require_analysis_run(run_id, "query")
        return QueryRun(None, self, run_id)

    def temporal_clustering_run(self, run_id: str):
        """Reopen an existing §22 temporal-clustering run as a ``TemporalClusteringRun`` handle
        (no active fit job) — for choosing a granularity, naming clusters, or exporting.

        The way a fitted run is reached to be interpreted: the fit leaves the run ``open`` rather
        than ``complete``, and the whole of interpretation happens through this handle.
        """
        from detail.api.temporal_clustering import TemporalClusteringRun

        self._require_analysis_run(run_id, "temporal-clustering")
        return TemporalClusteringRun(None, self, run_id)

    def _require_analysis_run(self, run_id: str, kind: str) -> None:
        """Refuse a run id that names no analysis run, before a handle is built on it.

        Raises:
            UserInputError: no ``analysis/<run_id>/analysis.yaml`` in this experiment.
        """
        adir = analysis_store.analysis_dir(self._dir, run_id)
        if not (adir / analysis_store.ANALYSIS_FILENAME).is_file():
            raise UserInputError(
                f"no {kind} run {run_id!r} in this experiment; `detail analysis list` "
                "shows its runs"
            )

    def cancel_analysis(self, run_id: str) -> None:
        """Stop an active analysis run (kill its worker), then record its real
        on-disk status (``cancelled`` if killed, ``complete`` if it finished). No-op
        once terminal. Raises FileNotFoundError if the run doesn't exist."""
        adir = analysis_store.analysis_dir(self._dir, run_id)
        record = analysis_store.read_analysis_yaml(adir)  # FileNotFoundError if absent
        if record.get("status") not in ACTIVE_STATUSES:
            return
        cancel_run_dir(adir)
        analysis_store.set_analysis_status(adir, rundir.read_status(adir).value)

    def delete_analysis(self, run_id: str) -> None:
        """Delete an analysis run (its ``analysis/<run_id>/`` directory).

        A *completed* analysis run is self-contained (it copied the derived values
        into its own CSVs), so it never blocks deleting its source runs — the
        analogue of the dataset/model lineage-dangle. Blocked only while the run is
        still active.

        Raises:
            FileNotFoundError: If no such analysis run exists.
            ValueError: If the run is still active.
        """
        record = analysis_store.read_analysis_yaml(  # FileNotFoundError if absent
            analysis_store.analysis_dir(self._dir, run_id)
        )
        if record.get("status") in ACTIVE_STATUSES:
            raise ValueError(
                f"analysis run {run_id!r} is still active — cancel it first"
            )
        analysis_store.delete_analysis(self._dir, run_id)

    # --- Credentials and model install (Section 5) -------------------------- #
    def set_hf_token(self, token: str) -> str:
        """Validate and store the Hugging Face token; return the account name.

        Writes the machine-global ``~/.config/detail/credentials.yaml`` (not
        experiment state), exposed here as the single API boundary (Tenet 2).
        """
        return credentials.set_hf_token(token)

    # Models are machine-global (§5) — these delegate to the experiment-free
    # ``api.models`` catalog (the GUI's top-level Models tab uses it directly).
    def check_model_access(
        self, model_id: str, variant: str | None = None
    ) -> ModelReadiness:
        """Proactive readiness for a model — drives 'set up access' UI states."""
        return api_models.model_readiness(model_id, variant)

    def install_model(
        self,
        model_id: str,
        progress_cb: Callable[[InstallProgress], None] | None = None,
        *,
        variant: str | None = None,
    ) -> None:
        """Ensure a model's weights are present; raises ModelNotReadyError if blocked.

        ``variant`` picks the size — each is a separate download (§5)."""
        api_models.install_model(model_id, progress_cb, variant=variant)

    def import_model(
        self,
        weights_path: Path | str,
        *,
        family: str | None = None,
        skeleton=None,
        name: str | None = None,
        made_by: str | None = None,
        description: str | None = None,
        notes: str | None = None,
        preview: Path | str | None = None,
    ) -> str:
        """Import an external checkpoint into the machine-global catalog — usable in *any*
        experiment. A pose checkpoint lands as a keypoint model and needs ``skeleton`` (a
        preset, library id or skeleton YAML) that fits it; see
        :func:`detail.api.models.import_model`. Optional ``made_by`` / ``description`` /
        ``notes`` / ``preview`` are stored as catalog metadata (§12). Returns the assigned
        id."""
        return api_models.import_model(
            weights_path,
            family=family,
            skeleton=skeleton,
            name=name,
            made_by=made_by,
            description=description,
            notes=notes,
            preview=preview,
        )

    @property
    def imported_models(self) -> list[ImportedModelRef]:
        """The machine-global imported models (shared across all experiments)."""
        return api_models.imported_models()

    def remove_imported_model(self, model_id: str) -> None:
        """Delete a machine-global imported model (raises if absent)."""
        api_models.remove_imported_model(model_id)

name property

Experiment display name (from config.yaml; decoupled from the folder).

description property

Experiment description (empty string if unset).

modified_at property

Unix mtime of the most recent experiment-level change.

The max mtime across config.yaml, recordings/ and runs/ — a cheap proxy for "last activity" without walking the whole tree.

recording_ids property

The recording ids in id order — the listing, without the records.

:attr:recordings builds a :class:Recording per id, and each one reads its recording.yaml to learn its name. A caller that only needs how many there are, or which ids exist, pays a file read per recording for a number it could have had from the directory listing.

recording_metadata property

The cohort metadata table: {recording_id: {column: value}} (§11).

metadata_columns property

User-defined grouping-variable columns (excluding recording_id).

import_runs property

Every recording that was imported, shaped like a run record (§3).

An import is the one long operation this app runs that is not a run: it writes no run record, and its state lives on the recording as import_status. This is the adapter that lets it be listed, counted and cancelled beside the families that do — the shape api.active.RUN_KINDS reads, carrying the recording id a surface needs to open it and the name a surface should show instead of that id (§11).

created_at is the recording's own, which is the right answer rather than a convenient one: create_shell mints the recording synchronously when the import is submitted, so it is the moment the import was asked for.

Read under a pin because every :class:Recording property is its own recording.yaml read and this wants three of them per recording — and the quit guard asks this question on the UI thread, where the difference is one round trip per recording instead of three (storage/read_cache.py).

distill_runs property

All distill-run records (§12), reconciled to their real on-disk status.

processing_runs property

Experiment-level processing-run records — the runs index (§15).

datasets property

Training datasets in the experiment (scans datasets/).

models property

Trained models in the experiment (scans models/).

analysis_runs property

Analysis runs in the experiment (scans analysis/).

export_runs property

Every export run in the experiment (scans exports/).

comparisons property

All saved comparisons in this experiment.

imported_models property

The machine-global imported models (shared across all experiments).

create(name, parent_dir=None) classmethod

Create the experiment directory structure and config.yaml.

parent_dir defaults to the managed workspace root (the default storage location, §2) — the GUI never picks a folder.

Source code in detail/api/experiment.py
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
@classmethod
def create(cls, name: str, parent_dir: Path | str | None = None) -> "Experiment":
    """Create the experiment directory structure and config.yaml.

    ``parent_dir`` defaults to the managed workspace root (the ``default``
    storage location, §2) — the GUI never picks a folder.
    """
    if parent_dir is None:
        parent_dir = locations.experiments_root()
    return cls(experiment_store.create_experiment(parent_dir, name))

open(experiment_dir) classmethod

Open an existing experiment (validates config.yaml).

Source code in detail/api/experiment.py
1594
1595
1596
1597
1598
@classmethod
def open(cls, experiment_dir: Path | str) -> "Experiment":
    """Open an existing experiment (validates config.yaml)."""
    experiment_store.read_config(experiment_dir)
    return cls(experiment_dir)

list_all() classmethod

All experiments in the managed workspace (storage default root, §2).

Source code in detail/api/experiment.py
1600
1601
1602
1603
@classmethod
def list_all(cls) -> list["Experiment"]:
    """All experiments in the managed workspace (storage ``default`` root, §2)."""
    return [cls(p) for p in locations.list_experiment_dirs()]

import_archive(archive, *, replace=False, name=None, progress=None) classmethod

Import an exported experiment bundle into the managed workspace (§15). Creates it, or replaces a same-id experiment when replace is True; name overrides the target id (import as a separate copy).

Parameters:

Name Type Description Default
progress Callable[[str, float, str], None] | None

(stage, fraction, detail) callback — reading → extracting → verifying → placing. A callback that raises stops the import with nothing placed.

None

A recording whose video is referenced in place is looked for where the exporting machine had it, and its video root registered here when a video there matches (#916); referenced_video_missing lists what was not found.

Raises:

Type Description
ValueError

Malformed/corrupt archive or unsupported schema_version.

FileExistsError

Target id exists and replace is False.

Source code in detail/api/experiment.py
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
@classmethod
def import_archive(
    cls,
    archive: Path | str,
    *,
    replace: bool = False,
    name: str | None = None,
    progress: Callable[[str, float, str], None] | None = None,
) -> "Experiment":
    """Import an exported experiment bundle into the managed workspace (§15).
    Creates it, or replaces a same-id experiment when ``replace`` is True; ``name``
    overrides the target id (import as a separate copy).

    Args:
        progress: ``(stage, fraction, detail)`` callback — ``reading`` →
            ``extracting`` → ``verifying`` → ``placing``. A callback that raises stops
            the import with nothing placed.

    A recording whose video is referenced in place is looked for where the exporting machine
    had it, and its video root registered here when a video there matches (#916);
    `referenced_video_missing` lists what was not found.

    Raises:
        ValueError: Malformed/corrupt archive or unsupported schema_version.
        FileExistsError: Target id exists and ``replace`` is False.
    """
    dest = export_store.import_experiment(
        archive,
        locations.experiments_root(),
        replace=replace,
        name=name,
        progress=progress,
    )
    return cls(dest)

replace_losses(archive, *, name=None) staticmethod

What importing archive with replace=True would delete and not bring back, or None when there is no experiment to replace.

The same answer an import without replace carries on its refusal (export_store.ExperimentExistsError.losses); replace_warning words it. Walks the existing experiment, so a surface calls it off the UI thread.

Raises:

Type Description
ValueError

archive is not a DETAIL export, or name is not a bare name.

Source code in detail/api/experiment.py
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
@staticmethod
def replace_losses(
    archive: Path | str, *, name: str | None = None
) -> "export_store.ReplaceLosses | None":
    """What importing ``archive`` with ``replace=True`` would delete and not bring back, or
    ``None`` when there is no experiment to replace.

    The same answer an import without ``replace`` carries on its refusal
    (`export_store.ExperimentExistsError.losses`); `replace_warning` words it. Walks the
    existing experiment, so a surface calls it off the UI thread.

    Raises:
        ValueError: ``archive`` is not a DETAIL export, or ``name`` is not a bare name.
    """
    manifest = export_store.read_manifest(archive)
    dest = export_store.import_target(locations.experiments_root(), manifest, name)
    if not dest.exists():
        return None
    return export_store.replace_losses(manifest, dest)

export(dest=None, *, include_video=False, include_datasets=False, gzip=False, progress=None)

Pack this experiment into a single portable archive (§15). Slim by default (outputs + metadata + models; no source video / datasets) — pass include_video / include_datasets for a full transfer. Returns the archive path (default <workspace>/<id>.segproj.tar).

progress is a (stage, fraction, detail) callback — scanning → checking → hashing → packing. The GUI does not call this directly: its Export runs the catalogue's bundle target as an export run (run_export), so the export is listed under Active processes and survives the window closing.

Source code in detail/api/experiment.py
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
def export(
    self,
    dest: Path | str | None = None,
    *,
    include_video: bool = False,
    include_datasets: bool = False,
    gzip: bool = False,
    progress: Callable[[str, float, str], None] | None = None,
) -> Path:
    """Pack this experiment into a single portable archive (§15). Slim by default
    (outputs + metadata + models; no source video / datasets) — pass
    ``include_video`` / ``include_datasets`` for a full transfer. Returns the
    archive path (default ``<workspace>/<id>.segproj.tar``).

    ``progress`` is a ``(stage, fraction, detail)`` callback — ``scanning`` →
    ``checking`` → ``hashing`` → ``packing``. The GUI does not call this directly: its
    Export runs the catalogue's ``bundle`` target as an export run (`run_export`), so the
    export is listed under Active processes and survives the window closing."""
    if dest is None:
        dest = self._dir.parent / f"{self._dir.name}.segproj.tar"
    return export_store.export_experiment(
        self._dir,
        dest,
        include_video=include_video,
        include_datasets=include_datasets,
        gzip=gzip,
        progress=progress,
    )

preview_image(width=PREVIEW_WIDTH)

A cached still identifying this experiment, or None if one can't be made.

The frame comes from the middle of the first recording whose video is on this machine: the opening frames are often a blank lead-in and the last ones an empty arena, so a midpoint is the one place likely to show the animal. It is written once to <experiment>/preview.jpg and regenerated only when older than modified_at, so listing a workspace costs a file read rather than a decode per experiment.

Never raises. None means there is nothing to show — no recordings, no video, a referenced video that isn't on this machine (§5 reference-in-place), or a cache that couldn't be written (read-only media) — and the caller renders a placeholder.

Source code in detail/api/experiment.py
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
def preview_image(self, width: int = PREVIEW_WIDTH) -> Path | None:
    """A cached still identifying this experiment, or ``None`` if one can't be made.

    The frame comes from the **middle** of the first recording whose video is on this
    machine: the opening frames are often a blank lead-in and the last ones an empty
    arena, so a midpoint is the one place likely to show the animal. It is written once
    to ``<experiment>/preview.jpg`` and regenerated only when older than
    ``modified_at``, so listing a workspace costs a file read rather than a decode per
    experiment.

    Never raises. ``None`` means there is nothing to show — no recordings, no video, a
    referenced video that isn't on this machine (§5 reference-in-place), or a cache that
    couldn't be written (read-only media) — and the caller renders a placeholder.
    """
    import cv2

    path = self._dir / PREVIEW_FILENAME
    with contextlib.suppress(OSError):
        if path.is_file() and path.stat().st_mtime >= self.modified_at:
            return path
    frame = self._middle_frame()
    if frame is None:
        return None
    height = max(int(frame.shape[0] * width / max(frame.shape[1], 1)), 1)
    thumb = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
    try:
        cv2.imwrite(str(path), rgb_to_bgr(thumb))  # get_frame returns RGB
    except (OSError, cv2.error):
        return None
    return path if path.is_file() else None

set_metadata(name=None, description=None)

Edit experiment identity (name / description) in config.yaml.

Only the given fields change; the experiment directory is not renamed.

Raises:

Type Description
ValueError

If name is given but empty.

Source code in detail/api/experiment.py
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
def set_metadata(
    self, name: str | None = None, description: str | None = None
) -> None:
    """Edit experiment identity (name / description) in config.yaml.

    Only the given fields change; the experiment directory is not renamed.

    Raises:
        ValueError: If ``name`` is given but empty.
    """
    experiment_store.set_metadata(self._dir, name=name, description=description)

notes(kind, entry_id='')

The user's notes on one entry, or "" when it has none.

kind is one of storage.notes.KINDS (experiment, recording, run, analysis_run, dataset, model, distill, export_run, comparison); experiment takes no entry_id.

Raises:

Type Description
ValueError

If kind is not an entry kind, or the id is missing or extra.

FileNotFoundError

If there is no such entry.

Source code in detail/api/experiment.py
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
def notes(self, kind: str, entry_id: str = "") -> str:
    """The user's notes on one entry, or ``""`` when it has none.

    ``kind`` is one of ``storage.notes.KINDS`` (``experiment``, ``recording``, ``run``,
    ``analysis_run``, ``dataset``, ``model``, ``distill``, ``export_run``,
    ``comparison``); ``experiment`` takes no ``entry_id``.

    Raises:
        ValueError: If ``kind`` is not an entry kind, or the id is missing or extra.
        FileNotFoundError: If there is no such entry.
    """
    return notes_store.read_notes(notes_store.entry_dir(self._dir, kind, entry_id))

set_notes(kind, entry_id, text)

Replace the user's notes on one entry; empty text clears them.

Safe while the entry's run is still going: the notes are a file of their own (notes.md), never a field in a record a worker is rewriting.

Raises:

Type Description
ValueError

If kind is not an entry kind, or the id is missing or extra.

FileNotFoundError

If there is no such entry.

Source code in detail/api/experiment.py
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
def set_notes(self, kind: str, entry_id: str, text: str) -> None:
    """Replace the user's notes on one entry; empty ``text`` clears them.

    Safe while the entry's run is still going: the notes are a file of their own
    (``notes.md``), never a field in a record a worker is rewriting.

    Raises:
        ValueError: If ``kind`` is not an entry kind, or the id is missing or extra.
        FileNotFoundError: If there is no such entry.
    """
    notes_store.write_notes(notes_store.entry_dir(self._dir, kind, entry_id), text)

create_recording(recording_id, metadata=None)

Create a recording at a chosen id (identity only — video/streams are optional, added later) and seed its metadata.csv row (§11).

The id is the caller's, which is what a script or a test wants. An application adding a recording a user is naming should call :meth:add_recording instead — it mints the id and leaves the name to the user.

Source code in detail/api/experiment.py
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
def create_recording(
    self, recording_id: str, metadata: dict[str, str] | None = None
) -> Recording:
    """Create a recording **at a chosen id** (identity only — video/streams are
    optional, added later) and seed its ``metadata.csv`` row (§11).

    The id is the caller's, which is what a script or a test wants. An *application*
    adding a recording a user is naming should call :meth:`add_recording` instead —
    it mints the id and leaves the name to the user.
    """
    recording_store.create_recording(
        self._dir, recording_id=recording_id, name=recording_id
    )
    metadata_store.upsert_row(self._dir, recording_id, metadata)
    return Recording(self._dir, recording_id)

add_recording(name, metadata=None)

Add a recording the user has named: the tool mints the id, the name is theirs.

name is normally the video's filename — a good starting label and a terrible identity, since the file gets moved, renamed, or joined by a second part. The id is opaque and permanent (recording_000); the name is editable and unique, and is what every surface displays.

A name already taken is suffixed (m27_day3 → m27_day3_2) rather than refused: the caller here is the tool, importing a folder where two files can legitimately share a name, and failing the import over a label would be absurd. A name a user types goes through :meth:Recording.set_name, which refuses.

Source code in detail/api/experiment.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
def add_recording(
    self, name: str, metadata: dict[str, str] | None = None
) -> Recording:
    """Add a recording the user has *named*: the tool mints the id, the name is theirs.

    ``name`` is normally the video's filename — a good starting label and a terrible
    identity, since the file gets moved, renamed, or joined by a second part. The id
    is opaque and permanent (``recording_000``); the name is editable and unique, and
    is what every surface displays.

    A name already taken is **suffixed** (``m27_day3`` → ``m27_day3_2``) rather than
    refused: the caller here is the tool, importing a folder where two files can
    legitimately share a name, and failing the import over a label would be absurd.
    A name a *user* types goes through :meth:`Recording.set_name`, which refuses.
    """
    recording_id = experiment_store.next_recording_id(self._dir)
    recording_store.create_recording(
        self._dir, recording_id=recording_id, name=self.unique_name(name)
    )
    metadata_store.upsert_row(self._dir, recording_id, metadata)
    return Recording(self._dir, recording_id)

missing_previews(recording_ids=None)

Preview builds missing on this machine across recording_ids (default: every recording), proxies before masks within each recording (§3 Video preview cache). One stat per part once this machine's cache knows the file.

Source code in detail/api/experiment.py
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
def missing_previews(self, recording_ids: list[str] | None = None) -> list:
    """Preview builds missing on this machine across ``recording_ids`` (default: every
    recording), proxies before masks within each recording (§3 *Video preview cache*).
    One stat per part once this machine's cache knows the file."""
    from detail.api import previews

    tasks = []
    for recording_id in recording_ids or self.recording_ids:
        recording = self.get_recording(recording_id)
        tasks.extend(previews.recording_tasks(recording.dir, recording_id))
    return tasks

build_previews(recording_ids=None, progress=None)

Build every missing preview for recording_ids (default: all) under one bar; returns a previews.PreviewBuildReport (built count, and each failure with why). The bar is weighed by video length across the whole batch, and its phase line names the recording, part and build in hand.

Source code in detail/api/experiment.py
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
def build_previews(
    self,
    recording_ids: list[str] | None = None,
    progress: Callable[[str, float, str], None] | None = None,
) -> "previews.PreviewBuildReport":
    """Build every missing preview for ``recording_ids`` (default: all) under one bar;
    returns a ``previews.PreviewBuildReport`` (built count, and each failure with why).
    The bar is weighed by video length across the whole batch, and its phase line names
    the recording, part and build in hand."""
    from detail.api import previews

    return previews.build_tasks(
        self.dir,
        self.missing_previews(recording_ids),
        self.recording_names(),
        progress,
    )

recording_names()

{recording_id: name} for every recording — the display map.

The name is the handle on every surface, so this is read per page build. It rides the mtime-cached recording_store.read_recording, the same read the recordings table already makes several of per row (no new I/O class — the UI-thread rule).

Source code in detail/api/experiment.py
1887
1888
1889
1890
1891
1892
1893
1894
def recording_names(self) -> dict[str, str]:
    """``{recording_id: name}`` for every recording — the display map.

    The name is the handle on every surface, so this is read per page build. It rides
    the mtime-cached ``recording_store.read_recording``, the same read the recordings
    table already makes several of per row (no new I/O class — the UI-thread rule).
    """
    return {r.id: r.name for r in self.recordings}

unique_name(name, *, exclude=None)

name, or the first free name_2 / name_3 … variant.

exclude skips one recording's own name, so renaming a recording to what it is already called is not a collision with itself.

Source code in detail/api/experiment.py
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
def unique_name(self, name: str, *, exclude: str | None = None) -> str:
    """``name``, or the first free ``name_2`` / ``name_3`` … variant.

    ``exclude`` skips one recording's own name, so renaming a recording to what it is
    already called is not a collision with itself.
    """
    taken = {n for rid, n in self.recording_names().items() if rid != exclude}
    if name not in taken:
        return name
    suffix = 2
    while f"{name}_{suffix}" in taken:
        suffix += 1
    return f"{name}_{suffix}"

video_not_packed()

Why a bundle with include_video would pack no video, or None when it would pack some (no_video_packed_reasons). Walks the experiment the way the export does, so a surface calls it off the UI thread.

Source code in detail/api/experiment.py
1913
1914
1915
1916
1917
1918
1919
def video_not_packed(self) -> str | None:
    """Why a bundle with ``include_video`` would pack no video, or ``None`` when it would
    pack some (`no_video_packed_reasons`). Walks the experiment the way the export does, so
    a surface calls it off the UI thread."""
    if export_store.packs_video(self._dir):
        return None
    return no_video_packed_reasons(self._dir)

referenced_video_missing()

Ids of recordings whose video is referenced in place and is not on this machine.

What is left after an import has looked where the exporting machine kept the video: locating one file of such a recording (Recording.relink_video_part) registers its folder, and every recording whose video is in that folder finds it too. A stat per part, so a surface calls this off the UI thread.

Source code in detail/api/experiment.py
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
def referenced_video_missing(self) -> list[str]:
    """Ids of recordings whose video is referenced in place and is not on this machine.

    What is left after an import has looked where the exporting machine kept the video:
    locating one file of such a recording (`Recording.relink_video_part`) registers its
    folder, and every recording whose video is in that folder finds it too. A stat per part,
    so a surface calls this off the UI thread.
    """
    return [
        recording_id
        for recording_id in export_store.referenced_video_recordings(self._dir)
        if not self.get_recording(recording_id).video_available
    ]

resolve_recording(ref)

A recording by id or name — what a user types is the name (§11).

An exact id wins, so a recording perversely named another's id can still be reached by its own id. Then a unique name. Anything else raises rather than guessing.

Raises:

Type Description
KeyError

no recording matches, or the name is ambiguous (only possible in an experiment whose names predate the uniqueness rule).

Source code in detail/api/experiment.py
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
def resolve_recording(self, ref: str) -> Recording:
    """A recording by id **or** name — what a user types is the name (§11).

    An exact id wins, so a recording perversely *named* another's id can still be
    reached by its own id. Then a unique name. Anything else raises rather than
    guessing.

    Raises:
        KeyError: no recording matches, or the name is ambiguous (only possible in an
            experiment whose names predate the uniqueness rule).
    """
    names = self.recording_names()
    if ref in names:
        return Recording(self._dir, ref)
    matches = [rid for rid, name in names.items() if name == ref]
    if len(matches) == 1:
        return Recording(self._dir, matches[0])
    if not matches:
        raise KeyError(
            f"no recording {ref!r} in this experiment — "
            f"known: {', '.join(sorted(names.values())) or '(none)'}"
        )
    raise KeyError(f"{ref!r} is the name of several recordings: {sorted(matches)}")

propagate_spatial(category_key, source, *, targets=None, names=None, progress=None)

Copy category_key from source onto targets (default: every other recording), never replacing what a target already has.

A target that already holds this category is skipped and reported, not overwritten — the operation has no undo and spans many recordings, so a correction is a deliberate delete on the recording that needs it. So is a target the category does not fit — a calibration onto a video of another shape, which is another rig. A target that refuses for any other reason is skipped too rather than aborting the batch, the same contract as apply_stream_preset.

Returns:

Type Description
PropagationResult

A PropagationResult — the recordings that took it, the ones that did not

PropagationResult

and why, and what the trip changed about the definitions themselves.

Raises:

Type Description
KeyError

source (or a ref in targets) matches no recording.

ValueError

unknown category_key, or source has nothing to copy — checked before any recording is touched (Tenet 10).

Source code in detail/api/experiment.py
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
def propagate_spatial(
    self,
    category_key: str,
    source: str,
    *,
    targets: list[str] | None = None,
    names: list[str] | None = None,
    progress: Callable[[str, float, str], None] | None = None,
) -> spatial_categories.PropagationResult:
    """Copy ``category_key`` from ``source`` onto ``targets`` (default: every other
    recording), never replacing what a target already has.

    A target that already holds this category is **skipped and reported**, not
    overwritten — the operation has no undo and spans many recordings, so a
    correction is a deliberate delete on the recording that needs it. So is a target
    the category does not fit — a calibration onto a video of another shape, which is
    another rig. A target that refuses for any other reason is skipped too rather than
    aborting the batch, the same contract as ``apply_stream_preset``.

    Returns:
        A ``PropagationResult`` — the recordings that took it, the ones that did not
        and why, and what the trip changed about the definitions themselves.

    Raises:
        KeyError: ``source`` (or a ref in ``targets``) matches no recording.
        ValueError: unknown ``category_key``, or ``source`` has nothing to copy —
            checked before any recording is touched (Tenet 10).
    """
    cat = spatial_categories.category(category_key)
    src = self.resolve_recording(source)
    if not cat.has_data(src):
        raise ValueError(
            f"recording {src.name!r} has no {cat.label.lower()} to copy"
        )
    dests = self._propagate_targets(src, targets)
    stage = f"copying {cat.label.lower()}"
    total = len(dests)
    copied: list[str] = []
    skipped: list[tuple[str, str]] = []
    flattened: list[str] = []
    refused: list[tuple[str, str, str]] = []
    for index, dest in enumerate(dests):
        detail = f"{dest.name} ({index + 1}/{total})"
        if progress is not None:
            progress(stage, index / total, detail)
        reason = cat.occupied(dest) or cat.unfit(src, dest)
        if reason is not None:
            skipped.append((dest.id, reason))
        else:
            try:
                added, dest_flattened, dest_refused = cat.give(src, dest, names)
            except (ValueError, FileNotFoundError, KeyError, OSError) as exc:
                skipped.append((dest.id, str(exc)))
            else:
                # Accumulated per target and tagged with it. Assigning them here kept
                # only the last target's notes, so a refusal on any other recording was
                # reported as "see the notes below" with no notes (#35 finding 12).
                flattened += [n for n in dest_flattened if n not in flattened]
                refused += [(dest.id, name, why) for name, why in dest_refused]
                # Only a target that actually received something counts as copied. A
                # set-shaped kind can have every one of its names refused, which is
                # not a failure and not a copy.
                (copied if added else skipped).append(
                    dest.id
                    if added
                    else (
                        dest.id,
                        "nothing new to add — everything offered was refused",
                    )
                )
        if progress is not None:
            progress(stage, (index + 1) / total, detail)
    return spatial_categories.PropagationResult(
        copied=copied, skipped=skipped, flattened=flattened, refused=refused
    )

propagate_field_of_view(source, **kwargs)

Copy source's field of view onto recordings that have none (Section 10). See propagate_spatial.

Source code in detail/api/experiment.py
2051
2052
2053
2054
2055
2056
def propagate_field_of_view(
    self, source: str, **kwargs
) -> spatial_categories.PropagationResult:
    """Copy ``source``'s field of view onto recordings that have none (Section 10).
    See ``propagate_spatial``."""
    return self.propagate_spatial("fov", source, **kwargs)

propagate_calibration(source, **kwargs)

Copy source's distance calibration onto recordings that have none (Section 10). See propagate_spatial.

Source code in detail/api/experiment.py
2058
2059
2060
2061
2062
2063
def propagate_calibration(
    self, source: str, **kwargs
) -> spatial_categories.PropagationResult:
    """Copy ``source``'s distance calibration onto recordings that have none
    (Section 10). See ``propagate_spatial``."""
    return self.propagate_spatial("calibration", source, **kwargs)

propagate_rois(source, **kwargs)

Copy source's regions of interest onto recordings that have none (Section 10). See propagate_spatial.

Source code in detail/api/experiment.py
2065
2066
2067
2068
2069
2070
def propagate_rois(
    self, source: str, **kwargs
) -> spatial_categories.PropagationResult:
    """Copy ``source``'s regions of interest onto recordings that have none
    (Section 10). See ``propagate_spatial``."""
    return self.propagate_spatial("roi", source, **kwargs)

propagate_points(source, **kwargs)

Copy source's points of interest onto recordings that have none (Section 10). See propagate_spatial.

Source code in detail/api/experiment.py
2072
2073
2074
2075
2076
2077
def propagate_points(
    self, source: str, **kwargs
) -> spatial_categories.PropagationResult:
    """Copy ``source``'s points of interest onto recordings that have none
    (Section 10). See ``propagate_spatial``."""
    return self.propagate_spatial("point", source, **kwargs)

import_behavior_labels(manifest_path, *, name='behavior', importer='behavior_csv', progress=None)

Batch-import behavior ground-truth labels onto existing recordings (Section 3).

Loads + validates the labels manifest (all problems reported upfront, Tenet 10), then adds each recording's file as a behavior-role stream named name (default "behavior"), each resolved against its own timestamp map. Every file in one batch uses the same importer (behavior_csv or boris). progress(index, total, recording_id, fraction, status) reports per recording. Returns the skipped recordings as [(recording_id, error), ...].

Raises:

Type Description
FileNotFoundError

If the manifest file is absent.

ValueError

If the manifest is malformed or references an unknown recording or missing file (nothing is imported).

Source code in detail/api/experiment.py
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
def import_behavior_labels(
    self,
    manifest_path: Path | str,
    *,
    name: str = "behavior",
    importer: str = "behavior_csv",
    progress: Callable[[int, int, str, float, str], None] | None = None,
) -> list[tuple[str, str]]:
    """Batch-import behavior ground-truth labels onto existing recordings (Section 3).

    Loads + validates the labels manifest (all problems reported upfront,
    Tenet 10), then adds each recording's file as a ``behavior``-role stream named
    ``name`` (default ``"behavior"``), each resolved against its own timestamp
    map. Every file in one batch uses the same ``importer`` (``behavior_csv`` or
    ``boris``). ``progress(index, total, recording_id, fraction, status)`` reports
    per recording. Returns the skipped recordings as ``[(recording_id, error), ...]``.

    Raises:
        FileNotFoundError: If the manifest file is absent.
        ValueError: If the manifest is malformed or references an unknown recording
            or missing file (nothing is imported).
    """
    from detail.api import imports as imports_mod
    from detail.storage import labels_manifest as labels_store

    manifest = labels_store.load_labels_manifest(manifest_path)
    mapping = labels_store.resolve_labels_manifest(
        manifest_path, manifest, experiment_store.discover_recordings(self._dir)
    )
    return imports_mod.import_label_batch(
        self, mapping, name=name, importer=importer, on_progress=progress
    )

heading_definitions()

Saved heading definitions, oldest first: {name, front, back} ([] if none).

Source code in detail/api/experiment.py
2113
2114
2115
def heading_definitions(self) -> list[dict]:
    """Saved heading definitions, oldest first: ``{name, front, back}`` (``[]`` if none)."""
    return heading_store.list_definitions(self._dir)

get_heading_definition(name)

Raises: ValueError if no definition named name exists.

Source code in detail/api/experiment.py
2117
2118
2119
def get_heading_definition(self, name: str) -> dict:
    """Raises: ValueError if no definition named ``name`` exists."""
    return heading_store.get_definition(self._dir, name)

save_heading_definition(name, front, back, *, overwrite=False)

Save a heading definition: the points whose mean is the front and the points whose mean is the back. Checked against a skeleton when a run uses it, not here.

Raises:

Type Description
ValueError

An invalid name or definition, or the name exists and overwrite is False.

Source code in detail/api/experiment.py
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
def save_heading_definition(
    self, name: str, front: list[str], back: list[str], *, overwrite: bool = False
) -> dict:
    """Save a heading definition: the points whose mean is the front and the points whose
    mean is the back. Checked against a skeleton when a run uses it, not here.

    Raises:
        ValueError: An invalid name or definition, or the name exists and ``overwrite``
            is False.
    """
    return heading_store.save_definition(
        self._dir, name, front, back, overwrite=overwrite
    )

delete_heading_definition(name)

Raises: ValueError if no definition named name exists.

Source code in detail/api/experiment.py
2135
2136
2137
def delete_heading_definition(self, name: str) -> None:
    """Raises: ValueError if no definition named ``name`` exists."""
    heading_store.delete_definition(self._dir, name)

export_heading_definition(name, out_path)

Write a saved definition to a standalone, shareable YAML file.

Raises:

Type Description
ValueError

No definition named name exists.

Source code in detail/api/experiment.py
2139
2140
2141
2142
2143
2144
2145
def export_heading_definition(self, name: str, out_path: Path | str) -> None:
    """Write a saved definition to a standalone, shareable YAML file.

    Raises:
        ValueError: No definition named ``name`` exists.
    """
    heading_store.export_definition(self._dir, name, out_path)

import_heading_definition(in_path, *, name=None, overwrite=False)

Import a definition from a standalone file; returns the name it was saved under.

Raises:

Type Description
FileNotFoundError

in_path does not exist.

ValueError

A malformed file, the wrong schema version, or (without overwrite) the name already exists.

Source code in detail/api/experiment.py
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
def import_heading_definition(
    self, in_path: Path | str, *, name: str | None = None, overwrite: bool = False
) -> str:
    """Import a definition from a standalone file; returns the name it was saved under.

    Raises:
        FileNotFoundError: ``in_path`` does not exist.
        ValueError: A malformed file, the wrong schema version, or (without
            ``overwrite``) the name already exists.
    """
    return heading_store.import_definition(
        self._dir, in_path, name=name, overwrite=overwrite
    )

list_stream_presets()

Saved importer setups for this experiment, oldest first ([] if none).

Source code in detail/api/experiment.py
2162
2163
2164
def list_stream_presets(self) -> list[dict]:
    """Saved importer setups for this experiment, oldest first (``[]`` if none)."""
    return stream_presets.list_presets(self._dir)

get_stream_preset(name)

Raises: ValueError if no preset named name exists.

Source code in detail/api/experiment.py
2166
2167
2168
def get_stream_preset(self, name: str) -> dict:
    """Raises: ValueError if no preset named ``name`` exists."""
    return stream_presets.get_preset(self._dir, name)

save_stream_preset(name, importer, config, *, offset_ns=None, overwrite=False)

Save an importer + its config for reuse on this experiment's other recordings.

Raises:

Type Description
ValueError

An invalid name, or the name exists and overwrite is False.

Source code in detail/api/experiment.py
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
def save_stream_preset(
    self,
    name: str,
    importer: str,
    config: dict | None,
    *,
    offset_ns: int | None = None,
    overwrite: bool = False,
) -> None:
    """Save an importer + its config for reuse on this experiment's other recordings.

    Raises:
        ValueError: An invalid name, or the name exists and ``overwrite`` is False.
    """
    stream_presets.save_preset(
        self._dir, name, importer, config, offset_ns=offset_ns, overwrite=overwrite
    )

check_new_stream_preset_name(name)

Refuse a name :meth:save_stream_preset would refuse without overwrite, so a caller that saves after other work can refuse before doing it.

Raises:

Type Description
ValueError

An invalid name, or a preset by that name exists.

Source code in detail/api/experiment.py
2188
2189
2190
2191
2192
2193
2194
2195
def check_new_stream_preset_name(self, name: str) -> None:
    """Refuse a name :meth:`save_stream_preset` would refuse without ``overwrite``, so a
    caller that saves after other work can refuse before doing it.

    Raises:
        ValueError: An invalid name, or a preset by that name exists.
    """
    stream_presets.check_new_name(self._dir, name)

delete_stream_preset(name)

Raises: ValueError if no preset named name exists.

Source code in detail/api/experiment.py
2197
2198
2199
def delete_stream_preset(self, name: str) -> None:
    """Raises: ValueError if no preset named ``name`` exists."""
    stream_presets.delete_preset(self._dir, name)

export_stream_preset(name, out_path)

Write a saved preset to a standalone, shareable YAML file.

Raises:

Type Description
ValueError

No preset named name exists.

Source code in detail/api/experiment.py
2201
2202
2203
2204
2205
2206
2207
def export_stream_preset(self, name: str, out_path: Path | str) -> None:
    """Write a saved preset to a standalone, shareable YAML file.

    Raises:
        ValueError: No preset named ``name`` exists.
    """
    stream_presets.export_preset(self._dir, name, out_path)

import_stream_preset(in_path, *, name=None, overwrite=False)

Import a preset from a standalone file; returns the name it was saved under.

Raises:

Type Description
FileNotFoundError

in_path does not exist.

ValueError

A malformed file, the wrong schema version, or (without overwrite) the name already exists.

Source code in detail/api/experiment.py
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
def import_stream_preset(
    self,
    in_path: Path | str,
    *,
    name: str | None = None,
    overwrite: bool = False,
) -> str:
    """Import a preset from a standalone file; returns the name it was saved under.

    Raises:
        FileNotFoundError: ``in_path`` does not exist.
        ValueError: A malformed file, the wrong schema version, or (without
            ``overwrite``) the name already exists.
    """
    return stream_presets.import_preset(
        self._dir, in_path, name=name, overwrite=overwrite
    )

apply_stream_preset(preset, sources, *, name, by_video=False, progress=None)

Import one stream per recording from a saved preset (Section 3).

The batch shape for a mapping worked out once. sources is [(recording_ref, file, offset_ns | None), ...] — one row per recording, with its own file and its own offset, because those are exactly what a preset cannot carry: each video and logger pair has its own skew, so one number applied to sixty recordings is one recording's answer given to all of them.

A recording that fails is recorded and skipped, so one unreadable file never sinks the batch — the same contract as import_behavior_labels.

Parameters:

Name Type Description Default
name str

The stream name to give each import (the same on every recording).

required
by_video bool

Each recording_ref is a video file name, matched by the same rule as a metadata import's file key (base name, any case, extension optional) — the key a table made alongside the recordings carries (#330). False: an id or a name.

False
progress Callable[[int, int, str, float, str], None] | None

progress(index, total, recording_id, fraction, status).

None

Returns:

Type Description
list[tuple[str, str]]

The skipped recordings as [(recording_ref, error), ...].

Raises:

Type Description
ValueError

If preset names nothing saved (nothing is imported).

Source code in detail/api/experiment.py
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
def apply_stream_preset(
    self,
    preset: str,
    sources: list[tuple[str, Path | str, int | None]],
    *,
    name: str,
    by_video: bool = False,
    progress: Callable[[int, int, str, float, str], None] | None = None,
) -> list[tuple[str, str]]:
    """Import one stream per recording from a saved preset (Section 3).

    The batch shape for a mapping worked out once. ``sources`` is
    ``[(recording_ref, file, offset_ns | None), ...]`` — **one row per recording, with
    its own file and its own offset**, because those are exactly what a preset cannot
    carry: each video and logger pair has its own skew, so one number applied to sixty
    recordings is one recording's answer given to all of them.

    A recording that fails is recorded and skipped, so one unreadable file never sinks
    the batch — the same contract as ``import_behavior_labels``.

    Args:
        name: The stream name to give each import (the same on every recording).
        by_video: Each ``recording_ref`` is a **video file name**, matched by the same
            rule as a metadata import's file key (base name, any case, extension
            optional) — the key a table made alongside the recordings carries (#330).
            ``False``: an id or a name.
        progress: ``progress(index, total, recording_id, fraction, status)``.

    Returns:
        The skipped recordings as ``[(recording_ref, error), ...]``.

    Raises:
        ValueError: If ``preset`` names nothing saved (nothing is imported).
    """
    self.get_stream_preset(preset)  # fail before touching any recording (Tenet 10)
    total = len(sources)
    skipped: list[tuple[str, str]] = []
    if by_video:
        names = self.recording_names()
        matches = self._video_file_matches(ref for ref, _, _ in sources)
    for index, (ref, path, offset_ns) in enumerate(sources):
        if progress is not None:
            progress(index, total, ref, 0.0, "importing")
        error = (
            _match_error("video file", ref, matches[ref], names)
            if by_video
            else None
        )
        if error is None:
            try:
                recording = (
                    self.get_recording(matches[ref][0])
                    if by_video
                    else self.resolve_recording(ref)
                )
                recording.add_stream_from_preset(
                    name, path, preset, offset_ns=offset_ns
                )
            except (ValueError, FileNotFoundError, KeyError, OSError) as exc:
                error = str(exc)
        if error is not None:
            skipped.append((ref, error))
        if progress is not None:
            progress(index, total, ref, 1.0, "done" if error is None else "skipped")
    return skipped

set_recording_metadata(recording_id, values)

Set/merge a recording's grouping variables; new columns are added (§11).

Source code in detail/api/experiment.py
2304
2305
2306
def set_recording_metadata(self, recording_id: str, values: dict[str, str]) -> None:
    """Set/merge a recording's grouping variables; new columns are added (§11)."""
    metadata_store.upsert_row(self._dir, recording_id, values)

add_metadata_column(name)

Add an empty grouping-variable column to the cohort table (§11).

Source code in detail/api/experiment.py
2308
2309
2310
def add_metadata_column(self, name: str) -> None:
    """Add an empty grouping-variable column to the cohort table (§11)."""
    metadata_store.add_column(self._dir, name)

delete_metadata_column(name)

Remove a grouping-variable column and its values from every recording (§11). Idempotent; recording_id cannot be deleted.

Source code in detail/api/experiment.py
2312
2313
2314
2315
def delete_metadata_column(self, name: str) -> None:
    """Remove a grouping-variable column and its values from every recording (§11).
    Idempotent; ``recording_id`` cannot be deleted."""
    metadata_store.delete_column(self._dir, name)

set_metadata_table(columns, rows)

Replace the whole cohort table (§11): columns in order, rows keyed by recording id. Commits a fully edited table — added/deleted columns and cell edits together — in one write; the bulk counterpart to :meth:set_recording_metadata.

Source code in detail/api/experiment.py
2317
2318
2319
2320
2321
2322
2323
2324
def set_metadata_table(
    self, columns: list[str], rows: dict[str, dict[str, str]]
) -> None:
    """Replace the whole cohort table (§11): ``columns`` in order, ``rows`` keyed by
    recording id. Commits a fully edited table — added/deleted columns and cell edits
    together — in one write; the bulk counterpart to :meth:`set_recording_metadata`.
    """
    metadata_store.write_metadata(self._dir, columns, rows)

metadata_csv_key(path)

(key_column, header) for a metadata CSV: the column an import would key on by default — None when none is recognised — and every column it has, so a surface can ask which one holds the video file name (#330).

Raises:

Type Description
FileNotFoundError

If the file is absent.

ValueError

An empty file, or an empty or duplicate column header.

Source code in detail/api/experiment.py
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
def metadata_csv_key(self, path: Path | str) -> tuple[str | None, list[str]]:
    """``(key_column, header)`` for a metadata CSV: the column an import would key on
    by default — ``None`` when none is recognised — and every column it has, so a
    surface can ask which one holds the video file name (#330).

    Raises:
        FileNotFoundError: If the file is absent.
        ValueError: An empty file, or an empty or duplicate column header.
    """
    header = metadata_store.read_import_header(path)
    return metadata_store.detect_key_column(header), header

import_metadata_csv(path, *, dry_run=False, key_column=None)

Bulk-apply recording grouping variables from a CSV (§11): merge-only, blank cells skipped, a row matching no recording rejected. Validates the whole file first — on any error nothing is applied (Tenet 10).

Each row is matched to a recording by its key column: recording_id, the recording's name, or its video file name — the key a sheet prepared before import actually carries, since the id is minted at import and the name is right only once every recording has been renamed (#330). A video file name is the base name, any case, extension optional, and matches any of the recording's video parts.

Parameters:

Name Type Description Default
key_column str | None

The column to key on. None detects it — recording_id, then name, then a video file name column (metadata_store.VIDEO_KEY_HEADERS). A column named here that is not the id or the name is matched as a video file name.

None

A name or file key is resolved to its id here and never sets anything: renaming is Recording.set_name, which enforces uniqueness.

Returns (errors, warnings, recordings_updated).

Source code in detail/api/experiment.py
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
def import_metadata_csv(
    self,
    path: Path | str,
    *,
    dry_run: bool = False,
    key_column: str | None = None,
) -> tuple[list[str], list[str], int]:
    """Bulk-apply recording grouping variables from a CSV (§11): merge-only,
    blank cells skipped, a row matching no recording rejected. Validates the whole
    file first — on **any** error nothing is applied (Tenet 10).

    Each row is matched to a recording by its **key column**: ``recording_id``, the
    recording's ``name``, or its **video file name** — the key a sheet prepared before
    import actually carries, since the id is minted at import and the name is right
    only once every recording has been renamed (#330). A video file name is the base
    name, any case, extension optional, and matches any of the recording's video parts.

    Args:
        key_column: The column to key on. ``None`` detects it — ``recording_id``, then
            ``name``, then a video file name column
            (``metadata_store.VIDEO_KEY_HEADERS``). A column named here that is not
            the id or the name is matched as a video file name.

    A name or file key is resolved to its id here and never *sets* anything: renaming
    is ``Recording.set_name``, which enforces uniqueness.

    Returns ``(errors, warnings, recordings_updated)``.
    """
    try:
        kind, columns, rows = metadata_store.load_import_csv(path, key_column)
    except (FileNotFoundError, ValueError) as exc:
        return [str(exc)], [], 0
    if kind != metadata_store.RECORDING_KEY:
        rows, errors = self._rekey_import_rows(kind, rows)
        if errors:
            return errors, [], 0
    errors, warnings = metadata_store.validate_import(
        columns, rows, [s.id for s in self.recordings]
    )
    if errors or dry_run:
        return errors, warnings, 0
    applied = metadata_store.apply_import(self._dir, columns, rows)
    return errors, warnings, applied

export_metadata_csv(path)

Write the current grouping variables to path as a fill-in CSV template (§11) — recording_id, name, file, then every column, one row per recording.

name and file (the first video part's file name, as the table shows it) ride along so the sheet is legible — an id alone tells a person filling it in nothing — and so the filled sheet can be keyed back on any of the three. Neither is a stored value: editing one here renames nothing.

Source code in detail/api/experiment.py
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
def export_metadata_csv(self, path: Path | str) -> None:
    """Write the current grouping variables to ``path`` as a fill-in CSV template
    (§11) — ``recording_id``, ``name``, ``file``, then every column, one row per
    recording.

    ``name`` and ``file`` (the first video part's file name, as the table shows it)
    ride along so the sheet is legible — an id alone tells a person filling it in
    nothing — and so the filled sheet can be keyed back on any of the three. Neither
    is a stored value: editing one here renames nothing.
    """
    with read_cache.pinned():
        files = {
            recording.id: next(
                (_base_name(s) for s in recording.video_sources if s), ""
            )
            for recording in self.recordings
        }
    metadata_store.export_metadata(
        self._dir, path, names=self.recording_names(), files=files
    )

cancel_import(recording_id)

Mark a recording's unfinished import cancelled. A no-op once it is terminal.

This records a decision; it does not reach into a worker. An import runs on a thread owned by whichever app has this experiment open (gui/import_queue.py), so there is no cross-process handle to pull — and on the path that matters, quitting, the worker dies with the process regardless. What the caller gets is the difference between a record that says cancelled and one left at queued for the next open to call failed: the same outcome, one of them blaming the user for it.

Raises:

Type Description
FileNotFoundError

If the recording doesn't exist.

Source code in detail/api/experiment.py
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
def cancel_import(self, recording_id: str) -> None:
    """Mark a recording's unfinished import cancelled. A no-op once it is terminal.

    This records a decision; it does not reach into a worker. An import runs on a thread
    owned by whichever app has this experiment open (`gui/import_queue.py`), so there is no
    cross-process handle to pull — and on the path that matters, quitting, the worker dies
    with the process regardless. What the caller gets is the difference between a record
    that says ``cancelled`` and one left at ``queued`` for the next open to call ``failed``:
    the same outcome, one of them blaming the user for it.

    Raises:
        FileNotFoundError: If the recording doesn't exist.
    """
    recording = self.get_recording(recording_id)
    if recording.import_status not in ("queued", "importing"):
        return
    recording_store.set_import_status(recording.dir, "cancelled")

reconcile_imports()

Flip orphaned import statuses (queued / importing left by a crash or close, with no active queue) to failed so they're visible + deletable, not stuck. Called on experiment open before the import queue starts (the in-memory queue can't resume — §3).

Source code in detail/api/experiment.py
2546
2547
2548
2549
2550
2551
2552
2553
def reconcile_imports(self) -> None:
    """Flip orphaned import statuses (``queued`` / ``importing`` left by a
    crash or close, with no active queue) to ``failed`` so they're visible +
    deletable, not stuck. Called on experiment open before the import queue starts
    (the in-memory queue can't resume — §3)."""
    for recording in self.recordings:
        if recording.import_status in ("queued", "importing"):
            recording_store.set_import_status(recording.dir, "failed")

reconcile_runs()

Fold each still-active processing run's real on-disk status back into its record on experiment open (§15). A run's coordinator + workers are detached and may outlive the app, but a crashed/SIGKILLed run can read running forever. Evidence-based (see :meth:_reconcile_run). Mirrors :meth:reconcile_imports.

Source code in detail/api/experiment.py
2555
2556
2557
2558
2559
2560
2561
2562
2563
def reconcile_runs(self) -> None:
    """Fold each still-active processing run's real on-disk status back into its
    record on experiment open (§15). A run's coordinator + workers are detached and
    may outlive the app, but a crashed/SIGKILLed run can read ``running`` forever.
    Evidence-based (see :meth:`_reconcile_run`). Mirrors :meth:`reconcile_imports`.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    for record in runs_store.list_runs(self._dir):
        self._reconcile_run(record)

reconcile_recording_runs()

Adopt each per-recording run's real status into its recording.yaml (§15).

_RecordedRun.wait() is what copies a job's terminal status into the recording, and a one-recording run has no coordinator to call it: a Ctrl-C, a closed terminal, or a script that never waits left the entry pending forever, the recording refused a second run, and tracking refused it as "not complete" (issue #28, finding 5). This is the backstop, run wherever an experiment is opened — the GUI and every CLI command.

Driven from PROCESSING_MODULES (every per-recording module's runs_key), so a new module is covered the day it registers. Cost: one recording.yaml read per recording, and one job.json read only per entry still marked active — never per run. An entry whose job is still active is left alone while its worker lives; one with no run dir yet is a launch in progress and is left alone too. Returns how many entries changed.

Source code in detail/api/experiment.py
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
def reconcile_recording_runs(self) -> int:
    """Adopt each per-recording run's real status into its ``recording.yaml`` (§15).

    ``_RecordedRun.wait()`` is what copies a job's terminal status into the recording, and
    a one-recording run has no coordinator to call it: a Ctrl-C, a closed terminal, or a
    script that never waits left the entry ``pending`` forever, the recording refused a
    second run, and tracking refused it as "not complete" (issue #28, finding 5). This is
    the backstop, run wherever an experiment is opened — the GUI and every CLI command.

    Driven from ``PROCESSING_MODULES`` (every per-recording module's ``runs_key``), so a
    new module is covered the day it registers. Cost: one ``recording.yaml`` read per
    recording, and one ``job.json`` read only per entry still marked active — never per
    run. An entry whose job is still active is left alone while its worker lives; one with
    no run dir yet is a launch in progress and is left alone too. Returns how many entries
    changed.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    return sum(
        self._reconcile_one_recording(recording_id)
        for recording_id in experiment_store.discover_recordings(self._dir)
    )

delete_recording(recording_id)

Delete a recording and everything it owns — its imported video, runs (detection / tracking / embedding / downsampling), arenas, and masks.

A processing run merely indexes per-recording runs (its outputs live in the recordings, Tenet 5), so the recording is pruned from every processing run's per_recording map and an emptied run record is removed — not blocked. Nothing outside a recording is computed from a whole recording today; a future cross-recording analysis would register as a dependent.

Refused while a run is using the recording (issue #28, finding 6): a processing run that lists it, a run of its own still going, or an analysis, distill, dataset or export run reading it. Deleting under a live worker orphaned it — the worker re-created the folder within seconds — and wiped the run record the coordinator was still writing, so the other recordings never ran. Every family is reconciled first, so a run that is only recorded as running (its process long gone) does not block the delete.

The recording leaves both of a run record's fields, per_recording and recording_ids (finding 10): a deleted id left in the plan made process retry fail reading its recording.yaml and process list count it.

Raises:

Type Description
FileNotFoundError

If no such recording exists.

ValueError

If a run is still using the recording — it names each one.

Source code in detail/api/experiment.py
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
def delete_recording(self, recording_id: str) -> None:
    """Delete a recording and everything it owns — its imported video, runs
    (detection / tracking / embedding / downsampling), arenas, and masks.

    A processing run merely *indexes* per-recording runs (its outputs live in
    the recordings, Tenet 5), so the recording is pruned from every processing
    run's ``per_recording`` map and an emptied run record is removed — not
    blocked. Nothing outside a recording is computed from a whole recording
    today; a future cross-recording analysis would register as a dependent.

    **Refused while a run is using the recording** (issue #28, finding 6): a processing
    run that lists it, a run of its own still going, or an analysis, distill, dataset or
    export run reading it. Deleting under a live worker orphaned it — the worker re-created
    the folder within seconds — and wiped the run record the coordinator was still writing,
    so the other recordings never ran. Every family is reconciled first, so a run that is
    only *recorded* as running (its process long gone) does not block the delete.

    The recording leaves both of a run record's fields, ``per_recording`` **and**
    ``recording_ids`` (finding 10): a deleted id left in the plan made ``process retry``
    fail reading its ``recording.yaml`` and ``process list`` count it.

    Raises:
        FileNotFoundError: If no such recording exists.
        ValueError: If a run is still using the recording — it names each one.
    """
    sdir = experiment_store.recording_path(self._dir, recording_id)
    if not sdir.is_dir():
        raise FileNotFoundError(f"recording {recording_id!r} not found")
    blockers = self._active_runs_reading(recording_id)
    if blockers:
        raise ValueError(
            f"cannot delete recording {recording_id!r} while a run is using it — "
            "cancel it or let it finish first:\n" + "\n".join(blockers)
        )
    shutil.rmtree(sdir)
    metadata_store.remove_row(
        self._dir, recording_id
    )  # prune its grouping vars (§11)
    for record in runs_store.list_runs(self._dir):
        per = record.get("per_recording", {})
        planned = list(record.get("recording_ids") or [])
        if recording_id not in per and recording_id not in planned:
            continue
        per.pop(recording_id, None)
        record["recording_ids"] = [sid for sid in planned if sid != recording_id]
        if per or record["recording_ids"]:
            record["per_recording"] = per
            runs_store.write_run(self._dir, record["id"], record)
        else:
            runs_store.delete_run(self._dir, record["id"])

delete()

Delete the whole experiment directory — every recording, run, model, and dataset it owns. Nothing outside an experiment depends on it, so this is never blocked (the cohesive delete strategy, gui_design §1.1). The Experiment instance is dead afterwards.

Raises:

Type Description
FileNotFoundError

If the experiment directory no longer exists.

Source code in detail/api/experiment.py
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
def delete(self) -> None:
    """Delete the whole experiment directory — every recording, run, model, and
    dataset it owns. Nothing outside an experiment depends on it, so this is
    never blocked (the cohesive delete strategy, gui_design §1.1). The
    ``Experiment`` instance is dead afterwards.

    Raises:
        FileNotFoundError: If the experiment directory no longer exists.
    """
    if not self._dir.is_dir():
        raise FileNotFoundError(f"experiment not found: {self._dir}")
    shutil.rmtree(self._dir)

run_processing(module_id, recording_ids, config, progress=None)

Run a processing module over a selection of recordings.

Validates every selected recording up front (Tenet 10), reserves the run record, then spawns a detached coordinator (executor/coordinator.py) that sequences the per-recording Recording.run calls and publishes aggregate progress. Returns an :class:AttachedRun polling that progress — so the run survives the app closing and any process can reattach (§15). Per-recording outputs land in each recording (Tenet 5).

progress takes the standard (stage, fraction, detail) callback and names each recording as the up-front checks reach it: over a large selection they read every recording's outputs, which is minutes, not a moment.

Raises:

Type Description
ValueError

For an unknown module_id, an empty selection, or any recording that fails the module's pre-run validation.

Source code in detail/api/experiment.py
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
def run_processing(
    self,
    module_id: str,
    recording_ids: list[str],
    config: dict,
    progress: Callable[[str, float, str], None] | None = None,
) -> "AttachedRun":
    """Run a processing module over a selection of recordings.

    Validates every selected recording up front (Tenet 10), reserves the run
    record, then spawns a **detached coordinator** (``executor/coordinator.py``)
    that sequences the per-recording ``Recording.run`` calls and publishes aggregate
    progress. Returns an :class:`AttachedRun` polling that progress — so the run
    survives the app closing and any process can reattach (§15). Per-recording
    outputs land in each recording (Tenet 5).

    ``progress`` takes the standard ``(stage, fraction, detail)`` callback and names
    each recording as the up-front checks reach it: over a large selection they read
    every recording's outputs, which is minutes, not a moment.

    Raises:
        ValueError: For an unknown ``module_id``, an empty selection, or any
            recording that fails the module's pre-run validation.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    module = PROCESSING_MODULES.get(module_id)
    if module is None:
        raise ValueError(
            f"unknown module_id {module_id!r}; "
            f"available: {sorted(PROCESSING_MODULES)}"
        )
    # The same recording named twice (a name and its id, say) would run twice: the second
    # run's id replaces the first in `per_recording`, leaving an output no run indexes and
    # a batch marked failed though both runs completed (issue #28, finding 7). Here, not in
    # a surface, so the CLI, the GUI and a script all get it. Order is kept.
    recording_ids = list(dict.fromkeys(recording_ids))
    if not recording_ids:
        raise ValueError("recording_ids must be non-empty")
    if module.batch:
        # A batch module validates the whole subset once and its cross-recording step
        # needs the normalized config in the record (there is no per-recording
        # re-validation by the coordinator).
        config = module.validate_batch(self._dir, recording_ids, dict(config))
    else:
        # Values that must agree across the selection (embedding's shared canvas)
        # are resolved once, here, and enrich the stored config — a per-recording
        # validate cannot see the other recordings (§6.5).
        shared = _RecordingSteps(
            self._dir, progress, "Resolving shared settings", len(recording_ids)
        )
        config = module.resolve_shared_config(
            self._dir, recording_ids, dict(config), on_recording=shared
        )
        shared.finish()
        checks = _RecordingSteps(
            self._dir, progress, "Validating", len(recording_ids)
        )
        for sid in recording_ids:
            checks(sid)
            sdir = experiment_store.recording_path(self._dir, sid)
            sdata = recording_store.read_recording(sdir)
            # Resolve the batch spec per recording before fail-fast validation (§6.5);
            # the stored run-record config keeps the spec so the coordinator re-resolves.
            module.validate(
                sdir, sdata, module.resolve_upstream_spec(sdir, sdata, dict(config))
            )
        checks.finish()
    config = _with_model_defaults(module, config)
    # Allocate and reserve under one lock: `next_run_id` is max+1 over a directory scan,
    # so two launches racing between the scan and the write both take the same id and the
    # loser's atomic replace fails on a tmp file the winner already consumed.
    # Reserve before spawning so the run is discoverable + a coordinator that starts and
    # then dies reconciles to failed (not stuck running).
    with runs_store.runs_lock(self._dir):
        run_id = runs_store.next_run_id(self._dir)
        runs_store.write_run(
            self._dir,
            run_id,
            {
                "id": run_id,
                "module_id": module_id,
                "recording_ids": recording_ids,
                "config": _jsonable(config),
                "per_recording": {},
                "status": "running",
                "created_at": utc_timestamp(),
            },
        )
    try:
        pid = spawn_coordinator(
            runs_store.run_dir(self._dir, run_id), tuple(_PIPELINE_RUNNERS)
        )
    except (
        Exception
    ) as exc:  # noqa: BLE001 — re-raised; must not leave a stuck record
        # The coordinator never launched (e.g. Popen OSError). Without a recorded
        # pid, reconcile can't tell this from a just-launched run, so mark the
        # reserved record failed here rather than leave it stuck "running".
        self._fail_run_record(run_id, f"coordinator failed to launch: {exc}")
        raise
    runs_store.set_coordinator_pid(self._dir, run_id, pid)
    return self.attach_run(run_id)

retry_run(run_id, progress=None)

Re-run a terminal processing run's incomplete recordings, into the same record.

Gap-fills rather than minting a new run: each recording already owns its own stage run id in per_recording, so the record is a map with holes in it. The re-spawned coordinator seeds those results and drives only what isn't complete, and the run rolls up to complete once every recording is (§15). Retried recordings get a fresh stage run id from Recording.run, so nothing appends into a half-written zarr — a recording is re-run whole, not resumed mid-way (§7 resume is not built).

Covers failed and cancelled runs alike: the set is every recording that isn't complete, including ones the coordinator never launched.

progress takes the (stage, fraction, detail) callback and names each recording as it is re-validated, as :meth:run_processing does.

Returns:

Name Type Description
An AttachedRun

class:AttachedRun streaming the re-spawned coordinator.

Raises:

Type Description
FileNotFoundError

If the run record does not exist.

ValueError

If the run is still running, its module is unknown, every recording is already complete, or any incomplete recording no longer validates.

Source code in detail/api/experiment.py
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
def retry_run(
    self,
    run_id: str,
    progress: Callable[[str, float, str], None] | None = None,
) -> "AttachedRun":
    """Re-run a terminal processing run's incomplete recordings, into the same record.

    Gap-fills rather than minting a new run: each recording already owns its own stage
    run id in ``per_recording``, so the record is a map with holes in it. The re-spawned
    coordinator seeds those results and drives only what isn't ``complete``, and the
    run rolls up to ``complete`` once every recording is (§15). Retried recordings get a
    *fresh* stage run id from ``Recording.run``, so nothing appends into a half-written
    zarr — a recording is re-run whole, not resumed mid-way (§7 resume is not built).

    Covers ``failed`` and ``cancelled`` runs alike: the set is every recording that
    isn't complete, including ones the coordinator never launched.

    ``progress`` takes the ``(stage, fraction, detail)`` callback and names each
    recording as it is re-validated, as :meth:`run_processing` does.

    Returns:
        An :class:`AttachedRun` streaming the re-spawned coordinator.

    Raises:
        FileNotFoundError: If the run record does not exist.
        ValueError: If the run is still running, its module is unknown, every recording
            is already complete, or any incomplete recording no longer validates.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    record = runs_store.read_run(self._dir, run_id)
    # A SIGKILLed coordinator leaves the record "running" forever and no CLI path
    # calls reconcile, so gating on a terminal status would reject a run that is
    # genuinely retryable. Reconcile mutates + persists in place.
    self._reconcile_run(record)
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(
            f"processing run {run_id!r} is still running — cancel it before retrying"
        )
    module_id = record.get("module_id")
    module = PROCESSING_MODULES.get(module_id)
    if module is None:
        raise ValueError(
            f"unknown module_id {module_id!r} for run {run_id!r}; "
            f"available: {sorted(PROCESSING_MODULES)}"
        )
    per_recording = dict(record.get("per_recording") or {})
    pending = [
        sid
        for sid in record.get("recording_ids") or []
        if per_recording.get(sid, {}).get("status") != JobStatus.COMPLETE.value
    ]
    if not pending:
        raise ValueError(
            f"processing run {run_id!r}: every recording is complete — nothing to retry"
        )
    # The record stores _jsonable(config); restore the typed values before validating,
    # whose checks read compute.backend / prompt.targets as objects (cf. __init__).
    config = _typed_config(record.get("config") or {})
    errors = self._validate_retry_recordings(module, pending, config, progress)
    if errors:
        detail = "; ".join(f"{sid}: {err}" for sid, err in errors.items())
        raise ValueError(f"cannot retry run {run_id!r} — {detail}")
    for sid in pending:
        per_recording[sid] = {"run_id": None, "status": JobStatus.PENDING.value}
    record["per_recording"] = per_recording
    record["status"] = "running"
    record.pop("error", None)
    runs_store.write_run(self._dir, run_id, record)
    # A cancelled run's sentinel outlives its coordinator; leave it and the fresh one
    # stops on its first recording and re-records cancelled (cf. resume_training).
    runs_store.clear_cancel(self._dir, run_id)
    # Seed the aggregate bar so a client reattaching before the coordinator's first
    # emit sees the real standing, not the finished run's stale recordings_done.
    runs_store.write_progress(
        self._dir,
        run_id,
        processing_progress_to_dict(
            ProcessingProgress(
                len(record["recording_ids"]) - len(pending),
                len(record["recording_ids"]),
                pending[0],
                None,
                0.0,
                len(record["recording_ids"]) - len(pending),
            )
        ),
    )
    try:
        pid = spawn_coordinator(
            runs_store.run_dir(self._dir, run_id), tuple(_PIPELINE_RUNNERS)
        )
    except (
        Exception
    ) as exc:  # noqa: BLE001 — re-raised; must not leave it "running"
        self._fail_run_record(run_id, f"coordinator failed to launch: {exc}")
        raise
    runs_store.set_coordinator_pid(self._dir, run_id, pid)
    return self.attach_run(run_id)

attach_run(run_id)

Reattach to a processing run by id — a live one streams its coordinator's progress, a terminal one returns at once. Works after an app restart because the coordinator + workers are detached and progress is on disk (§15).

Source code in detail/api/experiment.py
3079
3080
3081
3082
3083
def attach_run(self, run_id: str) -> "AttachedRun":
    """Reattach to a processing run by id — a live one streams its coordinator's
    progress, a terminal one returns at once. Works after an app restart because
    the coordinator + workers are detached and progress is on disk (§15)."""
    return AttachedRun(self, run_id)

attach_active_run(run_id)

An :class:AttachedRun when the run is still active (for a live reattach after reopen), else None — so the GUI shows a progress bar for a run that is still going and a static record for a finished one.

Source code in detail/api/experiment.py
3085
3086
3087
3088
3089
3090
3091
3092
def attach_active_run(self, run_id: str) -> "AttachedRun | None":
    """An :class:`AttachedRun` when the run is still active (for a live reattach
    after reopen), else ``None`` — so the GUI shows a progress bar for a run that
    is still going and a static record for a finished one."""
    with contextlib.suppress(FileNotFoundError):
        if runs_store.read_run(self._dir, run_id).get("status") in ACTIVE_STATUSES:
            return self.attach_run(run_id)
    return None

distill(name, classes, n_frames, *, source_recording_ids=None, sampling='stratified', logit_threshold=0.5, min_contour_area=100, val_split=0.15, background_share=LabelingConfig.model_fields['background_share'].default, negative_prompt=None, label_model_id='sam3', label_model_variant=None, label_compute=None, base_model='yolo11s-seg.pt', trainer_id='ultralytics_yolo', hyperparams=None, train_compute=None)

Distill a fast detector in one durable run (§12): label a frame sample with a prompt-capable model, then train a closed-set YOLO on those labels. negative_prompt names something in the video that is not the subject (a tether's cable): it is labelled as a class of its own so the student learns it apart, and the trained model never reports it (§12 Negative prompt).

Validates the union of the labeling and training pre-flight up front (Tenet 10), reserves the run record, then spawns a detached distill coordinator that sequences the two stages and publishes folded progress. Returns an :class:AttachedDistillRun — the run survives the app closing and any process can reattach. The trained model lands in models/<id>/ (usable in this experiment at once); promote it with :meth:promote_model for cross-experiment reuse.

Raises:

Type Description
ValueError

no/duplicate classes, a non-prompt-capable label model, a recording without video, n_frames above the frames available, the label model not ready, an unknown/unready trainer, an unsupported train backend, or invalid hyperparameters; or a negative_prompt that is also one of the classes.

Source code in detail/api/experiment.py
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
def distill(
    self,
    name: str,
    classes: list[LabelingClass],
    n_frames: int,
    *,
    source_recording_ids: list[str] | None = None,
    sampling: str = "stratified",
    logit_threshold: float = 0.5,
    min_contour_area: int = 100,
    val_split: float = 0.15,
    background_share: float = LabelingConfig.model_fields[
        "background_share"
    ].default,
    negative_prompt: str | None = None,
    label_model_id: str = "sam3",
    label_model_variant: str | None = None,
    label_compute: ComputeTarget | None = None,
    base_model: str = "yolo11s-seg.pt",
    trainer_id: str = "ultralytics_yolo",
    hyperparams: dict | None = None,
    train_compute: ComputeTarget | None = None,
) -> "AttachedDistillRun":
    """Distill a fast detector in one durable run (§12): label a frame sample with a
    prompt-capable model, then train a closed-set YOLO on those labels.
    ``negative_prompt`` names something in the video that is not the subject (a tether's
    cable): it is labelled as a class of its own so the student learns it apart, and the
    trained model never reports it (§12 *Negative prompt*).

    Validates the union of the labeling and training pre-flight up front (Tenet 10),
    reserves the run record, then spawns a **detached distill coordinator** that
    sequences the two stages and publishes folded progress. Returns an
    :class:`AttachedDistillRun` — the run survives the app closing and any process can
    reattach. The trained model lands in ``models/<id>/`` (usable in this experiment at
    once); promote it with :meth:`promote_model` for cross-experiment reuse.

    Raises:
        ValueError: no/duplicate classes, a non-prompt-capable label model, a recording
            without video, ``n_frames`` above the frames available, the label model not
            ready, an unknown/unready trainer, an unsupported train backend, or invalid
            hyperparameters; or a ``negative_prompt`` that is also one of the classes.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    recording_ids = self._sampling_recordings(source_recording_ids)
    if not classes:
        raise ValueError("labeling needs at least one class (a name + text prompt)")
    # The label stage adds the negative class itself (label_dataset); the clash is refused
    # here too, so a bad combination fails before the run exists (Tenet 10).
    with_negative_prompt(classes, negative_prompt)
    prompts = [c.prompt for c in classes]
    if len(set(prompts)) != len(prompts):
        raise ValueError(
            "two classes share a text prompt; prompts must be distinct"
        )
    capable = api_models.prompt_capable_models()
    if label_model_id not in capable:
        raise ValueError(
            f"model {label_model_id!r} cannot label — labeling needs a prompt-capable "
            f"model; choose one of {capable}"
        )
    lab_cfg = LabelingConfig.model_validate(
        {
            "model_id": label_model_id,
            "model_variant": label_model_variant,
            "n_frames": n_frames,
            "sampling": sampling,
            "logit_threshold": logit_threshold,
            "min_contour_area": min_contour_area,
            "val_split": val_split,
            "background_share": background_share,
            "negative_prompt": negative_prompt,
        }
    )
    trainer_cls = TRAINERS.get(trainer_id)
    if trainer_cls is None:
        raise ValueError(
            f"unknown trainer_id {trainer_id!r}; available: {sorted(TRAINERS)}"
        )
    trainer = trainer_cls()
    if not trainer.is_ready():
        raise ValueError(
            f"trainer {trainer_id!r} is not ready (install its backend)"
        )
    train_compute = train_compute or default_compute(trainer.supported_backends)
    if train_compute.backend not in trainer.supported_backends:
        raise ValueError(
            f"trainer {trainer_id!r} does not support backend "
            f"{train_compute.backend!r}; supports {trainer.supported_backends}"
        )
    if train_compute.backend == "cuda" and train_compute.device_indices:
        check_cuda_indices(train_compute.device_indices)
    hyperparams = trainer.validate_hyperparams(hyperparams or {})
    # Enforce the run-level composition + a non-empty name before the recording sweep.
    DistillConfig.model_validate(
        {
            "name": name,
            "base_model": base_model,
            "trainer_id": trainer_id,
            "labeling": lab_cfg.model_dump(),
            "training": hyperparams,
        }
    )
    if not recording_ids:
        raise ValueError("labeling needs at least one source recording with video")
    available = 0
    for sid in recording_ids:
        recording = self.get_recording(sid)  # raises if the recording is unknown
        data = recording_store.read_recording(recording.dir)
        files = data.get("video", {}).get("files", [])
        if not files:
            raise ValueError(
                f"recording {recording.name!r} has no video to sample; choose "
                "recordings that have video, or leave the choice empty to use all of them"
            )
        available += sum(
            len(recording_store.load_active_timestamps(recording.dir, data, i))
            for i in range(len(files))
        )
    if lab_cfg.n_frames > available:
        raise ValueError(
            f"n_frames={lab_cfg.n_frames} exceeds the {available} frames available "
            "across the selected recordings"
        )
    access = self.check_model_access(lab_cfg.model_id)
    if not access.ready:
        raise ValueError(f"{lab_cfg.model_id} is not ready — {access.message}")
    label_compute = label_compute or default_compute(
        api_models.supported_backends(lab_cfg.model_id)
    )
    run_id = distill_store.next_distill_id(self._dir)
    config = {
        "name": name,
        "base_model": base_model,
        "trainer_id": trainer_id,
        "classes": [c.to_dict() for c in classes],
        "source_recording_ids": recording_ids,
        "labeling": lab_cfg.model_dump(),
        "training": hyperparams,
        "label_compute": label_compute.to_dict(),
        "train_compute": train_compute.to_dict(),
    }
    # Reserve before spawning so the run is discoverable and a coordinator that dies on
    # launch reconciles to failed (not stuck running).
    distill_store.write_run(
        self._dir,
        run_id,
        {
            "id": run_id,
            "name": name,
            "status": "running",
            "created_at": utc_timestamp(),
            "config": config,
            "stages": {
                "label": {"status": "pending", "dataset_id": None},
                "train": {"status": "pending", "model_id": None},
            },
            "resume": False,
        },
    )
    try:
        pid = spawn_coordinator(
            distill_store.run_dir(self._dir, run_id),
            tuple(_PIPELINE_RUNNERS),
            entrypoint="detail.executor.distill_coordinator",
        )
    except (
        Exception
    ) as exc:  # noqa: BLE001 — re-raised; must not leave it "running"
        self._fail_distill_record(run_id, f"coordinator failed to launch: {exc}")
        raise
    distill_store.set_coordinator_pid(self._dir, run_id, pid)
    return self.attach_distill_run(run_id)

resume_distill(run_id)

Resume a terminal (failed / cancelled) distill run into the same record: reuse a complete labeled dataset, resume a partial model, and re-spawn the coordinator.

Raises:

Type Description
FileNotFoundError

If the run record does not exist.

ValueError

If the run is still running or already complete.

Source code in detail/api/experiment.py
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
def resume_distill(self, run_id: str) -> "AttachedDistillRun":
    """Resume a terminal (failed / cancelled) distill run into the same record: reuse a
    complete labeled dataset, resume a partial model, and re-spawn the coordinator.

    Raises:
        FileNotFoundError: If the run record does not exist.
        ValueError: If the run is still running or already complete.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    record = distill_store.read_run(self._dir, run_id)
    # A SIGKILLed coordinator reads "running" forever; reconcile mutates + persists.
    self._reconcile_distill_run(record)
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(
            f"distill run {run_id!r} is still running — cancel it before resuming"
        )
    stages = record.get("stages") or {}
    final = stages.get(distill_final_stage(record)) or {}
    if final.get("status") == JobStatus.COMPLETE.value:
        raise ValueError(
            f"distill run {run_id!r} is already complete — nothing to resume"
        )
    record["status"] = "running"
    record["resume"] = True
    record.pop("error", None)
    distill_store.write_run(self._dir, run_id, record)
    # A cancelled run's sentinel outlives its coordinator; clear it so the fresh one
    # doesn't stop on its first stage (cf. retry_run / resume_training).
    distill_store.clear_cancel(self._dir, run_id)
    try:
        pid = spawn_coordinator(
            distill_store.run_dir(self._dir, run_id),
            tuple(_PIPELINE_RUNNERS),
            entrypoint="detail.executor.distill_coordinator",
        )
    except (
        Exception
    ) as exc:  # noqa: BLE001 — re-raised; must not leave it "running"
        self._fail_distill_record(run_id, f"coordinator failed to launch: {exc}")
        raise
    distill_store.set_coordinator_pid(self._dir, run_id, pid)
    return self.attach_distill_run(run_id)

cancel_distill(run_id)

Stop an active distill run: kill the coordinator, cancel the live stage worker, and record the run's real status (complete if training actually finished, else cancelled). No-op once terminal. Raises FileNotFoundError if absent.

Source code in detail/api/experiment.py
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
def cancel_distill(self, run_id: str) -> None:
    """Stop an active distill run: kill the coordinator, cancel the live stage worker,
    and record the run's real status (``complete`` if training actually finished,
    else ``cancelled``). No-op once terminal. Raises FileNotFoundError if absent."""
    record = distill_store.read_run(self._dir, run_id)
    if record.get("status") not in ACTIVE_STATUSES:
        return
    distill_store.request_cancel(self._dir, run_id)
    kill_coordinator(
        distill_store.run_dir(self._dir, run_id),
        distill_store.read_coordinator_pid(self._dir, run_id),
    )
    stages = dict(record.get("stages") or {})
    for name in distill_stage_names(record):
        stage = dict(stages.get(name) or {})
        if stage.get("status") in ACTIVE_STATUSES:
            _, run_dir = self._distill_stage_status(name, stage)
            if run_dir is not None:
                cancel_run_dir(run_dir)
                try:
                    stage["status"] = rundir.read_status(run_dir).value
                except (FileNotFoundError, KeyError, ValueError):
                    stage["status"] = "cancelled"
            else:
                stage["status"] = "cancelled"
            stages[name] = stage
    record["stages"] = stages
    final_status = (stages.get(distill_final_stage(record)) or {}).get("status")
    record["status"] = (
        "complete" if final_status == JobStatus.COMPLETE.value else "cancelled"
    )
    distill_store.write_run(self._dir, run_id, record)

delete_distill(run_id)

Delete a distill run's index record only (distill/<id>/). The produced dataset, trained model, and any promoted global model are independent artifacts with their own lifecycles and are left intact — delete them explicitly.

Refused while the run is active (reconciled first, so a dead coordinator does not block): deleting the record under a live coordinator is the processing-run case of issue #28, finding 6 — the coordinator re-writes a record nothing lists any more.

Raises:

Type Description
FileNotFoundError

If the run record does not exist.

ValueError

If the run is still active.

Source code in detail/api/experiment.py
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
def delete_distill(self, run_id: str) -> None:
    """Delete a distill run's index record only (``distill/<id>/``). The produced
    dataset, trained model, and any promoted global model are independent artifacts
    with their own lifecycles and are left intact — delete them explicitly.

    Refused while the run is active (reconciled first, so a dead coordinator does not
    block): deleting the record under a live coordinator is the processing-run case of
    issue #28, finding 6 — the coordinator re-writes a record nothing lists any more.

    Raises:
        FileNotFoundError: If the run record does not exist.
        ValueError: If the run is still active.
    """
    record = self.distill_run_record(
        run_id
    )  # reconciled; FileNotFoundError if absent
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(
            f"distill run {run_id!r} is still active — cancel it first"
        )
    distill_store.delete_run(self._dir, run_id)

attach_distill_run(run_id)

Reattach to a distill run by id — a live one streams its coordinator's progress, a terminal one returns at once (§12).

Source code in detail/api/experiment.py
3382
3383
3384
3385
def attach_distill_run(self, run_id: str) -> "AttachedDistillRun":
    """Reattach to a distill run by id — a live one streams its coordinator's progress,
    a terminal one returns at once (§12)."""
    return AttachedDistillRun(self, run_id)

attach_active_distill_run(run_id)

An :class:AttachedDistillRun when the run is still active, else None — so the GUI shows a live bar for a running distill and a static record for a done one.

Source code in detail/api/experiment.py
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
def attach_active_distill_run(self, run_id: str) -> "AttachedDistillRun | None":
    """An :class:`AttachedDistillRun` when the run is still active, else ``None`` — so
    the GUI shows a live bar for a running distill and a static record for a done one.
    """
    with contextlib.suppress(FileNotFoundError):
        if (
            distill_store.read_run(self._dir, run_id).get("status")
            in ACTIVE_STATUSES
        ):
            return self.attach_distill_run(run_id)
    return None

distill_run_record(run_id)

The full distill.yaml for one run, reconciled (Tenet 2).

Raises:

Type Description
FileNotFoundError

If the run record does not exist.

Source code in detail/api/experiment.py
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
def distill_run_record(self, run_id: str) -> dict:
    """The full ``distill.yaml`` for one run, reconciled (Tenet 2).

    Raises:
        FileNotFoundError: If the run record does not exist.
    """
    record = distill_store.read_run(self._dir, run_id)
    if self._reconcile_distill_run(record):
        record = distill_store.read_run(self._dir, run_id)
    return record

reconcile_distill_runs()

Fold each still-active distill run's real on-disk status back into its record on experiment open (§12) — the SIGKILL backstop, mirroring :meth:reconcile_runs.

Source code in detail/api/experiment.py
3416
3417
3418
3419
3420
3421
3422
def reconcile_distill_runs(self) -> None:
    """Fold each still-active distill run's real on-disk status back into its record on
    experiment open (§12) — the SIGKILL backstop, mirroring :meth:`reconcile_runs`.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    for record in distill_store.list_runs(self._dir):
        self._reconcile_distill_run(record)

promote_model(model_id, name=None)

Promote a completed trained model into the machine-global catalog so it can be selected in any experiment (§12) — the on-demand step after a distill. The global model records its provenance (this experiment + the source dataset + base model + metrics), and its weights are copied so it stays self-contained. Returns the assigned global model id.

Raises:

Type Description
FileNotFoundError

If the model (or its weights file) does not exist.

ValueError

If the model is not complete or the derived global id collides.

Source code in detail/api/experiment.py
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
def promote_model(self, model_id: str, name: str | None = None) -> str:
    """Promote a completed trained model into the machine-global catalog so it can be
    selected in *any* experiment (§12) — the on-demand step after a distill. The global
    model records its provenance (this experiment + the source dataset + base model +
    metrics), and its weights are copied so it stays self-contained. Returns the assigned
    global model id.

    Raises:
        FileNotFoundError: If the model (or its weights file) does not exist.
        ValueError: If the model is not complete or the derived global id collides.
    """
    import_runner_modules(
        _PIPELINE_RUNNERS
    )  # populate registries for id validation
    return distilled_store.register_distilled_model(
        self._dir,
        model_id,
        source_experiment_name=self.name,
        source_experiment_id=self._dir.name,
        name=name,
    )

dataset_record(dataset_id)

The full dataset.yaml for one dataset (for detail views — Tenet 2).

Source code in detail/api/experiment.py
3553
3554
3555
3556
3557
def dataset_record(self, dataset_id: str) -> dict:
    """The full ``dataset.yaml`` for one dataset (for detail views — Tenet 2)."""
    return datasets_store.read_dataset_yaml(
        datasets_store.dataset_dir(self._dir, dataset_id)
    )

generate_dataset(name, source_run_id, frame_selection=None, val_split=0.15, min_contour_area=100)

Export a YOLO training dataset from a completed detection/tracking run (§12). No new inference — reuses the run's masks. Returns a run handle.

Raises:

Type Description
FileNotFoundError

If the source run record is absent.

ValueError

If the source run is not a complete detection/tracking run.

Source code in detail/api/experiment.py
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
def generate_dataset(
    self,
    name: str,
    source_run_id: str,
    frame_selection: dict | None = None,
    val_split: float = 0.15,
    min_contour_area: int = 100,
) -> DatasetRun:
    """Export a YOLO training dataset from a completed detection/tracking run
    (§12). No new inference — reuses the run's masks. Returns a run handle.

    Raises:
        FileNotFoundError: If the source run record is absent.
        ValueError: If the source run is not a complete detection/tracking run.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    record = runs_store.read_run(self._dir, source_run_id)  # raises if missing
    if record.get("module_id") not in ("detection", "tracking"):
        raise ValueError(
            f"dataset source must be a detection or tracking run, got "
            f"{record.get('module_id')!r}"
        )
    if record.get("status") != "complete":
        raise ValueError(
            f"source run {source_run_id!r} is {record.get('status')!r}, "
            "not complete"
        )
    dataset_id = datasets_store.next_dataset_id(self._dir)
    job = DatasetExportJob(
        job_id=dataset_id,
        dataset_id=dataset_id,
        name=name,
        source_run_id=source_run_id,
        frame_selection=frame_selection or {"mode": "all"},
        val_split=val_split,
        min_contour_area=min_contour_area,
        created_at=utc_timestamp(),
    )
    # An initial record so the dataset is discoverable while it runs, written
    # *before* submit so the runner's completion write (full record) is always
    # last — never clobbered by this one (the worker can finish fast).
    ddir = datasets_store.dataset_dir(self._dir, dataset_id)
    ddir.mkdir(parents=True, exist_ok=True)
    datasets_store.write_dataset_yaml(
        ddir,
        {
            "id": dataset_id,
            "name": name,
            "source": {"kind": "run_export", "run_id": source_run_id},
            "status": "running",
        },
    )
    executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
    executor.submit(job)  # run_dir = datasets/<id>/; writes job.json there
    return DatasetRun(ExecutorRunHandle(executor, dataset_id), self, dataset_id)

label_dataset(name, classes, n_frames, source_recording_ids=None, logit_threshold=0.5, min_contour_area=100, val_split=0.15, compute=None, sampling='stratified', model_id='sam3', model_variant=None, background_share=LabelingConfig.model_fields['background_share'].default, negative_prompt=None)

Build a YOLO dataset by running a prompt-capable model on a sample of frames (§12) — the distill-into-YOLO source, no existing detection run needed. model_id picks which prompt-capable model labels (sam3 by default), model_variant its size (None = the model's default). n_frames is sampled proportionally to recording length; sampling picks how frames are drawn within each video ("stratified" spreads them evenly across time, "uniform" is fully random). source_recording_ids=None uses every recording. Frames where the model found none of the classes are kept with an empty label, up to background_share of the dataset. negative_prompt adds a class for something that is not the subject (a tether's cable), labelled so a detector trained on the dataset learns it apart and never reports it (§12 Negative prompt). Returns a run handle.

The flat scalar parameters (model_id, model_variant, n_frames, sampling, logit_threshold, min_contour_area, val_split, background_share, negative_prompt) are validated by :class:LabelingConfig; the checks below need recording data and stay here.

Raises:

Type Description
ValueError

no classes, duplicate class prompts, a scalar out of its model bounds (bad sampling / val_split / n_frames / thresholds), a model that is not prompt-capable, a recording without video, n_frames above the frames available, the chosen model not ready, or a negative_prompt that is also one of the classes.

Source code in detail/api/experiment.py
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
def label_dataset(
    self,
    name: str,
    classes: list[LabelingClass],
    n_frames: int,
    source_recording_ids: list[str] | None = None,
    logit_threshold: float = 0.5,
    min_contour_area: int = 100,
    val_split: float = 0.15,
    compute: ComputeTarget | None = None,
    sampling: str = "stratified",
    model_id: str = "sam3",
    model_variant: str | None = None,
    background_share: float = LabelingConfig.model_fields[
        "background_share"
    ].default,
    negative_prompt: str | None = None,
) -> DatasetRun:
    """Build a YOLO dataset by running a prompt-capable model on a sample of frames (§12) —
    the distill-into-YOLO source, no existing detection run needed. ``model_id`` picks which
    prompt-capable model labels (``sam3`` by default), ``model_variant`` its size
    (``None`` = the model's default). ``n_frames`` is sampled proportionally to recording
    length; ``sampling`` picks how frames are drawn within each video (``"stratified"`` spreads
    them evenly across time, ``"uniform"`` is fully random). ``source_recording_ids=None`` uses
    every recording. Frames where the model found none of the classes are kept with an
    empty label, up to ``background_share`` of the dataset. ``negative_prompt`` adds a class
    for something that is not the subject (a tether's cable), labelled so a detector trained
    on the dataset learns it apart and never reports it (§12 *Negative prompt*). Returns a
    run handle.

    The flat scalar parameters (``model_id``, ``model_variant``, ``n_frames``, ``sampling``,
    ``logit_threshold``, ``min_contour_area``, ``val_split``, ``background_share``,
    ``negative_prompt``) are
    validated by
    :class:`LabelingConfig`; the checks below need recording data and stay here.

    Raises:
        ValueError: no classes, duplicate class prompts, a scalar out of its model bounds
            (bad ``sampling`` / ``val_split`` / ``n_frames`` / thresholds), a model that is not
            prompt-capable, a recording without video, ``n_frames`` above the frames available,
            the chosen model not ready, or a ``negative_prompt`` that is also one of the
            classes.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    recording_ids = self._sampling_recordings(source_recording_ids)
    compute = compute or default_compute(api_models.supported_backends(model_id))
    if not classes:
        raise ValueError("labeling needs at least one class (a name + text prompt)")
    prompts = [c.prompt for c in classes]
    if len(set(prompts)) != len(prompts):
        raise ValueError(
            "two classes share a text prompt; prompts must be distinct"
        )
    capable = api_models.prompt_capable_models()
    if model_id not in capable:
        raise ValueError(
            f"model {model_id!r} cannot label — labeling needs a prompt-capable model; "
            f"choose one of {capable}"
        )
    cfg = LabelingConfig.model_validate(
        {
            "model_id": model_id,
            "model_variant": model_variant,
            "n_frames": n_frames,
            "sampling": sampling,
            "logit_threshold": logit_threshold,
            "min_contour_area": min_contour_area,
            "val_split": val_split,
            "background_share": background_share,
            "negative_prompt": negative_prompt,
        }
    )
    # The negative prompt is labelled as one more class, recorded by name (Tenet 9).
    labelled, negative_classes = with_negative_prompt(classes, cfg.negative_prompt)
    if not recording_ids:
        raise ValueError("labeling needs at least one source recording with video")
    available = 0
    for sid in recording_ids:
        recording = self.get_recording(sid)  # raises if the recording is unknown
        data = recording_store.read_recording(recording.dir)
        files = data.get("video", {}).get("files", [])
        if not files:
            raise ValueError(
                f"recording {recording.name!r} has no video to sample; choose "
                "recordings that have video, or leave the choice empty to use all of them"
            )
        # Frame count from the PTS timestamp map (Tenet 8 / CLAUDE.md frame-count rule), not
        # cv2's CAP_PROP_FRAME_COUNT estimate — so the n_frames check matches what's sampleable.
        available += sum(
            len(recording_store.load_active_timestamps(recording.dir, data, i))
            for i in range(len(files))
        )
    if cfg.n_frames > available:
        raise ValueError(
            f"n_frames={cfg.n_frames} exceeds the {available} frames available across "
            "the selected recordings"
        )
    status = self.check_model_access(cfg.model_id)
    if not status.ready:
        raise ValueError(f"{cfg.model_id} is not ready — {status.message}")

    dataset_id = datasets_store.next_dataset_id(self._dir)
    job = LabelingJob(
        job_id=dataset_id,
        dataset_id=dataset_id,
        name=name,
        source_recording_ids=recording_ids,
        classes=labelled,
        n_frames=cfg.n_frames,
        logit_threshold=cfg.logit_threshold,
        min_contour_area=cfg.min_contour_area,
        val_split=cfg.val_split,
        background_share=cfg.background_share,
        compute=compute,
        created_at=utc_timestamp(),
        sampling=cfg.sampling,
        model_id=cfg.model_id,
        model_variant=cfg.model_variant,
        negative_classes=negative_classes,
    )
    ddir = datasets_store.dataset_dir(self._dir, dataset_id)
    ddir.mkdir(parents=True, exist_ok=True)
    datasets_store.write_dataset_yaml(
        ddir,
        {
            "id": dataset_id,
            "name": name,
            "source": {"kind": "labeling", "model": cfg.model_id},
            "status": "running",
        },
    )
    executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
    executor.submit(job)
    return DatasetRun(ExecutorRunHandle(executor, dataset_id), self, dataset_id)

keypoint_dataset(name, detect_runs=None, n_frames=None, **options)

Build a YOLO-pose dataset (§12 Distill keypoints, the label stage on its own). The teacher is detect_runs (finished keypoint detect runs: recording names or ids, each with a run id or None for the only one; tracking= may name the tracking run each recording's poses are assigned to, else the one on the detect run's detection run) or the patch method (example_set=, tracking=, model_id=, label_compute=); the other options are KeypointDatasetConfig's. Returns a DatasetRun.

Source code in detail/api/experiment.py
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
def keypoint_dataset(
    self, name: str, detect_runs=None, n_frames: int | None = None, **options
) -> "DatasetRun":
    """Build a YOLO-pose dataset (§12 *Distill keypoints*, the label stage on its own).
    The teacher is ``detect_runs`` (finished keypoint detect runs: recording names or ids,
    each with a run id or ``None`` for the only one; ``tracking=`` may name the tracking
    run each recording's poses are assigned to, else the one on the detect run's
    detection run) or the patch method (``example_set=``, ``tracking=``, ``model_id=``,
    ``label_compute=``); the other options are ``KeypointDatasetConfig``'s. Returns a
    ``DatasetRun``."""
    from detail.api import keypoint_distill as _kd

    return _kd.keypoint_dataset(self, name, detect_runs, n_frames, **options)

test_keypoints(detect_runs=None, **options)

Test a keypoint teacher on about a dozen frames drawn the way a distill would, with the held-out check against the example clicks; writes nothing (§12, Test cut-off…). Takes distill_keypoints's teacher keywords plus n_frames and seed. Returns a TeacherTest.

Source code in detail/api/experiment.py
3769
3770
3771
3772
3773
3774
3775
3776
def test_keypoints(self, detect_runs=None, **options):
    """Test a keypoint teacher on about a dozen frames drawn the way a distill would, with
    the held-out check against the example clicks; writes nothing (§12, *Test
    cut-off…*). Takes ``distill_keypoints``'s teacher keywords plus ``n_frames`` and
    ``seed``. Returns a ``TeacherTest``."""
    from detail.api import keypoint_distill as _kd

    return _kd.keypoint_test(self, detect_runs, **options)

distill_keypoints(name, detect_runs=None, n_frames=None, **options)

Distill a teacher into a fast YOLO-pose student in one durable run (label → train → register). The teacher is detect_runs or the patch method (example_set= + tracking=), as :meth:keypoint_dataset takes it. Options: KeypointDatasetConfig's fields plus base_model (a -pose checkpoint), trainer_id, hyperparams, train_compute and label_compute. Returns an :class:AttachedDistillRun.

Source code in detail/api/experiment.py
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
def distill_keypoints(
    self, name: str, detect_runs=None, n_frames: int | None = None, **options
) -> "AttachedDistillRun":
    """Distill a teacher into a fast YOLO-pose student in one durable run (label →
    train → register). The teacher is ``detect_runs`` or the patch method
    (``example_set=`` + ``tracking=``), as :meth:`keypoint_dataset` takes it. Options:
    ``KeypointDatasetConfig``'s fields plus ``base_model`` (a ``-pose`` checkpoint),
    ``trainer_id``, ``hyperparams``, ``train_compute`` and ``label_compute``. Returns an
    :class:`AttachedDistillRun`."""
    from detail.api import keypoint_distill as _kd

    return _kd.distill_keypoints(self, name, detect_runs, n_frames, **options)

example_sets(purpose='example')

This experiment's example sets of one purpose (None for all), id order.

Source code in detail/api/experiment.py
3792
3793
3794
3795
3796
def example_sets(self, purpose: str | None = "example") -> list:
    """This experiment's example sets of one purpose (``None`` for all), id order."""
    from detail.api import keypoints as _keypoints

    return _keypoints.example_sets(self, purpose)

example_set(set_id)

One example set; FileNotFoundError names the sets that exist.

Source code in detail/api/experiment.py
3798
3799
3800
3801
3802
def example_set(self, set_id: str):
    """One example set; ``FileNotFoundError`` names the sets that exist."""
    from detail.api import keypoints as _keypoints

    return _keypoints.example_set(self, set_id)

create_example_set(name, skeleton, *, purpose='example')

A new, empty example set holding a copy of skeleton.

Source code in detail/api/experiment.py
3804
3805
3806
3807
3808
def create_example_set(self, name: str, skeleton, *, purpose: str = "example"):
    """A new, empty example set holding a copy of ``skeleton``."""
    from detail.api import keypoints as _keypoints

    return _keypoints.create_example_set(self, name, skeleton, purpose=purpose)

sample_example_frames(set_id, sources, n_frames=5, **options)

Copy tracked frames into an example set (varied or spread); see api.keypoints.sample_example_frames for the options.

Source code in detail/api/experiment.py
3810
3811
3812
3813
3814
3815
3816
3817
def sample_example_frames(self, set_id: str, sources, n_frames: int = 5, **options):
    """Copy tracked frames into an example set (``varied`` or ``spread``); see
    ``api.keypoints.sample_example_frames`` for the options."""
    from detail.api import keypoints as _keypoints

    return _keypoints.sample_example_frames(
        self, set_id, sources, n_frames, **options
    )

add_example_frame(set_id, recording, tracking_run_id, part_id, frame_idx, track_id)

Copy one navigated-to frame into an example set.

Source code in detail/api/experiment.py
3819
3820
3821
3822
3823
3824
3825
3826
3827
def add_example_frame(
    self, set_id, recording, tracking_run_id, part_id, frame_idx, track_id
):
    """Copy one navigated-to frame into an example set."""
    from detail.api import keypoints as _keypoints

    return _keypoints.add_example_frame(
        self, set_id, recording, tracking_run_id, part_id, frame_idx, track_id
    )

set_example_marks(set_id, frame_index, marks)

Replace one frame's marks and write the set atomically.

Source code in detail/api/experiment.py
3829
3830
3831
3832
3833
def set_example_marks(self, set_id: str, frame_index: int, marks):
    """Replace one frame's marks and write the set atomically."""
    from detail.api import keypoints as _keypoints

    return _keypoints.set_example_marks(self, set_id, frame_index, marks)

remove_example_frame(set_id, frame_index)

Drop one frame from an example set (its PNG stays).

Source code in detail/api/experiment.py
3835
3836
3837
3838
3839
def remove_example_frame(self, set_id: str, frame_index: int):
    """Drop one frame from an example set (its PNG stays)."""
    from detail.api import keypoints as _keypoints

    return _keypoints.remove_example_frame(self, set_id, frame_index)

example_frame_image(set_id, frame_index)

One example frame's picture as RGB uint8.

Source code in detail/api/experiment.py
3841
3842
3843
3844
3845
def example_frame_image(self, set_id: str, frame_index: int):
    """One example frame's picture as RGB uint8."""
    from detail.api import keypoints as _keypoints

    return _keypoints.example_frame_image(self, set_id, frame_index)

update_example_set(set_id, *, name=None, skeleton=None)

Rename an example set, and/or change its skeleton until its first mark.

Source code in detail/api/experiment.py
3847
3848
3849
3850
3851
def update_example_set(self, set_id: str, *, name=None, skeleton=None):
    """Rename an example set, and/or change its skeleton until its first mark."""
    from detail.api import keypoints as _keypoints

    return _keypoints.update_example_set(self, set_id, name=name, skeleton=skeleton)

duplicate_example_set(set_id, *, name=None)

A new, empty set holding a copy of this set's skeleton.

Source code in detail/api/experiment.py
3853
3854
3855
3856
3857
def duplicate_example_set(self, set_id: str, *, name=None):
    """A new, empty set holding a copy of this set's skeleton."""
    from detail.api import keypoints as _keypoints

    return _keypoints.duplicate_example_set(self, set_id, name=name)

export_example_set(set_id, out_dir)

Write a set (examples.yaml + its frame images) to a folder.

Source code in detail/api/experiment.py
3859
3860
3861
3862
3863
def export_example_set(self, set_id: str, out_dir):
    """Write a set (``examples.yaml`` + its frame images) to a folder."""
    from detail.api import keypoints as _keypoints

    return _keypoints.export_example_set(self, set_id, out_dir)

example_set_runs(set_id)

(recording_id, run_id) of the keypoint detect runs that list a set.

Source code in detail/api/experiment.py
3865
3866
3867
3868
3869
def example_set_runs(self, set_id: str) -> list:
    """``(recording_id, run_id)`` of the keypoint detect runs that list a set."""
    from detail.api import keypoints as _keypoints

    return _keypoints.example_set_runs(self, set_id)

import_example_set(yaml_path)

Read a prepared example set (YAML + images beside it) in under a fresh id.

Source code in detail/api/experiment.py
3871
3872
3873
3874
3875
def import_example_set(self, yaml_path):
    """Read a prepared example set (YAML + images beside it) in under a fresh id."""
    from detail.api import keypoints as _keypoints

    return _keypoints.import_example_set(self, yaml_path)

delete_example_set(set_id)

Delete an example set no keypoint run lists.

Source code in detail/api/experiment.py
3877
3878
3879
3880
3881
def delete_example_set(self, set_id: str) -> None:
    """Delete an example set no keypoint run lists."""
    from detail.api import keypoints as _keypoints

    _keypoints.delete_example_set(self, set_id)

model_names()

{model_id: name} for every model this experiment can name — its own trained models plus the machine-global imported ones (§5/§12). The model twin of :meth:recording_names.

Records key on the model id, which is permanent; the name is what people read (§11). A label built from this falls back to the id for anything absent — a built-in model, whose id is its name, or a model deleted since the run. Cost is O(models), not O(recordings), so it is cheap enough to build per page render.

Source code in detail/api/experiment.py
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
def model_names(self) -> dict[str, str]:
    """``{model_id: name}`` for every model this experiment can name — its own trained
    models plus the machine-global imported ones (§5/§12). The model twin of
    :meth:`recording_names`.

    Records key on the model **id**, which is permanent; the **name** is what people
    read (§11). A label built from this falls back to the id for anything absent — a
    built-in model, whose id *is* its name, or a model deleted since the run. Cost is
    O(models), not O(recordings), so it is cheap enough to build per page render.
    """
    names = {m.id: m.name for m in self.models if m.name}
    names.update({m.id: m.name for m in self.imported_models if m.name})
    return names

model_record(model_id)

The full model.yaml for one trained model (for detail views — Tenet 2).

Source code in detail/api/experiment.py
3921
3922
3923
def model_record(self, model_id: str) -> dict:
    """The full ``model.yaml`` for one trained model (for detail views — Tenet 2)."""
    return models_store.read_model_yaml(models_store.model_dir(self._dir, model_id))

model_metric_history(model_id)

Per-epoch metrics for a trained model, oldest first; [] if it has none yet.

The series behind model_record's summary. final_metrics answers how good is this model; someone deciding whether to stop training early is asking the other question — is it still getting better — and one number cannot tell a run that has been improving for an hour from one that plateaued forty epochs ago.

Readable while the run is live, because it comes off the trainer's own on-disk record rather than progress events — so it is whole on a page opened after the run began, and a model that trained overnight has its curve in the morning.

Returns [] rather than raising when the trainer is not installed on this machine: reading a finished run's record must not require the backend that produced it (a model trained elsewhere and imported has no Ultralytics here), and a missing curve is the honest rendering of a history we cannot read.

Source code in detail/api/experiment.py
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
def model_metric_history(self, model_id: str) -> list[dict[str, float]]:
    """Per-epoch metrics for a trained model, oldest first; ``[]`` if it has none yet.

    The series behind `model_record`'s summary. `final_metrics` answers *how good is this
    model*; someone deciding whether to stop training early is asking the other question —
    *is it still getting better* — and one number cannot tell a run that has been improving
    for an hour from one that plateaued forty epochs ago.

    Readable while the run is live, because it comes off the trainer's own on-disk record
    rather than progress events — so it is whole on a page opened after the run began, and a
    model that trained overnight has its curve in the morning.

    Returns ``[]`` rather than raising when the trainer is not installed on this machine:
    reading a finished run's record must not require the backend that produced it (a model
    trained elsewhere and imported has no Ultralytics here), and a missing curve is the
    honest rendering of a history we cannot read.
    """
    record = self.model_record(model_id)  # FileNotFoundError if the model is gone
    # The registry's entrypoint, not a hope that something earlier in this process ran it:
    # `train_model` does, but a GUI that opens an existing model — or watches a distill whose
    # training runs in its detached coordinator — never trains here, found `TRAINERS` empty,
    # and drew no curve at all. The test session imports every registry up front, so the
    # suite could not see it.
    import_trainers()
    trainer_cls = TRAINERS.get(record.get("trainer_id", ""))
    if trainer_cls is None:
        return []
    return trainer_cls().metric_history(models_store.model_dir(self._dir, model_id))

train_model(name, dataset_id, trainer_id, base_model, hyperparams=None, compute=None)

Train a custom detection model from a dataset (§12). Returns a handle.

Raises:

Type Description
FileNotFoundError

If the dataset does not exist.

ValueError

If the dataset is not complete, the trainer is unknown or not ready, the backend is unsupported, or hyperparams are invalid.

Source code in detail/api/experiment.py
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
def train_model(
    self,
    name: str,
    dataset_id: str,
    trainer_id: str,
    base_model: str,
    hyperparams: dict | None = None,
    compute: ComputeTarget | None = None,
) -> ModelRun:
    """Train a custom detection model from a dataset (§12). Returns a handle.

    Raises:
        FileNotFoundError: If the dataset does not exist.
        ValueError: If the dataset is not complete, the trainer is unknown or
            not ready, the backend is unsupported, or hyperparams are invalid.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    ddir = datasets_store.dataset_dir(self._dir, dataset_id)
    if not (ddir / datasets_store.DATASET_FILENAME).is_file():
        raise FileNotFoundError(f"dataset {dataset_id!r} not found")
    if datasets_store.read_dataset_yaml(ddir).get("status") != "complete":
        raise ValueError(f"dataset {dataset_id!r} is not complete")
    trainer_cls = TRAINERS.get(trainer_id)
    if trainer_cls is None:
        raise ValueError(
            f"unknown trainer_id {trainer_id!r}; available: {sorted(TRAINERS)}"
        )
    trainer = trainer_cls()
    if not trainer.is_ready():
        raise ValueError(
            f"trainer {trainer_id!r} is not ready (install its backend)"
        )
    compute = compute or default_compute(trainer.supported_backends)
    if compute.backend not in trainer.supported_backends:
        raise ValueError(
            f"trainer {trainer_id!r} does not support backend "
            f"{compute.backend!r}; supports {trainer.supported_backends}"
        )
    if compute.backend == "cuda" and compute.device_indices:
        check_cuda_indices(compute.device_indices)
    hyperparams = trainer.validate_hyperparams(hyperparams or {})
    # A base checkpoint that cannot learn the dataset's labels (a -seg base on a pose
    # dataset, or the reverse) fails here, before anything is downloaded or written.
    check_base = getattr(trainer, "check_base_model", None)
    if check_base is not None:
        check_base(base_model, ddir)
    model_id = models_store.next_model_id(self._dir)
    job = TrainingJob(
        job_id=model_id,
        model_id=model_id,
        dataset_id=dataset_id,
        trainer_id=trainer_id,
        base_model=base_model,
        hyperparams=hyperparams,
        compute=compute,
        created_at=utc_timestamp(),
    )
    # Initial record (before submit) carrying the name + lineage; the runner
    # fills in classes/weights/metrics/status on completion.
    mdir = models_store.model_dir(self._dir, model_id)
    mdir.mkdir(parents=True, exist_ok=True)
    models_store.write_model_yaml(
        mdir,
        {
            "id": model_id,
            "name": name,
            "trainer_id": trainer_id,
            "dataset_id": dataset_id,
            "base_model": base_model,
            # Resolved (defaults filled) before the run starts: the live training curve
            # and `train status` read the epoch count from here.
            "hyperparams": dict(hyperparams),
            "status": "running",
        },
    )
    executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
    executor.submit(job)  # run_dir = models/<id>/; writes job.json there
    return ModelRun(ExecutorRunHandle(executor, model_id), self, model_id)

resume_training(model_id)

Resume a training that was killed or crashed mid-run (cancelled / failed) from its last checkpoint instead of restarting from epoch 0 (§12). Re-submits the original job; the runner picks up run/weights/last.pt. Returns a handle.

A partial model is refused: it stopped cleanly, so its checkpoint was finalized and holds nothing to resume (:data:RESUMABLE_TRAINING_STATUSES).

Raises:

Type Description
FileNotFoundError

If the model does not exist.

ValueError

If the model finished (complete / partial) or is running, its recorded training job is missing/unreadable, its trainer is unknown, or it has no checkpoint to resume from.

Source code in detail/api/experiment.py
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
def resume_training(self, model_id: str) -> ModelRun:
    """Resume a training that was killed or crashed mid-run (cancelled / failed) from
    its last checkpoint instead of restarting from epoch 0 (§12). Re-submits the original
    job; the runner picks up ``run/weights/last.pt``. Returns a handle.

    A ``partial`` model is refused: it stopped cleanly, so its checkpoint was finalized
    and holds nothing to resume (:data:`RESUMABLE_TRAINING_STATUSES`).

    Raises:
        FileNotFoundError: If the model does not exist.
        ValueError: If the model finished (complete / partial) or is running, its
            recorded training job is missing/unreadable, its trainer is unknown, or it has
            no checkpoint to resume from.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    mdir = models_store.model_dir(self._dir, model_id)
    record = models_store.read_model_yaml(mdir)  # FileNotFoundError if absent
    status = record.get("status")
    if status == "partial":
        raise ValueError(
            f"model {model_id!r} stopped cleanly, so its training is finished and its "
            "checkpoint holds nothing to resume. Its best weights are usable as they are; "
            "train a new model to train further."
        )
    if status not in RESUMABLE_TRAINING_STATUSES:
        raise ValueError(
            f"model {model_id!r} is {status!r}; only a cancelled or failed training "
            "can be resumed"
        )
    try:
        job = rundir.read_job(
            mdir
        )  # the original TrainingJob (run_dir = models/<id>/)
    except (FileNotFoundError, KeyError, ValueError) as exc:
        raise ValueError(
            f"model {model_id!r} has no recorded training job to resume ({exc})"
        ) from exc
    trainer_cls = TRAINERS.get(job.trainer_id)
    if trainer_cls is None:
        raise ValueError(
            f"unknown trainer_id {job.trainer_id!r} for model {model_id!r}"
        )
    if trainer_cls().checkpoint_path(mdir) is None:
        raise ValueError(
            f"model {model_id!r} has no checkpoint to resume from — train it first"
        )
    live = live_process_pid(mdir)
    if live is not None:
        raise ValueError(
            f"model {model_id!r} still has a training process running (pid {live}) — "
            "cancel it in DETAIL before resuming. A force-kill of the trainer alone "
            "leaves the worker above it alive and holding the GPU."
        )
    models_store.set_model_status(mdir, "running")
    # A cancelled/partial run left a `cancel` marker in the run dir; clear it or the resumed
    # worker's cancel watcher sees it and immediately re-cancels (cf. api/annotation.py).
    rundir.clear_cancel(mdir)
    executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
    executor.submit(job)  # same run dir: last.pt is present, so the runner resumes
    return ModelRun(ExecutorRunHandle(executor, model_id), self, model_id)

delete_dataset(dataset_id)

Delete a training dataset (images + labels + dataset.yaml).

Blocked only while active work would lose its inputs (gui_design §1.1): the dataset's own export, or a model still training from it. A completed model is self-contained (it copied its weights), so its lineage reference is left to dangle — it does not block.

Raises:

Type Description
FileNotFoundError

If no such dataset exists.

ValueError

If the dataset's export or a model training from it is active.

Source code in detail/api/experiment.py
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
def delete_dataset(self, dataset_id: str) -> None:
    """Delete a training dataset (images + labels + ``dataset.yaml``).

    Blocked only while *active* work would lose its inputs (gui_design §1.1):
    the dataset's own export, or a model still training from it. A *completed*
    model is self-contained (it copied its weights), so its lineage reference
    is left to dangle — it does not block.

    Raises:
        FileNotFoundError: If no such dataset exists.
        ValueError: If the dataset's export or a model training from it is active.
    """
    record = datasets_store.read_dataset_yaml(  # FileNotFoundError if absent
        datasets_store.dataset_dir(self._dir, dataset_id)
    )
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(
            f"dataset {dataset_id!r} is still being generated — wait for it"
        )
    blockers = [
        m.id
        for m in self.models
        if m.dataset_id == dataset_id and m.status in ACTIVE_STATUSES
    ]
    if blockers:
        raise ValueError(
            f"cannot delete dataset {dataset_id!r} — a model is training from "
            f"it: {', '.join(blockers)}"
        )
    datasets_store.delete_dataset(self._dir, dataset_id)

delete_model(model_id)

Delete a trained model (model.yaml + trainer run + weights).

Blocked only while active work would lose its inputs (gui_design §1.1): the model's own training, or a detection run still using it. A completed detection run keeps its own masks, so its lineage reference is left to dangle — it does not block.

Raises:

Type Description
FileNotFoundError

If no such model exists.

ValueError

If the model's training or a detection run using it is active.

Source code in detail/api/experiment.py
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
def delete_model(self, model_id: str) -> None:
    """Delete a trained model (``model.yaml`` + trainer run + weights).

    Blocked only while *active* work would lose its inputs (gui_design §1.1):
    the model's own training, or a detection run still using it. A *completed*
    detection run keeps its own masks, so its lineage reference is left to
    dangle — it does not block.

    Raises:
        FileNotFoundError: If no such model exists.
        ValueError: If the model's training or a detection run using it is active.
    """
    record = models_store.read_model_yaml(  # FileNotFoundError if absent
        models_store.model_dir(self._dir, model_id)
    )
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(f"model {model_id!r} is still training — wait for it")
    blockers = [
        run["id"]
        for run in self.processing_runs
        if run.get("module_id") == "detection"
        and run.get("status") in ACTIVE_STATUSES
        and run.get("config", {}).get("weights_source") == "trained"
        and run.get("config", {}).get("model_id") == model_id
    ]
    if blockers:
        raise ValueError(
            f"cannot delete model {model_id!r} — a detection run is using it: "
            f"{', '.join(blockers)}"
        )
    models_store.delete_model(self._dir, model_id)

delete_run(run_id)

Delete a processing run: its per-recording outputs (zarr stores + recording.yaml entries) and the experiment-level run record.

Refuses if any per-recording output is still depended on by a downstream run (e.g. tracking built on this detection) — delete those first. Nothing is removed until the whole run is clear to delete (Tenet 10).

Raises:

Type Description
FileNotFoundError

If no such run record exists.

ValueError

If the run is still active, or a downstream run depends on it.

Source code in detail/api/experiment.py
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
def delete_run(self, run_id: str) -> None:
    """Delete a processing run: its per-recording outputs (zarr stores +
    recording.yaml entries) and the experiment-level run record.

    Refuses if any per-recording output is still depended on by a downstream
    run (e.g. tracking built on this detection) — delete those first. Nothing
    is removed until the whole run is clear to delete (Tenet 10).

    Raises:
        FileNotFoundError: If no such run record exists.
        ValueError: If the run is still active, or a downstream run depends on it.
    """
    record = runs_store.read_run(self._dir, run_id)
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(f"run {run_id!r} is still active — wait for it to finish")
    module_id = record["module_id"]
    per_recording = record.get("per_recording", {})

    blockers = []
    for recording_id, info in per_recording.items():
        stage_run_id = info.get("run_id")
        if stage_run_id is None:
            continue
        recording = self.get_recording(recording_id)
        for dep_module, dep_run_id in recording.run_dependents(
            module_id, stage_run_id
        ):
            blockers.append(
                f"  {recording_id}: {dep_module} run {dep_run_id!r} depends on "
                f"{stage_run_id!r}"
            )
    if blockers:
        raise ValueError(
            f"cannot delete run {run_id!r} — delete its dependents first:\n"
            + "\n".join(blockers)
        )

    active = self._active_analysis_blockers(module_id, per_recording)
    if active:
        raise ValueError(
            f"cannot delete run {run_id!r} — an analysis run is still reading it:\n"
            + "\n".join(active)
        )

    for recording_id, info in per_recording.items():
        stage_run_id = info.get("run_id")
        if stage_run_id is not None:
            self.get_recording(recording_id).delete_run(module_id, stage_run_id)
    runs_store.delete_run(self._dir, run_id)

cancel_run(run_id)

Stop an active processing run: signal a live orchestrator (the on-disk cancel sentinel — works even after the app restarted), cancel each in-flight per-recording worker, and record each recording's real on-disk status. A recording the coordinator never launched is listed as cancelled (not run), so process retry picks it up. The run record becomes cancelled unless every planned recording actually completed (then complete — e.g. a worker that finished after the GUI was closed, so its results aren't hidden); see :func:roll_up_run_status. No-op once terminal.

Raises:

Type Description
FileNotFoundError

If no such run record exists.

Source code in detail/api/experiment.py
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
def cancel_run(self, run_id: str) -> None:
    """Stop an active processing run: signal a live orchestrator (the on-disk
    cancel sentinel — works even after the app restarted), cancel each in-flight
    per-recording worker, and record each recording's real on-disk status. A recording
    the coordinator never launched is listed as ``cancelled`` (not run), so ``process
    retry`` picks it up. The run record becomes ``cancelled`` unless every *planned*
    recording actually completed (then ``complete`` — e.g. a worker that finished after
    the GUI was closed, so its results aren't hidden); see :func:`roll_up_run_status`.
    No-op once terminal.

    Raises:
        FileNotFoundError: If no such run record exists.
    """
    record = runs_store.read_run(self._dir, run_id)
    if record.get("status") not in ACTIVE_STATUSES:
        return
    runs_store.request_cancel(
        self._dir, run_id
    )  # cooperative stop for the coordinator
    # Kill the coordinator so it can't launch the next recording before it notices
    # the flag; its own finalize and this record write both converge on cancelled.
    kill_coordinator(
        runs_store.run_dir(self._dir, run_id),
        runs_store.read_coordinator_pid(self._dir, run_id),
    )
    module_id = record["module_id"]
    per_recording = record.get("per_recording", {})
    for recording_id, info in per_recording.items():
        if info.get("status") not in ACTIVE_STATUSES:
            continue  # a recording that already finished keeps its real status
        stage_run_id = info.get("run_id")
        if stage_run_id is not None:
            info["status"] = self.get_recording(recording_id).cancel_run(
                module_id, stage_run_id
            )
        else:
            info["status"] = "cancelled"
    # Over the plan: a recording the coordinator never launched is listed as not run
    # (cancelled), so the run reads cancelled and `process retry` picks it up.
    record["status"] = roll_up_run_status(
        record.get("recording_ids") or [],
        per_recording,
        cancelled=True,
        unlaunched=(
            JobStatus.CANCELLED.value,
            "not run: the run was cancelled first",
        ),
    )
    record["per_recording"] = per_recording
    runs_store.write_run(self._dir, run_id, record)

cancel_model(model_id)

Stop an active model-training run (kill its worker), then record its real on-disk status — cancelled if killed, but complete if the worker actually finished (so a done run isn't mislabeled). No-op once terminal. Raises FileNotFoundError if the model doesn't exist.

Source code in detail/api/experiment.py
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
def cancel_model(self, model_id: str) -> None:
    """Stop an active model-training run (kill its worker), then record its real
    on-disk status — ``cancelled`` if killed, but ``complete`` if the worker
    actually finished (so a done run isn't mislabeled). No-op once terminal.
    Raises FileNotFoundError if the model doesn't exist."""
    mdir = models_store.model_dir(self._dir, model_id)
    record = models_store.read_model_yaml(mdir)  # FileNotFoundError if absent
    if record.get("status") not in ACTIVE_STATUSES:
        return
    cancel_run_dir(mdir)  # models/<id>/ is the run dir (job.json lives there)
    models_store.set_model_status(mdir, rundir.read_status(mdir).value)

stop_model(model_id)

Ask a training run to stop at its next epoch and keep what it has.

The counterpart to :meth:cancel_model, and the reason the two exist separately: cancel force-kills after three seconds, which on a run whose epochs take minutes means the worker dies mid-epoch and never writes weights.best or metrics into the record. The checkpoint file is on disk and nothing references it.

This only asks. The run stops at its next epoch boundary, runs its own completion path, and records the best weights it reached — which is what "the metrics look good, stop here" has to mean to be worth offering. The record's status stays as the worker leaves it (complete), because the run did finish, early.

No-op once terminal. Raises FileNotFoundError if the model does not exist.

Source code in detail/api/experiment.py
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
def stop_model(self, model_id: str) -> None:
    """Ask a training run to stop at its next epoch and **keep what it has**.

    The counterpart to :meth:`cancel_model`, and the reason the two exist separately: cancel
    force-kills after three seconds, which on a run whose epochs take minutes means the
    worker dies mid-epoch and never writes ``weights.best`` or ``metrics`` into the record.
    The checkpoint file is on disk and nothing references it.

    This only asks. The run stops at its next epoch boundary, runs its own completion path,
    and records the best weights it reached — which is what *"the metrics look good, stop
    here"* has to mean to be worth offering. The record's status stays as the worker leaves
    it (``complete``), because the run did finish, early.

    No-op once terminal. Raises FileNotFoundError if the model does not exist.
    """
    mdir = models_store.model_dir(self._dir, model_id)
    record = models_store.read_model_yaml(mdir)  # FileNotFoundError if absent
    if record.get("status") not in ACTIVE_STATUSES:
        return
    request_stop(mdir)

cancel_dataset(dataset_id)

Stop an active dataset-export run (kill its worker), then record its real on-disk status (cancelled if killed, complete if it finished). No-op once terminal. Raises FileNotFoundError if the dataset doesn't exist.

Source code in detail/api/experiment.py
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
def cancel_dataset(self, dataset_id: str) -> None:
    """Stop an active dataset-export run (kill its worker), then record its real
    on-disk status (``cancelled`` if killed, ``complete`` if it finished). No-op
    once terminal. Raises FileNotFoundError if the dataset doesn't exist."""
    ddir = datasets_store.dataset_dir(self._dir, dataset_id)
    record = datasets_store.read_dataset_yaml(ddir)  # FileNotFoundError if absent
    if record.get("status") not in ACTIVE_STATUSES:
        return
    cancel_run_dir(ddir)
    datasets_store.set_dataset_status(ddir, rundir.read_status(ddir).value)

attach_job_run(kind, run_id)

Reattach to a single-job run — a live one streams its worker's progress, a terminal one returns at once. Works from any process, after an app restart included: the worker is detached and its progress is on disk.

kind is a key of _JOB_RUN_KINDS. The typed wrappers below are what callers use; this is the shared body.

The runner modules are imported first, and that is not optional. A progress event is rebuilt from job.json by tag, and every tag outside core/dataclasses.py — every analysis module's, and the export's — is registered as a side effect of importing the module that defines it. Reattaching without that raises unknown progress event type the moment the first event is read. No test saw it because conftest's autouse _isolate_registries imports every runner into every test, so the registry is full in the suite and empty in a bare detail analysis attach.

Source code in detail/api/experiment.py
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
def attach_job_run(self, kind: str, run_id: str) -> AttachedJobRun:
    """Reattach to a single-job run — a live one streams its worker's progress, a
    terminal one returns at once. Works from any process, after an app restart
    included: the worker is detached and its progress is on disk.

    ``kind`` is a key of ``_JOB_RUN_KINDS``. The typed wrappers below are what callers
    use; this is the shared body.

    **The runner modules are imported first, and that is not optional.** A progress event is
    rebuilt from ``job.json`` by tag, and every tag outside `core/dataclasses.py` — every
    analysis module's, and the export's — is registered as a side effect of importing the
    module that defines it. Reattaching without that raises ``unknown progress event type``
    the moment the first event is read. No test saw it because ``conftest``'s autouse
    ``_isolate_registries`` imports every runner into every test, so the registry is full in
    the suite and empty in a bare ``detail analysis attach``.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    run_dir_for, read_record, set_status, _discover = self._JOB_RUN_KINDS[kind]
    run_dir = run_dir_for(self._dir, run_id)

    def finalize(rdir: Path, status: str) -> None:
        # On success the runner writes the full record, with its own detail;
        # `reconciled_status` is what decides when the envelope overrides it.
        adopted = reconciled_status(read_record(rdir).get("status"), status)
        if adopted is not None:
            set_status(rdir, adopted, rundir.read_envelope(rdir).get("error"))

    return AttachedJobRun(run_dir, run_id, finalize)

attach_active_job_run(kind, run_id)

An :class:AttachedJobRun when that run is still active, else None — so the GUI shows a live bar for a running one and a static record for a finished one. The single-job twin of :meth:attach_active_run.

Source code in detail/api/experiment.py
4390
4391
4392
4393
4394
4395
4396
def attach_active_job_run(self, kind: str, run_id: str) -> AttachedJobRun | None:
    """An :class:`AttachedJobRun` when that run is still active, else ``None`` — so the
    GUI shows a live bar for a running one and a static record for a finished one. The
    single-job twin of :meth:`attach_active_run`."""
    if self.job_run_active(kind, run_id):
        return self.attach_job_run(kind, run_id)
    return None

job_run_active(kind, run_id)

Whether that run's job is still working, whatever its record already claims.

The record is usually enough. An authored run (§21) is the exception: its runner writes open before the work that ends the job, so for that stretch the record says "ready to interpret" while the job is still writing what interpreting reads. Believed, the run page built the workspace mid-fit and its tabs read an artifact that did not exist yet ("no behavior_output.yaml"). So an authored status is checked against the job envelope, which is the one place that knows the job has not finished.

Source code in detail/api/experiment.py
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
def job_run_active(self, kind: str, run_id: str) -> bool:
    """Whether that run's job is still working, whatever its record already claims.

    The record is usually enough. An **authored** run (§21) is the exception: its runner
    writes ``open`` before the work that ends the job, so for that stretch the record says
    "ready to interpret" while the job is still writing what interpreting reads. Believed,
    the run page built the workspace mid-fit and its tabs read an artifact that did not
    exist yet ("no behavior_output.yaml"). So an authored status is checked against the job
    envelope, which is the one place that knows the job has not finished.
    """
    run_dir_for, read_record, _set, _discover = self._JOB_RUN_KINDS[kind]
    run_dir = run_dir_for(self._dir, run_id)
    try:
        status = read_record(run_dir).get("status")
    except FileNotFoundError:
        return False
    if status in ACTIVE_STATUSES:
        return True
    if status not in AUTHORED_STATUSES:
        return False
    try:
        return rundir.read_status(run_dir).value in ACTIVE_STATUSES
    except (FileNotFoundError, KeyError, ValueError):
        return False

analysis_job_active(run_id)

:meth:job_run_active for an analysis run.

Source code in detail/api/experiment.py
4423
4424
4425
def analysis_job_active(self, run_id: str) -> bool:
    """:meth:`job_run_active` for an analysis run."""
    return self.job_run_active("analysis", run_id)

attach_analysis_run(run_id)

Reattach to an analysis run by id (§16).

Source code in detail/api/experiment.py
4427
4428
4429
def attach_analysis_run(self, run_id: str) -> AttachedJobRun:
    """Reattach to an analysis run by id (§16)."""
    return self.attach_job_run("analysis", run_id)

attach_active_analysis_run(run_id)

A handle for a still-active analysis run, else None (§16).

Source code in detail/api/experiment.py
4431
4432
4433
def attach_active_analysis_run(self, run_id: str) -> AttachedJobRun | None:
    """A handle for a still-active analysis run, else ``None`` (§16)."""
    return self.attach_active_job_run("analysis", run_id)

attach_dataset_run(dataset_id)

Reattach to a dataset-export run by id (§12).

Source code in detail/api/experiment.py
4435
4436
4437
def attach_dataset_run(self, dataset_id: str) -> AttachedJobRun:
    """Reattach to a dataset-export run by id (§12)."""
    return self.attach_job_run("dataset", dataset_id)

attach_active_dataset_run(dataset_id)

A handle for a still-active dataset export, else None (§12).

Source code in detail/api/experiment.py
4439
4440
4441
def attach_active_dataset_run(self, dataset_id: str) -> AttachedJobRun | None:
    """A handle for a still-active dataset export, else ``None`` (§12)."""
    return self.attach_active_job_run("dataset", dataset_id)

attach_model_run(model_id)

Reattach to a training run by id (§12).

Source code in detail/api/experiment.py
4443
4444
4445
def attach_model_run(self, model_id: str) -> AttachedJobRun:
    """Reattach to a training run by id (§12)."""
    return self.attach_job_run("model", model_id)

attach_active_model_run(model_id)

A handle for a still-active training run, else None (§12).

Source code in detail/api/experiment.py
4447
4448
4449
def attach_active_model_run(self, model_id: str) -> AttachedJobRun | None:
    """A handle for a still-active training run, else ``None`` (§12)."""
    return self.attach_active_job_run("model", model_id)

attach_export_run(run_id)

Reattach to an export run by id (#354).

Source code in detail/api/experiment.py
4451
4452
4453
def attach_export_run(self, run_id: str) -> AttachedJobRun:
    """Reattach to an export run by id (#354)."""
    return self.attach_job_run("export", run_id)

attach_active_export_run(run_id)

A handle for a still-active export, else None (#354).

Source code in detail/api/experiment.py
4455
4456
4457
def attach_active_export_run(self, run_id: str) -> AttachedJobRun | None:
    """A handle for a still-active export, else ``None`` (#354)."""
    return self.attach_active_job_run("export", run_id)

reconcile_job_runs()

Fold every still-active single-job run's real on-disk status back into its record on experiment open — the SIGKILL backstop for analysis, dataset, model and export runs alike (§12/§16), beside :meth:reconcile_runs for processing runs.

Driven by _JOB_RUN_KINDS, so a fifth kind inherits the backstop by adding a table entry. Without it a killed worker leaves a record reading running forever, which also cannot be deleted — every delete method refuses an active record.

Source code in detail/api/experiment.py
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
def reconcile_job_runs(self) -> None:
    """Fold every still-active single-job run's real on-disk status back into its record
    on experiment open — the SIGKILL backstop for analysis, dataset, model and export
    runs alike (§12/§16), beside :meth:`reconcile_runs` for processing runs.

    Driven by ``_JOB_RUN_KINDS``, so a fifth kind inherits the backstop by adding a
    table entry. Without it a killed worker leaves a record reading ``running`` forever,
    which also cannot be deleted — every delete method refuses an active record.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    for kind, (_dir_for, _read, _set, discover) in self._JOB_RUN_KINDS.items():
        for run_id in discover(self._dir):
            self._reconcile_job_run(kind, run_id)

reconcile_analysis_runs()

The analysis slice of :meth:reconcile_job_runs — kept because callers name it, and because a caller that only touched analysis should not sweep every kind.

Source code in detail/api/experiment.py
4527
4528
4529
4530
4531
4532
def reconcile_analysis_runs(self) -> None:
    """The analysis slice of :meth:`reconcile_job_runs` — kept because callers name it,
    and because a caller that only touched analysis should not sweep every kind."""
    import_runner_modules(_PIPELINE_RUNNERS)
    for run_id in analysis_store.discover_analyses(self._dir):
        self._reconcile_job_run("analysis", run_id)

reconcile_analysis_run(run_id)

Reconcile one analysis run against its job envelope; True if the record moved.

One job.json read, so a surface can afford it on the way into a run's page rather than trusting a record last reconciled when the experiment was opened. That gap is real: a run that fails during a session keeps its optimistic record until something sweeps, and the surface that shows it is exactly the one about to offer its results.

Source code in detail/api/experiment.py
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
def reconcile_analysis_run(self, run_id: str) -> bool:
    """Reconcile one analysis run against its job envelope; ``True`` if the record moved.

    One ``job.json`` read, so a surface can afford it on the way into a run's page rather
    than trusting a record last reconciled when the experiment was opened. That gap is
    real: a run that fails *during* a session keeps its optimistic record until something
    sweeps, and the surface that shows it is exactly the one about to offer its results.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    return self._reconcile_job_run("analysis", run_id)

export_record(run_id)

The full record for one export run (for detail views).

Source code in detail/api/experiment.py
4592
4593
4594
4595
4596
def export_record(self, run_id: str) -> dict:
    """The full record for one export run (for detail views)."""
    return export_runs_store.read_export_yaml(
        export_runs_store.export_dir(self._dir, run_id)
    )

run_export(subject_kind, subject_id, target_ids, parent, *, scope=None, **options)

Export target_ids from a subject into a new folder under parent, as a run.

One request is one run, however many targets it covers: they share a destination folder and a manifest because that is what was asked for once. The targets become the run's units.

parent is resolved to a machine-local alias (storage/roots.py) before it reaches the job: everything in a job lands in the run record via runners.job_params, a record is .yaml, and an absolute path in one would make experiment.export refuse this experiment permanently (Tenet 6).

The folder name is minted here rather than in the worker so a surface can say where the files are going before the run starts.

Raises:

Type Description
ExportError

if a target is unknown, cannot run for this subject, or the request is one exporters.check_request refuses (a target twice, a scope a target does not take, a cluster or frame range the subject does not have).

ValueError

if options["theme"] is not a chart theme (light / dark).

Source code in detail/api/experiment.py
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
def run_export(
    self,
    subject_kind: str,
    subject_id: str,
    target_ids: Sequence[str],
    parent: Path | str,
    *,
    scope=None,
    **options,
) -> "ExportRun":
    """Export ``target_ids`` from a subject into a new folder under ``parent``, as a run.

    **One request is one run**, however many targets it covers: they share a destination
    folder and a manifest because that is what was asked for once. The targets become the
    run's units.

    ``parent`` is resolved to a machine-local alias (`storage/roots.py`) before it reaches
    the job: everything in a job lands in the run record via ``runners.job_params``, a record
    is ``.yaml``, and an absolute path in one would make ``experiment.export`` refuse this
    experiment permanently (Tenet 6).

    The folder name is minted here rather than in the worker so a surface can say where the
    files are going before the run starts.

    Raises:
        ExportError: if a target is unknown, cannot run for this subject, or the request is
            one ``exporters.check_request`` refuses (a target twice, a scope a target does
            not take, a cluster or frame range the subject does not have).
        ValueError: if ``options["theme"]`` is not a chart theme (``light`` / ``dark``).
    """
    from detail.api import exporters
    from detail.pipeline.export_run import EXPORT_ROOTS_KEY
    from detail.storage import roots

    import_runner_modules(_PIPELINE_RUNNERS)
    subject = exporters.ExportSubject(subject_kind, self._dir, subject_id)
    targets = [exporters.target(subject_kind, t) for t in target_ids]
    for target in targets:
        reason = exporters.unavailable_reason(target, subject)
        if reason is not None:
            raise exporters.ExportError(
                f"cannot export {target.label.lower()}: {reason}"
            )
    self._check_export_recordings(subject, scope)
    exporters.check_request(subject, targets, scope)
    if options.get("theme") is not None:
        from detail.core.chart_theme import theme as chart_theme

        # Refused here, where the caller can see it, rather than in the worker minutes later
        # as a failed run.
        chart_theme(options["theme"])

    parent = Path(parent).expanduser()
    parent.mkdir(parents=True, exist_ok=True)
    alias = roots.resolve_or_register(EXPORT_ROOTS_KEY, parent)
    rel = parent.resolve().relative_to(
        roots.root(EXPORT_ROOTS_KEY, alias).resolve()
    )

    run_id = export_runs_store.reserve_export_id(self._dir)
    job = ExportJob(
        job_id=run_id,
        subject_kind=subject_kind,
        subject_id=subject_id,
        target_ids=[t.id for t in targets],
        destination={"root": alias, "rel": rel.as_posix()},
        folder=exporters.folder_name(subject),
        created_at=utc_timestamp(),
        scope=_scope_dict(scope),
        options=dict(options),
    )
    # Written before submit so the run is discoverable while it runs, and so the runner's
    # completion write is always last — the worker can finish before this returns.
    rdir = export_runs_store.export_dir(self._dir, run_id)
    export_runs_store.write_export_yaml(
        rdir,
        {
            "id": run_id,
            "subject_kind": subject_kind,
            "subject_id": subject_id,
            "target_ids": [t.id for t in targets],
            "folder": job.folder,
            "destination": dict(job.destination),
            "params": job_params(job),
            "status": "running",
            "created_at": job.created_at,
        },
    )
    executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
    executor.submit(job)
    return ExportRun(ExecutorRunHandle(executor, run_id), self, run_id)

estimate_export(subject_kind, subject_id, target_ids, parent=None, *, scope=None, **options)

How big an export would be and how long it would take, without writing it.

The same arguments as :meth:run_export, and the answer is what the Export dialog and detail export run show before they start: an :class:exporters.ExportEstimate, one entry per target plus the free space on parent's drive. A video target times a few dozen frames on this machine to answer (about a second); everything else reads sizes and row counts from disk.

Raises:

Type Description
ExportError

if a target is unknown, scope names a recording the export does not span, or the request is one exporters.check_request refuses.

Source code in detail/api/experiment.py
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
def estimate_export(
    self,
    subject_kind: str,
    subject_id: str,
    target_ids: Sequence[str],
    parent: Path | str | None = None,
    *,
    scope=None,
    **options,
):
    """How big an export would be and how long it would take, without writing it.

    The same arguments as :meth:`run_export`, and the answer is what the Export dialog and
    ``detail export run`` show before they start: an :class:`exporters.ExportEstimate`, one
    entry per target plus the free space on ``parent``'s drive. A video target times a few
    dozen frames on this machine to answer (about a second); everything else reads sizes and
    row counts from disk.

    Raises:
        ExportError: if a target is unknown, ``scope`` names a recording the export does
            not span, or the request is one ``exporters.check_request`` refuses.
    """
    from detail.api import exporters

    subject = exporters.ExportSubject(subject_kind, self._dir, subject_id)
    targets = [exporters.target(subject_kind, t) for t in target_ids]
    scope = scope or exporters.ExportScope()
    self._check_export_recordings(subject, scope)
    exporters.check_request(subject, targets, scope)
    return exporters.estimate(
        subject, targets, scope=scope, parent=parent, **options
    )

cancel_export(run_id)

Stop an active export run. No-op once terminal.

Raises:

Type Description
FileNotFoundError

If the run doesn't exist.

Source code in detail/api/experiment.py
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
def cancel_export(self, run_id: str) -> None:
    """Stop an active export run. No-op once terminal.

    Raises:
        FileNotFoundError: If the run doesn't exist.
    """
    rdir = export_runs_store.export_dir(self._dir, run_id)
    record = export_runs_store.read_export_yaml(rdir)
    if record.get("status") not in ACTIVE_STATUSES:
        return
    cancel_run_dir(rdir)
    export_runs_store.set_export_status(rdir, rundir.read_status(rdir).value)

delete_export(run_id)

Delete an export run's record. Blocked while it is still active.

Deletes the record, never the exported files: those are in the user's own folder, outside the experiment, and forgetting a run is not a request to delete its output.

Source code in detail/api/experiment.py
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
def delete_export(self, run_id: str) -> None:
    """Delete an export run's record. Blocked while it is still active.

    Deletes the record, never the exported files: those are in the user's own folder,
    outside the experiment, and forgetting a run is not a request to delete its output.
    """
    record = export_runs_store.read_export_yaml(
        export_runs_store.export_dir(self._dir, run_id)
    )
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(
            f"export run {run_id!r} is still {record.get('status')}; cancel it first"
        )
    export_runs_store.delete_export(self._dir, run_id)

analysis_record(run_id)

The full analysis.yaml for one analysis run (for detail views).

Source code in detail/api/experiment.py
4780
4781
4782
4783
4784
def analysis_record(self, run_id: str) -> dict:
    """The full ``analysis.yaml`` for one analysis run (for detail views)."""
    return analysis_store.read_analysis_yaml(
        analysis_store.analysis_dir(self._dir, run_id)
    )

analysis_run_dir(run_id)

The on-disk output directory for an analysis run (analysis/<run_id>/) — for opening it in a file manager.

Source code in detail/api/experiment.py
4786
4787
4788
4789
def analysis_run_dir(self, run_id: str) -> Path:
    """The on-disk output directory for an analysis run (``analysis/<run_id>/``)
    — for opening it in a file manager."""
    return analysis_store.analysis_dir(self._dir, run_id)

location_plots(run_id)

Plots of a completed location-export run (DESIGN_PLAN §16 "Location plots"): its animals' paths, occupancy, speed and body, drawn from the run's own CSVs.

Returns:

Type Description
LocationPlots

A LocationPlots: build(view) for a PlotSpec, export(view, stem)

LocationPlots

for files.

Raises:

Type Description
ValueError

The run is not a location export, or has no completed recording.

Source code in detail/api/experiment.py
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
def location_plots(self, run_id: str) -> "LocationPlots":
    """Plots of a completed location-export run (DESIGN_PLAN §16 "Location plots"): its
    animals' paths, occupancy, speed and body, drawn from the run's own CSVs.

    Returns:
        A ``LocationPlots``: ``build(view)`` for a ``PlotSpec``, ``export(view, stem)``
        for files.

    Raises:
        ValueError: The run is not a location export, or has no completed recording.
    """
    from detail.api.location_plots import LocationPlots

    return LocationPlots(self, run_id)

run_analysis(module_id, config)

Launch an experiment-scoped analysis run (§16): one module over a selection of recordings, producing artifacts in analysis/<run_id>/. A single executor job (not a per-recording fan-out). Returns a run handle.

Raises:

Type Description
ValueError

If the module is unknown or config validation fails.

Source code in detail/api/experiment.py
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
def run_analysis(self, module_id: str, config: dict) -> AnalysisRun:
    """Launch an experiment-scoped analysis run (§16): one module over a selection
    of recordings, producing artifacts in ``analysis/<run_id>/``. A single
    executor job (not a per-recording fan-out). Returns a run handle.

    Raises:
        ValueError: If the module is unknown or config validation fails.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    module = ANALYSIS_MODULES.get(module_id)
    if module is None:
        raise ValueError(f"unknown analysis module: {module_id!r}")
    config = module.validate(self._dir, dict(config))
    run_id = analysis_store.reserve_analysis_id(self._dir)
    job = module.build_job(run_id, config)
    # An initial record so the run is discoverable while it runs, written
    # *before* submit so the runner's completion write (full record) is always
    # last — never clobbered by this one (the worker can finish fast).
    adir = analysis_store.analysis_dir(self._dir, run_id)
    adir.mkdir(parents=True, exist_ok=True)
    analysis_store.write_analysis_yaml(
        adir,
        {
            "id": run_id,
            "module_id": module_id,
            "recording_ids": config.get("source_recording_ids", []),
            "status": "running",
            "created_at": utc_timestamp(),
        },
    )
    executor = LocalExecutor(self._dir, runner_modules=_PIPELINE_RUNNERS)
    executor.submit(job)  # run_dir = analysis/<run_id>/; writes job.json there
    return AnalysisRun(ExecutorRunHandle(executor, run_id), self, run_id)

run_comparison(config, *, progress=None, stop_check=None)

Run a §24 comparison — group statistics across recording metadata — and save it.

Source code in detail/api/experiment.py
4840
4841
4842
4843
4844
def run_comparison(self, config, *, progress=None, stop_check=None):
    """Run a §24 comparison — group statistics across recording metadata — and save it."""
    from detail.api.comparison import run_comparison

    return run_comparison(self, config, progress=progress, stop_check=stop_check)

get_comparison(comparison_id)

Handle for an existing comparison in this experiment.

Source code in detail/api/experiment.py
4846
4847
4848
4849
4850
def get_comparison(self, comparison_id: str):
    """Handle for an existing comparison in this experiment."""
    from detail.api.comparison import Comparison

    return Comparison(self, comparison_id)

measures(run_id)

The §23 measures of one analysis run's behavior artifact (§19).

Source code in detail/api/experiment.py
4852
4853
4854
4855
4856
def measures(self, run_id: str):
    """The §23 measures of one analysis run's behavior artifact (§19)."""
    from detail.api.measures import Measures

    return Measures(self, run_id)

authored_run(run_id)

The §21 handle for an authored run, or None if this run is not one.

A computed run (a location export, an eval) has no authored state and pins nothing, so it has no handle of this kind — the caller shows no snapshot surface rather than an empty one.

Source code in detail/api/experiment.py
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
def authored_run(self, run_id: str):
    """The §21 handle for an authored run, or ``None`` if this run is not one.

    A computed run (a location export, an eval) has no authored state and pins nothing, so it
    has no handle of this kind — the caller shows no snapshot surface rather than an empty one.
    """
    try:
        record = self.analysis_record(run_id)
    except (FileNotFoundError, KeyError):
        return None
    accessor = self._AUTHORED_RUN_ACCESSORS.get(record.get("module_id"))
    if accessor is None:
        return None
    try:
        return getattr(self, accessor)(run_id)
    except (KeyError, ValueError, FileNotFoundError):
        return None

comparisons_using(run_id)

{snapshot_id: [comparison_id, ...]} for one analysis run's pinned artifacts.

Derived, never stored. A snapshot records why it was taken but not what consumed it: an export has no stable identifier to keep (its path lies outside the experiment, and an absolute path in an experiment file is a hard rule), and a comparison id does not exist until after the pin. So the link is read back off the consumers, which is also the §21 rule that a fact checkable from the store gets no second writer.

One pass over comparisons/, which holds tens of records in a real experiment rather than thousands. Records written before source_snapshot existed carry none and are skipped rather than guessed at.

Source code in detail/api/experiment.py
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
def comparisons_using(self, run_id: str) -> dict[str, list[str]]:
    """``{snapshot_id: [comparison_id, ...]}`` for one analysis run's pinned artifacts.

    **Derived, never stored.** A snapshot records why it was taken but not what consumed it:
    an export has no stable identifier to keep (its path lies outside the experiment, and an
    absolute path in an experiment file is a hard rule), and a comparison id does not exist
    until after the pin. So the link is read back off the consumers, which is also the §21 rule
    that a fact checkable from the store gets no second writer.

    One pass over ``comparisons/``, which holds tens of records in a real experiment rather
    than thousands. Records written before ``source_snapshot`` existed carry none and are
    skipped rather than guessed at.
    """
    from detail.storage import comparisons as comparisons_store

    out: dict[str, list[str]] = {}
    for cid in comparisons_store.discover_comparisons(self._dir):
        try:
            record = comparisons_store.read_comparison_yaml(
                comparisons_store.comparison_dir(self._dir, cid)
            )
        except dirscan.UNREADABLE_RECORD_ERRORS:
            continue  # a half-written or foreign folder is not a comparison
        if not isinstance(record, dict) or record.get("source_run_id") != run_id:
            continue
        snapshot = record.get("source_snapshot")
        if snapshot:
            out.setdefault(str(snapshot), []).append(cid)
    return out

delete_comparison(comparison_id)

Delete a comparison and everything it wrote, exports included.

Raises:

Type Description
FileNotFoundError

no comparison with that id.

Source code in detail/api/experiment.py
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
def delete_comparison(self, comparison_id: str) -> None:
    """Delete a comparison and everything it wrote, exports included.

    Raises:
        FileNotFoundError: no comparison with that id.
    """
    from detail.storage import comparisons as comparisons_store

    if comparison_id not in comparisons_store.discover_comparisons(self._dir):
        raise FileNotFoundError(
            f"no comparison {comparison_id!r} in {self._dir}; "
            f"have {comparisons_store.discover_comparisons(self._dir)}"
        )
    comparisons_store.delete_comparison(self._dir, comparison_id)

query_run(run_id)

Reopen an existing §20 Query run as a QueryRun handle (no active search job) — for calibrating a cutoff, naming a behavior, or exporting the artifact.

The way a searched run is reached to be calibrated: the search leaves the run open rather than complete, and the whole of calibration happens through this handle.

Source code in detail/api/experiment.py
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
def query_run(self, run_id: str):
    """Reopen an existing §20 Query run as a ``QueryRun`` handle (no active search job) —
    for calibrating a cutoff, naming a behavior, or exporting the artifact.

    The way a searched run is reached to be calibrated: the search leaves the run ``open``
    rather than ``complete``, and the whole of calibration happens through this handle.
    """
    from detail.api.query import QueryRun

    self._require_analysis_run(run_id, "query")
    return QueryRun(None, self, run_id)

temporal_clustering_run(run_id)

Reopen an existing §22 temporal-clustering run as a TemporalClusteringRun handle (no active fit job) — for choosing a granularity, naming clusters, or exporting.

The way a fitted run is reached to be interpreted: the fit leaves the run open rather than complete, and the whole of interpretation happens through this handle.

Source code in detail/api/experiment.py
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
def temporal_clustering_run(self, run_id: str):
    """Reopen an existing §22 temporal-clustering run as a ``TemporalClusteringRun`` handle
    (no active fit job) — for choosing a granularity, naming clusters, or exporting.

    The way a fitted run is reached to be interpreted: the fit leaves the run ``open`` rather
    than ``complete``, and the whole of interpretation happens through this handle.
    """
    from detail.api.temporal_clustering import TemporalClusteringRun

    self._require_analysis_run(run_id, "temporal-clustering")
    return TemporalClusteringRun(None, self, run_id)

cancel_analysis(run_id)

Stop an active analysis run (kill its worker), then record its real on-disk status (cancelled if killed, complete if it finished). No-op once terminal. Raises FileNotFoundError if the run doesn't exist.

Source code in detail/api/experiment.py
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
def cancel_analysis(self, run_id: str) -> None:
    """Stop an active analysis run (kill its worker), then record its real
    on-disk status (``cancelled`` if killed, ``complete`` if it finished). No-op
    once terminal. Raises FileNotFoundError if the run doesn't exist."""
    adir = analysis_store.analysis_dir(self._dir, run_id)
    record = analysis_store.read_analysis_yaml(adir)  # FileNotFoundError if absent
    if record.get("status") not in ACTIVE_STATUSES:
        return
    cancel_run_dir(adir)
    analysis_store.set_analysis_status(adir, rundir.read_status(adir).value)

delete_analysis(run_id)

Delete an analysis run (its analysis/<run_id>/ directory).

A completed analysis run is self-contained (it copied the derived values into its own CSVs), so it never blocks deleting its source runs — the analogue of the dataset/model lineage-dangle. Blocked only while the run is still active.

Raises:

Type Description
FileNotFoundError

If no such analysis run exists.

ValueError

If the run is still active.

Source code in detail/api/experiment.py
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
def delete_analysis(self, run_id: str) -> None:
    """Delete an analysis run (its ``analysis/<run_id>/`` directory).

    A *completed* analysis run is self-contained (it copied the derived values
    into its own CSVs), so it never blocks deleting its source runs — the
    analogue of the dataset/model lineage-dangle. Blocked only while the run is
    still active.

    Raises:
        FileNotFoundError: If no such analysis run exists.
        ValueError: If the run is still active.
    """
    record = analysis_store.read_analysis_yaml(  # FileNotFoundError if absent
        analysis_store.analysis_dir(self._dir, run_id)
    )
    if record.get("status") in ACTIVE_STATUSES:
        raise ValueError(
            f"analysis run {run_id!r} is still active — cancel it first"
        )
    analysis_store.delete_analysis(self._dir, run_id)

set_hf_token(token)

Validate and store the Hugging Face token; return the account name.

Writes the machine-global ~/.config/detail/credentials.yaml (not experiment state), exposed here as the single API boundary (Tenet 2).

Source code in detail/api/experiment.py
5010
5011
5012
5013
5014
5015
5016
def set_hf_token(self, token: str) -> str:
    """Validate and store the Hugging Face token; return the account name.

    Writes the machine-global ``~/.config/detail/credentials.yaml`` (not
    experiment state), exposed here as the single API boundary (Tenet 2).
    """
    return credentials.set_hf_token(token)

check_model_access(model_id, variant=None)

Proactive readiness for a model — drives 'set up access' UI states.

Source code in detail/api/experiment.py
5020
5021
5022
5023
5024
def check_model_access(
    self, model_id: str, variant: str | None = None
) -> ModelReadiness:
    """Proactive readiness for a model — drives 'set up access' UI states."""
    return api_models.model_readiness(model_id, variant)

install_model(model_id, progress_cb=None, *, variant=None)

Ensure a model's weights are present; raises ModelNotReadyError if blocked.

variant picks the size — each is a separate download (§5).

Source code in detail/api/experiment.py
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
def install_model(
    self,
    model_id: str,
    progress_cb: Callable[[InstallProgress], None] | None = None,
    *,
    variant: str | None = None,
) -> None:
    """Ensure a model's weights are present; raises ModelNotReadyError if blocked.

    ``variant`` picks the size — each is a separate download (§5)."""
    api_models.install_model(model_id, progress_cb, variant=variant)

import_model(weights_path, *, family=None, skeleton=None, name=None, made_by=None, description=None, notes=None, preview=None)

Import an external checkpoint into the machine-global catalog — usable in any experiment. A pose checkpoint lands as a keypoint model and needs skeleton (a preset, library id or skeleton YAML) that fits it; see :func:detail.api.models.import_model. Optional made_by / description / notes / preview are stored as catalog metadata (§12). Returns the assigned id.

Source code in detail/api/experiment.py
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
def import_model(
    self,
    weights_path: Path | str,
    *,
    family: str | None = None,
    skeleton=None,
    name: str | None = None,
    made_by: str | None = None,
    description: str | None = None,
    notes: str | None = None,
    preview: Path | str | None = None,
) -> str:
    """Import an external checkpoint into the machine-global catalog — usable in *any*
    experiment. A pose checkpoint lands as a keypoint model and needs ``skeleton`` (a
    preset, library id or skeleton YAML) that fits it; see
    :func:`detail.api.models.import_model`. Optional ``made_by`` / ``description`` /
    ``notes`` / ``preview`` are stored as catalog metadata (§12). Returns the assigned
    id."""
    return api_models.import_model(
        weights_path,
        family=family,
        skeleton=skeleton,
        name=name,
        made_by=made_by,
        description=description,
        notes=notes,
        preview=preview,
    )

remove_imported_model(model_id)

Delete a machine-global imported model (raises if absent).

Source code in detail/api/experiment.py
5072
5073
5074
def remove_imported_model(self, model_id: str) -> None:
    """Delete a machine-global imported model (raises if absent)."""
    api_models.remove_imported_model(model_id)

detail.api.recording.Recording

Source code in detail/api/recording.py
 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
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
class Recording:
    def __init__(self, experiment_dir: Path | str, recording_id: str) -> None:
        self._experiment_dir = Path(experiment_dir)
        self.id = recording_id
        self.name = recording_store.read_recording(self.dir)["name"]

    @property
    def dir(self) -> Path:
        return experiment_store.recording_path(self._experiment_dir, self.id)

    @property
    def import_status(self) -> str:
        """``ready`` | ``queued`` | ``importing`` | ``failed`` | ``cancelled`` —
        defaults to ``ready`` for recordings created before the field existed (and
        for ones with no deferred import work)."""
        return recording_store.read_recording(self.dir).get("import_status", "ready")

    @property
    def video_available(self) -> bool:
        """True iff the recording has video parts **and** all their files are present
        on disk. False for a video-excluded export (entries + timestamps kept, the
        ``.mp4`` blobs absent) — preview surfaces check this to degrade gracefully
        instead of failing to decode."""
        files = (
            recording_store.read_recording(self.dir).get("video", {}).get("files", [])
        )
        return bool(files) and all(self._part_present(f) for f in files)

    def _part_present(self, part: dict) -> bool:
        """Whether one part's pixels are reachable on this machine.

        A reference-in-place part resolves through the machine-local video-root registry,
        which *raises* when the alias is not registered (a cross-machine export, a reset
        storage.yaml) — while a merely missing file just resolves to an absent path. Both
        mean "not reachable here", so both answer False: this is the presence gate, and
        every caller of :attr:`video_available` treats it as a question, not an assertion.
        The raise is left in place for the readers that actually need the pixels — they
        must fail loudly rather than silently skip a recording.
        """
        try:
            return recording_store.resolve_part_video_path(self.dir, part).is_file()
        except video_roots.MissingVideoRootError:
            return False

    def add_video_part(
        self,
        path: Path | str,
        storage: str = "default",
        video_root: str | None = None,
        progress: Callable[[str, float, str], None] | None = None,
        should_stop: Callable[[], bool] | None = None,
    ) -> None:
        """Import a video file as the next part: register it with the recording,
        generate its timestamp map, and append it to ``recording.yaml`` (Section 3).

        The source is **copied in** verbatim, so the recording holds the footage at its
        original rate and resolution — a stage that wants fewer frames sets a
        ``every_n_frames`` on the run (§4), which needs no second copy. With
        ``storage="reference"`` the part is **referenced in place**: the video is *not*
        copied; the recording stores its location (a ``{root, rel}`` reference — the seam a
        remote backend plugs into) plus a content fingerprint, so a moved or changed file can
        be detected (Section 2). ``video_root`` is optional — when omitted, the video's own
        folder is remembered automatically (the caller references a path, never picks a
        location). The external source is only read, never modified. ``t_ns`` is each frame's
        time, global across parts (offset by the cumulative duration before it, Tenet 8).

        Raises:
            FileNotFoundError: If ``path`` is not a file.
            ValueError: If a reference import is missing/mismatched against its video root.
            UserInputError: If the video's resolution or frame rate is not the recording's.
                Every part of a recording shares both (§3): boxes, masks and calibrations are
                in its pixels, and a detection run decodes every part's masks at one size.
        """
        src = Path(path)
        if not src.is_file():
            raise FileNotFoundError(f"video file not found: {path}")
        reference = storage == "reference"
        rel: str | None = None
        data = recording_store.read_recording(self.dir)
        video = data.get("video") or {"storage": storage, "files": []}

        index = len(video["files"])
        part_name = f"part_{index + 1:03d}"
        # Checked before a referenced file's folder is registered as a video root: a part
        # refused here leaves nothing behind, on the machine or in the experiment.
        probe = video_store.probe_video(src)
        if video["files"] and video.get("resolution"):
            # A recording written before its rate was recorded is held to its size alone.
            first = {
                "resolution": video["resolution"],
                "fps": video.get("fps_container") or probe["fps"],
            }
            differs = video_integrity.another_parts_shape(first, probe)
            if differs is not None:
                raise UserInputError(
                    f"{src.name} cannot be another part of this recording: {differs}. "
                    "Every part of a recording has one picture size and one frame rate; "
                    "add it as a recording of its own."
                )
        if reference:
            if video_root is None:
                # No location given (the GUI/CLI default): remember the video's own folder
                # automatically — the user references a path, never picks a location.
                video_root = video_roots.resolve_or_register_root(src)
            root_dir = video_roots.video_root(video_root)
            if root_dir is None:
                raise ValueError(
                    f"video root {video_root!r} is not registered; register it with "
                    f"`detail video-root set {video_root} <path>`"
                )
            try:
                rel = src.resolve().relative_to(root_dir.resolve()).as_posix()
            except ValueError:
                raise ValueError(
                    f"video {src} is not under video root {video_root!r} ({root_dir})"
                )
        fps = probe["fps"]
        # Integer ns from the parts' own maps, each re-based to start at 0 — the
        # offset is the only thing that places this part in the recording (Tenet 8).
        offset_ns = recording_store.video_end_ns(self.dir, data)
        dest = self.dir / "video" / f"{part_name}.mp4"
        on_timestamps = (
            (lambda f: progress(STAGE_TIMESTAMPS, f, ""))
            if progress is not None
            else None
        )
        try:
            if reference:
                # Reference in place: read the source's timestamps, never copy it.
                local_t_ns = video_store.generate_timestamps(
                    src, fps, progress=on_timestamps
                )
                eff_fps = fps
                eff_resolution = probe["resolution"]
            else:
                local_t_ns = video_store.generate_timestamps(
                    src, fps, progress=on_timestamps
                )
                on_bytes = (
                    (lambda d, t: progress(STAGE_COPYING, d / t, _size_label(d, t)))
                    if progress is not None
                    else None
                )
                video_store.copy_with_progress(
                    src, dest, progress=on_bytes, should_stop=should_stop
                )
                eff_fps = fps
                eff_resolution = probe["resolution"]
        except video_store.ImportStopped:
            dest.unlink(missing_ok=True)  # remove the partial part; no entry written
            raise
        t_ns = local_t_ns + offset_ns
        # Measured, not len/advertised-fps: the PTS map was demuxed precisely so this
        # number is real, and it sets every later part's offset (see offset_ns above).
        duration_s = video_store.part_duration_ns(local_t_ns, eff_fps) / (
            video_store.NS_PER_SECOND
        )

        ts_rel = f"video/timestamps/generated/{part_name}.csv"
        recording_store.write_timestamps_csv(self.dir / ts_rel, t_ns)

        if index == 0:
            video.update(
                fps_container=fps,
                fps_actual=eff_fps,
                fps_source="container",
                resolution=eff_resolution,
                total_duration_s=0.0,
            )
        entry = {
            "index": index,
            "id": part_name,  # stable stem for zarr/progress names (Section 3)
            "timestamps": {"generated": ts_rel, "user": None, "active": "generated"},
        }
        if reference:
            # No absolute path in the experiment file (Tenet 6): the location is a
            # {root, rel} reference resolved through the machine-local video-root
            # registry, plus a content fingerprint to detect a moved/changed file.
            entry["source"] = {"root": video_root, "rel": rel}
            entry["fingerprint"] = integrity.file_fingerprint(src)
            entry["frame_count"] = len(t_ns)
        else:
            entry["file"] = f"video/{part_name}.mp4"
            # Where this was copied *from*, in the same {root, rel} shape a referenced
            # part uses (Tenet 6 — the absolute path is composed at display time, never
            # stored). Provenance rather than a location: the tool owns the copy, so
            # nothing reads this to find pixels, but "which file was this?" still needs an
            # answer once the name has been edited away from the filename.
            #
            # Deliberately **not** ``source``: ``resolve_part_video_path`` keys on that to
            # decide where a part's frames live, so reusing it would send every read to
            # the external original instead of the copy — deleting the original would then
            # break runs we hold the footage for.
            origin_root = video_roots.resolve_or_register_root(src)
            origin_dir = video_roots.video_root(origin_root)
            entry["origin"] = {
                "root": origin_root,
                "rel": src.resolve().relative_to(origin_dir.resolve()).as_posix(),
            }
            # The copy's own fingerprint, in the shape a referenced part records: what
            # putting the video back after a slim import checks a candidate file against
            # (`relink_video_part`). Taken from the copy, which is the file the tool holds.
            entry["fingerprint"] = integrity.file_fingerprint(dest)
        video["files"].append(entry)
        video["total_duration_s"] += duration_s
        data["video"] = video
        recording_store.write_recording(self.dir, data)

    def verify_videos(self) -> list[video_integrity.VideoIssue]:
        """Check every video part is present and (for referenced parts) unchanged (Section 2).

        Returns the list of integrity issues (empty means all good) — the same check the run
        pre-flight gate enforces, exposed so a user can check without launching a run.
        """
        data = recording_store.read_recording(self.dir)
        return video_integrity.validate_source_videos(self.dir, data)

    def relink_video_part(
        self,
        part_index: int,
        new_path: Path | str,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> str | None:
        """Point a part at its video file again: Locate video, and ``recording relink``.

        **A referenced part** is pointed at a moved or renamed file, verified by fingerprint:
        the new file's content fingerprint must match what was recorded. A mismatch means the
        content *changed*, not just moved, and is refused (remove and re-add the recording
        instead). The new path need not be under a registered video root: one is registered
        for it, the way an import does. When the part's own root is not registered on this
        machine (an experiment made elsewhere) and the file sits where that root would put it,
        the root itself is registered, so every other recording referencing it resolves too.

        **A copied part whose file is missing** (an experiment imported from a bundle without
        its video, or replaced by one) has the file **copied back in** to its
        ``video/part_NNN.mp4``; the part stays a copied part. The file is accepted only if
        its frame times match the part's recorded timestamp map exactly (count and every
        ``t_ns``, both re-based to start at 0) and its resolution matches the recording's,
        and, for a part that recorded a fingerprint, only if that matches too. The copy goes
        to a sibling temporary file moved into place when complete, so a cancel (``progress``
        raising) leaves no half file. A copied part whose file is present is refused: there
        is nothing to put back.

        ``progress(stage, fraction, detail)`` reports a put-back's two long steps,
        :data:`STAGE_TIMESTAMPS` then :data:`STAGE_COPYING`. A referenced relink reads two
        MiB and reports nothing.

        Returns:
            The video-root alias this call registered on this machine, or ``None`` if it
            used one that was already registered (always ``None`` for a copied part).

        Raises:
            FileNotFoundError: ``new_path`` is not a file.
            IndexError: ``part_index`` is out of range.
            ValueError: the content differs from a referenced part's.
            UserInputError: a copied part's video is already here, or the file is not that
                part's video (it names what differs).
        """
        new = Path(new_path)
        if not new.is_file():
            raise FileNotFoundError(f"video file not found: {new_path}")
        data = recording_store.read_recording(self.dir)
        files = data.get("video", {}).get("files", [])
        if not (0 <= part_index < len(files)):
            raise IndexError(f"part_index {part_index} out of range [0, {len(files)})")
        part = files[part_index]
        if part.get("source") is None:
            self._put_back_copied_part(part_index, data, new, progress)
            return None
        current = integrity.file_fingerprint(new)
        if not integrity.same_content(current, part.get("fingerprint")):
            raise ValueError(
                f"{new} has different content than the recorded video — it is a changed or "
                "different video, not a move; remove and re-add the recording to use it"
            )
        alias, rel, registered = _relink_root(new, part["source"])
        part["source"] = {"root": alias, "rel": rel}
        part["fingerprint"] = current  # a moved/renamed file may have a fresh mtime
        recording_store.write_recording(self.dir, data)
        return registered

    def _put_back_copied_part(
        self,
        part_index: int,
        data: dict,
        new: Path,
        progress: Callable[[str, float, str], None] | None,
    ) -> None:
        """Copy ``new`` in as copied part ``part_index``'s missing file (`relink_video_part`)."""
        part = data["video"]["files"][part_index]
        stem = recording_store.part_stem(part)
        dest = self.dir / part["file"]
        if dest.is_file():
            raise UserInputError(
                f"part {part_index} ({stem}) is a copied part and its video is already "
                f"here ({dest}): there is nothing to put back"
            )
        wrong = f"{new} is not the video of part {part_index} ({stem})"
        recorded = part.get("fingerprint")
        if recorded and not integrity.same_content(
            integrity.file_fingerprint(new), recorded
        ):
            raise UserInputError(
                f"{wrong}: its content differs from the file that was copied in"
            )
        try:
            probe = video_store.probe_video(new)
        except (OSError, ValueError) as exc:
            raise UserInputError(f"{wrong}: it cannot be read as a video ({exc})")
        on_timestamps = (
            (lambda f: progress(STAGE_TIMESTAMPS, f, ""))
            if progress is not None
            else None
        )
        candidate = video_store.generate_timestamps(
            new, probe["fps"], progress=on_timestamps
        )
        stored = recording_store.TimestampMap.from_csv(
            self.dir / part["timestamps"]["generated"]
        )
        differs = video_integrity.part_video_mismatch(
            stored.values,
            candidate,
            recorded_resolution=data["video"].get("resolution"),
            resolution=probe["resolution"],
        )
        if differs is not None:
            raise UserInputError(f"{wrong}: {differs}")
        dest.parent.mkdir(parents=True, exist_ok=True)
        staging = dest.with_name(f"{dest.name}.{uuid.uuid4().hex}.tmp")
        on_bytes = (
            (
                lambda d, t: progress(
                    STAGE_COPYING, d / t if t else 1.0, _size_label(d, t)
                )
            )
            if progress is not None
            else None
        )
        try:
            video_store.copy_with_progress(new, staging, progress=on_bytes)
            atomic.replace(staging, dest)
        except BaseException:
            # A cancel raises out of the progress callback mid-copy; nothing half-copied stays.
            staging.unlink(missing_ok=True)
            raise
        # Re-read: the copy can take minutes, and the recording may have been edited meanwhile.
        fresh = recording_store.read_recording(self.dir)
        for entry in fresh["video"]["files"]:
            if entry.get("id") == part.get("id") and entry.get("file") == part["file"]:
                entry["fingerprint"] = integrity.file_fingerprint(dest)
        recording_store.write_recording(self.dir, fresh)

    def parts_to_locate(self) -> list["LocatablePart"]:
        """The parts Locate video can act on: every referenced part, and each copied part
        whose file is not here, with the file it was copied from when that is on this machine.

        Reads the recording's parts, a ``stat`` per copied part, and resolves each missing
        copied part's ``origin``, which can be a network share: call it off the UI thread.
        """
        data = recording_store.read_recording(self.dir)
        out = []
        for position, part in enumerate(recording_store.video_files(data)):
            stem = recording_store.part_stem(part)
            if part.get("source") is not None:
                out.append(LocatablePart(position, stem, copied=False))
                continue
            if (self.dir / part["file"]).is_file():
                continue
            out.append(
                LocatablePart(
                    position,
                    stem,
                    copied=True,
                    copied_from=_copied_from(part.get("origin")),
                    origin_name=Path((part.get("origin") or {}).get("rel", "")).name,
                )
            )
        return out

    def define_arena(
        self,
        name: str,
        keyframes: list[tuple[int, list[tuple[float, float]]]],
    ) -> str:
        """Define a named arena polygon (Section 10).

        Each keyframe is ``(frame_idx, [(x, y), ...])`` with recording-global
        ``frame_idx`` (0 = first frame of part_001) and normalized vertices in
        ``[0, 1]``. All keyframes must have the same vertex count.

        Returns:
            The auto-assigned stable arena id (e.g. ``"arena_001"``) — this is
            what ``TrackingJob.arena_ids`` refers to.

        Raises:
            ValueError: If keyframes are invalid (see
                ``storage.spatial.write_arena_keyframes``) or the name is empty
                or already in use within this recording.
        """
        arena_id = spatial_store.next_arena_id(self.dir)
        n_vertices = spatial_store.write_arena_keyframes(self.dir, arena_id, keyframes)
        spatial_store.append_arena_to_recording_yaml(
            self.dir, arena_id, name, n_vertices
        )
        return arena_id

    def arena_dependents(self, arena_id: str) -> list[str]:
        """Tracking run ids that used ``arena_id`` — editing or removing the arena
        would make their recorded region inconsistent, so it is blocked while any
        exist (delete those runs first)."""
        data = recording_store.read_recording(self.dir)
        return [
            t["id"]
            for t in data.get("tracking_runs", [])
            if arena_id in (t.get("arena_ids") or [])
        ]

    def arena_keyframes(
        self, arena_id: str
    ) -> list[tuple[int, list[tuple[float, float]]]]:
        """The arena's polygon keyframes as ``[(frame_idx, [(x, y), ...]), ...]``
        (normalized vertices), e.g. to reload it into the editor.

        Raises:
            ValueError: If no arena with this id exists in the recording.
        """
        arenas = {a["id"]: a for a in self.arenas}
        if arena_id not in arenas:
            raise ValueError(f"unknown arena_id {arena_id!r}")
        # Cached on the CSV's own mtime. The spatial map reads one of these **per recording**
        # every time a result page opens, which at a hundred recordings is a hundred CSV parses
        # for a polygon that changes only when somebody edits the arena. The keyframes are
        # rebuilt into fresh lists below, so a hit hands nobody a shared mutable.
        path = spatial_store.arena_keyframes_path(self.dir, arena_id)
        pk = read_cache.cached_read(
            ("arena_keyframes", str(self.dir), arena_id),
            path,
            lambda: spatial_store.read_arena_keyframes(
                self.dir, arena_id, arenas[arena_id]["n_vertices"]
            ),
        )
        return [
            (int(frame), [(float(x), float(y)) for x, y in verts])
            for frame, verts in pk.keyframes
        ]

    def clear_arenas(self) -> None:
        """Remove all arenas (keyframes + recording.yaml entries) so the recording's
        single arena can be redrawn. Already-computed runs are unaffected.

        Raises:
            ValueError: If a tracking run used one of the arenas (see
                ``arena_dependents``) — delete that run first.
        """
        arenas = recording_store.read_recording(self.dir).get("arenas", [])
        blocked = {
            a["id"]: deps for a in arenas if (deps := self.arena_dependents(a["id"]))
        }
        if blocked:
            detail = "; ".join(f"{aid} ← {deps}" for aid, deps in blocked.items())
            raise ValueError(
                f"cannot edit/clear arena(s) used by tracking runs: {detail} "
                "— delete those runs first"
            )
        for arena in arenas:
            spatial_store.delete_arena(self.dir, arena["id"])

    def delete_arena(self, arena_id: str) -> None:
        """Remove a single arena (keyframes + recording.yaml entry). Already-computed
        runs are unaffected — the polygon was applied at run time.

        Raises:
            ValueError: If a tracking run used this arena (see ``arena_dependents``)
                — delete that run first.
        """
        deps = self.arena_dependents(arena_id)
        if deps:
            raise ValueError(
                f"cannot delete arena {arena_id!r} used by tracking runs: {deps} "
                "— delete those runs first"
            )
        spatial_store.delete_arena(self.dir, arena_id)

    # --- ROIs and POIs (Section 10, analysis-time) -------------------------- #
    # Regions of interest (polygons) and points of interest (single points) are
    # analysis-time definitions: unlike arenas they do NOT affect detection or
    # tracking, so there is no run-lock and delete is unconditional. Each may
    # carry an optional ``active`` interval (whole video when ``None``).

    def _spatial_entry(self, kind: str, manifest_key: str, def_id: str) -> dict:
        entries = {
            e["id"]: e
            for e in recording_store.read_recording(self.dir).get(manifest_key, [])
        }
        if def_id not in entries:
            raise ValueError(f"unknown {kind} id {def_id!r}")
        return entries[def_id]

    def _spatial_keyframes(
        self, kind: str, manifest_key: str, def_id: str
    ) -> list[tuple[int, list[tuple[float, float]]]]:
        entry = self._spatial_entry(kind, manifest_key, def_id)
        pk = spatial_store.read_keyframes(self.dir, kind, def_id, entry["n_vertices"])
        return [
            (int(f), [(float(x), float(y)) for x, y in verts])
            for f, verts in pk.keyframes
        ]

    def _spatial_at_frame(
        self, kind: str, manifest_key: str, def_id: str, frame_idx: int
    ) -> np.ndarray | None:
        entry = self._spatial_entry(kind, manifest_key, def_id)
        pk = spatial_store.read_keyframes(self.dir, kind, def_id, entry["n_vertices"])
        active = entry.get("active")
        interval = (active["start"], active["end"]) if active else None
        return active_polygon_at_frame(pk, interval, frame_idx)

    def define_roi(
        self,
        name: str,
        keyframes: list[tuple[int, list[tuple[float, float]]]],
        active: tuple[int, int] | None = None,
    ) -> str:
        """Define a named region-of-interest polygon (Section 10).

        ROIs are **analysis-time only** — they do not affect detection or
        tracking. Keyframes match ``define_arena`` (recording-global ``frame_idx``,
        normalized ``[0, 1]`` vertices, >= 3 per keyframe). ``active`` is an
        optional inclusive ``(start, end)`` recording-global frame interval the ROI
        is present for; ``None`` = whole video.

        Returns:
            The auto-assigned stable id (e.g. ``"roi_001"``).

        Raises:
            ValueError: If keyframes/active are invalid, or the name is empty or
                already used within this recording.
        """
        roi_id = spatial_store.next_id(self.dir, "roi")
        n = spatial_store.write_keyframes(self.dir, "roi", roi_id, keyframes)
        spatial_store.append_to_manifest(self.dir, "roi", roi_id, name, n, active)
        return roi_id

    def roi_keyframes(self, roi_id: str) -> list[tuple[int, list[tuple[float, float]]]]:
        """The ROI's polygon keyframes (to reload it into the editor).

        Raises:
            ValueError: If no ROI with this id exists in the recording.
        """
        return self._spatial_keyframes("roi", "rois", roi_id)

    def roi_at_frame(self, roi_id: str, frame_idx: int) -> np.ndarray | None:
        """The ROI polygon at ``frame_idx`` as an ``(n_vertices, 2)`` array, or
        ``None`` if the ROI is not active at that frame (Section 10)."""
        return self._spatial_at_frame("roi", "rois", roi_id, frame_idx)

    def delete_roi(self, roi_id: str) -> None:
        """Remove an ROI (keyframes + recording.yaml entry). Unconditional: a finished
        location run keeps its own rows, and the id is never given to another ROI."""
        spatial_store.delete_def(self.dir, "roi", roi_id)

    def define_point(
        self,
        name: str,
        keyframes: list[tuple[int, list[tuple[float, float]]]],
        active: tuple[int, int] | None = None,
    ) -> str:
        """Define a named point of interest (Section 10) — a landmark point
        (lever, port, hopper).

        Each keyframe carries exactly **one** normalized vertex; a single keyframe
        is a static point, more keyframes move it (e.g. a panning camera).
        Analysis-time only (does not affect detection/tracking). ``active`` as in
        ``define_roi``. Distinct from pose keypoints (user-placed, not model-derived).

        Returns:
            The auto-assigned stable id (e.g. ``"point_001"``).
        """
        point_id = spatial_store.next_id(self.dir, "point")
        n = spatial_store.write_keyframes(self.dir, "point", point_id, keyframes)
        spatial_store.append_to_manifest(self.dir, "point", point_id, name, n, active)
        return point_id

    def point_keyframes(
        self, point_id: str
    ) -> list[tuple[int, list[tuple[float, float]]]]:
        """The POI's keyframes (one vertex each).

        Raises:
            ValueError: If no POI with this id exists in the recording.
        """
        return self._spatial_keyframes("point", "points", point_id)

    def point_at_frame(self, point_id: str, frame_idx: int) -> np.ndarray | None:
        """The point as a ``(1, 2)`` array at ``frame_idx``, or ``None`` if the POI
        is not active at that frame (Section 10)."""
        return self._spatial_at_frame("point", "points", point_id, frame_idx)

    def delete_point(self, point_id: str) -> None:
        """Remove a POI (keyframes + recording.yaml entry). Unconditional."""
        spatial_store.delete_def(self.dir, "point", point_id)

    def set_rois(self, defs: list[dict]) -> list[str]:
        """Replace **all** ROIs in one transaction — the multi-region manager's "Save all"
        (Section 10). Each entry is ``{"name", "keyframes", "active", "id"}`` (``active``
        and ``id`` optional). An entry carrying the id of an ROI that exists keeps it; any
        other gets an id never used in this recording before. Returns the ids, in order.

        Raises:
            ValueError: If any def is invalid (empty/duplicate name or id, bad
                keyframes/active).
        """
        return spatial_store.replace_defs(self.dir, "roi", defs)

    def set_points(self, defs: list[dict]) -> list[str]:
        """Replace **all** POIs in one transaction — the manager's "Save all" (Section 10).
        Each entry is ``{"name", "keyframes", "active", "id"}``; each keyframe carries one
        vertex. Ids are kept and minted as in :meth:`set_rois`. Returns the ids, in order.
        """
        return spatial_store.replace_defs(self.dir, "point", defs)

    def check_spatial_defs(self, kind: str, defs: list[dict]) -> None:
        """Refuse a whole set of ``kind`` (``"arena"``, ``"roi"`` or ``"point"``) definitions
        the way :meth:`set_rois` / :meth:`set_points` / :meth:`define_arena` would, writing
        nothing — for a caller that commits several kinds at once and must not have written
        one before another is refused (the scene editor's Save).

        Raises:
            ValueError: An empty or duplicated name or id, or invalid keyframes / active.
        """
        spatial_store.validate_defs(kind, defs)

    def check_distance_calibration(
        self, points: list[tuple[float, float]], distance_mm: float
    ) -> None:
        """Refuse what :meth:`set_distance_calibration` would refuse, writing nothing.

        Raises:
            ValueError: if there is no video, the points coincide, or ``distance_mm <= 0``.
        """
        spatial_store.calibration_from_points(
            points, distance_mm, self._require_resolution()
        )

    def export_spatial_csv(self, path: Path | str) -> None:
        """Write this recording's whole spatial setup to a round-trippable CSV (Section 10)
        — the field of view, the distance calibration, and the ROIs + POIs — for sharing or
        importing onto another recording.

        One file per recording rather than one per kind; the import side is per kind, so a
        single export can feed any of them.
        """
        spatial_store.export_spatial(self.dir, path)

    def import_spatial_csv(
        self, path: Path | str, kinds: tuple[str, ...] = ("roi", "point")
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take the ``kinds`` rows of an exported spatial CSV onto this recording (§10).

        Goes through :meth:`receive_spatial`, so a setup **pulled** from a file obeys the
        same rules as one **pushed** from a recording: nothing is replaced, a name already
        here is refused rather than suffixed ``(2)``, keyframe motion is flattened, and an
        active window does not travel.

        All or nothing across ``kinds``: every definition is checked before the first is
        written, so a bad point does not leave the regions above it behind (a retry then
        refused them as "already exists").

        Returns:
            ``(added, flattened, refused)``.
        """
        by_kind = {}
        for d in spatial_store.load_spatial_csv(path):
            by_kind.setdefault(d["kind"], []).append(d)
        added, flattened, refused = self._receive_spatial_kinds(
            {kind: by_kind.get(kind, []) for kind in kinds}
        )
        if not added and not refused:
            raise ValueError(f"{path} carries no {' or '.join(kinds)}")
        return added, flattened, refused

    def import_scene_csv(
        self, path: Path | str
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take everything an exported spatial CSV carries onto this recording (§10): its
        field of view, distance calibration, regions and points, each by its own rules
        (:meth:`import_field_of_view_csv`, :meth:`import_calibration_csv`,
        :meth:`import_spatial_csv`). Nothing is replaced.

        Only the kinds the file holds are tried. A kind it does not carry is not a refusal:
        trying all four turned a one-region file into one "Added" line and three "Not added"
        ones, which reads as a partial failure (#35 finding 14). A kind refused whole (this
        recording already has a field of view or a calibration) is one refusal, named by
        what it is.

        Returns:
            ``(added, flattened, refused)``.

        Raises:
            FileNotFoundError: the file is absent.
            ValueError: the file is malformed, or carries no scene geometry at all.
        """
        held = spatial_store.spatial_csv_kinds(path)
        if not held:
            raise ValueError(f"{path} carries no scene geometry")
        # All or nothing, like every import (#29): the whole file is parsed, and every kind
        # it carries is either refused here as a whole (reported, nothing written) or checked
        # with the rest before the first write, so a bad point cannot leave the field of view
        # above it behind.
        by_kind: dict[str, list[dict]] = {}
        for d in spatial_store.load_spatial_csv(path):
            by_kind.setdefault(d["kind"], []).append(d)
        block = (
            spatial_store.load_calibration_csv(path) if "calibration" in held else None
        )
        refused: list[tuple[str, str]] = []
        if by_kind.get("arena"):
            refusal = self.field_of_view_refusal()
            if refusal is not None:
                refused.append(("field of view", f"recording {self.name!r} {refusal}"))
                del by_kind["arena"]
        if block is not None:
            if self.distance_calibration is not None:
                refused.append(
                    (
                        "distance calibration",
                        f"recording {self.name!r} already has a distance calibration — "
                        "delete it here first; nothing is overwritten",
                    )
                )
                block = None
            else:
                try:
                    spatial_store.check_calibration_block(block, self.video_resolution)
                except ValueError as exc:
                    refused.append(("distance calibration", str(exc)))
                    block = None
        kinds = ("arena", *self._PER_DEFINITION_KINDS)
        added, flattened, kind_refused = self._receive_spatial_kinds(
            {kind: by_kind[kind] for kind in kinds if by_kind.get(kind)}
        )
        refused = refused + kind_refused
        if block is not None:
            spatial_store.write_calibration_block(
                self.dir, block, self.video_resolution
            )
            added.append("distance calibration")
        return added, flattened, refused

    def import_spatial_from(
        self, source: "Recording", kinds: tuple[str, ...] = ("roi", "point")
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take another recording's ROIs/POIs onto this one (§10) — the *pull* twin of
        ``Experiment.propagate_rois`` / ``propagate_points``, and the same rules.

        Returns:
            ``(added, flattened, refused)``.
        """
        added, flattened, refused = self._receive_spatial_kinds(
            {kind: spatial_store.read_defs(source.dir, kind) for kind in kinds}
        )
        if not added and not refused:
            raise ValueError(
                f"recording {source.name!r} has no {' or '.join(kinds)} to copy"
            )
        return added, flattened, refused

    #: Kinds whose collisions are judged per definition rather than per kind. Mirrors
    #: `gui.arena.SpatialKind.collision_grain` so the API and CLI need not import the GUI
    #: to know the rule. A field of view and a calibration are refused whole — two arenas
    #: break the batch tracking picker, which intersects arena *ids* across recordings, and
    #: there is one pixel scale. Regions and points are sets, so only the taken names are
    #: refused; failing a whole set on one clash would kill "pull one more zone from a
    #: template", which is what `recording import-spatial` has always been for.
    _PER_DEFINITION_KINDS = ("roi", "point")

    def field_of_view_refusal(self) -> str | None:
        """Why this recording cannot receive a field of view, or ``None``.

        One sentence for both directions. It lived only on the push side, so pulling a
        field of view onto a locked recording said "already has one" and stopped, while
        pushing the identical setup named the tracking runs you would have to delete
        first — same situation, two qualities of advice.

        It carries no "here" or "there": the pull direction reads it about the recording
        you are on and the push direction reads it about a row in a list of sixty others,
        so either word is wrong half the time.
        """
        if not self.arenas:
            return None
        blocking = sorted(
            {
                run_id
                for arena in self.arenas
                for run_id in self.arena_dependents(arena["id"])
            }
        )
        if blocking:
            return (
                "already has a field of view, used by tracking "
                f"{'runs' if len(blocking) > 1 else 'run'} {', '.join(blocking)} — "
                "delete those runs, then that field of view"
            )
        return "already has a field of view — delete the existing one first"

    def receive_spatial(
        self, defs: list[dict], kind: str
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take ``defs`` (already parsed, from a recording or a CSV) onto this recording.

        The one door for a setup arriving from elsewhere, whichever direction it was
        started from and whichever source it came from. Applies
        ``storage.spatial.prepare_for_arrival``'s timeline policy, then refuses by name for
        the set-shaped kinds — nothing is ever replaced.

        Returns:
            ``(added, flattened, refused)`` — names written, names whose keyframe motion
            was dropped, and ``[(name, reason), ...]`` left behind.

        Raises:
            ValueError: A definition that is not valid (nothing is written).
        """
        return self._receive_spatial_kinds({kind: defs})

    def _receive_spatial_kinds(
        self, defs_by_kind: dict[str, list[dict]]
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """:meth:`receive_spatial` over several kinds at once, written in one go.

        The policy is applied kind by kind, then everything that may arrive is handed to
        ``storage.spatial.import_spatial`` together, which checks every definition before
        writing the first. Applied a kind at a time, a bad point was refused only after the
        regions had been written (#29).
        """
        planned: list[dict] = []
        flattened: list[str] = []
        refused: list[tuple[str, str]] = []
        for kind, defs in defs_by_kind.items():
            prepared, f, r = spatial_store.prepare_for_arrival(defs)
            flattened += f
            refused += r
            if kind in self._PER_DEFINITION_KINDS:
                taken = {e["name"] for e in spatial_store.list_defs(self.dir, kind)}
                keep = []
                for d in prepared:
                    if d["name"] in taken:
                        refused.append(
                            (
                                d["name"],
                                f"already exists on {self.name} — rename or delete the "
                                "existing one first; nothing is overwritten",
                            )
                        )
                    else:
                        keep.append(d)
                prepared = keep
            planned += prepared
        # Never raises for "nothing to take": a single windowed region must not abort a
        # transfer whose points were perfectly transferable — the caller could see
        # neither. Refusals are data; the caller decides.
        if planned:
            spatial_store.import_spatial(self.dir, planned)
        return [d["name"] for d in planned], flattened, refused

    def propagate_spatial_from(
        self, source: "Recording", kind: str, names: list[str] | None = None
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take a copy of ``source``'s ``kind`` definitions (Section 10).

        A thin read in front of :meth:`receive_spatial`, which owns the policy.

        Returns:
            ``(added, flattened, refused)``.
        """
        defs = spatial_store.read_defs(source.dir, kind)
        if names is not None:
            defs = [d for d in defs if d["name"] in set(names)]
        return self.receive_spatial(defs, kind)

    # --- field-of-view carry-over (§10) ------------------------------------- #
    # Recordings off one rig share a field of view, so it carries over like the ROIs/POIs
    # do — but by **replacement**, not appending: "make this recording match that one"
    # means one field of view, not a second one. Replacing goes through ``clear_arenas``,
    # so a field of view a tracking run depends on refuses rather than silently
    # invalidating that run's recorded region (DESIGN_PLAN §4016).

    def import_field_of_view_from(
        self, source: "Recording"
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take ``source``'s field of view onto this recording (§10).

        **Never replaces.** A recording that already has one keeps it; delete it here first
        (and the tracking runs holding it, which ``arena_dependents`` names). This used to
        ``clear_arenas()`` and copy over the top after a Yes/No — the same operation the
        *push* direction refuses outright, which is how one setup arriving from elsewhere
        came to have two contradictory rules depending on which way you started it.

        Returns:
            ``(added, flattened, refused)``.
        """
        refusal = self.field_of_view_refusal()
        if refusal is not None:
            raise ValueError(f"recording {self.name!r} {refusal}")
        defs = spatial_store.read_defs(source.dir, "arena")
        if not defs:
            raise ValueError(f"recording {source.name!r} has no field of view to copy")
        return self.receive_spatial(defs, "arena")

    def import_field_of_view_csv(
        self, path: Path | str
    ) -> tuple[list[str], list[str], list[tuple[str, str]]]:
        """Take the field of view out of an exported spatial CSV (§10). Never replaces —
        see :meth:`import_field_of_view_from`.

        Returns:
            ``(added, flattened, refused)``.
        """
        defs = [d for d in spatial_store.load_spatial_csv(path) if d["kind"] == "arena"]
        if not defs:
            raise ValueError(f"{path} carries no field of view")
        refusal = self.field_of_view_refusal()
        if refusal is not None:
            raise ValueError(f"recording {self.name!r} {refusal}")
        return self.receive_spatial(defs, "arena")

    # --- distance-calibration carry-over (§10) ------------------------------ #
    # Singular, so it always replaces. Unlike the field of view there is no run lock:
    # a completed analysis run already wrote its CSVs, so only future runs see the change.

    def import_calibration_from(self, source: "Recording") -> dict:
        """Take ``source``'s distance calibration onto this recording (§10).

        Never replaces: there is one pixel scale, so a recording that already has one keeps
        it. Nothing to flatten for the timeline — a calibration is two points, a distance
        and the resolution it was measured at, with no frame index anywhere. Refused onto a
        video of a different shape, where no one pixel scale is right.

        Raises:
            ValueError: the source has none, this recording already has one, or its video's
                aspect ratio differs from the one the calibration was measured on.
        """
        if self.distance_calibration is not None:
            raise ValueError(
                f"recording {self.name!r} already has a distance calibration — delete it "
                "here first; nothing is overwritten"
            )
        return spatial_store.copy_calibration(
            source.dir, self.dir, self.video_resolution
        )

    def import_calibration_csv(self, path: Path | str) -> dict:
        """Take the distance calibration out of an exported spatial CSV (§10). Never
        replaces — see :meth:`import_calibration_from`.

        Raises:
            FileNotFoundError | ValueError: a missing/malformed CSV, one carrying no
                calibration, a recording that already has one, or one whose video is a
                different shape from the one the calibration was measured on.
        """
        block = spatial_store.load_calibration_csv(path)
        if block is None:
            raise ValueError(f"{path} carries no distance calibration")
        if self.distance_calibration is not None:
            raise ValueError(
                f"recording {self.name!r} already has a distance calibration — delete it "
                "here first; nothing is overwritten"
            )
        return spatial_store.write_calibration_block(
            self.dir, block, self.video_resolution
        )

    # --- distance calibration (§10) ----------------------------------------- #
    @property
    def distance_calibration(self) -> dict | None:
        """The recording's distance-calibration block (Section 10), or ``None`` if not set.
        Fields: ``pixels_per_mm``, ``ref_resolution`` ``[W, H]``, and (for a two-point pick)
        the normalized ``points`` and ``distance_mm``."""
        return spatial_store.read_calibration(self.dir)

    @property
    def pixels_per_mm(self) -> float | None:
        """``pixels_per_mm`` at the recording's current video resolution (rescaled from the
        calibration's own resolution), or ``None`` if uncalibrated. With no video yet, the
        calibration's own value at its ``ref_resolution`` (:meth:`calibration_reference`).

        Raises:
            ValueError: the calibration cannot describe this video — see
                :meth:`calibration_refusal`, which a display should ask first.
        """
        cal = self.distance_calibration
        if cal is None:
            return None
        resolution = self.video_resolution
        if resolution is None:
            # No video yet (a calibration copied onto it is allowed): the stored value, at the
            # calibration's own resolution — `calibration_reference` says which.
            return float(cal["pixels_per_mm"])
        return spatial_store.pixels_per_mm_at(cal, *resolution)

    def calibration_reference(self) -> str:
        """How to read :attr:`pixels_per_mm`: ``""`` when it is at this recording's video, or
        ``" at WxH (no video yet)"`` when the recording has no video and the number is the
        calibration's own, at the resolution it was measured on."""
        cal = self.distance_calibration
        if cal is None or self.video_resolution is not None:
            return ""
        ref_w, ref_h = (int(v) for v in cal["ref_resolution"])
        return f" at {ref_w}x{ref_h} (no video yet)"

    def calibration_refusal(self) -> str | None:
        """Why this recording's distance calibration gives no scale for its video, or
        ``None`` (also when it has no calibration or no video).

        Reachable although every carry-over refuses it: the video can be replaced after
        the calibration was set, and a calibration copied before the refusal existed is
        still on disk.
        """
        return self.calibration_refusal_for(self.distance_calibration)

    def calibration_refusal_for(self, calibration: dict | None) -> str | None:
        """Why ``calibration`` gives no scale for this recording's video, or ``None``
        (also when either is missing). The question a copy asks of a target before it is
        offered: a calibration belongs to a rig, and a video of another shape is another
        rig."""
        res = self.video_resolution
        if calibration is None or res is None:
            return None
        return spatial_store.calibration_aspect_refusal(calibration, *res)

    def set_distance_calibration(
        self, points: list[tuple[float, float]], distance_mm: float
    ) -> dict:
        """Calibrate from two normalized points a known real distance (mm) apart — the GUI
        two-point pick (Section 10). Uses the current video resolution as the reference.

        Raises:
            ValueError: if there is no video, the points coincide, or ``distance_mm <= 0``.
        """
        return spatial_store.write_calibration_from_points(
            self.dir, points, distance_mm, self._require_resolution()
        )

    def set_pixels_per_mm(self, pixels_per_mm: float) -> dict:
        """Calibrate directly from a ``pixels_per_mm`` scalar (the CLI/scripted path, no
        two-point pick), measured at the current video resolution (Section 10).

        Raises:
            ValueError: if there is no video or ``pixels_per_mm <= 0``.
        """
        return spatial_store.write_calibration_scalar(
            self.dir, pixels_per_mm, self._require_resolution()
        )

    def clear_distance_calibration(self) -> None:
        """Remove the distance calibration (idempotent)."""
        spatial_store.delete_calibration(self.dir)

    def _require_resolution(self) -> tuple[int, int]:
        res = self.video_resolution
        if res is None:
            raise ValueError("cannot calibrate a recording with no imported video")
        return res

    # --- location export (per-recording ROI/POI spatial features) ------------- #
    def _require_complete_tracking(self, tracking_run_id: str) -> dict:
        rec = {r["id"]: r for r in self.tracking_runs}.get(tracking_run_id)
        if rec is None:
            raise UserInputError(
                f"tracking run {tracking_run_id!r} not found in recording {self.name!r}; "
                f"its tracking runs are {[r['id'] for r in self.tracking_runs]}"
            )
        if rec.get("status") != "complete":
            raise UserInputError(
                f"tracking run {tracking_run_id!r} is {rec.get('status')!r}, not complete"
            )
        return rec

    def location_tables(
        self,
        tracking_run_id: str,
        *,
        keypoint_run_id: str | None = None,
        progress: Callable[[str, float, str], None] | None = None,
        **options: float | bool | None,
    ):
        """Per-frame, per-track spatial features for a completed tracking run —
        bbox/centroids/areas, the body's centre, area, length and width, and position
        relative to this recording's ROIs/POIs.

        Returns an ``analysis.locations.LocationTables`` (compute only, no write) —
        the reuse hook for a preview or a future analysis module. Read-only; the
        compute is pure (no executor, no run record).

        Args:
            tracking_run_id: A complete tracking run of this recording.
            keypoint_run_id: A complete keypoint track run whose poses went to that tracking
                run, read into a fourth table (``keypoints``); ``None`` reads no keypoints.
            progress: ``(stage, fraction, detail)``, called as the tracked rows are
                measured: a recording's export takes minutes, and without it looks hung.
            **options: The measurement options of ``configs.location_export``:
                ``sample_fps`` (rows per second per subject; unset is every tracked
                frame).

        Raises:
            ValueError: If the tracking run is missing or not complete, an option is not
                one this export has, or one is outside its bounds; or the keypoint track run
                is not complete or assigned its poses to another tracking run.
        """
        from detail.analysis import locations as _locations
        from detail.configs import location_export as _config
        from detail.core.progress import ThrottledProgress

        self._require_complete_tracking(tracking_run_id)
        unknown = sorted(set(options) - set(_config.option_names()))
        if unknown:
            raise UserInputError(
                f"location export has no option {', '.join(unknown)}; it has "
                f"{', '.join(_config.option_names())}"
            )
        resolved = _config.options_from(options)
        on_rows = None
        if progress is not None:
            # The compute reports per tracked row, hundreds of thousands of them, so the
            # throttle keeps the callback off its loop.
            emit = ThrottledProgress(lambda event: progress(*event))

            def on_rows(done: int, total: int) -> None:
                fraction = done / total if total else 1.0
                emit(
                    ("measuring", fraction, f"{done:,} of {total:,} rows"),
                    force=done >= total,
                )

            on_rows(0, 1)  # the bar moves before the first part is read
        if keypoint_run_id is not None:
            entry = {r.get("id"): r for r in self.keypoint_track_runs}.get(
                keypoint_run_id
            )
            if entry is None or entry.get("status") != "complete":
                state = "missing" if entry is None else repr(entry.get("status"))
                raise UserInputError(
                    f"keypoint track run {keypoint_run_id!r} is {state}, not complete"
                )
        return _locations.compute_location_tables(
            self,
            tracking_run_id,
            on_progress=on_rows,
            options=resolved,
            keypoint_run_id=keypoint_run_id,
        )

    def export_locations(
        self,
        tracking_run_id: str,
        out_dir: Path | str,
        *,
        keypoint_run_id: str | None = None,
        progress: Callable[[str, float, str], None] | None = None,
        **options: float | bool | None,
    ) -> Path:
        """Compute + write the three location CSVs (``tracks`` / ``roi_relations`` /
        ``point_relations``, and ``keypoints`` with a ``keypoint_run_id``) + a
        ``locations.yaml`` manifest into a new folder under ``out_dir``; returns that folder. Tables keyed by ``t_ns`` (joins with streams).
        ``progress`` and ``options`` are :meth:`location_tables`'s; ``progress`` also hears
        the write.

        The names are fixed, so each export gets its own folder: writing them straight into
        ``out_dir`` replaced one recording's files with the next one's (#29)."""
        from detail.api import exporters
        from detail.storage import location_export

        tables = self.location_tables(
            tracking_run_id,
            keypoint_run_id=keypoint_run_id,
            progress=progress,
            **options,
        )
        dest = exporters.new_export_folder(
            exporters.ExportSubject("recording", self._experiment_dir, self.id),
            out_dir,
            what=f"{tracking_run_id}_locations",
        )
        if progress is not None:
            progress("writing", 0.0, dest.name)
        written = location_export.write_location_tables(dest, tables)
        if progress is not None:
            progress("writing", 1.0, dest.name)
        return written

    def backfill_kinematics(
        self, embed_run_id: str, *, progress=None, overwrite: bool = False
    ) -> int:
        """Write the §14 ``kinematics/`` sibling for an embedding run that has none.

        A run made before kinematics existed has no per-frame geometry, so nothing downstream
        can say *where* a behavior happened. This regenerates it from the detection zarr — the
        masks and boxes are still there — without a GPU, a model, or a video decode. Returns the
        number of parts written.

        ``progress`` takes the standard ``(stage, fraction, detail)`` callback; on a long
        recording this is minutes, and a silent long op is indistinguishable from a hang.
        Already-written parts are skipped unless ``overwrite``, so an interrupted run resumes.
        """
        from detail.pipeline import kinematics_backfill

        return kinematics_backfill.backfill_run(
            self.dir, embed_run_id, progress=progress, overwrite=overwrite
        )

    def missing_previews(self, tracking_run_ids: list[str] | None = None) -> list:
        """The preview builds this recording is missing on this machine (§3 *Video preview
        cache*) — each part's proxy, and each complete tracking run's masks. One stat per part
        once the cache knows the file; empty when everything is built."""
        from detail.api import previews

        return previews.recording_tasks(
            self.dir, self.id, tracking_run_ids=tracking_run_ids
        )

    def build_preview(
        self,
        progress: Callable[[str, float, str], None] | None = None,
        *,
        tracking_run_ids: list[str] | None = None,
        masks: bool = True,
    ) -> "previews.PreviewBuildReport":
        """Build this recording's display-only previews on this machine; returns a
        ``previews.PreviewBuildReport`` (``built``, and ``failed`` — each failed build with
        why; one failure does not stop the rest).

        Each part's proxy (480x270 at most, 15 fps) and, with ``masks``, each complete
        tracking run's masks at proxy size (``tracking_run_ids`` limits which). They live in
        the machine-local preview cache, never in the experiment, and no pipeline stage reads
        them (§3). Minutes per hour of video, so ``progress`` takes the standard
        ``(stage, fraction, detail)`` callback; a callback that raises stops the build and the
        part in hand is discarded.
        """
        from detail.api import previews

        tasks = self.missing_previews(tracking_run_ids)
        if not masks:
            tasks = [task for task in tasks if task.kind == previews.PROXY]
        return previews.build_tasks(
            self._experiment_dir, tasks, {self.id: self.name}, progress
        )

    def kinematics_missing_parts(self, embed_run_id: str) -> list[Path]:
        """Embedding parts of this run with no kinematics sibling — empty when it is complete."""
        from detail.pipeline import kinematics_backfill

        return kinematics_backfill.missing_parts(self.dir, embed_run_id)

    def kinematics(self, embed_run_id: str, track_id: int = 0) -> dict | None:
        """Where the subject was on each embedded frame (§14), or ``None`` if never captured.

        ``{frame_idx, t_ns, cx_norm, cy_norm, mask_area_norm, bbox_norm}``, all normalized to the
        frame so two recordings of different resolutions are comparable. The same rows, in the
        same order, as the embedding run's own — without reading the embedding column beside it.

        ``None`` for a run made before this was captured; :meth:`backfill_kinematics` fills it in.
        """
        from detail.api.run_preview import load_track_kinematics

        return load_track_kinematics(self.dir, embed_run_id, track_id)

    # --- streams (Section 3) ------------------------------------------------ #
    def add_stream(
        self,
        name: str,
        raw_path: Path | str,
        importer: str,
        aux_paths: dict[str, Path | str] | None = None,
        covered_behaviors: list[str] | None = None,
        origin: str | None = None,
        config: dict | None = None,
        offset_ns: int = 0,
    ) -> None:
        """Import a time-series stream and record it in recording.yaml (Section 3).

        Runs the named ``StreamImporter`` over ``raw_path`` (plus any
        ``aux_paths`` it declares) to produce canonical rows in stream-local time,
        copies the source files verbatim into ``streams/<name>/raw/``, writes the
        canonical CSV, and appends the manifest. The folder is built aside and moved into
        place only once every check has passed, so a refused import leaves nothing behind.

        Args:
            name: Unique, path-safe stream name (also the directory name).
            raw_path: The primary data file to import.
            importer: A registered importer id (e.g. ``"medpc"``).
            aux_paths: Extra files keyed by the importer's ``aux_inputs`` keys
                (e.g. ``{"program": "...SelfAdmin.MPC"}`` for MED-PC).
            covered_behaviors: For a ``behavior`` stream, the full scored-behavior
                vocabulary (declares behaviors that were scored but never occurred,
                so they still count as covered for eval eligibility). Must be a
                superset of the labels present. Defaults to the labels present.
            origin: For a ``behavior`` stream, ``"ground_truth"`` (a human scored
                the video) or ``"predicted"`` (a method's output, re-ingested).
                Defaults to the file's own ``origin`` column when it has one — the
                tool's own exporters write it — and to ``"ground_truth"`` otherwise.
                A predicted stream is never read as ground truth (§19), so marking
                it is what keeps a method from scoring against itself.
            config: The importer's own parameters, matching its ``config_model``
                (e.g. ``CsvStreamConfig``'s time column + channels). ``None`` means
                the importer's own defaults, which is what every importer did before
                it had a config. Validated against the model up front (Tenet 10).
            offset_ns: The stream's alignment offset, set at import instead of as a
                separate edit afterwards — ``video_t_ns = stream_t_ns + offset_ns``,
                positive if the stream began after the video. Only meaningful on an
                external clock; a ``video_frames`` / ``video_seconds`` stream is
                anchored at import and a non-zero offset for one is refused rather
                than stored, because it would be silently ignored on read.

        Raises:
            ValueError: Unknown importer, invalid/duplicate name, a missing
                required aux input, a ``config`` its model rejects, a non-zero
                ``offset_ns`` on a video-anchored stream, ``covered_behaviors`` not
                covering a present label, or an ``origin`` outside the allowed set.
            FileNotFoundError: If ``raw_path`` or any aux path is not a file.
        """
        import_stream_importers()
        streams_store.validate_stream_name(name)
        importer_cls = STREAM_IMPORTERS.get(importer)
        if importer_cls is None:
            raise ValueError(
                f"unknown importer {importer!r}; available: {sorted(STREAM_IMPORTERS)}"
            )
        config = self._validated_stream_config(importer, importer_cls, config)
        raw_path = Path(raw_path)
        if not raw_path.is_file():
            raise FileNotFoundError(f"stream data file not found: {raw_path}")
        resolved_aux = {k: Path(v) for k, v in (aux_paths or {}).items()}
        instance = importer_cls()
        missing = [a.key for a in instance.aux_inputs if a.key not in resolved_aux]
        if missing:
            raise ValueError(
                f"importer {importer!r} requires aux file(s) {missing} "
                f"(pass them in aux_paths)"
            )
        for key, path in resolved_aux.items():
            if not path.is_file():
                raise FileNotFoundError(f"aux file {key!r} not found: {path}")
        data = recording_store.read_recording(self.dir)
        if any(s.get("name") == name for s in data.get("streams", [])):
            raise ValueError(f"stream name {name!r} already exists in recording")
        # A name that differs only by case is the same folder on macOS and Windows, so the
        # second import would write its files into the first stream's (#29).
        same = [
            s.get("name")
            for s in data.get("streams", [])
            if str(s.get("name", "")).casefold() == name.casefold()
        ]
        if same:
            raise UserInputError(
                f"stream name {name!r} differs from the existing stream {same[0]!r} only by "
                "case, which is one folder on macOS and Windows; choose another name"
            )
        if covered_behaviors is not None and instance.role != "behavior":
            # By the importer's role, before anything is copied: an events CSV has a `label`
            # column too, and the vocabulary was stored on it where nothing reads it.
            raise UserInputError(
                f"covered_behaviors only applies to a behavior stream; importer "
                f"{importer!r} makes a {instance.role or 'data'} stream"
            )

        sdir = streams_store.stream_dir(self.dir, name)
        if sdir.exists():
            # No recorded stream owns this folder (the same name, or one differing only by
            # case, is refused above): an import that failed before imports were staged left
            # it behind, and it is not anyone's data.
            shutil.rmtree(sdir)
        # Built aside and moved into place only after every check below has passed, right
        # before the manifest names it. Written straight into `streams/<name>/`, a refused
        # import left `raw/` (and sometimes the canonical CSV) with no manifest entry, and
        # a retry with another file kept the first one in `raw/` for good (#29).
        with atomic.staged_dir(sdir) as stage:
            raw_dir = stage / streams_store.RAW_DIRNAME
            canonical_dir = stage / streams_store.CANONICAL_DIRNAME
            raw_dir.mkdir()
            # Where `raw/` will be once moved into place: the manifest names that, never
            # the staging folder it is built in.
            raw_rel = (
                f"{streams_store.STREAMS_DIRNAME}/{name}/{streams_store.RAW_DIRNAME}"
            )
            raw_entries = [self._copy_raw(raw_dir, raw_rel, raw_path, 0, "data")]
            for i, (key, path) in enumerate(resolved_aux.items(), start=1):
                raw_entries.append(
                    self._copy_raw(raw_dir, raw_rel, path, i, key, raw_entries)
                )

            result = instance.import_stream(
                raw_path, canonical_dir, resolved_aux, config
            )
            # Only a frame/time-clocked importer needs the timestamp map; a t_ns-native
            # stream (e.g. MED-PC) skips it, so a recording without video still imports.
            needs_map = bool(result.frame_columns or result.time_columns)
            frame_t_ns = (
                self.frame_timestamps() if needs_map else np.empty(0, dtype=np.int64)
            )
            rows = clock_store.resolve_native_columns(
                result.columns,
                result.rows,
                result.frame_columns,
                result.time_columns,
                frame_t_ns,
            )
            canonical_name = streams_store.write_canonical_csv(
                canonical_dir, result.columns, rows
            )
            canonical_rel = (
                f"{streams_store.STREAMS_DIRNAME}/{name}/"
                f"{streams_store.CANONICAL_DIRNAME}/{canonical_name}"
            )
            dtypes = result.dtypes or streams_store.default_dtypes(result.columns)
            metadata = dict(result.metadata or {})
            if covered_behaviors is not None:
                if "label" not in result.columns:
                    raise ValueError(
                        "covered_behaviors only applies to a labeled (behavior) stream"
                    )
                present = {r[result.columns.index("label")] for r in result.rows}
                missing = present - set(covered_behaviors)
                if missing:
                    raise ValueError(
                        "covered_behaviors must include every labeled behavior; missing "
                        f"{sorted(missing)}"
                    )
                metadata["covered_behaviors"] = sorted(set(covered_behaviors))
            resolved_origin = self._resolve_stream_origin(instance, result, origin)
            # Checked against the *resolved* clock, not the importer's declared one: a CSV read
            # on the frame kind reports `video_frames` from a `stream_seconds` importer, so the
            # declared clock would wrongly accept an offset that read time then ignores.
            resolved_clock = result.clock or instance.clock
            streams_store.check_offset_allowed(name, resolved_clock, int(offset_ns))
            manifest = {
                "name": name,
                "type": result.type,
                "shape": result.shape
                or streams_store.stream_shape({"type": result.type}),
                "role": instance.role,
                "clock": resolved_clock,
                "columns": result.columns,
                "dtypes": dtypes,
                "importer": importer,
                "alignment": {"offset_ns": int(offset_ns), "active": "offset"},
                "raw": raw_entries,
                "files": [{"index": 0, "file": canonical_rel}],
                "metadata": metadata,
            }
            if result.sample_rate_hz is not None:
                manifest["sample_rate_hz"] = result.sample_rate_hz
            if resolved_origin is not None:
                manifest["origin"] = resolved_origin
        try:
            streams_store.append_stream_to_recording_yaml(self.dir, manifest)
        except BaseException:
            shutil.rmtree(sdir, ignore_errors=True)
            raise

    @staticmethod
    def _validated_stream_config(
        importer: str, importer_cls, config: dict | None
    ) -> dict | None:
        """``config`` checked against the importer's ``config_model``, or ``None``.

        Validated here rather than inside the importer so a bad mapping is refused before
        anything is copied or written (Tenet 10), and so every caller — API, CLI, GUI,
        bundle manifest — gets the same message from one place.

        Raises:
            ValueError: If the importer declares no ``config_model`` but a config was
                given, or the model rejects it.
        """
        if config is None:
            return None
        model = getattr(importer_cls, "config_model", None)
        if model is None:
            raise ValueError(
                f"importer {importer!r} takes no config, but one was given "
                f"({sorted(config)})"
            )
        try:
            return model.model_validate(config).model_dump()
        except PydanticValidationError as exc:
            raise ValueError(
                f"invalid config for importer {importer!r}: {exc}"
            ) from None

    @staticmethod
    def _resolve_stream_origin(importer, result, origin: str | None) -> str | None:
        """Where this stream's labels came from, or ``None`` for a non-behavior stream.

        Priority: the caller's explicit argument, then the imported file's own ``origin``
        column (the tool's own exporters write one, so a prediction self-identifies), then
        ``ground_truth``. The explicit argument wins so a user can correct a file that
        misdeclares itself — or mark a prediction that came from somewhere else entirely.

        Raises:
            ValueError: ``origin`` is outside the allowed set, or was passed for a stream
                that carries no labels (where it would mean nothing).
        """
        if importer.role != "behavior":
            if origin is not None:
                raise ValueError(
                    "origin only applies to a labeled (behavior) stream; "
                    f"importer {importer.importer_id!r} has role {importer.role!r}"
                )
            return None
        resolved = origin or (result.metadata or {}).get("origin")
        resolved = str(resolved or streams_store.DEFAULT_BEHAVIOR_ORIGIN)
        if resolved not in streams_store.BEHAVIOR_ORIGINS:
            raise ValueError(
                f"origin must be one of {sorted(streams_store.BEHAVIOR_ORIGINS)}, got "
                f"{resolved!r}"
            )
        return resolved

    def list_stream_presets(self) -> list[dict]:
        """The **experiment's** saved importer setups (Section 3).

        On ``Recording`` as well as ``Experiment`` because a preset is used from a
        recording — the surface that imports a stream should not have to reach past itself
        to find out what setups exist.
        """
        return stream_presets.list_presets(self._experiment_dir)

    def get_stream_preset(self, name: str) -> dict:
        """Raises: ValueError if no preset named ``name`` exists."""
        return stream_presets.get_preset(self._experiment_dir, name)

    def save_stream_preset(
        self,
        name: str,
        importer: str,
        config: dict | None,
        *,
        offset_ns: int | None = None,
        overwrite: bool = False,
    ) -> None:
        """Save an importer + config on the experiment, for its other recordings.

        Raises:
            ValueError: An invalid name, or the name exists and ``overwrite`` is False.
        """
        stream_presets.save_preset(
            self._experiment_dir,
            name,
            importer,
            config,
            offset_ns=offset_ns,
            overwrite=overwrite,
        )

    def add_stream_from_preset(
        self,
        name: str,
        raw_path: Path | str,
        preset: str,
        *,
        offset_ns: int | None = None,
        aux_paths: dict[str, Path | str] | None = None,
        origin: str | None = None,
    ) -> None:
        """Import a stream using a saved preset's importer + config (Section 3).

        The preset supplies the ``importer`` and its ``config``; everything that belongs to
        *this* recording — the file, the stream name, the alignment offset — stays an
        argument, because those are what differ between recordings even when the mapping
        does not.

        Args:
            offset_ns: This recording's alignment offset. ``None`` uses the preset's own,
                if it declared one, else 0. Alignment is per recording, so a preset rarely
                carries one (see ``storage/stream_presets.py``).

        Raises:
            ValueError: Unknown preset, or any ``add_stream`` error.
            FileNotFoundError: If ``raw_path`` is not a file.
        """
        entry = stream_presets.get_preset(self._experiment_dir, preset)
        resolved_offset = entry.get("offset_ns", 0) if offset_ns is None else offset_ns
        self.add_stream(
            name,
            raw_path=raw_path,
            importer=entry["importer"],
            aux_paths=aux_paths,
            origin=origin,
            config=entry.get("config") or None,
            offset_ns=int(resolved_offset),
        )

    def _copy_raw(
        self,
        raw_dir: Path,
        raw_rel: str,
        src: Path,
        index: int,
        role: str,
        copied: Sequence[dict] = (),
    ) -> dict:
        """Copy a source file into the stream's ``raw/`` dir (``raw_dir``, where it is being
        built); return its manifest entry, which names it under ``raw_rel``, the
        recording-relative posix path ``raw/`` will have once the stream is in place.

        The copy keeps the file's own name unless an earlier file of this stream (``copied``)
        already has it — a MED-PC data file and its program both called ``same.txt`` — when it
        is prefixed with its role (``program_same.txt``). Copying both to ``raw/same.txt`` kept
        only the last, so the verbatim copy of the data was gone while the manifest still
        listed it (#29).
        """
        taken = {Path(entry["file"]).name.casefold() for entry in copied}
        name = src.name
        if name.casefold() in taken:
            name = f"{role}_{src.name}"
        n = 2
        while name.casefold() in taken:
            name, n = f"{role}{n}_{src.name}", n + 1
        dest = raw_dir / name
        shutil.copy2(src, dest)
        return {
            "index": index,
            "file": f"{raw_rel}/{name}",
            "role": role,
        }

    @property
    def streams(self) -> list[dict]:
        """Stream manifest entries from recording.yaml (empty list if none)."""
        return streams_store.list_streams(self.dir)

    def streams_by_role(self, role: str) -> list[dict]:
        """Stream manifest entries with the given ``role`` (Section 3).

        The discovery surface a role-consuming module reads through — e.g. an
        evaluation against ground truth finds recordings carrying a ``behavior``-role stream.
        """
        return streams_store.streams_by_role(self.dir, role)

    @property
    def is_annotated(self) -> bool:
        """Whether the recording carries behavior ground-truth labels (Section 3).

        Presence of any **ground-truth** ``behavior``-role stream means the recording
        is annotated; per-behavior eligibility uses ``is_annotated_for`` (an ethogram
        scores only some behaviors). It is what an evaluation against ground truth gates a
        recording on.

        A stream carrying a method's own re-ingested output (``origin: predicted``)
        does not annotate anything — counting it here would let a run be gated in on
        the very predictions it is about to be scored against (§19).
        """
        from detail.analysis.behavior_labels import ground_truth_streams

        return bool(ground_truth_streams(self))

    def _behavior_stream(self) -> dict | None:
        """The recording's ``behavior``-role stream manifest, or ``None`` if it carries none.

        Routed through ``behavior_labels.resolve_behavior_stream`` so the implicit choice is
        made in exactly one place: with several streams and no name it raises rather than
        taking whichever was added first (see that function for why).
        """
        from detail.analysis.behavior_labels import resolve_behavior_stream

        name = resolve_behavior_stream(self, None)
        if name is None:
            return None
        return next((s for s in self.streams if s.get("name") == name), None)

    def covered_behaviors(self, name: str | None = None) -> list[str]:
        """Behaviors the annotation *scored* (Section 3) — the eligibility vocabulary.

        Reads the manifest's ``covered_behaviors`` (importers declare it, so a
        scored-but-never-occurred behavior still counts); falls back to the distinct
        labels present for a legacy stream that predates the field. ``name`` selects
        a stream; default is the first ``behavior`` stream. Empty if none.
        """
        manifest = (
            next((s for s in self.streams if s.get("name") == name), None)
            if name is not None
            else self._behavior_stream()
        )
        if manifest is None:
            return []
        covered = (manifest.get("metadata") or {}).get("covered_behaviors")
        if covered is not None:
            return list(covered)
        return sorted({r[2] for r in self.stream_events(manifest["name"])})

    def behavior_types(self, name: str | None = None) -> dict[str, str]:
        """Per-behavior ``point``/``state`` type (Section 3).

        Reads the manifest's ``behavior_types`` (importers derive it — BORIS from its
        type column, the CSV from interval durations); falls back to inferring from
        the stream's own durations for a legacy stream. ``name`` selects a stream;
        default is the first ``behavior`` stream. Empty if none.
        """
        manifest = (
            next((s for s in self.streams if s.get("name") == name), None)
            if name is not None
            else self._behavior_stream()
        )
        if manifest is None:
            return {}
        types = (manifest.get("metadata") or {}).get("behavior_types")
        if types is not None:
            return dict(types)
        has_duration: dict[str, bool] = {}
        for row in self.stream_events(manifest["name"]):
            label, start, end = row[2], row[0], row[1]
            has_duration[label] = has_duration.get(label, False) or (end > start)
        return {
            label: ("state" if dur else "point") for label, dur in has_duration.items()
        }

    def is_annotated_for(self, behavior: str, name: str | None = None) -> bool:
        """Whether the recording's annotation scored ``behavior`` (Section 3).

        True iff ``behavior`` is in the stream's covered vocabulary — so a query
        "miss" of it counts as a real false negative, not an unscored behavior.

        A **predicted** stream never makes a recording eligible, whether it was named
        or resolved (§19): a method scored against its own output measures nothing,
        and the failure is silent because the numbers come out looking excellent.
        Returns ``False`` rather than raising — this is an eligibility question, and
        "not annotated for this" is the honest answer to it.
        """
        if name is not None:
            entry = next((s for s in self.streams if s.get("name") == name), None)
            if entry is not None and streams_store.is_predicted(entry):
                return False
        return behavior in self.covered_behaviors(name)

    def stream_events(self, name: str) -> list[tuple]:
        """The stream's canonical rows, typed per its manifest ``dtypes`` (Section 3).

        For a MED-PC ``events`` stream each row is ``(t_ns, code, label)``; for a
        ``behavior`` interval stream ``(t_ns, end_t_ns, label, subject, start_frame,
        end_frame)``; for a continuous stream ``(t_ns, *channels)``.

        ``t_ns`` is **stream-local**: the manifest's ``alignment.offset_ns`` is not applied
        here. For a video-anchored stream (``video_frames`` / ``video_seconds``, e.g.
        behavior labels) that is already video time, because the offset of such a stream is
        definitionally 0. For an external-clock stream it is the device's own time, and
        ``stream_preview(name).events(aligned=True)`` is the accessor that maps it to video
        time. The distinction matters to anything *computing* an offset — the sync-to-video
        helper derives ``frame_t_ns - anchor_t_ns`` from these rows, and pre-aligned rows
        would count the offset twice.

        Raises:
            FileNotFoundError: If the stream's canonical file is absent.
        """
        manifest = next((s for s in self.streams if s.get("name") == name), None)
        dtypes = manifest.get("dtypes") if manifest else None
        _columns, rows = streams_store.read_canonical(self.dir, name, dtypes=dtypes)
        return rows

    def stream_row_counts(self) -> dict[str, int | None]:
        """``{stream name: data rows}`` for every stream, ``None`` where its file is missing.

        For a table that shows a count per stream: it reads each canonical file to the end
        (a long sensor trace is seconds), so a GUI calls it off the UI thread. A stream whose
        file is gone is ``None`` rather than raising, so one missing file costs its own row and
        not the others' counts.
        """
        counts: dict[str, int | None] = {}
        for manifest in self.streams:
            name = manifest.get("name")
            try:
                counts[name] = streams_store.count_canonical_rows(self.dir, name)
            except FileNotFoundError:
                counts[name] = None
        return counts

    def stream_preview(self, name: str):
        """A read-only accessor for previewing a stream (Section 3): its events in
        stream-local and video-aligned time, grouped for a timeline raster.

        Raises:
            ValueError: If no stream with this name exists in the recording.
        """
        from detail.api.run_preview import StreamPreview

        return StreamPreview(self.dir, name)

    def set_stream_offset(self, name: str, offset_ns: int) -> None:
        """Set the stream's constant alignment offset (signed ns; Section 3).

        ``video_t_ns = stream_t_ns + offset_ns`` — positive if the stream began
        after the video, negative if before. Applied at read time; the canonical
        data is never rewritten.

        Raises:
            ValueError: If no stream with this name exists, or it is on the video's own
                clock (``video_frames`` / ``video_seconds``, e.g. behavior labels), which
                has no offset to set.
        """
        streams_store.set_stream_offset(self.dir, name, offset_ns)

    def stream_dependents(self, name: str) -> list[str]:
        """Runs that build on this stream and would be orphaned by deleting it.

        Aggregates every consumer registered for the stream's ``role`` in
        ``STREAM_CONSUMERS``. Empty today — no stage consumes streams yet — but a
        future consumer registers there without editing this method, keeping the
        deletion strategy (gui_design §1.1) uniform.
        """
        manifest = next((s for s in self.streams if s.get("name") == name), None)
        if manifest is None:
            return []
        dependents: list[str] = []
        for consumer in STREAM_CONSUMERS.get(manifest.get("role"), []):
            dependents.extend(consumer(self.dir, name))
        return dependents

    def delete_stream(self, name: str) -> None:
        """Remove a stream's directory + its recording.yaml entry (idempotent)."""
        streams_store.delete_stream(self.dir, name)

    def set_name(self, name: str) -> None:
        """Rename the recording (id/dir unchanged) — the label every surface displays.

        A name a user typed that is already taken is **refused**, not silently suffixed:
        the tool quietly renaming what someone deliberately typed is the worse failure.
        (The import path, where the *tool* proposes filenames and collisions are routine,
        suffixes instead — ``Experiment.add_recording``.)

        Raises:
            ValueError: If ``name`` is empty, or another recording already has it.
        """
        # Local import: api.experiment imports Recording at module level, so this would
        # be circular at the top.
        from detail.api.experiment import Experiment

        experiment = Experiment.open(self._experiment_dir)
        holder = next(
            (
                rid
                for rid, existing in experiment.recording_names().items()
                if existing == name and rid != self.id
            ),
            None,
        )
        if holder is not None:
            raise ValueError(
                f"another recording is already named {name!r} (id {holder}); "
                "names identify recordings to you, so they have to be unique"
            )
        recording_store.set_name(self.dir, name)
        self.name = name

    @property
    def video_sources(self) -> list[str]:
        """Where each video part's footage came from — one entry per part, ``""`` when
        unknown (a part imported before origins were recorded; honest, not a guess).

        One accessor because the user's question is the same ("which file is this?"). Both
        kinds store ``{root, rel}`` and are composed into an absolute path here, at display
        time — what they *mean* differs: a **referenced** part's ``source`` is the video's
        live location (relinking rewrites it, so this follows the file), while a **copied**
        part's ``origin`` is where it came from (the tool holds the footage; the original
        may since have moved, and nothing breaks if it has).
        """
        parts = (
            recording_store.read_recording(self.dir).get("video", {}).get("files", [])
        )
        out = []
        for part in parts:
            ref = part.get("source") or part.get("origin")
            if not ref:
                # A part imported before origins were recorded. `origin_name` covers the
                # brief window when only the filename was kept.
                out.append(part.get("origin_name", ""))
                continue
            try:
                out.append(str(video_roots.resolve_video_ref(ref)))
            except video_roots.MissingVideoRootError:
                # The root isn't registered on this machine (an experiment carried over
                # from another box). Name the file, since the path would be a guess;
                # whether the video is reachable is verify_videos' question, not this one.
                out.append(Path(ref.get("rel", "")).name)
        return out

    def reorder_video_parts(self, new_order: list[int]) -> None:
        """Reorder the video parts and re-offset global timestamps (Tenet 8).

        Part order is the recording's time reference, so this applies only before
        any processing run exists. ``new_order`` is the current part indices in
        the desired sequence.

        Raises:
            ValueError: If a processing run already exists (it was computed
                against the current order), or ``new_order`` is invalid.
        """
        data = recording_store.read_recording(self.dir)
        n_runs = sum(
            len(data.get(key) or [])
            for key in (
                "detection_runs",
                "tracking_runs",
                "embedding_runs",
            )
        )
        if n_runs:
            raise ValueError(
                f"cannot reorder video parts: {n_runs} processing run(s) exist "
                "and were computed against the current order — delete them first"
            )
        recording_store.reorder_video_parts(self.dir, new_order)

    @property
    def video_parts(self) -> list[dict]:
        """Video part entries from recording.yaml — ``[{index, file, timestamps}, ...]``.

        Read accessor so callers never read recording.yaml directly (Tenet 2)."""
        return (
            recording_store.read_recording(self.dir).get("video", {}).get("files", [])
        )

    @property
    def video_fps(self) -> float | None:
        """The recording's frame rate, or None if no video has been imported.

        The container's advertised rate, read from ``recording.yaml`` — cheap enough for a
        form to consult per keystroke. It is a *display* number: the frame-exact reference
        is the PTS timestamp map, and a stride is an exact integer either way (§4, Tenet 8).
        """
        video = recording_store.read_recording(self.dir).get("video", {})
        fps = video.get("fps_actual")
        return float(fps) if fps else None

    @property
    def video_resolution(self) -> tuple[int, int] | None:
        """The recording's source video resolution ``(width, height)``, or None if
        no video has been imported."""
        video = recording_store.read_recording(self.dir).get("video", {})
        res = video.get("resolution")
        return (int(res[0]), int(res[1])) if res else None

    @property
    def part_frame_counts(self) -> list[int]:
        """Frame count of each video part, from its active timestamp map.

        Lets a caller map a recording-global frame index to ``(part_index,
        local_idx)`` — e.g. the arena-draw canvas's single continuous frame
        slider (§10)."""
        data = recording_store.read_recording(self.dir)
        files = data.get("video", {}).get("files", [])
        return [
            len(recording_store.load_active_timestamps(self.dir, data, i))
            for i in range(len(files))
        ]

    def frame_t_ns(self, global_frame_idx: int) -> int:
        """Video ``t_ns`` of a recording-global frame index (Section 3, Tenet 8).

        Maps the continuous frame index (0 = first frame of part_001) to its
        ``(part, local)`` position via the per-part active timestamp maps and
        returns that frame's global ``t_ns``. Powers stream→video alignment
        (the "sync to video frame" offset = ``frame_t_ns(frame) - anchor_t_ns``).

        Raises:
            IndexError: If ``global_frame_idx`` is negative or past the last frame.
        """
        if global_frame_idx < 0:
            raise IndexError(f"global_frame_idx must be >= 0, got {global_frame_idx}")
        data = recording_store.read_recording(self.dir)
        files = data.get("video", {}).get("files", [])
        remaining = global_frame_idx
        for part_index in range(len(files)):
            tmap = recording_store.load_active_timestamps(self.dir, data, part_index)
            if remaining < len(tmap):
                return tmap.t_ns(remaining)
            remaining -= len(tmap)
        raise IndexError(
            f"global_frame_idx {global_frame_idx} is past the end of the recording"
        )

    def frame_timestamps(self) -> np.ndarray:
        """Concatenated global video ``t_ns`` per recording-global frame index.

        One int64 value per frame across all parts (Tenet 8) — the timeline axis
        for previews, and the inverse of ``frame_t_ns`` for a whole recording
        without re-reading the maps per lookup. Empty when no video is imported.
        """
        data = recording_store.read_recording(self.dir)
        files = data.get("video", {}).get("files", [])
        if not files:
            return np.empty(0, dtype=np.int64)
        return np.concatenate(
            [
                recording_store.load_active_timestamps(self.dir, data, i).values
                for i in range(len(files))
            ]
        )

    @property
    def arenas(self) -> list[dict]:
        """Arena entries from recording.yaml — ``[{id, name, n_vertices}, ...]``."""
        return recording_store.read_recording(self.dir).get("arenas", [])

    @property
    def rois(self) -> list[dict]:
        """ROI entries — ``[{id, name, n_vertices, active}, ...]`` (``active`` is
        ``{start, end}`` or ``None`` = whole video)."""
        return recording_store.read_recording(self.dir).get("rois", [])

    @property
    def points(self) -> list[dict]:
        """POI entries — ``[{id, name, n_vertices, active}, ...]`` (``n_vertices``
        is 1; ``active`` is ``{start, end}`` or ``None`` = whole video)."""
        return recording_store.read_recording(self.dir).get("points", [])

    def _cursor_for(self, part_index: int, path, timestamps):
        """The reader for one part, keeping its place between calls.

        Playback asks for the *next* frame forty times a second, and
        :func:`~detail.storage.video.read_frame_at` re-opens and re-seeks for every one of them —
        over an order of magnitude slower than a cursor on a 1080p part, so 1x playback
        showed a fraction of its frames and 4x was unreachable.

        **One cursor, not one per part.** A cursor holds an open container, and this object is
        held for a dialog's lifetime by each arena and stream surface; keeping one per part would
        make the number of open file handles a property of how many parts a recording happens to
        have. Surfaces scrub within a part and cross a boundary rarely, so switching parts closes
        the old one and opens the new — the cost of a boundary crossing is exactly the seek it
        replaced.

        Keyed on the resolved path as well as the index, so a relinked video (``RelinkVideoDialog``)
        is not served from a cursor still holding the file it replaced.

        Held for this object's lifetime, but the *file* is not: the cursor closes its container
        after ``FrameCursor.IDLE_CLOSE_S`` without a request, so a user can move the video in a
        file manager while the page showing it stays open — on Windows an open handle forbids it.
        """
        from detail.storage.video import FrameCursor

        key = (int(part_index), str(path))
        if getattr(self, "_frame_cursor_key", None) != key:
            existing = getattr(self, "_frame_cursor", None)
            if existing is not None:
                existing.close()
            self._frame_cursor = FrameCursor(path, timestamps=timestamps)
            self._frame_cursor_key = key
        return self._frame_cursor

    def get_frame(self, part_index: int, frame_idx: int) -> np.ndarray:
        """Decode a single RGB frame from a video part — inspection helper.

        Intended for preview / inspection (e.g. arena drawing backdrop, GUI
        thumbnails). Frame seeking is permitted here under Tenet 11's preview
        exemption. Seeks through the part's timestamp map, so the frame returned
        is the ``frame_idx``-th in presentation order.

        Returns:
            ``(H, W, 3) uint8`` RGB array.

        Raises:
            IndexError: If ``part_index`` is out of range, or if the requested
                ``frame_idx`` cannot be decoded (e.g. past end-of-file).
        """
        data = recording_store.read_recording(self.dir)
        files = data.get("video", {}).get("files", [])
        if not (0 <= part_index < len(files)):
            raise IndexError(f"part_index {part_index} out of range [0, {len(files)})")
        if frame_idx < 0:
            raise IndexError(f"frame_idx must be >= 0, got {frame_idx}")
        path = recording_store.resolve_part_video_path(self.dir, files[part_index])
        # Cached: a thumbnail grid calls this per tile, and the map is both the seek
        # index and immutable once written.
        timestamps = recording_store.load_active_timestamps_cached(
            self.dir, data, part_index
        ).values
        decoded = self._cursor_for(part_index, path, timestamps).frame(frame_idx)
        if decoded is None:
            raise IndexError(
                f"could not decode frame {frame_idx} from part {part_index} ({path.name})"
            )
        _actual, frame_bgr = decoded
        return bgr_to_rgb(frame_bgr)  # cv2 returns BGR; API surface is RGB

    @property
    def detection_runs(self) -> list[dict]:
        return recording_store.read_recording(self.dir).get("detection_runs", [])

    def detection_preview(self, run_id: str):
        """A read-only per-frame overlay accessor for a completed detection run
        (decode + boxes), for in-GUI preview without writing an annotated video.

        Raises:
            ValueError: If no detection run with this id exists in the recording.
        """
        from detail.api.run_preview import DetectionPreview

        return DetectionPreview(self.dir, run_id)

    @property
    def tracking_runs(self) -> list[dict]:
        return recording_store.read_recording(self.dir).get("tracking_runs", [])

    def tracking_preview(self, run_id: str):
        """A read-only per-frame overlay accessor for a completed tracking run
        (decode + boxes colored by track id), for in-GUI preview.

        Raises:
            ValueError: If no tracking run with this id exists in the recording.
        """
        from detail.api.run_preview import TrackingPreview

        return TrackingPreview(self.dir, run_id)

    @property
    def embedding_runs(self) -> list[dict]:
        return recording_store.read_recording(self.dir).get("embedding_runs", [])

    def run_dependents(self, module_id: str, run_id: str) -> list[tuple[str, str]]:
        """Runs in this recording that build on ``run_id`` and would be orphaned by
        deleting it — as ``(module_id, downstream_run_id)`` pairs."""
        data = recording_store.read_recording(self.dir)
        return [
            (downstream_module, entry["id"])
            for downstream_module, downstream_key, ref_field in _downstream_edges(
                module_id
            )
            for entry in data.get(downstream_key, [])
            if entry.get(ref_field) == run_id
        ]

    def delete_run(self, module_id: str, run_id: str) -> None:
        """Remove a per-recording run's output directory + its recording.yaml entry.

        The caller must ensure nothing depends on it (see ``run_dependents``).
        Idempotent: a missing directory or entry is skipped.
        """
        module = _module_owning_output(module_id)
        out_dir = self.dir / module.output_path(run_id).rstrip("/")
        if out_dir.is_dir():
            shutil.rmtree(out_dir)
        recording_store.remove_run_entry(self.dir, module.runs_key, run_id)

    def cancel_run(self, module_id: str, run_id: str) -> str:
        """Stop a per-recording run: kill its worker (graceful-then-force, via the
        run dir — works even after the GUI restarted) and record its **real** on-disk
        status in recording.yaml. Returns that status — usually ``cancelled``, but a
        graceful stop keeps ``partial`` and a worker that already finished keeps
        ``complete`` (so a done run isn't relabeled). Idempotent."""
        module = _module_owning_output(module_id)
        out_dir = self.dir / module.output_path(run_id).rstrip("/")
        if out_dir.is_dir():
            cancel_run_dir(out_dir)
            status = rundir.read_status(out_dir).value
        else:
            status = "cancelled"  # nothing ran (no run dir) → treat as cancelled
        recording_store.set_run_status(self.dir, module.runs_key, run_id, status)
        return status

    def run(self, module_id: str, config: dict) -> RunHandle:
        """Run a processing module (§6.5): validate, submit, record, return a handle.

        The single backbone behind every ``run_*`` stage method. The module
        (detection / tracking / embedding, or a future stage)
        owns validation, job construction, and the recording.yaml record shape.

        Raises:
            ValueError: For an unknown ``module_id`` or any failed pre-run
                validation.
            ModelNotReadyError: If a model-backed stage's weights/credentials
                are not in place.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        module = PROCESSING_MODULES.get(module_id)
        if module is None:
            raise ValueError(
                f"unknown module_id {module_id!r}; available: "
                f"{sorted(PROCESSING_MODULES)}"
            )
        data = recording_store.read_recording(self.dir)
        # Resolve a batch <upstream>_spec to this recording's own run id before validate
        # (§6.5). A no-op for the explicit-id path (CLI/typed wrappers) or a module
        # with no lineage parent.
        config = module.resolve_upstream_spec(self.dir, data, config)
        config = module.validate(self.dir, data, config)

        # Reserve the id + record atomically (under the recording lock) so concurrent runs on
        # this recording — e.g. several embeddings pinned to different GPUs — never collide on the
        # id or lose-update the record. The record is committed as PENDING, then submitted, then
        # advanced to its real status; a submit failure marks it failed rather than orphaning it.
        run_id = self._reserve_run(
            module.runs_key,
            module.id_prefix,
            lambda rid: module.run_record(rid, config, JobStatus.PENDING.value),
        )
        executor = LocalExecutor(self._experiment_dir, runner_modules=_PIPELINE_RUNNERS)
        try:
            job = module.build_job(self.id, run_id, config)
            executor.submit(job)
        except Exception:
            self._set_run_status(module.runs_key, run_id, JobStatus.FAILED.value)
            raise
        self._set_run_status(module.runs_key, run_id, executor.status(run_id).value)
        return _RecordedRun(
            ExecutorRunHandle(executor, run_id), self, run_id, module.runs_key
        )

    def run_render_preview(
        self,
        tracking_run_id: str,
        track_ids: list[int],
        renderer_spec: list[dict],
        n_sample_frames: int,
        save_as: str | None = None,
        seed: int | None = None,
    ) -> list[RenderPreviewResult]:
        """Sample N detections from the requested tracks and render each (Section 14).

        Synchronous: blocks while N samples are decoded + rendered. Not an
        executor job — no zarr, no recovery, no recording.yaml entry. ``save_as``
        writes source + rendered JPGs and ``preview.json`` to
        ``embeddings/render_previews/<save_as>/`` for inspection in any image
        viewer.

        Raises:
            ValueError: For any failed pre-run validation.
        """
        data = recording_store.read_recording(self.dir)
        self._validate_render_preview(
            data, tracking_run_id, track_ids, renderer_spec, n_sample_frames
        )
        job = RenderPreviewJob(
            tracking_run_id=tracking_run_id,
            track_ids=list(track_ids),
            renderer_spec=renderer_spec,
            n_sample_frames=n_sample_frames,
        )
        return _render_preview_pipeline.run_render_preview(
            self.dir, job, save_as=save_as, seed=seed
        )

    def run_embedding(
        self,
        tracking_run_id: str,
        track_ids: list[int],
        model_id: str | None = None,
        renderer_spec: list[dict] | None = None,
        batch_size: int = 32,
        compute: ComputeTarget | None = None,
        model_variant: str | None = None,
        constructor: str | None = None,
        readout: str | None = None,
        input_size: int | None = None,
        every_n_frames: int | None = None,
        *,
        align: str = "none",
        keypoint_run_id: str | None = None,
        heading: str | None = None,
        max_gap_s: float = 0.5,
        mirror_hold_s: float = 1.0,
        facing_camera_ratio: float = 0.5,
    ) -> RunHandle:
        """Embed the selected tracks through the renderer + model (Section 14).

        ``constructor`` is the name the ``renderer_spec`` was resolved from; passing it records the
        constructor on the run so a constructor-axis comparison can read it (the spec alone does not
        name it). ``renderer_spec`` ``None`` resolves the constructor per recording in ``validate``,
        which is the route an **aligned** run takes (the aligned canvas is sized from the turned
        masks and the alignment step is inserted there). ``readout`` selects the feature read-out
        and ``input_size`` the model input resolution (both recorded for the model / resolution
        comparison axes). ``every_n_frames`` omitted inherits the tracking run's cadence.

        §14 *Egocentric alignment*: ``align`` ``rotate`` / ``mirror`` turns each subject image so
        the animal faces right, reading the heading from ``keypoint_run_id`` (a keypoint track run on
        the same tracking run) through the saved heading definition ``heading``; ``max_gap_s``,
        ``mirror_hold_s`` and ``facing_camera_ratio`` are its settings and part of the run's
        identity. ``model_id`` omitted runs the configured default (``EmbeddingConfig``), and
        ``renderer_spec`` and ``constructor`` both omitted render the default constructor.
        Thin wrapper over ``run``."""
        from detail.api import models as api_models
        from detail.configs.embedding import EmbeddingConfig

        model_id = model_id or EmbeddingConfig.model_fields["model_id"].default

        return self.run(
            "embedding",
            {
                "tracking_run_id": tracking_run_id,
                "track_ids": list(track_ids),
                "model_id": model_id,
                "model_variant": model_variant,
                "renderer_spec": renderer_spec,
                "constructor": constructor,
                "readout": readout,
                "input_size": input_size,
                "batch_size": batch_size,
                "every_n_frames": every_n_frames,
                "align": align,
                "keypoint_run_id": keypoint_run_id,
                "heading": heading,
                "max_gap_s": max_gap_s,
                "mirror_hold_s": mirror_hold_s,
                "facing_camera_ratio": facing_camera_ratio,
                "compute": compute
                or default_compute(api_models.supported_backends(model_id)),
            },
        )

    def track_ids(self, tracking_run_id: str) -> list[int]:
        """Sorted track ids a completed tracking run produced (from its
        ``tracks.zarr``). ``[]`` when the run has no tracks summary yet.

        A completed run's ``tracks.zarr`` is immutable, so the read is cached against
        its mtime — the GUI reads this once per selected recording on every selection
        change, and over many recordings the repeated zarr opens are the select-all lag.
        """
        tracks_path = self.dir / "tracking" / tracking_run_id / "tracks.zarr"
        if not tracks_path.exists():
            return []
        return list(
            read_cache.cached_read(
                ("track_ids", str(tracks_path)),
                tracks_path,
                lambda: sorted(
                    int(t) for t in PartZarrReader(tracks_path).read()["track_id"]
                ),
            )
        )

    def embedding_preview(self, run_id: str):
        """A read-only accessor for a completed embedding run (Section 14): run
        metadata, per-track coverage, a 2-D PCA of the embeddings, and the frame +
        model input behind any point.

        Raises:
            ValueError: If no embedding run with this id exists in the recording.
        """
        from detail.api.run_preview import EmbeddingPreview

        return EmbeddingPreview(self.dir, run_id)

    def input_image_preview(
        self,
        tracking_run_id: str,
        renderer_spec: list[dict],
        *,
        alignment: dict | None = None,
    ):
        """A read-only scrubber accessor: per source frame, the original frame and
        the model-input image a constructor produces for a track (Section 14).

        ``alignment`` (§14) is the resolved alignment a run would record — ``align``,
        ``keypoint_run_id``, ``heading_definition``, ``heading_cutoff``, ``max_gap_s``,
        ``mirror_hold_s``, ``facing_camera_ratio`` — so the preview turns each input the way
        the run will, and shows no input where the run would embed no row.

        Raises:
            ValueError: If no tracking run with this id exists in the recording.
        """
        from detail.api.run_preview import InputImagePreview

        return InputImagePreview(
            self.dir, tracking_run_id, renderer_spec, alignment=alignment
        )

    def resolve_constructor(
        self,
        constructor: str,
        tracking_run_id: str,
        track_ids: list[int],
        model_id: str | None = None,
        resize: int | None = None,
        input_size: int | None = None,
        canvas_px: int | None = None,
    ) -> list[dict]:
        """Resolve a named input-image constructor to a concrete renderer_spec for
        this recording (Section 14), computing the shared canvas from this recording's
        masks when the constructor needs it — or taking ``canvas_px`` as given, which is
        how an aligned preview passes the canvas sized from the turned masks (§14). The same resolution an embedding run
        applies — use it to preview a constructor's inputs before launching.

        ``model_id`` supplies the default resize target (the model's input size) so a
        preview shows exactly the image the run will embed; ``input_size`` (the model
        resolution knob) overrides that default, and ``resize`` overrides both.

        Raises:
            ValueError: For an unknown constructor, or tracks with no detections.
        """
        from detail.pipeline.embedding import resolve_renderer_spec

        return resolve_renderer_spec(
            self.dir,
            tracking_run_id,
            list(track_ids),
            constructor,
            model_id=model_id,
            resize=resize,
            input_size=input_size,
            canvas_px=canvas_px,
        )

    def run_prompt_test(
        self,
        model_id: str,
        prompts: list[Prompt],
        n_sample_frames: int,
        compute: ComputeTarget,
        save_as: str | None = None,
        seed: int | None = None,
        model_variant: str | None = None,
        display_classes: list[str] | None = None,
        min_conf: float = 0.0,
        on_result=None,
    ) -> list[PromptTestResult]:
        """Preview a detection model on M sampled frames and return per-frame results (Section 8).

        Open-vocab models (SAM3) compare the N candidate ``prompts``, one
        result column each. A trained/imported closed-set model takes no prompt —
        it previews its own classes; ``display_classes`` picks which (default: all),
        one result column per class.

        The model runs wide open, so every returned detection is a proposal with its own
        ``confidence`` — filter the results at whatever threshold you want to look at.
        ``min_conf`` applies only to the JPGs ``save_as`` writes, which can't be
        re-thresholded once they exist.

        Synchronous: blocks until the predictions complete. Not an executor job — no
        zarr, no recovery, no recording.yaml entry. ``save_as`` writes overlay JPGs and
        ``test.json`` to ``detections/prompt_tests/<save_as>/`` for inspection.

        Raises:
            ValueError: For any failed pre-run validation.
            ModelNotReadyError: If the model's weights / credentials are not in place.
        """
        import_runner_modules(_PIPELINE_RUNNERS)
        data = recording_store.read_recording(self.dir)
        closed_set, model_classes = self._validate_prompt_test(
            data,
            model_id,
            prompts,
            n_sample_frames,
            compute,
            model_variant,
            display_classes,
        )
        if closed_set:
            chosen = list(display_classes) if display_classes else model_classes
            job_prompts = [
                Prompt(targets=[PromptTarget(class_name=c, cue=TextCue(c))])
                for c in chosen
            ]
        else:
            job_prompts = list(prompts)
        job = PromptTestJob(
            recording_id=self.id,
            model_id=model_id,
            prompts=job_prompts,
            n_sample_frames=n_sample_frames,
            compute=compute,
            model_variant=model_variant,
        )
        return _prompt_test_pipeline.run_prompt_test(
            self.dir,
            job,
            save_as=save_as,
            seed=seed,
            min_conf=min_conf,
            on_result=on_result,
        )

    def run_detection(
        self,
        model_id: str,
        prompt: Prompt,
        compute: ComputeTarget,
        conf_threshold: float = 0.5,
        confirm_fn=None,
        model_variant: str | None = None,
        batch_size: int | None = None,
        every_n_frames: int = 1,
    ) -> RunHandle:
        """Detect on each video part with the given model + prompt (Section 7).
        Thin wrapper over ``run``."""
        return self.run(
            "detection",
            {
                "model_id": model_id,
                "model_variant": model_variant,
                "prompt": prompt,
                "compute": compute,
                "conf_threshold": conf_threshold,
                "batch_size": batch_size,
                "every_n_frames": every_n_frames,
            },
        )

    def run_tracking(
        self,
        detection_run_id: str,
        tracker_id: str | None = None,
        hyperparams: dict | None = None,
        arena_ids: list[str] | None = None,
        arena_name: str | None = None,
        every_n_frames: int | None = None,
    ) -> RunHandle:
        """Link detections into tracks, optionally arena-filtered (Section 13).
        Thin wrapper over ``run``. ``every_n_frames`` omitted inherits the detection run's.

        ``tracker_id`` omitted takes ``configs.tracking.DEFAULT_TRACKER``, and ``hyperparams``
        omitted takes the chosen tracker's own defaults. Both are left *out* of the config
        rather than passed as ``None``: ``run`` does no None-stripping, and a ``None`` is
        rejected by the model before ``validate`` can resolve it.

        ``arena_name`` is the field of view **by name**, which is the same field of view on
        every recording; ``arena_ids`` names this recording's own arena directly. Prefer the
        name for anything that runs over more than one recording — an id is minted per
        recording, so the same one is a different polygon on the recording next to it.
        """
        config = {
            "detection_run_id": detection_run_id,
            "arena_ids": arena_ids,
            "arena_name": arena_name,
            "every_n_frames": every_n_frames,
        }
        if tracker_id is not None:
            config["tracker_id"] = tracker_id
        if hyperparams is not None:
            config["hyperparams"] = hyperparams
        return self.run("tracking", config)

    # -- keypoints (§26): PR 4 -- the detect stage ------------------------------- #
    def run_keypoint_detect(
        self,
        detection: str,
        model_id: str,
        *,
        example_set_id: str | None = None,
        min_pose_confidence: float | None = None,
        model_variant: str | None = None,
        decode: str | None = None,
        side_rule: str | None = None,
        crop_px: int | None = None,
        every_n_frames: int | None = None,
        batch_size: int | None = None,
        compute: ComputeTarget | None = None,
    ) -> RunHandle:
        """Place a skeleton's points on the animals of a detection run (§26
        ``keypoint_detect``): one row per pose instance, no subject — ``keypoint_track``
        gives each to a tracked subject.

        ``detection`` is the detection run id. ``model_id`` names the method
        (``dinov3_match``, which learns from ``example_set_id``'s marked frames, or a
        distilled student, which keeps every pose at or above ``min_pose_confidence``).
        ``decode`` / ``side_rule`` / ``crop_px`` left unset are resolved against the
        skeleton and written back to the run record; ``every_n_frames`` omitted inherits the
        detection run's cadence. Thin wrapper over ``run``.
        """
        from detail.api import models as api_models

        config = {
            "detection_run_id": detection,
            "model_id": model_id,
            "model_variant": model_variant,
            "example_set_id": example_set_id,
            "min_pose_confidence": min_pose_confidence,
            "decode": decode,
            "side_rule": side_rule,
            "crop_px": crop_px,
            "every_n_frames": every_n_frames,
            "compute": compute
            or default_compute(api_models.supported_backends(model_id)),
        }
        if batch_size is not None:
            config["batch_size"] = int(batch_size)
        return self.run("keypoint_detect", config)

    def keypoint_detect_run(self, run_id: str):
        """A detect run's reader (§26): its record, skeleton, parts, instances, coverage."""
        from detail.storage.keypoint_runs import KeypointDetectRun

        return KeypointDetectRun(self.dir, run_id)

    def keypoint_instances(self, run_id: str, part_id: str) -> dict:
        """Every pose instance a detect run placed in one video part, unassigned (§26
        *Analysis and export*): ``{column: array}`` with ``frame_idx``, ``t_ns``, ``bbox``,
        ``confidence``, ``detection_row``, ``points``, ``point_scores``, ``candidates`` /
        ``candidate_scores`` when kept and ``extras/<name>``. Zero rows for a part where
        nothing was placed.

        Raises:
            KeyError: ``part_id`` is not a video part of this recording.
        """
        from detail.storage import keypoint_runs

        run = self.keypoint_detect_run(run_id)
        if part_id in run.part_ids():
            return run.rows(part_id)
        parts = [
            recording_store.part_stem(f)
            for f in recording_store.video_files(
                recording_store.read_recording(self.dir)
            )
        ]
        if part_id not in parts:
            raise KeyError(
                f"no video part {part_id!r} in recording {self.id!r}; parts: {parts}"
            )
        empty = keypoint_runs._instance_columns(
            len(run.meta["skeleton"]["names"]), run.n_candidates
        )
        del empty["row"]
        return empty

    # -- keypoints (§26): PR 5 -- the track stage ---------------------------------- #
    def run_keypoint_track(
        self,
        detect: str,
        method: str | None = None,
        config: dict | None = None,
        *,
        tracking: str | None = None,
        match_min_inside: float | None = None,
        match_mask_grow: float | None = None,
    ) -> RunHandle:
        """Give a detect run's instances to a tracking run's subjects and settle them over
        time (§26 ``keypoint_track``).

        ``detect`` is the keypoint detect run id; ``tracking`` the tracking run whose
        subjects the instances are assigned to — omitted, the one complete tracking run on
        the detect run's detection run (several are refused, named). ``match_min_inside`` /
        ``match_mask_grow`` left unset take the assignment's defaults. ``method`` omitted
        takes the detect run's method's own default (``dinov3_match``: ``temporal_decode``);
        ``config`` holds the method's settings, every field of which is resolved and
        recorded. CPU only, seconds per recording. Thin wrapper over ``run``.
        """
        run_config = {
            "detect_run_id": detect,
            "tracking_run_id": tracking,
            "method": method,
            "config": dict(config or {}),
        }
        if match_min_inside is not None:
            run_config["match_min_inside"] = float(match_min_inside)
        if match_mask_grow is not None:
            run_config["match_mask_grow"] = float(match_mask_grow)
        return self.run("keypoint_track", run_config)

    def keypoint_track_run(self, run_id: str):
        """A track run's reader (§26): record, skeleton, parts, rows, coverage."""
        from detail.storage.keypoint_runs import KeypointTrackRun

        return KeypointTrackRun(self.dir, run_id)

    def keypoints(self, run_id: str, track_id: int) -> dict[str, dict]:
        """The final points of one track, every part — ``{part_id: {frame_idx, t_ns, points,
        point_scores, changed}}`` (§26 *Surfaces*)."""
        run = self.keypoint_track_run(run_id)
        return {
            part_id: run.rows(track_id, part_id) for part_id in run.part_ids(track_id)
        }

    @property
    def keypoint_detect_runs(self) -> list[dict]:
        """The keypoint detect run records (§26), as ``detection_runs`` is. `run_spec` reads a
        module's runs off the live Recording by ``runs_key``, so without this every picker of
        a keypoint run listed nothing in the app while the dict-driven tests passed."""
        return recording_store.read_recording(self.dir).get("keypoint_detect_runs", [])

    @property
    def keypoint_track_runs(self) -> list[dict]:
        """The keypoint track run records (§26); see ``keypoint_detect_runs``."""
        return recording_store.read_recording(self.dir).get("keypoint_track_runs", [])

    # --- validation (all hard errors, Tenet 10) ----------------------------- #
    # Stage validation lives on each ProcessingModule (§6.5). These two remain
    # for the synchronous inspection tools (§8 prompt-test, §14 render-preview),
    # which are not modules.
    def _validate_render_preview(
        self, data, tracking_run_id, track_ids, renderer_spec, n_sample_frames
    ) -> None:
        if n_sample_frames <= 0:
            raise ValueError(f"n_sample_frames must be > 0, got {n_sample_frames}")
        run = {r["id"]: r for r in data.get("tracking_runs", [])}.get(tracking_run_id)
        if run is None:
            raise ValueError(
                f"tracking run {tracking_run_id!r} not found in recording {self.id!r}"
            )
        if run.get("status") != "complete":
            raise ValueError(
                f"tracking run {tracking_run_id!r} is {run.get('status')!r}, not complete"
            )
        tracks_path = self.dir / "tracking" / tracking_run_id / "tracks.zarr"
        existing = {int(t) for t in PartZarrReader(tracks_path).read()["track_id"]}
        missing = [t for t in track_ids if int(t) not in existing]
        if missing:
            raise ValueError(
                f"track_ids {missing} not in tracking run {tracking_run_id!r}; "
                f"available: {sorted(existing)}"
            )
        unknown = sorted(
            {s["type"] for s in renderer_spec if s["type"] not in TRANSFORMS}
        )
        if unknown:
            raise ValueError(
                f"unknown transform types {unknown}; available: {sorted(TRANSFORMS)}"
            )

    def _validate_prompt_test(
        self,
        data,
        model_id,
        prompts,
        n_sample_frames,
        compute,
        model_variant=None,
        display_classes=None,
    ) -> tuple[bool, list[str]]:
        """Validate a prompt-test request. Returns ``(closed_set, model_classes)`` so
        the caller can build the closed-set class columns. Resolves through the shared
        resolver so a trained/imported model id (not just a pretrained one) is accepted.
        """
        if n_sample_frames <= 0:
            raise ValueError(f"n_sample_frames must be > 0, got {n_sample_frames}")
        model, _ = resolve_detection_model_auto(
            self.dir.parents[1], model_id, model_variant
        )
        if compute.backend not in model.supported_backends:
            raise ValueError(
                f"backend {compute.backend!r} not supported by {model_id!r}; "
                f"supported: {list(model.supported_backends)}"
            )
        closed_set = not model.supported_cue_types
        model_classes = list(getattr(model, "classes", []))
        if closed_set:
            if prompts:
                raise ValueError(
                    f"model {model_id!r} is closed-set and takes no text prompts; "
                    "choose which of its classes to preview instead"
                )
            for name in display_classes or []:
                if name not in model_classes:
                    raise ValueError(
                        f"class {name!r} is not one of {model_id!r}'s classes: "
                        f"{model_classes}"
                    )
        else:
            if display_classes:
                raise ValueError(
                    "display_classes only applies to a closed-set (trained/imported) "
                    f"model; {model_id!r} is open-vocab — pass text prompts instead"
                )
            if not prompts:
                raise ValueError("prompts must be non-empty")
            supported = list(model.supported_cue_types)
            unsupported: set[str] = set()
            for prompt in prompts:
                for target in prompt.targets:
                    if type(target.cue) not in supported:
                        unsupported.add(type(target.cue).__name__)
            if unsupported:
                raise ValueError(
                    f"model {model_id!r} does not support cue types {sorted(unsupported)}; "
                    f"supported: {[c.__name__ for c in supported]}"
                )
        status = model.readiness()
        if not status.ready:
            raise ModelNotReadyError(status)
        files = data.get("video", {}).get("files", [])
        if not files:
            raise ValueError(f"recording {self.id!r} has no video parts")
        for part in files:
            src = recording_store.resolve_part_video_path(self.dir, part)
            if not src.is_file():
                raise ValueError(
                    f"video for part {recording_store.part_stem(part)!r} is missing "
                    f"(expected at {src})"
                )
        return closed_set, model_classes

    # --- recording.yaml bookkeeping ------------------------------------------- #
    def _next_run_id(self, runs: list[dict], prefix: str) -> str:
        """Claim the next ``<prefix>_NN`` run id in this recording, never reused: an analysis
        record's ``tracking_run_ids`` and a tracking run's detection id name these, so a new
        run must not take a deleted one's id (``storage/id_allocator.py``)."""
        taken = [str(run.get("id")) for run in runs]
        return id_allocator.claim(self.dir, prefix, digits=2, taken=taken)

    def _reserve_run(self, key: str, prefix: str, make_record) -> str:
        """Allocate the next run id and append its record atomically under the recording lock.

        Serializing the read → allocate → append → write is what lets concurrent runs on one
        recording (e.g. embeddings on separate GPUs) get distinct ids without losing each other's
        records. ``make_record(run_id)`` builds the record once the id is known.
        """
        with recording_store.recording_lock(self.dir):
            data = recording_store.read_recording(self.dir)
            run_id = self._next_run_id(data.get(key, []), prefix)
            data.setdefault(key, []).append(make_record(run_id))
            recording_store.write_recording(self.dir, data)
        return run_id

    def _set_run_status(self, key: str, run_id: str, status: str) -> None:
        with recording_store.recording_lock(self.dir):
            data = recording_store.read_recording(self.dir)
            for run in data.get(key, []):
                if run.get("id") == run_id:
                    run["status"] = status
            recording_store.write_recording(self.dir, data)

import_status property

ready | queued | importing | failed | cancelled — defaults to ready for recordings created before the field existed (and for ones with no deferred import work).

video_available property

True iff the recording has video parts and all their files are present on disk. False for a video-excluded export (entries + timestamps kept, the .mp4 blobs absent) — preview surfaces check this to degrade gracefully instead of failing to decode.

distance_calibration property

The recording's distance-calibration block (Section 10), or None if not set. Fields: pixels_per_mm, ref_resolution [W, H], and (for a two-point pick) the normalized points and distance_mm.

pixels_per_mm property

pixels_per_mm at the recording's current video resolution (rescaled from the calibration's own resolution), or None if uncalibrated. With no video yet, the calibration's own value at its ref_resolution (:meth:calibration_reference).

Raises:

Type Description
ValueError

the calibration cannot describe this video — see :meth:calibration_refusal, which a display should ask first.

streams property

Stream manifest entries from recording.yaml (empty list if none).

is_annotated property

Whether the recording carries behavior ground-truth labels (Section 3).

Presence of any ground-truth behavior-role stream means the recording is annotated; per-behavior eligibility uses is_annotated_for (an ethogram scores only some behaviors). It is what an evaluation against ground truth gates a recording on.

A stream carrying a method's own re-ingested output (origin: predicted) does not annotate anything — counting it here would let a run be gated in on the very predictions it is about to be scored against (§19).

video_sources property

Where each video part's footage came from — one entry per part, "" when unknown (a part imported before origins were recorded; honest, not a guess).

One accessor because the user's question is the same ("which file is this?"). Both kinds store {root, rel} and are composed into an absolute path here, at display time — what they mean differs: a referenced part's source is the video's live location (relinking rewrites it, so this follows the file), while a copied part's origin is where it came from (the tool holds the footage; the original may since have moved, and nothing breaks if it has).

video_parts property

Video part entries from recording.yaml — [{index, file, timestamps}, ...].

Read accessor so callers never read recording.yaml directly (Tenet 2).

video_fps property

The recording's frame rate, or None if no video has been imported.

The container's advertised rate, read from recording.yaml — cheap enough for a form to consult per keystroke. It is a display number: the frame-exact reference is the PTS timestamp map, and a stride is an exact integer either way (§4, Tenet 8).

video_resolution property

The recording's source video resolution (width, height), or None if no video has been imported.

part_frame_counts property

Frame count of each video part, from its active timestamp map.

Lets a caller map a recording-global frame index to (part_index, local_idx) — e.g. the arena-draw canvas's single continuous frame slider (§10).

arenas property

Arena entries from recording.yaml — [{id, name, n_vertices}, ...].

rois property

ROI entries — [{id, name, n_vertices, active}, ...] (active is {start, end} or None = whole video).

points property

POI entries — [{id, name, n_vertices, active}, ...] (n_vertices is 1; active is {start, end} or None = whole video).

keypoint_detect_runs property

The keypoint detect run records (§26), as detection_runs is. run_spec reads a module's runs off the live Recording by runs_key, so without this every picker of a keypoint run listed nothing in the app while the dict-driven tests passed.

keypoint_track_runs property

The keypoint track run records (§26); see keypoint_detect_runs.

add_video_part(path, storage='default', video_root=None, progress=None, should_stop=None)

Import a video file as the next part: register it with the recording, generate its timestamp map, and append it to recording.yaml (Section 3).

The source is copied in verbatim, so the recording holds the footage at its original rate and resolution — a stage that wants fewer frames sets a every_n_frames on the run (§4), which needs no second copy. With storage="reference" the part is referenced in place: the video is not copied; the recording stores its location (a {root, rel} reference — the seam a remote backend plugs into) plus a content fingerprint, so a moved or changed file can be detected (Section 2). video_root is optional — when omitted, the video's own folder is remembered automatically (the caller references a path, never picks a location). The external source is only read, never modified. t_ns is each frame's time, global across parts (offset by the cumulative duration before it, Tenet 8).

Raises:

Type Description
FileNotFoundError

If path is not a file.

ValueError

If a reference import is missing/mismatched against its video root.

UserInputError

If the video's resolution or frame rate is not the recording's. Every part of a recording shares both (§3): boxes, masks and calibrations are in its pixels, and a detection run decodes every part's masks at one size.

Source code in detail/api/recording.py
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
def add_video_part(
    self,
    path: Path | str,
    storage: str = "default",
    video_root: str | None = None,
    progress: Callable[[str, float, str], None] | None = None,
    should_stop: Callable[[], bool] | None = None,
) -> None:
    """Import a video file as the next part: register it with the recording,
    generate its timestamp map, and append it to ``recording.yaml`` (Section 3).

    The source is **copied in** verbatim, so the recording holds the footage at its
    original rate and resolution — a stage that wants fewer frames sets a
    ``every_n_frames`` on the run (§4), which needs no second copy. With
    ``storage="reference"`` the part is **referenced in place**: the video is *not*
    copied; the recording stores its location (a ``{root, rel}`` reference — the seam a
    remote backend plugs into) plus a content fingerprint, so a moved or changed file can
    be detected (Section 2). ``video_root`` is optional — when omitted, the video's own
    folder is remembered automatically (the caller references a path, never picks a
    location). The external source is only read, never modified. ``t_ns`` is each frame's
    time, global across parts (offset by the cumulative duration before it, Tenet 8).

    Raises:
        FileNotFoundError: If ``path`` is not a file.
        ValueError: If a reference import is missing/mismatched against its video root.
        UserInputError: If the video's resolution or frame rate is not the recording's.
            Every part of a recording shares both (§3): boxes, masks and calibrations are
            in its pixels, and a detection run decodes every part's masks at one size.
    """
    src = Path(path)
    if not src.is_file():
        raise FileNotFoundError(f"video file not found: {path}")
    reference = storage == "reference"
    rel: str | None = None
    data = recording_store.read_recording(self.dir)
    video = data.get("video") or {"storage": storage, "files": []}

    index = len(video["files"])
    part_name = f"part_{index + 1:03d}"
    # Checked before a referenced file's folder is registered as a video root: a part
    # refused here leaves nothing behind, on the machine or in the experiment.
    probe = video_store.probe_video(src)
    if video["files"] and video.get("resolution"):
        # A recording written before its rate was recorded is held to its size alone.
        first = {
            "resolution": video["resolution"],
            "fps": video.get("fps_container") or probe["fps"],
        }
        differs = video_integrity.another_parts_shape(first, probe)
        if differs is not None:
            raise UserInputError(
                f"{src.name} cannot be another part of this recording: {differs}. "
                "Every part of a recording has one picture size and one frame rate; "
                "add it as a recording of its own."
            )
    if reference:
        if video_root is None:
            # No location given (the GUI/CLI default): remember the video's own folder
            # automatically — the user references a path, never picks a location.
            video_root = video_roots.resolve_or_register_root(src)
        root_dir = video_roots.video_root(video_root)
        if root_dir is None:
            raise ValueError(
                f"video root {video_root!r} is not registered; register it with "
                f"`detail video-root set {video_root} <path>`"
            )
        try:
            rel = src.resolve().relative_to(root_dir.resolve()).as_posix()
        except ValueError:
            raise ValueError(
                f"video {src} is not under video root {video_root!r} ({root_dir})"
            )
    fps = probe["fps"]
    # Integer ns from the parts' own maps, each re-based to start at 0 — the
    # offset is the only thing that places this part in the recording (Tenet 8).
    offset_ns = recording_store.video_end_ns(self.dir, data)
    dest = self.dir / "video" / f"{part_name}.mp4"
    on_timestamps = (
        (lambda f: progress(STAGE_TIMESTAMPS, f, ""))
        if progress is not None
        else None
    )
    try:
        if reference:
            # Reference in place: read the source's timestamps, never copy it.
            local_t_ns = video_store.generate_timestamps(
                src, fps, progress=on_timestamps
            )
            eff_fps = fps
            eff_resolution = probe["resolution"]
        else:
            local_t_ns = video_store.generate_timestamps(
                src, fps, progress=on_timestamps
            )
            on_bytes = (
                (lambda d, t: progress(STAGE_COPYING, d / t, _size_label(d, t)))
                if progress is not None
                else None
            )
            video_store.copy_with_progress(
                src, dest, progress=on_bytes, should_stop=should_stop
            )
            eff_fps = fps
            eff_resolution = probe["resolution"]
    except video_store.ImportStopped:
        dest.unlink(missing_ok=True)  # remove the partial part; no entry written
        raise
    t_ns = local_t_ns + offset_ns
    # Measured, not len/advertised-fps: the PTS map was demuxed precisely so this
    # number is real, and it sets every later part's offset (see offset_ns above).
    duration_s = video_store.part_duration_ns(local_t_ns, eff_fps) / (
        video_store.NS_PER_SECOND
    )

    ts_rel = f"video/timestamps/generated/{part_name}.csv"
    recording_store.write_timestamps_csv(self.dir / ts_rel, t_ns)

    if index == 0:
        video.update(
            fps_container=fps,
            fps_actual=eff_fps,
            fps_source="container",
            resolution=eff_resolution,
            total_duration_s=0.0,
        )
    entry = {
        "index": index,
        "id": part_name,  # stable stem for zarr/progress names (Section 3)
        "timestamps": {"generated": ts_rel, "user": None, "active": "generated"},
    }
    if reference:
        # No absolute path in the experiment file (Tenet 6): the location is a
        # {root, rel} reference resolved through the machine-local video-root
        # registry, plus a content fingerprint to detect a moved/changed file.
        entry["source"] = {"root": video_root, "rel": rel}
        entry["fingerprint"] = integrity.file_fingerprint(src)
        entry["frame_count"] = len(t_ns)
    else:
        entry["file"] = f"video/{part_name}.mp4"
        # Where this was copied *from*, in the same {root, rel} shape a referenced
        # part uses (Tenet 6 — the absolute path is composed at display time, never
        # stored). Provenance rather than a location: the tool owns the copy, so
        # nothing reads this to find pixels, but "which file was this?" still needs an
        # answer once the name has been edited away from the filename.
        #
        # Deliberately **not** ``source``: ``resolve_part_video_path`` keys on that to
        # decide where a part's frames live, so reusing it would send every read to
        # the external original instead of the copy — deleting the original would then
        # break runs we hold the footage for.
        origin_root = video_roots.resolve_or_register_root(src)
        origin_dir = video_roots.video_root(origin_root)
        entry["origin"] = {
            "root": origin_root,
            "rel": src.resolve().relative_to(origin_dir.resolve()).as_posix(),
        }
        # The copy's own fingerprint, in the shape a referenced part records: what
        # putting the video back after a slim import checks a candidate file against
        # (`relink_video_part`). Taken from the copy, which is the file the tool holds.
        entry["fingerprint"] = integrity.file_fingerprint(dest)
    video["files"].append(entry)
    video["total_duration_s"] += duration_s
    data["video"] = video
    recording_store.write_recording(self.dir, data)

verify_videos()

Check every video part is present and (for referenced parts) unchanged (Section 2).

Returns the list of integrity issues (empty means all good) — the same check the run pre-flight gate enforces, exposed so a user can check without launching a run.

Source code in detail/api/recording.py
492
493
494
495
496
497
498
499
def verify_videos(self) -> list[video_integrity.VideoIssue]:
    """Check every video part is present and (for referenced parts) unchanged (Section 2).

    Returns the list of integrity issues (empty means all good) — the same check the run
    pre-flight gate enforces, exposed so a user can check without launching a run.
    """
    data = recording_store.read_recording(self.dir)
    return video_integrity.validate_source_videos(self.dir, data)

Point a part at its video file again: Locate video, and recording relink.

A referenced part is pointed at a moved or renamed file, verified by fingerprint: the new file's content fingerprint must match what was recorded. A mismatch means the content changed, not just moved, and is refused (remove and re-add the recording instead). The new path need not be under a registered video root: one is registered for it, the way an import does. When the part's own root is not registered on this machine (an experiment made elsewhere) and the file sits where that root would put it, the root itself is registered, so every other recording referencing it resolves too.

A copied part whose file is missing (an experiment imported from a bundle without its video, or replaced by one) has the file copied back in to its video/part_NNN.mp4; the part stays a copied part. The file is accepted only if its frame times match the part's recorded timestamp map exactly (count and every t_ns, both re-based to start at 0) and its resolution matches the recording's, and, for a part that recorded a fingerprint, only if that matches too. The copy goes to a sibling temporary file moved into place when complete, so a cancel (progress raising) leaves no half file. A copied part whose file is present is refused: there is nothing to put back.

progress(stage, fraction, detail) reports a put-back's two long steps, :data:STAGE_TIMESTAMPS then :data:STAGE_COPYING. A referenced relink reads two MiB and reports nothing.

Returns:

Type Description
str | None

The video-root alias this call registered on this machine, or None if it

str | None

used one that was already registered (always None for a copied part).

Raises:

Type Description
FileNotFoundError

new_path is not a file.

IndexError

part_index is out of range.

ValueError

the content differs from a referenced part's.

UserInputError

a copied part's video is already here, or the file is not that part's video (it names what differs).

Source code in detail/api/recording.py
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
def relink_video_part(
    self,
    part_index: int,
    new_path: Path | str,
    progress: Callable[[str, float, str], None] | None = None,
) -> str | None:
    """Point a part at its video file again: Locate video, and ``recording relink``.

    **A referenced part** is pointed at a moved or renamed file, verified by fingerprint:
    the new file's content fingerprint must match what was recorded. A mismatch means the
    content *changed*, not just moved, and is refused (remove and re-add the recording
    instead). The new path need not be under a registered video root: one is registered
    for it, the way an import does. When the part's own root is not registered on this
    machine (an experiment made elsewhere) and the file sits where that root would put it,
    the root itself is registered, so every other recording referencing it resolves too.

    **A copied part whose file is missing** (an experiment imported from a bundle without
    its video, or replaced by one) has the file **copied back in** to its
    ``video/part_NNN.mp4``; the part stays a copied part. The file is accepted only if
    its frame times match the part's recorded timestamp map exactly (count and every
    ``t_ns``, both re-based to start at 0) and its resolution matches the recording's,
    and, for a part that recorded a fingerprint, only if that matches too. The copy goes
    to a sibling temporary file moved into place when complete, so a cancel (``progress``
    raising) leaves no half file. A copied part whose file is present is refused: there
    is nothing to put back.

    ``progress(stage, fraction, detail)`` reports a put-back's two long steps,
    :data:`STAGE_TIMESTAMPS` then :data:`STAGE_COPYING`. A referenced relink reads two
    MiB and reports nothing.

    Returns:
        The video-root alias this call registered on this machine, or ``None`` if it
        used one that was already registered (always ``None`` for a copied part).

    Raises:
        FileNotFoundError: ``new_path`` is not a file.
        IndexError: ``part_index`` is out of range.
        ValueError: the content differs from a referenced part's.
        UserInputError: a copied part's video is already here, or the file is not that
            part's video (it names what differs).
    """
    new = Path(new_path)
    if not new.is_file():
        raise FileNotFoundError(f"video file not found: {new_path}")
    data = recording_store.read_recording(self.dir)
    files = data.get("video", {}).get("files", [])
    if not (0 <= part_index < len(files)):
        raise IndexError(f"part_index {part_index} out of range [0, {len(files)})")
    part = files[part_index]
    if part.get("source") is None:
        self._put_back_copied_part(part_index, data, new, progress)
        return None
    current = integrity.file_fingerprint(new)
    if not integrity.same_content(current, part.get("fingerprint")):
        raise ValueError(
            f"{new} has different content than the recorded video — it is a changed or "
            "different video, not a move; remove and re-add the recording to use it"
        )
    alias, rel, registered = _relink_root(new, part["source"])
    part["source"] = {"root": alias, "rel": rel}
    part["fingerprint"] = current  # a moved/renamed file may have a fresh mtime
    recording_store.write_recording(self.dir, data)
    return registered

parts_to_locate()

The parts Locate video can act on: every referenced part, and each copied part whose file is not here, with the file it was copied from when that is on this machine.

Reads the recording's parts, a stat per copied part, and resolves each missing copied part's origin, which can be a network share: call it off the UI thread.

Source code in detail/api/recording.py
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def parts_to_locate(self) -> list["LocatablePart"]:
    """The parts Locate video can act on: every referenced part, and each copied part
    whose file is not here, with the file it was copied from when that is on this machine.

    Reads the recording's parts, a ``stat`` per copied part, and resolves each missing
    copied part's ``origin``, which can be a network share: call it off the UI thread.
    """
    data = recording_store.read_recording(self.dir)
    out = []
    for position, part in enumerate(recording_store.video_files(data)):
        stem = recording_store.part_stem(part)
        if part.get("source") is not None:
            out.append(LocatablePart(position, stem, copied=False))
            continue
        if (self.dir / part["file"]).is_file():
            continue
        out.append(
            LocatablePart(
                position,
                stem,
                copied=True,
                copied_from=_copied_from(part.get("origin")),
                origin_name=Path((part.get("origin") or {}).get("rel", "")).name,
            )
        )
    return out

define_arena(name, keyframes)

Define a named arena polygon (Section 10).

Each keyframe is (frame_idx, [(x, y), ...]) with recording-global frame_idx (0 = first frame of part_001) and normalized vertices in [0, 1]. All keyframes must have the same vertex count.

Returns:

Type Description
str

The auto-assigned stable arena id (e.g. "arena_001") — this is

str

what TrackingJob.arena_ids refers to.

Raises:

Type Description
ValueError

If keyframes are invalid (see storage.spatial.write_arena_keyframes) or the name is empty or already in use within this recording.

Source code in detail/api/recording.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
def define_arena(
    self,
    name: str,
    keyframes: list[tuple[int, list[tuple[float, float]]]],
) -> str:
    """Define a named arena polygon (Section 10).

    Each keyframe is ``(frame_idx, [(x, y), ...])`` with recording-global
    ``frame_idx`` (0 = first frame of part_001) and normalized vertices in
    ``[0, 1]``. All keyframes must have the same vertex count.

    Returns:
        The auto-assigned stable arena id (e.g. ``"arena_001"``) — this is
        what ``TrackingJob.arena_ids`` refers to.

    Raises:
        ValueError: If keyframes are invalid (see
            ``storage.spatial.write_arena_keyframes``) or the name is empty
            or already in use within this recording.
    """
    arena_id = spatial_store.next_arena_id(self.dir)
    n_vertices = spatial_store.write_arena_keyframes(self.dir, arena_id, keyframes)
    spatial_store.append_arena_to_recording_yaml(
        self.dir, arena_id, name, n_vertices
    )
    return arena_id

arena_dependents(arena_id)

Tracking run ids that used arena_id — editing or removing the arena would make their recorded region inconsistent, so it is blocked while any exist (delete those runs first).

Source code in detail/api/recording.py
691
692
693
694
695
696
697
698
699
700
def arena_dependents(self, arena_id: str) -> list[str]:
    """Tracking run ids that used ``arena_id`` — editing or removing the arena
    would make their recorded region inconsistent, so it is blocked while any
    exist (delete those runs first)."""
    data = recording_store.read_recording(self.dir)
    return [
        t["id"]
        for t in data.get("tracking_runs", [])
        if arena_id in (t.get("arena_ids") or [])
    ]

arena_keyframes(arena_id)

The arena's polygon keyframes as [(frame_idx, [(x, y), ...]), ...] (normalized vertices), e.g. to reload it into the editor.

Raises:

Type Description
ValueError

If no arena with this id exists in the recording.

Source code in detail/api/recording.py
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def arena_keyframes(
    self, arena_id: str
) -> list[tuple[int, list[tuple[float, float]]]]:
    """The arena's polygon keyframes as ``[(frame_idx, [(x, y), ...]), ...]``
    (normalized vertices), e.g. to reload it into the editor.

    Raises:
        ValueError: If no arena with this id exists in the recording.
    """
    arenas = {a["id"]: a for a in self.arenas}
    if arena_id not in arenas:
        raise ValueError(f"unknown arena_id {arena_id!r}")
    # Cached on the CSV's own mtime. The spatial map reads one of these **per recording**
    # every time a result page opens, which at a hundred recordings is a hundred CSV parses
    # for a polygon that changes only when somebody edits the arena. The keyframes are
    # rebuilt into fresh lists below, so a hit hands nobody a shared mutable.
    path = spatial_store.arena_keyframes_path(self.dir, arena_id)
    pk = read_cache.cached_read(
        ("arena_keyframes", str(self.dir), arena_id),
        path,
        lambda: spatial_store.read_arena_keyframes(
            self.dir, arena_id, arenas[arena_id]["n_vertices"]
        ),
    )
    return [
        (int(frame), [(float(x), float(y)) for x, y in verts])
        for frame, verts in pk.keyframes
    ]

clear_arenas()

Remove all arenas (keyframes + recording.yaml entries) so the recording's single arena can be redrawn. Already-computed runs are unaffected.

Raises:

Type Description
ValueError

If a tracking run used one of the arenas (see arena_dependents) — delete that run first.

Source code in detail/api/recording.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
def clear_arenas(self) -> None:
    """Remove all arenas (keyframes + recording.yaml entries) so the recording's
    single arena can be redrawn. Already-computed runs are unaffected.

    Raises:
        ValueError: If a tracking run used one of the arenas (see
            ``arena_dependents``) — delete that run first.
    """
    arenas = recording_store.read_recording(self.dir).get("arenas", [])
    blocked = {
        a["id"]: deps for a in arenas if (deps := self.arena_dependents(a["id"]))
    }
    if blocked:
        detail = "; ".join(f"{aid} ← {deps}" for aid, deps in blocked.items())
        raise ValueError(
            f"cannot edit/clear arena(s) used by tracking runs: {detail} "
            "— delete those runs first"
        )
    for arena in arenas:
        spatial_store.delete_arena(self.dir, arena["id"])

delete_arena(arena_id)

Remove a single arena (keyframes + recording.yaml entry). Already-computed runs are unaffected — the polygon was applied at run time.

Raises:

Type Description
ValueError

If a tracking run used this arena (see arena_dependents) — delete that run first.

Source code in detail/api/recording.py
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
def delete_arena(self, arena_id: str) -> None:
    """Remove a single arena (keyframes + recording.yaml entry). Already-computed
    runs are unaffected — the polygon was applied at run time.

    Raises:
        ValueError: If a tracking run used this arena (see ``arena_dependents``)
            — delete that run first.
    """
    deps = self.arena_dependents(arena_id)
    if deps:
        raise ValueError(
            f"cannot delete arena {arena_id!r} used by tracking runs: {deps} "
            "— delete those runs first"
        )
    spatial_store.delete_arena(self.dir, arena_id)

define_roi(name, keyframes, active=None)

Define a named region-of-interest polygon (Section 10).

ROIs are analysis-time only — they do not affect detection or tracking. Keyframes match define_arena (recording-global frame_idx, normalized [0, 1] vertices, >= 3 per keyframe). active is an optional inclusive (start, end) recording-global frame interval the ROI is present for; None = whole video.

Returns:

Type Description
str

The auto-assigned stable id (e.g. "roi_001").

Raises:

Type Description
ValueError

If keyframes/active are invalid, or the name is empty or already used within this recording.

Source code in detail/api/recording.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
def define_roi(
    self,
    name: str,
    keyframes: list[tuple[int, list[tuple[float, float]]]],
    active: tuple[int, int] | None = None,
) -> str:
    """Define a named region-of-interest polygon (Section 10).

    ROIs are **analysis-time only** — they do not affect detection or
    tracking. Keyframes match ``define_arena`` (recording-global ``frame_idx``,
    normalized ``[0, 1]`` vertices, >= 3 per keyframe). ``active`` is an
    optional inclusive ``(start, end)`` recording-global frame interval the ROI
    is present for; ``None`` = whole video.

    Returns:
        The auto-assigned stable id (e.g. ``"roi_001"``).

    Raises:
        ValueError: If keyframes/active are invalid, or the name is empty or
            already used within this recording.
    """
    roi_id = spatial_store.next_id(self.dir, "roi")
    n = spatial_store.write_keyframes(self.dir, "roi", roi_id, keyframes)
    spatial_store.append_to_manifest(self.dir, "roi", roi_id, name, n, active)
    return roi_id

roi_keyframes(roi_id)

The ROI's polygon keyframes (to reload it into the editor).

Raises:

Type Description
ValueError

If no ROI with this id exists in the recording.

Source code in detail/api/recording.py
828
829
830
831
832
833
834
def roi_keyframes(self, roi_id: str) -> list[tuple[int, list[tuple[float, float]]]]:
    """The ROI's polygon keyframes (to reload it into the editor).

    Raises:
        ValueError: If no ROI with this id exists in the recording.
    """
    return self._spatial_keyframes("roi", "rois", roi_id)

roi_at_frame(roi_id, frame_idx)

The ROI polygon at frame_idx as an (n_vertices, 2) array, or None if the ROI is not active at that frame (Section 10).

Source code in detail/api/recording.py
836
837
838
839
def roi_at_frame(self, roi_id: str, frame_idx: int) -> np.ndarray | None:
    """The ROI polygon at ``frame_idx`` as an ``(n_vertices, 2)`` array, or
    ``None`` if the ROI is not active at that frame (Section 10)."""
    return self._spatial_at_frame("roi", "rois", roi_id, frame_idx)

delete_roi(roi_id)

Remove an ROI (keyframes + recording.yaml entry). Unconditional: a finished location run keeps its own rows, and the id is never given to another ROI.

Source code in detail/api/recording.py
841
842
843
844
def delete_roi(self, roi_id: str) -> None:
    """Remove an ROI (keyframes + recording.yaml entry). Unconditional: a finished
    location run keeps its own rows, and the id is never given to another ROI."""
    spatial_store.delete_def(self.dir, "roi", roi_id)

define_point(name, keyframes, active=None)

Define a named point of interest (Section 10) — a landmark point (lever, port, hopper).

Each keyframe carries exactly one normalized vertex; a single keyframe is a static point, more keyframes move it (e.g. a panning camera). Analysis-time only (does not affect detection/tracking). active as in define_roi. Distinct from pose keypoints (user-placed, not model-derived).

Returns:

Type Description
str

The auto-assigned stable id (e.g. "point_001").

Source code in detail/api/recording.py
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
def define_point(
    self,
    name: str,
    keyframes: list[tuple[int, list[tuple[float, float]]]],
    active: tuple[int, int] | None = None,
) -> str:
    """Define a named point of interest (Section 10) — a landmark point
    (lever, port, hopper).

    Each keyframe carries exactly **one** normalized vertex; a single keyframe
    is a static point, more keyframes move it (e.g. a panning camera).
    Analysis-time only (does not affect detection/tracking). ``active`` as in
    ``define_roi``. Distinct from pose keypoints (user-placed, not model-derived).

    Returns:
        The auto-assigned stable id (e.g. ``"point_001"``).
    """
    point_id = spatial_store.next_id(self.dir, "point")
    n = spatial_store.write_keyframes(self.dir, "point", point_id, keyframes)
    spatial_store.append_to_manifest(self.dir, "point", point_id, name, n, active)
    return point_id

point_keyframes(point_id)

The POI's keyframes (one vertex each).

Raises:

Type Description
ValueError

If no POI with this id exists in the recording.

Source code in detail/api/recording.py
868
869
870
871
872
873
874
875
876
def point_keyframes(
    self, point_id: str
) -> list[tuple[int, list[tuple[float, float]]]]:
    """The POI's keyframes (one vertex each).

    Raises:
        ValueError: If no POI with this id exists in the recording.
    """
    return self._spatial_keyframes("point", "points", point_id)

point_at_frame(point_id, frame_idx)

The point as a (1, 2) array at frame_idx, or None if the POI is not active at that frame (Section 10).

Source code in detail/api/recording.py
878
879
880
881
def point_at_frame(self, point_id: str, frame_idx: int) -> np.ndarray | None:
    """The point as a ``(1, 2)`` array at ``frame_idx``, or ``None`` if the POI
    is not active at that frame (Section 10)."""
    return self._spatial_at_frame("point", "points", point_id, frame_idx)

delete_point(point_id)

Remove a POI (keyframes + recording.yaml entry). Unconditional.

Source code in detail/api/recording.py
883
884
885
def delete_point(self, point_id: str) -> None:
    """Remove a POI (keyframes + recording.yaml entry). Unconditional."""
    spatial_store.delete_def(self.dir, "point", point_id)

set_rois(defs)

Replace all ROIs in one transaction — the multi-region manager's "Save all" (Section 10). Each entry is {"name", "keyframes", "active", "id"} (active and id optional). An entry carrying the id of an ROI that exists keeps it; any other gets an id never used in this recording before. Returns the ids, in order.

Raises:

Type Description
ValueError

If any def is invalid (empty/duplicate name or id, bad keyframes/active).

Source code in detail/api/recording.py
887
888
889
890
891
892
893
894
895
896
897
def set_rois(self, defs: list[dict]) -> list[str]:
    """Replace **all** ROIs in one transaction — the multi-region manager's "Save all"
    (Section 10). Each entry is ``{"name", "keyframes", "active", "id"}`` (``active``
    and ``id`` optional). An entry carrying the id of an ROI that exists keeps it; any
    other gets an id never used in this recording before. Returns the ids, in order.

    Raises:
        ValueError: If any def is invalid (empty/duplicate name or id, bad
            keyframes/active).
    """
    return spatial_store.replace_defs(self.dir, "roi", defs)

set_points(defs)

Replace all POIs in one transaction — the manager's "Save all" (Section 10). Each entry is {"name", "keyframes", "active", "id"}; each keyframe carries one vertex. Ids are kept and minted as in :meth:set_rois. Returns the ids, in order.

Source code in detail/api/recording.py
899
900
901
902
903
904
def set_points(self, defs: list[dict]) -> list[str]:
    """Replace **all** POIs in one transaction — the manager's "Save all" (Section 10).
    Each entry is ``{"name", "keyframes", "active", "id"}``; each keyframe carries one
    vertex. Ids are kept and minted as in :meth:`set_rois`. Returns the ids, in order.
    """
    return spatial_store.replace_defs(self.dir, "point", defs)

check_spatial_defs(kind, defs)

Refuse a whole set of kind ("arena", "roi" or "point") definitions the way :meth:set_rois / :meth:set_points / :meth:define_arena would, writing nothing — for a caller that commits several kinds at once and must not have written one before another is refused (the scene editor's Save).

Raises:

Type Description
ValueError

An empty or duplicated name or id, or invalid keyframes / active.

Source code in detail/api/recording.py
906
907
908
909
910
911
912
913
914
915
def check_spatial_defs(self, kind: str, defs: list[dict]) -> None:
    """Refuse a whole set of ``kind`` (``"arena"``, ``"roi"`` or ``"point"``) definitions
    the way :meth:`set_rois` / :meth:`set_points` / :meth:`define_arena` would, writing
    nothing — for a caller that commits several kinds at once and must not have written
    one before another is refused (the scene editor's Save).

    Raises:
        ValueError: An empty or duplicated name or id, or invalid keyframes / active.
    """
    spatial_store.validate_defs(kind, defs)

check_distance_calibration(points, distance_mm)

Refuse what :meth:set_distance_calibration would refuse, writing nothing.

Raises:

Type Description
ValueError

if there is no video, the points coincide, or distance_mm <= 0.

Source code in detail/api/recording.py
917
918
919
920
921
922
923
924
925
926
927
def check_distance_calibration(
    self, points: list[tuple[float, float]], distance_mm: float
) -> None:
    """Refuse what :meth:`set_distance_calibration` would refuse, writing nothing.

    Raises:
        ValueError: if there is no video, the points coincide, or ``distance_mm <= 0``.
    """
    spatial_store.calibration_from_points(
        points, distance_mm, self._require_resolution()
    )

export_spatial_csv(path)

Write this recording's whole spatial setup to a round-trippable CSV (Section 10) — the field of view, the distance calibration, and the ROIs + POIs — for sharing or importing onto another recording.

One file per recording rather than one per kind; the import side is per kind, so a single export can feed any of them.

Source code in detail/api/recording.py
929
930
931
932
933
934
935
936
937
def export_spatial_csv(self, path: Path | str) -> None:
    """Write this recording's whole spatial setup to a round-trippable CSV (Section 10)
    — the field of view, the distance calibration, and the ROIs + POIs — for sharing or
    importing onto another recording.

    One file per recording rather than one per kind; the import side is per kind, so a
    single export can feed any of them.
    """
    spatial_store.export_spatial(self.dir, path)

import_spatial_csv(path, kinds=('roi', 'point'))

Take the kinds rows of an exported spatial CSV onto this recording (§10).

Goes through :meth:receive_spatial, so a setup pulled from a file obeys the same rules as one pushed from a recording: nothing is replaced, a name already here is refused rather than suffixed (2), keyframe motion is flattened, and an active window does not travel.

All or nothing across kinds: every definition is checked before the first is written, so a bad point does not leave the regions above it behind (a retry then refused them as "already exists").

Returns:

Type Description
tuple[list[str], list[str], list[tuple[str, str]]]

(added, flattened, refused).

Source code in detail/api/recording.py
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
def import_spatial_csv(
    self, path: Path | str, kinds: tuple[str, ...] = ("roi", "point")
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take the ``kinds`` rows of an exported spatial CSV onto this recording (§10).

    Goes through :meth:`receive_spatial`, so a setup **pulled** from a file obeys the
    same rules as one **pushed** from a recording: nothing is replaced, a name already
    here is refused rather than suffixed ``(2)``, keyframe motion is flattened, and an
    active window does not travel.

    All or nothing across ``kinds``: every definition is checked before the first is
    written, so a bad point does not leave the regions above it behind (a retry then
    refused them as "already exists").

    Returns:
        ``(added, flattened, refused)``.
    """
    by_kind = {}
    for d in spatial_store.load_spatial_csv(path):
        by_kind.setdefault(d["kind"], []).append(d)
    added, flattened, refused = self._receive_spatial_kinds(
        {kind: by_kind.get(kind, []) for kind in kinds}
    )
    if not added and not refused:
        raise ValueError(f"{path} carries no {' or '.join(kinds)}")
    return added, flattened, refused

import_scene_csv(path)

Take everything an exported spatial CSV carries onto this recording (§10): its field of view, distance calibration, regions and points, each by its own rules (:meth:import_field_of_view_csv, :meth:import_calibration_csv, :meth:import_spatial_csv). Nothing is replaced.

Only the kinds the file holds are tried. A kind it does not carry is not a refusal: trying all four turned a one-region file into one "Added" line and three "Not added" ones, which reads as a partial failure (#35 finding 14). A kind refused whole (this recording already has a field of view or a calibration) is one refusal, named by what it is.

Returns:

Type Description
tuple[list[str], list[str], list[tuple[str, str]]]

(added, flattened, refused).

Raises:

Type Description
FileNotFoundError

the file is absent.

ValueError

the file is malformed, or carries no scene geometry at all.

Source code in detail/api/recording.py
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
def import_scene_csv(
    self, path: Path | str
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take everything an exported spatial CSV carries onto this recording (§10): its
    field of view, distance calibration, regions and points, each by its own rules
    (:meth:`import_field_of_view_csv`, :meth:`import_calibration_csv`,
    :meth:`import_spatial_csv`). Nothing is replaced.

    Only the kinds the file holds are tried. A kind it does not carry is not a refusal:
    trying all four turned a one-region file into one "Added" line and three "Not added"
    ones, which reads as a partial failure (#35 finding 14). A kind refused whole (this
    recording already has a field of view or a calibration) is one refusal, named by
    what it is.

    Returns:
        ``(added, flattened, refused)``.

    Raises:
        FileNotFoundError: the file is absent.
        ValueError: the file is malformed, or carries no scene geometry at all.
    """
    held = spatial_store.spatial_csv_kinds(path)
    if not held:
        raise ValueError(f"{path} carries no scene geometry")
    # All or nothing, like every import (#29): the whole file is parsed, and every kind
    # it carries is either refused here as a whole (reported, nothing written) or checked
    # with the rest before the first write, so a bad point cannot leave the field of view
    # above it behind.
    by_kind: dict[str, list[dict]] = {}
    for d in spatial_store.load_spatial_csv(path):
        by_kind.setdefault(d["kind"], []).append(d)
    block = (
        spatial_store.load_calibration_csv(path) if "calibration" in held else None
    )
    refused: list[tuple[str, str]] = []
    if by_kind.get("arena"):
        refusal = self.field_of_view_refusal()
        if refusal is not None:
            refused.append(("field of view", f"recording {self.name!r} {refusal}"))
            del by_kind["arena"]
    if block is not None:
        if self.distance_calibration is not None:
            refused.append(
                (
                    "distance calibration",
                    f"recording {self.name!r} already has a distance calibration — "
                    "delete it here first; nothing is overwritten",
                )
            )
            block = None
        else:
            try:
                spatial_store.check_calibration_block(block, self.video_resolution)
            except ValueError as exc:
                refused.append(("distance calibration", str(exc)))
                block = None
    kinds = ("arena", *self._PER_DEFINITION_KINDS)
    added, flattened, kind_refused = self._receive_spatial_kinds(
        {kind: by_kind[kind] for kind in kinds if by_kind.get(kind)}
    )
    refused = refused + kind_refused
    if block is not None:
        spatial_store.write_calibration_block(
            self.dir, block, self.video_resolution
        )
        added.append("distance calibration")
    return added, flattened, refused

import_spatial_from(source, kinds=('roi', 'point'))

Take another recording's ROIs/POIs onto this one (§10) — the pull twin of Experiment.propagate_rois / propagate_points, and the same rules.

Returns:

Type Description
tuple[list[str], list[str], list[tuple[str, str]]]

(added, flattened, refused).

Source code in detail/api/recording.py
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
def import_spatial_from(
    self, source: "Recording", kinds: tuple[str, ...] = ("roi", "point")
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take another recording's ROIs/POIs onto this one (§10) — the *pull* twin of
    ``Experiment.propagate_rois`` / ``propagate_points``, and the same rules.

    Returns:
        ``(added, flattened, refused)``.
    """
    added, flattened, refused = self._receive_spatial_kinds(
        {kind: spatial_store.read_defs(source.dir, kind) for kind in kinds}
    )
    if not added and not refused:
        raise ValueError(
            f"recording {source.name!r} has no {' or '.join(kinds)} to copy"
        )
    return added, flattened, refused

field_of_view_refusal()

Why this recording cannot receive a field of view, or None.

One sentence for both directions. It lived only on the push side, so pulling a field of view onto a locked recording said "already has one" and stopped, while pushing the identical setup named the tracking runs you would have to delete first — same situation, two qualities of advice.

It carries no "here" or "there": the pull direction reads it about the recording you are on and the push direction reads it about a row in a list of sixty others, so either word is wrong half the time.

Source code in detail/api/recording.py
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def field_of_view_refusal(self) -> str | None:
    """Why this recording cannot receive a field of view, or ``None``.

    One sentence for both directions. It lived only on the push side, so pulling a
    field of view onto a locked recording said "already has one" and stopped, while
    pushing the identical setup named the tracking runs you would have to delete
    first — same situation, two qualities of advice.

    It carries no "here" or "there": the pull direction reads it about the recording
    you are on and the push direction reads it about a row in a list of sixty others,
    so either word is wrong half the time.
    """
    if not self.arenas:
        return None
    blocking = sorted(
        {
            run_id
            for arena in self.arenas
            for run_id in self.arena_dependents(arena["id"])
        }
    )
    if blocking:
        return (
            "already has a field of view, used by tracking "
            f"{'runs' if len(blocking) > 1 else 'run'} {', '.join(blocking)} — "
            "delete those runs, then that field of view"
        )
    return "already has a field of view — delete the existing one first"

receive_spatial(defs, kind)

Take defs (already parsed, from a recording or a CSV) onto this recording.

The one door for a setup arriving from elsewhere, whichever direction it was started from and whichever source it came from. Applies storage.spatial.prepare_for_arrival's timeline policy, then refuses by name for the set-shaped kinds — nothing is ever replaced.

Returns:

Type Description
list[str]

(added, flattened, refused) — names written, names whose keyframe motion

list[str]

was dropped, and [(name, reason), ...] left behind.

Raises:

Type Description
ValueError

A definition that is not valid (nothing is written).

Source code in detail/api/recording.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
def receive_spatial(
    self, defs: list[dict], kind: str
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take ``defs`` (already parsed, from a recording or a CSV) onto this recording.

    The one door for a setup arriving from elsewhere, whichever direction it was
    started from and whichever source it came from. Applies
    ``storage.spatial.prepare_for_arrival``'s timeline policy, then refuses by name for
    the set-shaped kinds — nothing is ever replaced.

    Returns:
        ``(added, flattened, refused)`` — names written, names whose keyframe motion
        was dropped, and ``[(name, reason), ...]`` left behind.

    Raises:
        ValueError: A definition that is not valid (nothing is written).
    """
    return self._receive_spatial_kinds({kind: defs})

propagate_spatial_from(source, kind, names=None)

Take a copy of source's kind definitions (Section 10).

A thin read in front of :meth:receive_spatial, which owns the policy.

Returns:

Type Description
tuple[list[str], list[str], list[tuple[str, str]]]

(added, flattened, refused).

Source code in detail/api/recording.py
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
def propagate_spatial_from(
    self, source: "Recording", kind: str, names: list[str] | None = None
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take a copy of ``source``'s ``kind`` definitions (Section 10).

    A thin read in front of :meth:`receive_spatial`, which owns the policy.

    Returns:
        ``(added, flattened, refused)``.
    """
    defs = spatial_store.read_defs(source.dir, kind)
    if names is not None:
        defs = [d for d in defs if d["name"] in set(names)]
    return self.receive_spatial(defs, kind)

import_field_of_view_from(source)

Take source's field of view onto this recording (§10).

Never replaces. A recording that already has one keeps it; delete it here first (and the tracking runs holding it, which arena_dependents names). This used to clear_arenas() and copy over the top after a Yes/No — the same operation the push direction refuses outright, which is how one setup arriving from elsewhere came to have two contradictory rules depending on which way you started it.

Returns:

Type Description
tuple[list[str], list[str], list[tuple[str, str]]]

(added, flattened, refused).

Source code in detail/api/recording.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
def import_field_of_view_from(
    self, source: "Recording"
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take ``source``'s field of view onto this recording (§10).

    **Never replaces.** A recording that already has one keeps it; delete it here first
    (and the tracking runs holding it, which ``arena_dependents`` names). This used to
    ``clear_arenas()`` and copy over the top after a Yes/No — the same operation the
    *push* direction refuses outright, which is how one setup arriving from elsewhere
    came to have two contradictory rules depending on which way you started it.

    Returns:
        ``(added, flattened, refused)``.
    """
    refusal = self.field_of_view_refusal()
    if refusal is not None:
        raise ValueError(f"recording {self.name!r} {refusal}")
    defs = spatial_store.read_defs(source.dir, "arena")
    if not defs:
        raise ValueError(f"recording {source.name!r} has no field of view to copy")
    return self.receive_spatial(defs, "arena")

import_field_of_view_csv(path)

Take the field of view out of an exported spatial CSV (§10). Never replaces — see :meth:import_field_of_view_from.

Returns:

Type Description
tuple[list[str], list[str], list[tuple[str, str]]]

(added, flattened, refused).

Source code in detail/api/recording.py
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
def import_field_of_view_csv(
    self, path: Path | str
) -> tuple[list[str], list[str], list[tuple[str, str]]]:
    """Take the field of view out of an exported spatial CSV (§10). Never replaces —
    see :meth:`import_field_of_view_from`.

    Returns:
        ``(added, flattened, refused)``.
    """
    defs = [d for d in spatial_store.load_spatial_csv(path) if d["kind"] == "arena"]
    if not defs:
        raise ValueError(f"{path} carries no field of view")
    refusal = self.field_of_view_refusal()
    if refusal is not None:
        raise ValueError(f"recording {self.name!r} {refusal}")
    return self.receive_spatial(defs, "arena")

import_calibration_from(source)

Take source's distance calibration onto this recording (§10).

Never replaces: there is one pixel scale, so a recording that already has one keeps it. Nothing to flatten for the timeline — a calibration is two points, a distance and the resolution it was measured at, with no frame index anywhere. Refused onto a video of a different shape, where no one pixel scale is right.

Raises:

Type Description
ValueError

the source has none, this recording already has one, or its video's aspect ratio differs from the one the calibration was measured on.

Source code in detail/api/recording.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
def import_calibration_from(self, source: "Recording") -> dict:
    """Take ``source``'s distance calibration onto this recording (§10).

    Never replaces: there is one pixel scale, so a recording that already has one keeps
    it. Nothing to flatten for the timeline — a calibration is two points, a distance
    and the resolution it was measured at, with no frame index anywhere. Refused onto a
    video of a different shape, where no one pixel scale is right.

    Raises:
        ValueError: the source has none, this recording already has one, or its video's
            aspect ratio differs from the one the calibration was measured on.
    """
    if self.distance_calibration is not None:
        raise ValueError(
            f"recording {self.name!r} already has a distance calibration — delete it "
            "here first; nothing is overwritten"
        )
    return spatial_store.copy_calibration(
        source.dir, self.dir, self.video_resolution
    )

import_calibration_csv(path)

Take the distance calibration out of an exported spatial CSV (§10). Never replaces — see :meth:import_calibration_from.

Raises:

Type Description
FileNotFoundError | ValueError

a missing/malformed CSV, one carrying no calibration, a recording that already has one, or one whose video is a different shape from the one the calibration was measured on.

Source code in detail/api/recording.py
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
def import_calibration_csv(self, path: Path | str) -> dict:
    """Take the distance calibration out of an exported spatial CSV (§10). Never
    replaces — see :meth:`import_calibration_from`.

    Raises:
        FileNotFoundError | ValueError: a missing/malformed CSV, one carrying no
            calibration, a recording that already has one, or one whose video is a
            different shape from the one the calibration was measured on.
    """
    block = spatial_store.load_calibration_csv(path)
    if block is None:
        raise ValueError(f"{path} carries no distance calibration")
    if self.distance_calibration is not None:
        raise ValueError(
            f"recording {self.name!r} already has a distance calibration — delete it "
            "here first; nothing is overwritten"
        )
    return spatial_store.write_calibration_block(
        self.dir, block, self.video_resolution
    )

calibration_reference()

How to read :attr:pixels_per_mm: "" when it is at this recording's video, or " at WxH (no video yet)" when the recording has no video and the number is the calibration's own, at the resolution it was measured on.

Source code in detail/api/recording.py
1284
1285
1286
1287
1288
1289
1290
1291
1292
def calibration_reference(self) -> str:
    """How to read :attr:`pixels_per_mm`: ``""`` when it is at this recording's video, or
    ``" at WxH (no video yet)"`` when the recording has no video and the number is the
    calibration's own, at the resolution it was measured on."""
    cal = self.distance_calibration
    if cal is None or self.video_resolution is not None:
        return ""
    ref_w, ref_h = (int(v) for v in cal["ref_resolution"])
    return f" at {ref_w}x{ref_h} (no video yet)"

calibration_refusal()

Why this recording's distance calibration gives no scale for its video, or None (also when it has no calibration or no video).

Reachable although every carry-over refuses it: the video can be replaced after the calibration was set, and a calibration copied before the refusal existed is still on disk.

Source code in detail/api/recording.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
def calibration_refusal(self) -> str | None:
    """Why this recording's distance calibration gives no scale for its video, or
    ``None`` (also when it has no calibration or no video).

    Reachable although every carry-over refuses it: the video can be replaced after
    the calibration was set, and a calibration copied before the refusal existed is
    still on disk.
    """
    return self.calibration_refusal_for(self.distance_calibration)

calibration_refusal_for(calibration)

Why calibration gives no scale for this recording's video, or None (also when either is missing). The question a copy asks of a target before it is offered: a calibration belongs to a rig, and a video of another shape is another rig.

Source code in detail/api/recording.py
1304
1305
1306
1307
1308
1309
1310
1311
1312
def calibration_refusal_for(self, calibration: dict | None) -> str | None:
    """Why ``calibration`` gives no scale for this recording's video, or ``None``
    (also when either is missing). The question a copy asks of a target before it is
    offered: a calibration belongs to a rig, and a video of another shape is another
    rig."""
    res = self.video_resolution
    if calibration is None or res is None:
        return None
    return spatial_store.calibration_aspect_refusal(calibration, *res)

set_distance_calibration(points, distance_mm)

Calibrate from two normalized points a known real distance (mm) apart — the GUI two-point pick (Section 10). Uses the current video resolution as the reference.

Raises:

Type Description
ValueError

if there is no video, the points coincide, or distance_mm <= 0.

Source code in detail/api/recording.py
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
def set_distance_calibration(
    self, points: list[tuple[float, float]], distance_mm: float
) -> dict:
    """Calibrate from two normalized points a known real distance (mm) apart — the GUI
    two-point pick (Section 10). Uses the current video resolution as the reference.

    Raises:
        ValueError: if there is no video, the points coincide, or ``distance_mm <= 0``.
    """
    return spatial_store.write_calibration_from_points(
        self.dir, points, distance_mm, self._require_resolution()
    )

set_pixels_per_mm(pixels_per_mm)

Calibrate directly from a pixels_per_mm scalar (the CLI/scripted path, no two-point pick), measured at the current video resolution (Section 10).

Raises:

Type Description
ValueError

if there is no video or pixels_per_mm <= 0.

Source code in detail/api/recording.py
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def set_pixels_per_mm(self, pixels_per_mm: float) -> dict:
    """Calibrate directly from a ``pixels_per_mm`` scalar (the CLI/scripted path, no
    two-point pick), measured at the current video resolution (Section 10).

    Raises:
        ValueError: if there is no video or ``pixels_per_mm <= 0``.
    """
    return spatial_store.write_calibration_scalar(
        self.dir, pixels_per_mm, self._require_resolution()
    )

clear_distance_calibration()

Remove the distance calibration (idempotent).

Source code in detail/api/recording.py
1338
1339
1340
def clear_distance_calibration(self) -> None:
    """Remove the distance calibration (idempotent)."""
    spatial_store.delete_calibration(self.dir)

location_tables(tracking_run_id, *, keypoint_run_id=None, progress=None, **options)

Per-frame, per-track spatial features for a completed tracking run — bbox/centroids/areas, the body's centre, area, length and width, and position relative to this recording's ROIs/POIs.

Returns an analysis.locations.LocationTables (compute only, no write) — the reuse hook for a preview or a future analysis module. Read-only; the compute is pure (no executor, no run record).

Parameters:

Name Type Description Default
tracking_run_id str

A complete tracking run of this recording.

required
keypoint_run_id str | None

A complete keypoint track run whose poses went to that tracking run, read into a fourth table (keypoints); None reads no keypoints.

None
progress Callable[[str, float, str], None] | None

(stage, fraction, detail), called as the tracked rows are measured: a recording's export takes minutes, and without it looks hung.

None
**options float | bool | None

The measurement options of configs.location_export: sample_fps (rows per second per subject; unset is every tracked frame).

{}

Raises:

Type Description
ValueError

If the tracking run is missing or not complete, an option is not one this export has, or one is outside its bounds; or the keypoint track run is not complete or assigned its poses to another tracking run.

Source code in detail/api/recording.py
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
def location_tables(
    self,
    tracking_run_id: str,
    *,
    keypoint_run_id: str | None = None,
    progress: Callable[[str, float, str], None] | None = None,
    **options: float | bool | None,
):
    """Per-frame, per-track spatial features for a completed tracking run —
    bbox/centroids/areas, the body's centre, area, length and width, and position
    relative to this recording's ROIs/POIs.

    Returns an ``analysis.locations.LocationTables`` (compute only, no write) —
    the reuse hook for a preview or a future analysis module. Read-only; the
    compute is pure (no executor, no run record).

    Args:
        tracking_run_id: A complete tracking run of this recording.
        keypoint_run_id: A complete keypoint track run whose poses went to that tracking
            run, read into a fourth table (``keypoints``); ``None`` reads no keypoints.
        progress: ``(stage, fraction, detail)``, called as the tracked rows are
            measured: a recording's export takes minutes, and without it looks hung.
        **options: The measurement options of ``configs.location_export``:
            ``sample_fps`` (rows per second per subject; unset is every tracked
            frame).

    Raises:
        ValueError: If the tracking run is missing or not complete, an option is not
            one this export has, or one is outside its bounds; or the keypoint track run
            is not complete or assigned its poses to another tracking run.
    """
    from detail.analysis import locations as _locations
    from detail.configs import location_export as _config
    from detail.core.progress import ThrottledProgress

    self._require_complete_tracking(tracking_run_id)
    unknown = sorted(set(options) - set(_config.option_names()))
    if unknown:
        raise UserInputError(
            f"location export has no option {', '.join(unknown)}; it has "
            f"{', '.join(_config.option_names())}"
        )
    resolved = _config.options_from(options)
    on_rows = None
    if progress is not None:
        # The compute reports per tracked row, hundreds of thousands of them, so the
        # throttle keeps the callback off its loop.
        emit = ThrottledProgress(lambda event: progress(*event))

        def on_rows(done: int, total: int) -> None:
            fraction = done / total if total else 1.0
            emit(
                ("measuring", fraction, f"{done:,} of {total:,} rows"),
                force=done >= total,
            )

        on_rows(0, 1)  # the bar moves before the first part is read
    if keypoint_run_id is not None:
        entry = {r.get("id"): r for r in self.keypoint_track_runs}.get(
            keypoint_run_id
        )
        if entry is None or entry.get("status") != "complete":
            state = "missing" if entry is None else repr(entry.get("status"))
            raise UserInputError(
                f"keypoint track run {keypoint_run_id!r} is {state}, not complete"
            )
    return _locations.compute_location_tables(
        self,
        tracking_run_id,
        on_progress=on_rows,
        options=resolved,
        keypoint_run_id=keypoint_run_id,
    )

export_locations(tracking_run_id, out_dir, *, keypoint_run_id=None, progress=None, **options)

Compute + write the three location CSVs (tracks / roi_relations / point_relations, and keypoints with a keypoint_run_id) + a locations.yaml manifest into a new folder under out_dir; returns that folder. Tables keyed by t_ns (joins with streams). progress and options are :meth:location_tables's; progress also hears the write.

The names are fixed, so each export gets its own folder: writing them straight into out_dir replaced one recording's files with the next one's (#29).

Source code in detail/api/recording.py
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
def export_locations(
    self,
    tracking_run_id: str,
    out_dir: Path | str,
    *,
    keypoint_run_id: str | None = None,
    progress: Callable[[str, float, str], None] | None = None,
    **options: float | bool | None,
) -> Path:
    """Compute + write the three location CSVs (``tracks`` / ``roi_relations`` /
    ``point_relations``, and ``keypoints`` with a ``keypoint_run_id``) + a
    ``locations.yaml`` manifest into a new folder under ``out_dir``; returns that folder. Tables keyed by ``t_ns`` (joins with streams).
    ``progress`` and ``options`` are :meth:`location_tables`'s; ``progress`` also hears
    the write.

    The names are fixed, so each export gets its own folder: writing them straight into
    ``out_dir`` replaced one recording's files with the next one's (#29)."""
    from detail.api import exporters
    from detail.storage import location_export

    tables = self.location_tables(
        tracking_run_id,
        keypoint_run_id=keypoint_run_id,
        progress=progress,
        **options,
    )
    dest = exporters.new_export_folder(
        exporters.ExportSubject("recording", self._experiment_dir, self.id),
        out_dir,
        what=f"{tracking_run_id}_locations",
    )
    if progress is not None:
        progress("writing", 0.0, dest.name)
    written = location_export.write_location_tables(dest, tables)
    if progress is not None:
        progress("writing", 1.0, dest.name)
    return written

backfill_kinematics(embed_run_id, *, progress=None, overwrite=False)

Write the §14 kinematics/ sibling for an embedding run that has none.

A run made before kinematics existed has no per-frame geometry, so nothing downstream can say where a behavior happened. This regenerates it from the detection zarr — the masks and boxes are still there — without a GPU, a model, or a video decode. Returns the number of parts written.

progress takes the standard (stage, fraction, detail) callback; on a long recording this is minutes, and a silent long op is indistinguishable from a hang. Already-written parts are skipped unless overwrite, so an interrupted run resumes.

Source code in detail/api/recording.py
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
def backfill_kinematics(
    self, embed_run_id: str, *, progress=None, overwrite: bool = False
) -> int:
    """Write the §14 ``kinematics/`` sibling for an embedding run that has none.

    A run made before kinematics existed has no per-frame geometry, so nothing downstream
    can say *where* a behavior happened. This regenerates it from the detection zarr — the
    masks and boxes are still there — without a GPU, a model, or a video decode. Returns the
    number of parts written.

    ``progress`` takes the standard ``(stage, fraction, detail)`` callback; on a long
    recording this is minutes, and a silent long op is indistinguishable from a hang.
    Already-written parts are skipped unless ``overwrite``, so an interrupted run resumes.
    """
    from detail.pipeline import kinematics_backfill

    return kinematics_backfill.backfill_run(
        self.dir, embed_run_id, progress=progress, overwrite=overwrite
    )

missing_previews(tracking_run_ids=None)

The preview builds this recording is missing on this machine (§3 Video preview cache) — each part's proxy, and each complete tracking run's masks. One stat per part once the cache knows the file; empty when everything is built.

Source code in detail/api/recording.py
1494
1495
1496
1497
1498
1499
1500
1501
1502
def missing_previews(self, tracking_run_ids: list[str] | None = None) -> list:
    """The preview builds this recording is missing on this machine (§3 *Video preview
    cache*) — each part's proxy, and each complete tracking run's masks. One stat per part
    once the cache knows the file; empty when everything is built."""
    from detail.api import previews

    return previews.recording_tasks(
        self.dir, self.id, tracking_run_ids=tracking_run_ids
    )

build_preview(progress=None, *, tracking_run_ids=None, masks=True)

Build this recording's display-only previews on this machine; returns a previews.PreviewBuildReport (built, and failed — each failed build with why; one failure does not stop the rest).

Each part's proxy (480x270 at most, 15 fps) and, with masks, each complete tracking run's masks at proxy size (tracking_run_ids limits which). They live in the machine-local preview cache, never in the experiment, and no pipeline stage reads them (§3). Minutes per hour of video, so progress takes the standard (stage, fraction, detail) callback; a callback that raises stops the build and the part in hand is discarded.

Source code in detail/api/recording.py
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
def build_preview(
    self,
    progress: Callable[[str, float, str], None] | None = None,
    *,
    tracking_run_ids: list[str] | None = None,
    masks: bool = True,
) -> "previews.PreviewBuildReport":
    """Build this recording's display-only previews on this machine; returns a
    ``previews.PreviewBuildReport`` (``built``, and ``failed`` — each failed build with
    why; one failure does not stop the rest).

    Each part's proxy (480x270 at most, 15 fps) and, with ``masks``, each complete
    tracking run's masks at proxy size (``tracking_run_ids`` limits which). They live in
    the machine-local preview cache, never in the experiment, and no pipeline stage reads
    them (§3). Minutes per hour of video, so ``progress`` takes the standard
    ``(stage, fraction, detail)`` callback; a callback that raises stops the build and the
    part in hand is discarded.
    """
    from detail.api import previews

    tasks = self.missing_previews(tracking_run_ids)
    if not masks:
        tasks = [task for task in tasks if task.kind == previews.PROXY]
    return previews.build_tasks(
        self._experiment_dir, tasks, {self.id: self.name}, progress
    )

kinematics_missing_parts(embed_run_id)

Embedding parts of this run with no kinematics sibling — empty when it is complete.

Source code in detail/api/recording.py
1531
1532
1533
1534
1535
def kinematics_missing_parts(self, embed_run_id: str) -> list[Path]:
    """Embedding parts of this run with no kinematics sibling — empty when it is complete."""
    from detail.pipeline import kinematics_backfill

    return kinematics_backfill.missing_parts(self.dir, embed_run_id)

kinematics(embed_run_id, track_id=0)

Where the subject was on each embedded frame (§14), or None if never captured.

{frame_idx, t_ns, cx_norm, cy_norm, mask_area_norm, bbox_norm}, all normalized to the frame so two recordings of different resolutions are comparable. The same rows, in the same order, as the embedding run's own — without reading the embedding column beside it.

None for a run made before this was captured; :meth:backfill_kinematics fills it in.

Source code in detail/api/recording.py
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
def kinematics(self, embed_run_id: str, track_id: int = 0) -> dict | None:
    """Where the subject was on each embedded frame (§14), or ``None`` if never captured.

    ``{frame_idx, t_ns, cx_norm, cy_norm, mask_area_norm, bbox_norm}``, all normalized to the
    frame so two recordings of different resolutions are comparable. The same rows, in the
    same order, as the embedding run's own — without reading the embedding column beside it.

    ``None`` for a run made before this was captured; :meth:`backfill_kinematics` fills it in.
    """
    from detail.api.run_preview import load_track_kinematics

    return load_track_kinematics(self.dir, embed_run_id, track_id)

add_stream(name, raw_path, importer, aux_paths=None, covered_behaviors=None, origin=None, config=None, offset_ns=0)

Import a time-series stream and record it in recording.yaml (Section 3).

Runs the named StreamImporter over raw_path (plus any aux_paths it declares) to produce canonical rows in stream-local time, copies the source files verbatim into streams/<name>/raw/, writes the canonical CSV, and appends the manifest. The folder is built aside and moved into place only once every check has passed, so a refused import leaves nothing behind.

Parameters:

Name Type Description Default
name str

Unique, path-safe stream name (also the directory name).

required
raw_path Path | str

The primary data file to import.

required
importer str

A registered importer id (e.g. "medpc").

required
aux_paths dict[str, Path | str] | None

Extra files keyed by the importer's aux_inputs keys (e.g. {"program": "...SelfAdmin.MPC"} for MED-PC).

None
covered_behaviors list[str] | None

For a behavior stream, the full scored-behavior vocabulary (declares behaviors that were scored but never occurred, so they still count as covered for eval eligibility). Must be a superset of the labels present. Defaults to the labels present.

None
origin str | None

For a behavior stream, "ground_truth" (a human scored the video) or "predicted" (a method's output, re-ingested). Defaults to the file's own origin column when it has one — the tool's own exporters write it — and to "ground_truth" otherwise. A predicted stream is never read as ground truth (§19), so marking it is what keeps a method from scoring against itself.

None
config dict | None

The importer's own parameters, matching its config_model (e.g. CsvStreamConfig's time column + channels). None means the importer's own defaults, which is what every importer did before it had a config. Validated against the model up front (Tenet 10).

None
offset_ns int

The stream's alignment offset, set at import instead of as a separate edit afterwards — video_t_ns = stream_t_ns + offset_ns, positive if the stream began after the video. Only meaningful on an external clock; a video_frames / video_seconds stream is anchored at import and a non-zero offset for one is refused rather than stored, because it would be silently ignored on read.

0

Raises:

Type Description
ValueError

Unknown importer, invalid/duplicate name, a missing required aux input, a config its model rejects, a non-zero offset_ns on a video-anchored stream, covered_behaviors not covering a present label, or an origin outside the allowed set.

FileNotFoundError

If raw_path or any aux path is not a file.

Source code in detail/api/recording.py
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
def add_stream(
    self,
    name: str,
    raw_path: Path | str,
    importer: str,
    aux_paths: dict[str, Path | str] | None = None,
    covered_behaviors: list[str] | None = None,
    origin: str | None = None,
    config: dict | None = None,
    offset_ns: int = 0,
) -> None:
    """Import a time-series stream and record it in recording.yaml (Section 3).

    Runs the named ``StreamImporter`` over ``raw_path`` (plus any
    ``aux_paths`` it declares) to produce canonical rows in stream-local time,
    copies the source files verbatim into ``streams/<name>/raw/``, writes the
    canonical CSV, and appends the manifest. The folder is built aside and moved into
    place only once every check has passed, so a refused import leaves nothing behind.

    Args:
        name: Unique, path-safe stream name (also the directory name).
        raw_path: The primary data file to import.
        importer: A registered importer id (e.g. ``"medpc"``).
        aux_paths: Extra files keyed by the importer's ``aux_inputs`` keys
            (e.g. ``{"program": "...SelfAdmin.MPC"}`` for MED-PC).
        covered_behaviors: For a ``behavior`` stream, the full scored-behavior
            vocabulary (declares behaviors that were scored but never occurred,
            so they still count as covered for eval eligibility). Must be a
            superset of the labels present. Defaults to the labels present.
        origin: For a ``behavior`` stream, ``"ground_truth"`` (a human scored
            the video) or ``"predicted"`` (a method's output, re-ingested).
            Defaults to the file's own ``origin`` column when it has one — the
            tool's own exporters write it — and to ``"ground_truth"`` otherwise.
            A predicted stream is never read as ground truth (§19), so marking
            it is what keeps a method from scoring against itself.
        config: The importer's own parameters, matching its ``config_model``
            (e.g. ``CsvStreamConfig``'s time column + channels). ``None`` means
            the importer's own defaults, which is what every importer did before
            it had a config. Validated against the model up front (Tenet 10).
        offset_ns: The stream's alignment offset, set at import instead of as a
            separate edit afterwards — ``video_t_ns = stream_t_ns + offset_ns``,
            positive if the stream began after the video. Only meaningful on an
            external clock; a ``video_frames`` / ``video_seconds`` stream is
            anchored at import and a non-zero offset for one is refused rather
            than stored, because it would be silently ignored on read.

    Raises:
        ValueError: Unknown importer, invalid/duplicate name, a missing
            required aux input, a ``config`` its model rejects, a non-zero
            ``offset_ns`` on a video-anchored stream, ``covered_behaviors`` not
            covering a present label, or an ``origin`` outside the allowed set.
        FileNotFoundError: If ``raw_path`` or any aux path is not a file.
    """
    import_stream_importers()
    streams_store.validate_stream_name(name)
    importer_cls = STREAM_IMPORTERS.get(importer)
    if importer_cls is None:
        raise ValueError(
            f"unknown importer {importer!r}; available: {sorted(STREAM_IMPORTERS)}"
        )
    config = self._validated_stream_config(importer, importer_cls, config)
    raw_path = Path(raw_path)
    if not raw_path.is_file():
        raise FileNotFoundError(f"stream data file not found: {raw_path}")
    resolved_aux = {k: Path(v) for k, v in (aux_paths or {}).items()}
    instance = importer_cls()
    missing = [a.key for a in instance.aux_inputs if a.key not in resolved_aux]
    if missing:
        raise ValueError(
            f"importer {importer!r} requires aux file(s) {missing} "
            f"(pass them in aux_paths)"
        )
    for key, path in resolved_aux.items():
        if not path.is_file():
            raise FileNotFoundError(f"aux file {key!r} not found: {path}")
    data = recording_store.read_recording(self.dir)
    if any(s.get("name") == name for s in data.get("streams", [])):
        raise ValueError(f"stream name {name!r} already exists in recording")
    # A name that differs only by case is the same folder on macOS and Windows, so the
    # second import would write its files into the first stream's (#29).
    same = [
        s.get("name")
        for s in data.get("streams", [])
        if str(s.get("name", "")).casefold() == name.casefold()
    ]
    if same:
        raise UserInputError(
            f"stream name {name!r} differs from the existing stream {same[0]!r} only by "
            "case, which is one folder on macOS and Windows; choose another name"
        )
    if covered_behaviors is not None and instance.role != "behavior":
        # By the importer's role, before anything is copied: an events CSV has a `label`
        # column too, and the vocabulary was stored on it where nothing reads it.
        raise UserInputError(
            f"covered_behaviors only applies to a behavior stream; importer "
            f"{importer!r} makes a {instance.role or 'data'} stream"
        )

    sdir = streams_store.stream_dir(self.dir, name)
    if sdir.exists():
        # No recorded stream owns this folder (the same name, or one differing only by
        # case, is refused above): an import that failed before imports were staged left
        # it behind, and it is not anyone's data.
        shutil.rmtree(sdir)
    # Built aside and moved into place only after every check below has passed, right
    # before the manifest names it. Written straight into `streams/<name>/`, a refused
    # import left `raw/` (and sometimes the canonical CSV) with no manifest entry, and
    # a retry with another file kept the first one in `raw/` for good (#29).
    with atomic.staged_dir(sdir) as stage:
        raw_dir = stage / streams_store.RAW_DIRNAME
        canonical_dir = stage / streams_store.CANONICAL_DIRNAME
        raw_dir.mkdir()
        # Where `raw/` will be once moved into place: the manifest names that, never
        # the staging folder it is built in.
        raw_rel = (
            f"{streams_store.STREAMS_DIRNAME}/{name}/{streams_store.RAW_DIRNAME}"
        )
        raw_entries = [self._copy_raw(raw_dir, raw_rel, raw_path, 0, "data")]
        for i, (key, path) in enumerate(resolved_aux.items(), start=1):
            raw_entries.append(
                self._copy_raw(raw_dir, raw_rel, path, i, key, raw_entries)
            )

        result = instance.import_stream(
            raw_path, canonical_dir, resolved_aux, config
        )
        # Only a frame/time-clocked importer needs the timestamp map; a t_ns-native
        # stream (e.g. MED-PC) skips it, so a recording without video still imports.
        needs_map = bool(result.frame_columns or result.time_columns)
        frame_t_ns = (
            self.frame_timestamps() if needs_map else np.empty(0, dtype=np.int64)
        )
        rows = clock_store.resolve_native_columns(
            result.columns,
            result.rows,
            result.frame_columns,
            result.time_columns,
            frame_t_ns,
        )
        canonical_name = streams_store.write_canonical_csv(
            canonical_dir, result.columns, rows
        )
        canonical_rel = (
            f"{streams_store.STREAMS_DIRNAME}/{name}/"
            f"{streams_store.CANONICAL_DIRNAME}/{canonical_name}"
        )
        dtypes = result.dtypes or streams_store.default_dtypes(result.columns)
        metadata = dict(result.metadata or {})
        if covered_behaviors is not None:
            if "label" not in result.columns:
                raise ValueError(
                    "covered_behaviors only applies to a labeled (behavior) stream"
                )
            present = {r[result.columns.index("label")] for r in result.rows}
            missing = present - set(covered_behaviors)
            if missing:
                raise ValueError(
                    "covered_behaviors must include every labeled behavior; missing "
                    f"{sorted(missing)}"
                )
            metadata["covered_behaviors"] = sorted(set(covered_behaviors))
        resolved_origin = self._resolve_stream_origin(instance, result, origin)
        # Checked against the *resolved* clock, not the importer's declared one: a CSV read
        # on the frame kind reports `video_frames` from a `stream_seconds` importer, so the
        # declared clock would wrongly accept an offset that read time then ignores.
        resolved_clock = result.clock or instance.clock
        streams_store.check_offset_allowed(name, resolved_clock, int(offset_ns))
        manifest = {
            "name": name,
            "type": result.type,
            "shape": result.shape
            or streams_store.stream_shape({"type": result.type}),
            "role": instance.role,
            "clock": resolved_clock,
            "columns": result.columns,
            "dtypes": dtypes,
            "importer": importer,
            "alignment": {"offset_ns": int(offset_ns), "active": "offset"},
            "raw": raw_entries,
            "files": [{"index": 0, "file": canonical_rel}],
            "metadata": metadata,
        }
        if result.sample_rate_hz is not None:
            manifest["sample_rate_hz"] = result.sample_rate_hz
        if resolved_origin is not None:
            manifest["origin"] = resolved_origin
    try:
        streams_store.append_stream_to_recording_yaml(self.dir, manifest)
    except BaseException:
        shutil.rmtree(sdir, ignore_errors=True)
        raise

list_stream_presets()

The experiment's saved importer setups (Section 3).

On Recording as well as Experiment because a preset is used from a recording — the surface that imports a stream should not have to reach past itself to find out what setups exist.

Source code in detail/api/recording.py
1801
1802
1803
1804
1805
1806
1807
1808
def list_stream_presets(self) -> list[dict]:
    """The **experiment's** saved importer setups (Section 3).

    On ``Recording`` as well as ``Experiment`` because a preset is used from a
    recording — the surface that imports a stream should not have to reach past itself
    to find out what setups exist.
    """
    return stream_presets.list_presets(self._experiment_dir)

get_stream_preset(name)

Raises: ValueError if no preset named name exists.

Source code in detail/api/recording.py
1810
1811
1812
def get_stream_preset(self, name: str) -> dict:
    """Raises: ValueError if no preset named ``name`` exists."""
    return stream_presets.get_preset(self._experiment_dir, name)

save_stream_preset(name, importer, config, *, offset_ns=None, overwrite=False)

Save an importer + config on the experiment, for its other recordings.

Raises:

Type Description
ValueError

An invalid name, or the name exists and overwrite is False.

Source code in detail/api/recording.py
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
def save_stream_preset(
    self,
    name: str,
    importer: str,
    config: dict | None,
    *,
    offset_ns: int | None = None,
    overwrite: bool = False,
) -> None:
    """Save an importer + config on the experiment, for its other recordings.

    Raises:
        ValueError: An invalid name, or the name exists and ``overwrite`` is False.
    """
    stream_presets.save_preset(
        self._experiment_dir,
        name,
        importer,
        config,
        offset_ns=offset_ns,
        overwrite=overwrite,
    )

add_stream_from_preset(name, raw_path, preset, *, offset_ns=None, aux_paths=None, origin=None)

Import a stream using a saved preset's importer + config (Section 3).

The preset supplies the importer and its config; everything that belongs to this recording — the file, the stream name, the alignment offset — stays an argument, because those are what differ between recordings even when the mapping does not.

Parameters:

Name Type Description Default
offset_ns int | None

This recording's alignment offset. None uses the preset's own, if it declared one, else 0. Alignment is per recording, so a preset rarely carries one (see storage/stream_presets.py).

None

Raises:

Type Description
ValueError

Unknown preset, or any add_stream error.

FileNotFoundError

If raw_path is not a file.

Source code in detail/api/recording.py
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
def add_stream_from_preset(
    self,
    name: str,
    raw_path: Path | str,
    preset: str,
    *,
    offset_ns: int | None = None,
    aux_paths: dict[str, Path | str] | None = None,
    origin: str | None = None,
) -> None:
    """Import a stream using a saved preset's importer + config (Section 3).

    The preset supplies the ``importer`` and its ``config``; everything that belongs to
    *this* recording — the file, the stream name, the alignment offset — stays an
    argument, because those are what differ between recordings even when the mapping
    does not.

    Args:
        offset_ns: This recording's alignment offset. ``None`` uses the preset's own,
            if it declared one, else 0. Alignment is per recording, so a preset rarely
            carries one (see ``storage/stream_presets.py``).

    Raises:
        ValueError: Unknown preset, or any ``add_stream`` error.
        FileNotFoundError: If ``raw_path`` is not a file.
    """
    entry = stream_presets.get_preset(self._experiment_dir, preset)
    resolved_offset = entry.get("offset_ns", 0) if offset_ns is None else offset_ns
    self.add_stream(
        name,
        raw_path=raw_path,
        importer=entry["importer"],
        aux_paths=aux_paths,
        origin=origin,
        config=entry.get("config") or None,
        offset_ns=int(resolved_offset),
    )

streams_by_role(role)

Stream manifest entries with the given role (Section 3).

The discovery surface a role-consuming module reads through — e.g. an evaluation against ground truth finds recordings carrying a behavior-role stream.

Source code in detail/api/recording.py
1914
1915
1916
1917
1918
1919
1920
def streams_by_role(self, role: str) -> list[dict]:
    """Stream manifest entries with the given ``role`` (Section 3).

    The discovery surface a role-consuming module reads through — e.g. an
    evaluation against ground truth finds recordings carrying a ``behavior``-role stream.
    """
    return streams_store.streams_by_role(self.dir, role)

covered_behaviors(name=None)

Behaviors the annotation scored (Section 3) — the eligibility vocabulary.

Reads the manifest's covered_behaviors (importers declare it, so a scored-but-never-occurred behavior still counts); falls back to the distinct labels present for a legacy stream that predates the field. name selects a stream; default is the first behavior stream. Empty if none.

Source code in detail/api/recording.py
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
def covered_behaviors(self, name: str | None = None) -> list[str]:
    """Behaviors the annotation *scored* (Section 3) — the eligibility vocabulary.

    Reads the manifest's ``covered_behaviors`` (importers declare it, so a
    scored-but-never-occurred behavior still counts); falls back to the distinct
    labels present for a legacy stream that predates the field. ``name`` selects
    a stream; default is the first ``behavior`` stream. Empty if none.
    """
    manifest = (
        next((s for s in self.streams if s.get("name") == name), None)
        if name is not None
        else self._behavior_stream()
    )
    if manifest is None:
        return []
    covered = (manifest.get("metadata") or {}).get("covered_behaviors")
    if covered is not None:
        return list(covered)
    return sorted({r[2] for r in self.stream_events(manifest["name"])})

behavior_types(name=None)

Per-behavior point/state type (Section 3).

Reads the manifest's behavior_types (importers derive it — BORIS from its type column, the CSV from interval durations); falls back to inferring from the stream's own durations for a legacy stream. name selects a stream; default is the first behavior stream. Empty if none.

Source code in detail/api/recording.py
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
def behavior_types(self, name: str | None = None) -> dict[str, str]:
    """Per-behavior ``point``/``state`` type (Section 3).

    Reads the manifest's ``behavior_types`` (importers derive it — BORIS from its
    type column, the CSV from interval durations); falls back to inferring from
    the stream's own durations for a legacy stream. ``name`` selects a stream;
    default is the first ``behavior`` stream. Empty if none.
    """
    manifest = (
        next((s for s in self.streams if s.get("name") == name), None)
        if name is not None
        else self._behavior_stream()
    )
    if manifest is None:
        return {}
    types = (manifest.get("metadata") or {}).get("behavior_types")
    if types is not None:
        return dict(types)
    has_duration: dict[str, bool] = {}
    for row in self.stream_events(manifest["name"]):
        label, start, end = row[2], row[0], row[1]
        has_duration[label] = has_duration.get(label, False) or (end > start)
    return {
        label: ("state" if dur else "point") for label, dur in has_duration.items()
    }

is_annotated_for(behavior, name=None)

Whether the recording's annotation scored behavior (Section 3).

True iff behavior is in the stream's covered vocabulary — so a query "miss" of it counts as a real false negative, not an unscored behavior.

A predicted stream never makes a recording eligible, whether it was named or resolved (§19): a method scored against its own output measures nothing, and the failure is silent because the numbers come out looking excellent. Returns False rather than raising — this is an eligibility question, and "not annotated for this" is the honest answer to it.

Source code in detail/api/recording.py
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
def is_annotated_for(self, behavior: str, name: str | None = None) -> bool:
    """Whether the recording's annotation scored ``behavior`` (Section 3).

    True iff ``behavior`` is in the stream's covered vocabulary — so a query
    "miss" of it counts as a real false negative, not an unscored behavior.

    A **predicted** stream never makes a recording eligible, whether it was named
    or resolved (§19): a method scored against its own output measures nothing,
    and the failure is silent because the numbers come out looking excellent.
    Returns ``False`` rather than raising — this is an eligibility question, and
    "not annotated for this" is the honest answer to it.
    """
    if name is not None:
        entry = next((s for s in self.streams if s.get("name") == name), None)
        if entry is not None and streams_store.is_predicted(entry):
            return False
    return behavior in self.covered_behaviors(name)

stream_events(name)

The stream's canonical rows, typed per its manifest dtypes (Section 3).

For a MED-PC events stream each row is (t_ns, code, label); for a behavior interval stream (t_ns, end_t_ns, label, subject, start_frame, end_frame); for a continuous stream (t_ns, *channels).

t_ns is stream-local: the manifest's alignment.offset_ns is not applied here. For a video-anchored stream (video_frames / video_seconds, e.g. behavior labels) that is already video time, because the offset of such a stream is definitionally 0. For an external-clock stream it is the device's own time, and stream_preview(name).events(aligned=True) is the accessor that maps it to video time. The distinction matters to anything computing an offset — the sync-to-video helper derives frame_t_ns - anchor_t_ns from these rows, and pre-aligned rows would count the offset twice.

Raises:

Type Description
FileNotFoundError

If the stream's canonical file is absent.

Source code in detail/api/recording.py
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
def stream_events(self, name: str) -> list[tuple]:
    """The stream's canonical rows, typed per its manifest ``dtypes`` (Section 3).

    For a MED-PC ``events`` stream each row is ``(t_ns, code, label)``; for a
    ``behavior`` interval stream ``(t_ns, end_t_ns, label, subject, start_frame,
    end_frame)``; for a continuous stream ``(t_ns, *channels)``.

    ``t_ns`` is **stream-local**: the manifest's ``alignment.offset_ns`` is not applied
    here. For a video-anchored stream (``video_frames`` / ``video_seconds``, e.g.
    behavior labels) that is already video time, because the offset of such a stream is
    definitionally 0. For an external-clock stream it is the device's own time, and
    ``stream_preview(name).events(aligned=True)`` is the accessor that maps it to video
    time. The distinction matters to anything *computing* an offset — the sync-to-video
    helper derives ``frame_t_ns - anchor_t_ns`` from these rows, and pre-aligned rows
    would count the offset twice.

    Raises:
        FileNotFoundError: If the stream's canonical file is absent.
    """
    manifest = next((s for s in self.streams if s.get("name") == name), None)
    dtypes = manifest.get("dtypes") if manifest else None
    _columns, rows = streams_store.read_canonical(self.dir, name, dtypes=dtypes)
    return rows

stream_row_counts()

{stream name: data rows} for every stream, None where its file is missing.

For a table that shows a count per stream: it reads each canonical file to the end (a long sensor trace is seconds), so a GUI calls it off the UI thread. A stream whose file is gone is None rather than raising, so one missing file costs its own row and not the others' counts.

Source code in detail/api/recording.py
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
def stream_row_counts(self) -> dict[str, int | None]:
    """``{stream name: data rows}`` for every stream, ``None`` where its file is missing.

    For a table that shows a count per stream: it reads each canonical file to the end
    (a long sensor trace is seconds), so a GUI calls it off the UI thread. A stream whose
    file is gone is ``None`` rather than raising, so one missing file costs its own row and
    not the others' counts.
    """
    counts: dict[str, int | None] = {}
    for manifest in self.streams:
        name = manifest.get("name")
        try:
            counts[name] = streams_store.count_canonical_rows(self.dir, name)
        except FileNotFoundError:
            counts[name] = None
    return counts

stream_preview(name)

A read-only accessor for previewing a stream (Section 3): its events in stream-local and video-aligned time, grouped for a timeline raster.

Raises:

Type Description
ValueError

If no stream with this name exists in the recording.

Source code in detail/api/recording.py
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
def stream_preview(self, name: str):
    """A read-only accessor for previewing a stream (Section 3): its events in
    stream-local and video-aligned time, grouped for a timeline raster.

    Raises:
        ValueError: If no stream with this name exists in the recording.
    """
    from detail.api.run_preview import StreamPreview

    return StreamPreview(self.dir, name)

set_stream_offset(name, offset_ns)

Set the stream's constant alignment offset (signed ns; Section 3).

video_t_ns = stream_t_ns + offset_ns — positive if the stream began after the video, negative if before. Applied at read time; the canonical data is never rewritten.

Raises:

Type Description
ValueError

If no stream with this name exists, or it is on the video's own clock (video_frames / video_seconds, e.g. behavior labels), which has no offset to set.

Source code in detail/api/recording.py
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
def set_stream_offset(self, name: str, offset_ns: int) -> None:
    """Set the stream's constant alignment offset (signed ns; Section 3).

    ``video_t_ns = stream_t_ns + offset_ns`` — positive if the stream began
    after the video, negative if before. Applied at read time; the canonical
    data is never rewritten.

    Raises:
        ValueError: If no stream with this name exists, or it is on the video's own
            clock (``video_frames`` / ``video_seconds``, e.g. behavior labels), which
            has no offset to set.
    """
    streams_store.set_stream_offset(self.dir, name, offset_ns)

stream_dependents(name)

Runs that build on this stream and would be orphaned by deleting it.

Aggregates every consumer registered for the stream's role in STREAM_CONSUMERS. Empty today — no stage consumes streams yet — but a future consumer registers there without editing this method, keeping the deletion strategy (gui_design §1.1) uniform.

Source code in detail/api/recording.py
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
def stream_dependents(self, name: str) -> list[str]:
    """Runs that build on this stream and would be orphaned by deleting it.

    Aggregates every consumer registered for the stream's ``role`` in
    ``STREAM_CONSUMERS``. Empty today — no stage consumes streams yet — but a
    future consumer registers there without editing this method, keeping the
    deletion strategy (gui_design §1.1) uniform.
    """
    manifest = next((s for s in self.streams if s.get("name") == name), None)
    if manifest is None:
        return []
    dependents: list[str] = []
    for consumer in STREAM_CONSUMERS.get(manifest.get("role"), []):
        dependents.extend(consumer(self.dir, name))
    return dependents

delete_stream(name)

Remove a stream's directory + its recording.yaml entry (idempotent).

Source code in detail/api/recording.py
2099
2100
2101
def delete_stream(self, name: str) -> None:
    """Remove a stream's directory + its recording.yaml entry (idempotent)."""
    streams_store.delete_stream(self.dir, name)

set_name(name)

Rename the recording (id/dir unchanged) — the label every surface displays.

A name a user typed that is already taken is refused, not silently suffixed: the tool quietly renaming what someone deliberately typed is the worse failure. (The import path, where the tool proposes filenames and collisions are routine, suffixes instead — Experiment.add_recording.)

Raises:

Type Description
ValueError

If name is empty, or another recording already has it.

Source code in detail/api/recording.py
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
def set_name(self, name: str) -> None:
    """Rename the recording (id/dir unchanged) — the label every surface displays.

    A name a user typed that is already taken is **refused**, not silently suffixed:
    the tool quietly renaming what someone deliberately typed is the worse failure.
    (The import path, where the *tool* proposes filenames and collisions are routine,
    suffixes instead — ``Experiment.add_recording``.)

    Raises:
        ValueError: If ``name`` is empty, or another recording already has it.
    """
    # Local import: api.experiment imports Recording at module level, so this would
    # be circular at the top.
    from detail.api.experiment import Experiment

    experiment = Experiment.open(self._experiment_dir)
    holder = next(
        (
            rid
            for rid, existing in experiment.recording_names().items()
            if existing == name and rid != self.id
        ),
        None,
    )
    if holder is not None:
        raise ValueError(
            f"another recording is already named {name!r} (id {holder}); "
            "names identify recordings to you, so they have to be unique"
        )
    recording_store.set_name(self.dir, name)
    self.name = name

reorder_video_parts(new_order)

Reorder the video parts and re-offset global timestamps (Tenet 8).

Part order is the recording's time reference, so this applies only before any processing run exists. new_order is the current part indices in the desired sequence.

Raises:

Type Description
ValueError

If a processing run already exists (it was computed against the current order), or new_order is invalid.

Source code in detail/api/recording.py
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
def reorder_video_parts(self, new_order: list[int]) -> None:
    """Reorder the video parts and re-offset global timestamps (Tenet 8).

    Part order is the recording's time reference, so this applies only before
    any processing run exists. ``new_order`` is the current part indices in
    the desired sequence.

    Raises:
        ValueError: If a processing run already exists (it was computed
            against the current order), or ``new_order`` is invalid.
    """
    data = recording_store.read_recording(self.dir)
    n_runs = sum(
        len(data.get(key) or [])
        for key in (
            "detection_runs",
            "tracking_runs",
            "embedding_runs",
        )
    )
    if n_runs:
        raise ValueError(
            f"cannot reorder video parts: {n_runs} processing run(s) exist "
            "and were computed against the current order — delete them first"
        )
    recording_store.reorder_video_parts(self.dir, new_order)

frame_t_ns(global_frame_idx)

Video t_ns of a recording-global frame index (Section 3, Tenet 8).

Maps the continuous frame index (0 = first frame of part_001) to its (part, local) position via the per-part active timestamp maps and returns that frame's global t_ns. Powers stream→video alignment (the "sync to video frame" offset = frame_t_ns(frame) - anchor_t_ns).

Raises:

Type Description
IndexError

If global_frame_idx is negative or past the last frame.

Source code in detail/api/recording.py
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
def frame_t_ns(self, global_frame_idx: int) -> int:
    """Video ``t_ns`` of a recording-global frame index (Section 3, Tenet 8).

    Maps the continuous frame index (0 = first frame of part_001) to its
    ``(part, local)`` position via the per-part active timestamp maps and
    returns that frame's global ``t_ns``. Powers stream→video alignment
    (the "sync to video frame" offset = ``frame_t_ns(frame) - anchor_t_ns``).

    Raises:
        IndexError: If ``global_frame_idx`` is negative or past the last frame.
    """
    if global_frame_idx < 0:
        raise IndexError(f"global_frame_idx must be >= 0, got {global_frame_idx}")
    data = recording_store.read_recording(self.dir)
    files = data.get("video", {}).get("files", [])
    remaining = global_frame_idx
    for part_index in range(len(files)):
        tmap = recording_store.load_active_timestamps(self.dir, data, part_index)
        if remaining < len(tmap):
            return tmap.t_ns(remaining)
        remaining -= len(tmap)
    raise IndexError(
        f"global_frame_idx {global_frame_idx} is past the end of the recording"
    )

frame_timestamps()

Concatenated global video t_ns per recording-global frame index.

One int64 value per frame across all parts (Tenet 8) — the timeline axis for previews, and the inverse of frame_t_ns for a whole recording without re-reading the maps per lookup. Empty when no video is imported.

Source code in detail/api/recording.py
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
def frame_timestamps(self) -> np.ndarray:
    """Concatenated global video ``t_ns`` per recording-global frame index.

    One int64 value per frame across all parts (Tenet 8) — the timeline axis
    for previews, and the inverse of ``frame_t_ns`` for a whole recording
    without re-reading the maps per lookup. Empty when no video is imported.
    """
    data = recording_store.read_recording(self.dir)
    files = data.get("video", {}).get("files", [])
    if not files:
        return np.empty(0, dtype=np.int64)
    return np.concatenate(
        [
            recording_store.load_active_timestamps(self.dir, data, i).values
            for i in range(len(files))
        ]
    )

get_frame(part_index, frame_idx)

Decode a single RGB frame from a video part — inspection helper.

Intended for preview / inspection (e.g. arena drawing backdrop, GUI thumbnails). Frame seeking is permitted here under Tenet 11's preview exemption. Seeks through the part's timestamp map, so the frame returned is the frame_idx-th in presentation order.

Returns:

Type Description
ndarray

(H, W, 3) uint8 RGB array.

Raises:

Type Description
IndexError

If part_index is out of range, or if the requested frame_idx cannot be decoded (e.g. past end-of-file).

Source code in detail/api/recording.py
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
def get_frame(self, part_index: int, frame_idx: int) -> np.ndarray:
    """Decode a single RGB frame from a video part — inspection helper.

    Intended for preview / inspection (e.g. arena drawing backdrop, GUI
    thumbnails). Frame seeking is permitted here under Tenet 11's preview
    exemption. Seeks through the part's timestamp map, so the frame returned
    is the ``frame_idx``-th in presentation order.

    Returns:
        ``(H, W, 3) uint8`` RGB array.

    Raises:
        IndexError: If ``part_index`` is out of range, or if the requested
            ``frame_idx`` cannot be decoded (e.g. past end-of-file).
    """
    data = recording_store.read_recording(self.dir)
    files = data.get("video", {}).get("files", [])
    if not (0 <= part_index < len(files)):
        raise IndexError(f"part_index {part_index} out of range [0, {len(files)})")
    if frame_idx < 0:
        raise IndexError(f"frame_idx must be >= 0, got {frame_idx}")
    path = recording_store.resolve_part_video_path(self.dir, files[part_index])
    # Cached: a thumbnail grid calls this per tile, and the map is both the seek
    # index and immutable once written.
    timestamps = recording_store.load_active_timestamps_cached(
        self.dir, data, part_index
    ).values
    decoded = self._cursor_for(part_index, path, timestamps).frame(frame_idx)
    if decoded is None:
        raise IndexError(
            f"could not decode frame {frame_idx} from part {part_index} ({path.name})"
        )
    _actual, frame_bgr = decoded
    return bgr_to_rgb(frame_bgr)  # cv2 returns BGR; API surface is RGB

detection_preview(run_id)

A read-only per-frame overlay accessor for a completed detection run (decode + boxes), for in-GUI preview without writing an annotated video.

Raises:

Type Description
ValueError

If no detection run with this id exists in the recording.

Source code in detail/api/recording.py
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
def detection_preview(self, run_id: str):
    """A read-only per-frame overlay accessor for a completed detection run
    (decode + boxes), for in-GUI preview without writing an annotated video.

    Raises:
        ValueError: If no detection run with this id exists in the recording.
    """
    from detail.api.run_preview import DetectionPreview

    return DetectionPreview(self.dir, run_id)

tracking_preview(run_id)

A read-only per-frame overlay accessor for a completed tracking run (decode + boxes colored by track id), for in-GUI preview.

Raises:

Type Description
ValueError

If no tracking run with this id exists in the recording.

Source code in detail/api/recording.py
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
def tracking_preview(self, run_id: str):
    """A read-only per-frame overlay accessor for a completed tracking run
    (decode + boxes colored by track id), for in-GUI preview.

    Raises:
        ValueError: If no tracking run with this id exists in the recording.
    """
    from detail.api.run_preview import TrackingPreview

    return TrackingPreview(self.dir, run_id)

run_dependents(module_id, run_id)

Runs in this recording that build on run_id and would be orphaned by deleting it — as (module_id, downstream_run_id) pairs.

Source code in detail/api/recording.py
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
def run_dependents(self, module_id: str, run_id: str) -> list[tuple[str, str]]:
    """Runs in this recording that build on ``run_id`` and would be orphaned by
    deleting it — as ``(module_id, downstream_run_id)`` pairs."""
    data = recording_store.read_recording(self.dir)
    return [
        (downstream_module, entry["id"])
        for downstream_module, downstream_key, ref_field in _downstream_edges(
            module_id
        )
        for entry in data.get(downstream_key, [])
        if entry.get(ref_field) == run_id
    ]

delete_run(module_id, run_id)

Remove a per-recording run's output directory + its recording.yaml entry.

The caller must ensure nothing depends on it (see run_dependents). Idempotent: a missing directory or entry is skipped.

Source code in detail/api/recording.py
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
def delete_run(self, module_id: str, run_id: str) -> None:
    """Remove a per-recording run's output directory + its recording.yaml entry.

    The caller must ensure nothing depends on it (see ``run_dependents``).
    Idempotent: a missing directory or entry is skipped.
    """
    module = _module_owning_output(module_id)
    out_dir = self.dir / module.output_path(run_id).rstrip("/")
    if out_dir.is_dir():
        shutil.rmtree(out_dir)
    recording_store.remove_run_entry(self.dir, module.runs_key, run_id)

cancel_run(module_id, run_id)

Stop a per-recording run: kill its worker (graceful-then-force, via the run dir — works even after the GUI restarted) and record its real on-disk status in recording.yaml. Returns that status — usually cancelled, but a graceful stop keeps partial and a worker that already finished keeps complete (so a done run isn't relabeled). Idempotent.

Source code in detail/api/recording.py
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
def cancel_run(self, module_id: str, run_id: str) -> str:
    """Stop a per-recording run: kill its worker (graceful-then-force, via the
    run dir — works even after the GUI restarted) and record its **real** on-disk
    status in recording.yaml. Returns that status — usually ``cancelled``, but a
    graceful stop keeps ``partial`` and a worker that already finished keeps
    ``complete`` (so a done run isn't relabeled). Idempotent."""
    module = _module_owning_output(module_id)
    out_dir = self.dir / module.output_path(run_id).rstrip("/")
    if out_dir.is_dir():
        cancel_run_dir(out_dir)
        status = rundir.read_status(out_dir).value
    else:
        status = "cancelled"  # nothing ran (no run dir) → treat as cancelled
    recording_store.set_run_status(self.dir, module.runs_key, run_id, status)
    return status

run(module_id, config)

Run a processing module (§6.5): validate, submit, record, return a handle.

The single backbone behind every run_* stage method. The module (detection / tracking / embedding, or a future stage) owns validation, job construction, and the recording.yaml record shape.

Raises:

Type Description
ValueError

For an unknown module_id or any failed pre-run validation.

ModelNotReadyError

If a model-backed stage's weights/credentials are not in place.

Source code in detail/api/recording.py
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
def run(self, module_id: str, config: dict) -> RunHandle:
    """Run a processing module (§6.5): validate, submit, record, return a handle.

    The single backbone behind every ``run_*`` stage method. The module
    (detection / tracking / embedding, or a future stage)
    owns validation, job construction, and the recording.yaml record shape.

    Raises:
        ValueError: For an unknown ``module_id`` or any failed pre-run
            validation.
        ModelNotReadyError: If a model-backed stage's weights/credentials
            are not in place.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    module = PROCESSING_MODULES.get(module_id)
    if module is None:
        raise ValueError(
            f"unknown module_id {module_id!r}; available: "
            f"{sorted(PROCESSING_MODULES)}"
        )
    data = recording_store.read_recording(self.dir)
    # Resolve a batch <upstream>_spec to this recording's own run id before validate
    # (§6.5). A no-op for the explicit-id path (CLI/typed wrappers) or a module
    # with no lineage parent.
    config = module.resolve_upstream_spec(self.dir, data, config)
    config = module.validate(self.dir, data, config)

    # Reserve the id + record atomically (under the recording lock) so concurrent runs on
    # this recording — e.g. several embeddings pinned to different GPUs — never collide on the
    # id or lose-update the record. The record is committed as PENDING, then submitted, then
    # advanced to its real status; a submit failure marks it failed rather than orphaning it.
    run_id = self._reserve_run(
        module.runs_key,
        module.id_prefix,
        lambda rid: module.run_record(rid, config, JobStatus.PENDING.value),
    )
    executor = LocalExecutor(self._experiment_dir, runner_modules=_PIPELINE_RUNNERS)
    try:
        job = module.build_job(self.id, run_id, config)
        executor.submit(job)
    except Exception:
        self._set_run_status(module.runs_key, run_id, JobStatus.FAILED.value)
        raise
    self._set_run_status(module.runs_key, run_id, executor.status(run_id).value)
    return _RecordedRun(
        ExecutorRunHandle(executor, run_id), self, run_id, module.runs_key
    )

run_render_preview(tracking_run_id, track_ids, renderer_spec, n_sample_frames, save_as=None, seed=None)

Sample N detections from the requested tracks and render each (Section 14).

Synchronous: blocks while N samples are decoded + rendered. Not an executor job — no zarr, no recovery, no recording.yaml entry. save_as writes source + rendered JPGs and preview.json to embeddings/render_previews/<save_as>/ for inspection in any image viewer.

Raises:

Type Description
ValueError

For any failed pre-run validation.

Source code in detail/api/recording.py
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
def run_render_preview(
    self,
    tracking_run_id: str,
    track_ids: list[int],
    renderer_spec: list[dict],
    n_sample_frames: int,
    save_as: str | None = None,
    seed: int | None = None,
) -> list[RenderPreviewResult]:
    """Sample N detections from the requested tracks and render each (Section 14).

    Synchronous: blocks while N samples are decoded + rendered. Not an
    executor job — no zarr, no recovery, no recording.yaml entry. ``save_as``
    writes source + rendered JPGs and ``preview.json`` to
    ``embeddings/render_previews/<save_as>/`` for inspection in any image
    viewer.

    Raises:
        ValueError: For any failed pre-run validation.
    """
    data = recording_store.read_recording(self.dir)
    self._validate_render_preview(
        data, tracking_run_id, track_ids, renderer_spec, n_sample_frames
    )
    job = RenderPreviewJob(
        tracking_run_id=tracking_run_id,
        track_ids=list(track_ids),
        renderer_spec=renderer_spec,
        n_sample_frames=n_sample_frames,
    )
    return _render_preview_pipeline.run_render_preview(
        self.dir, job, save_as=save_as, seed=seed
    )

run_embedding(tracking_run_id, track_ids, model_id=None, renderer_spec=None, batch_size=32, compute=None, model_variant=None, constructor=None, readout=None, input_size=None, every_n_frames=None, *, align='none', keypoint_run_id=None, heading=None, max_gap_s=0.5, mirror_hold_s=1.0, facing_camera_ratio=0.5)

Embed the selected tracks through the renderer + model (Section 14).

constructor is the name the renderer_spec was resolved from; passing it records the constructor on the run so a constructor-axis comparison can read it (the spec alone does not name it). renderer_spec None resolves the constructor per recording in validate, which is the route an aligned run takes (the aligned canvas is sized from the turned masks and the alignment step is inserted there). readout selects the feature read-out and input_size the model input resolution (both recorded for the model / resolution comparison axes). every_n_frames omitted inherits the tracking run's cadence.

§14 Egocentric alignment: align rotate / mirror turns each subject image so the animal faces right, reading the heading from keypoint_run_id (a keypoint track run on the same tracking run) through the saved heading definition heading; max_gap_s, mirror_hold_s and facing_camera_ratio are its settings and part of the run's identity. model_id omitted runs the configured default (EmbeddingConfig), and renderer_spec and constructor both omitted render the default constructor. Thin wrapper over run.

Source code in detail/api/recording.py
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
def run_embedding(
    self,
    tracking_run_id: str,
    track_ids: list[int],
    model_id: str | None = None,
    renderer_spec: list[dict] | None = None,
    batch_size: int = 32,
    compute: ComputeTarget | None = None,
    model_variant: str | None = None,
    constructor: str | None = None,
    readout: str | None = None,
    input_size: int | None = None,
    every_n_frames: int | None = None,
    *,
    align: str = "none",
    keypoint_run_id: str | None = None,
    heading: str | None = None,
    max_gap_s: float = 0.5,
    mirror_hold_s: float = 1.0,
    facing_camera_ratio: float = 0.5,
) -> RunHandle:
    """Embed the selected tracks through the renderer + model (Section 14).

    ``constructor`` is the name the ``renderer_spec`` was resolved from; passing it records the
    constructor on the run so a constructor-axis comparison can read it (the spec alone does not
    name it). ``renderer_spec`` ``None`` resolves the constructor per recording in ``validate``,
    which is the route an **aligned** run takes (the aligned canvas is sized from the turned
    masks and the alignment step is inserted there). ``readout`` selects the feature read-out
    and ``input_size`` the model input resolution (both recorded for the model / resolution
    comparison axes). ``every_n_frames`` omitted inherits the tracking run's cadence.

    §14 *Egocentric alignment*: ``align`` ``rotate`` / ``mirror`` turns each subject image so
    the animal faces right, reading the heading from ``keypoint_run_id`` (a keypoint track run on
    the same tracking run) through the saved heading definition ``heading``; ``max_gap_s``,
    ``mirror_hold_s`` and ``facing_camera_ratio`` are its settings and part of the run's
    identity. ``model_id`` omitted runs the configured default (``EmbeddingConfig``), and
    ``renderer_spec`` and ``constructor`` both omitted render the default constructor.
    Thin wrapper over ``run``."""
    from detail.api import models as api_models
    from detail.configs.embedding import EmbeddingConfig

    model_id = model_id or EmbeddingConfig.model_fields["model_id"].default

    return self.run(
        "embedding",
        {
            "tracking_run_id": tracking_run_id,
            "track_ids": list(track_ids),
            "model_id": model_id,
            "model_variant": model_variant,
            "renderer_spec": renderer_spec,
            "constructor": constructor,
            "readout": readout,
            "input_size": input_size,
            "batch_size": batch_size,
            "every_n_frames": every_n_frames,
            "align": align,
            "keypoint_run_id": keypoint_run_id,
            "heading": heading,
            "max_gap_s": max_gap_s,
            "mirror_hold_s": mirror_hold_s,
            "facing_camera_ratio": facing_camera_ratio,
            "compute": compute
            or default_compute(api_models.supported_backends(model_id)),
        },
    )

track_ids(tracking_run_id)

Sorted track ids a completed tracking run produced (from its tracks.zarr). [] when the run has no tracks summary yet.

A completed run's tracks.zarr is immutable, so the read is cached against its mtime — the GUI reads this once per selected recording on every selection change, and over many recordings the repeated zarr opens are the select-all lag.

Source code in detail/api/recording.py
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
def track_ids(self, tracking_run_id: str) -> list[int]:
    """Sorted track ids a completed tracking run produced (from its
    ``tracks.zarr``). ``[]`` when the run has no tracks summary yet.

    A completed run's ``tracks.zarr`` is immutable, so the read is cached against
    its mtime — the GUI reads this once per selected recording on every selection
    change, and over many recordings the repeated zarr opens are the select-all lag.
    """
    tracks_path = self.dir / "tracking" / tracking_run_id / "tracks.zarr"
    if not tracks_path.exists():
        return []
    return list(
        read_cache.cached_read(
            ("track_ids", str(tracks_path)),
            tracks_path,
            lambda: sorted(
                int(t) for t in PartZarrReader(tracks_path).read()["track_id"]
            ),
        )
    )

embedding_preview(run_id)

A read-only accessor for a completed embedding run (Section 14): run metadata, per-track coverage, a 2-D PCA of the embeddings, and the frame + model input behind any point.

Raises:

Type Description
ValueError

If no embedding run with this id exists in the recording.

Source code in detail/api/recording.py
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
def embedding_preview(self, run_id: str):
    """A read-only accessor for a completed embedding run (Section 14): run
    metadata, per-track coverage, a 2-D PCA of the embeddings, and the frame +
    model input behind any point.

    Raises:
        ValueError: If no embedding run with this id exists in the recording.
    """
    from detail.api.run_preview import EmbeddingPreview

    return EmbeddingPreview(self.dir, run_id)

input_image_preview(tracking_run_id, renderer_spec, *, alignment=None)

A read-only scrubber accessor: per source frame, the original frame and the model-input image a constructor produces for a track (Section 14).

alignment (§14) is the resolved alignment a run would record — align, keypoint_run_id, heading_definition, heading_cutoff, max_gap_s, mirror_hold_s, facing_camera_ratio — so the preview turns each input the way the run will, and shows no input where the run would embed no row.

Raises:

Type Description
ValueError

If no tracking run with this id exists in the recording.

Source code in detail/api/recording.py
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
def input_image_preview(
    self,
    tracking_run_id: str,
    renderer_spec: list[dict],
    *,
    alignment: dict | None = None,
):
    """A read-only scrubber accessor: per source frame, the original frame and
    the model-input image a constructor produces for a track (Section 14).

    ``alignment`` (§14) is the resolved alignment a run would record — ``align``,
    ``keypoint_run_id``, ``heading_definition``, ``heading_cutoff``, ``max_gap_s``,
    ``mirror_hold_s``, ``facing_camera_ratio`` — so the preview turns each input the way
    the run will, and shows no input where the run would embed no row.

    Raises:
        ValueError: If no tracking run with this id exists in the recording.
    """
    from detail.api.run_preview import InputImagePreview

    return InputImagePreview(
        self.dir, tracking_run_id, renderer_spec, alignment=alignment
    )

resolve_constructor(constructor, tracking_run_id, track_ids, model_id=None, resize=None, input_size=None, canvas_px=None)

Resolve a named input-image constructor to a concrete renderer_spec for this recording (Section 14), computing the shared canvas from this recording's masks when the constructor needs it — or taking canvas_px as given, which is how an aligned preview passes the canvas sized from the turned masks (§14). The same resolution an embedding run applies — use it to preview a constructor's inputs before launching.

model_id supplies the default resize target (the model's input size) so a preview shows exactly the image the run will embed; input_size (the model resolution knob) overrides that default, and resize overrides both.

Raises:

Type Description
ValueError

For an unknown constructor, or tracks with no detections.

Source code in detail/api/recording.py
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
def resolve_constructor(
    self,
    constructor: str,
    tracking_run_id: str,
    track_ids: list[int],
    model_id: str | None = None,
    resize: int | None = None,
    input_size: int | None = None,
    canvas_px: int | None = None,
) -> list[dict]:
    """Resolve a named input-image constructor to a concrete renderer_spec for
    this recording (Section 14), computing the shared canvas from this recording's
    masks when the constructor needs it — or taking ``canvas_px`` as given, which is
    how an aligned preview passes the canvas sized from the turned masks (§14). The same resolution an embedding run
    applies — use it to preview a constructor's inputs before launching.

    ``model_id`` supplies the default resize target (the model's input size) so a
    preview shows exactly the image the run will embed; ``input_size`` (the model
    resolution knob) overrides that default, and ``resize`` overrides both.

    Raises:
        ValueError: For an unknown constructor, or tracks with no detections.
    """
    from detail.pipeline.embedding import resolve_renderer_spec

    return resolve_renderer_spec(
        self.dir,
        tracking_run_id,
        list(track_ids),
        constructor,
        model_id=model_id,
        resize=resize,
        input_size=input_size,
        canvas_px=canvas_px,
    )

run_prompt_test(model_id, prompts, n_sample_frames, compute, save_as=None, seed=None, model_variant=None, display_classes=None, min_conf=0.0, on_result=None)

Preview a detection model on M sampled frames and return per-frame results (Section 8).

Open-vocab models (SAM3) compare the N candidate prompts, one result column each. A trained/imported closed-set model takes no prompt — it previews its own classes; display_classes picks which (default: all), one result column per class.

The model runs wide open, so every returned detection is a proposal with its own confidence — filter the results at whatever threshold you want to look at. min_conf applies only to the JPGs save_as writes, which can't be re-thresholded once they exist.

Synchronous: blocks until the predictions complete. Not an executor job — no zarr, no recovery, no recording.yaml entry. save_as writes overlay JPGs and test.json to detections/prompt_tests/<save_as>/ for inspection.

Raises:

Type Description
ValueError

For any failed pre-run validation.

ModelNotReadyError

If the model's weights / credentials are not in place.

Source code in detail/api/recording.py
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
def run_prompt_test(
    self,
    model_id: str,
    prompts: list[Prompt],
    n_sample_frames: int,
    compute: ComputeTarget,
    save_as: str | None = None,
    seed: int | None = None,
    model_variant: str | None = None,
    display_classes: list[str] | None = None,
    min_conf: float = 0.0,
    on_result=None,
) -> list[PromptTestResult]:
    """Preview a detection model on M sampled frames and return per-frame results (Section 8).

    Open-vocab models (SAM3) compare the N candidate ``prompts``, one
    result column each. A trained/imported closed-set model takes no prompt —
    it previews its own classes; ``display_classes`` picks which (default: all),
    one result column per class.

    The model runs wide open, so every returned detection is a proposal with its own
    ``confidence`` — filter the results at whatever threshold you want to look at.
    ``min_conf`` applies only to the JPGs ``save_as`` writes, which can't be
    re-thresholded once they exist.

    Synchronous: blocks until the predictions complete. Not an executor job — no
    zarr, no recovery, no recording.yaml entry. ``save_as`` writes overlay JPGs and
    ``test.json`` to ``detections/prompt_tests/<save_as>/`` for inspection.

    Raises:
        ValueError: For any failed pre-run validation.
        ModelNotReadyError: If the model's weights / credentials are not in place.
    """
    import_runner_modules(_PIPELINE_RUNNERS)
    data = recording_store.read_recording(self.dir)
    closed_set, model_classes = self._validate_prompt_test(
        data,
        model_id,
        prompts,
        n_sample_frames,
        compute,
        model_variant,
        display_classes,
    )
    if closed_set:
        chosen = list(display_classes) if display_classes else model_classes
        job_prompts = [
            Prompt(targets=[PromptTarget(class_name=c, cue=TextCue(c))])
            for c in chosen
        ]
    else:
        job_prompts = list(prompts)
    job = PromptTestJob(
        recording_id=self.id,
        model_id=model_id,
        prompts=job_prompts,
        n_sample_frames=n_sample_frames,
        compute=compute,
        model_variant=model_variant,
    )
    return _prompt_test_pipeline.run_prompt_test(
        self.dir,
        job,
        save_as=save_as,
        seed=seed,
        min_conf=min_conf,
        on_result=on_result,
    )

run_detection(model_id, prompt, compute, conf_threshold=0.5, confirm_fn=None, model_variant=None, batch_size=None, every_n_frames=1)

Detect on each video part with the given model + prompt (Section 7). Thin wrapper over run.

Source code in detail/api/recording.py
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
def run_detection(
    self,
    model_id: str,
    prompt: Prompt,
    compute: ComputeTarget,
    conf_threshold: float = 0.5,
    confirm_fn=None,
    model_variant: str | None = None,
    batch_size: int | None = None,
    every_n_frames: int = 1,
) -> RunHandle:
    """Detect on each video part with the given model + prompt (Section 7).
    Thin wrapper over ``run``."""
    return self.run(
        "detection",
        {
            "model_id": model_id,
            "model_variant": model_variant,
            "prompt": prompt,
            "compute": compute,
            "conf_threshold": conf_threshold,
            "batch_size": batch_size,
            "every_n_frames": every_n_frames,
        },
    )

run_tracking(detection_run_id, tracker_id=None, hyperparams=None, arena_ids=None, arena_name=None, every_n_frames=None)

Link detections into tracks, optionally arena-filtered (Section 13). Thin wrapper over run. every_n_frames omitted inherits the detection run's.

tracker_id omitted takes configs.tracking.DEFAULT_TRACKER, and hyperparams omitted takes the chosen tracker's own defaults. Both are left out of the config rather than passed as None: run does no None-stripping, and a None is rejected by the model before validate can resolve it.

arena_name is the field of view by name, which is the same field of view on every recording; arena_ids names this recording's own arena directly. Prefer the name for anything that runs over more than one recording — an id is minted per recording, so the same one is a different polygon on the recording next to it.

Source code in detail/api/recording.py
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
def run_tracking(
    self,
    detection_run_id: str,
    tracker_id: str | None = None,
    hyperparams: dict | None = None,
    arena_ids: list[str] | None = None,
    arena_name: str | None = None,
    every_n_frames: int | None = None,
) -> RunHandle:
    """Link detections into tracks, optionally arena-filtered (Section 13).
    Thin wrapper over ``run``. ``every_n_frames`` omitted inherits the detection run's.

    ``tracker_id`` omitted takes ``configs.tracking.DEFAULT_TRACKER``, and ``hyperparams``
    omitted takes the chosen tracker's own defaults. Both are left *out* of the config
    rather than passed as ``None``: ``run`` does no None-stripping, and a ``None`` is
    rejected by the model before ``validate`` can resolve it.

    ``arena_name`` is the field of view **by name**, which is the same field of view on
    every recording; ``arena_ids`` names this recording's own arena directly. Prefer the
    name for anything that runs over more than one recording — an id is minted per
    recording, so the same one is a different polygon on the recording next to it.
    """
    config = {
        "detection_run_id": detection_run_id,
        "arena_ids": arena_ids,
        "arena_name": arena_name,
        "every_n_frames": every_n_frames,
    }
    if tracker_id is not None:
        config["tracker_id"] = tracker_id
    if hyperparams is not None:
        config["hyperparams"] = hyperparams
    return self.run("tracking", config)

run_keypoint_detect(detection, model_id, *, example_set_id=None, min_pose_confidence=None, model_variant=None, decode=None, side_rule=None, crop_px=None, every_n_frames=None, batch_size=None, compute=None)

Place a skeleton's points on the animals of a detection run (§26 keypoint_detect): one row per pose instance, no subject — keypoint_track gives each to a tracked subject.

detection is the detection run id. model_id names the method (dinov3_match, which learns from example_set_id's marked frames, or a distilled student, which keeps every pose at or above min_pose_confidence). decode / side_rule / crop_px left unset are resolved against the skeleton and written back to the run record; every_n_frames omitted inherits the detection run's cadence. Thin wrapper over run.

Source code in detail/api/recording.py
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
def run_keypoint_detect(
    self,
    detection: str,
    model_id: str,
    *,
    example_set_id: str | None = None,
    min_pose_confidence: float | None = None,
    model_variant: str | None = None,
    decode: str | None = None,
    side_rule: str | None = None,
    crop_px: int | None = None,
    every_n_frames: int | None = None,
    batch_size: int | None = None,
    compute: ComputeTarget | None = None,
) -> RunHandle:
    """Place a skeleton's points on the animals of a detection run (§26
    ``keypoint_detect``): one row per pose instance, no subject — ``keypoint_track``
    gives each to a tracked subject.

    ``detection`` is the detection run id. ``model_id`` names the method
    (``dinov3_match``, which learns from ``example_set_id``'s marked frames, or a
    distilled student, which keeps every pose at or above ``min_pose_confidence``).
    ``decode`` / ``side_rule`` / ``crop_px`` left unset are resolved against the
    skeleton and written back to the run record; ``every_n_frames`` omitted inherits the
    detection run's cadence. Thin wrapper over ``run``.
    """
    from detail.api import models as api_models

    config = {
        "detection_run_id": detection,
        "model_id": model_id,
        "model_variant": model_variant,
        "example_set_id": example_set_id,
        "min_pose_confidence": min_pose_confidence,
        "decode": decode,
        "side_rule": side_rule,
        "crop_px": crop_px,
        "every_n_frames": every_n_frames,
        "compute": compute
        or default_compute(api_models.supported_backends(model_id)),
    }
    if batch_size is not None:
        config["batch_size"] = int(batch_size)
    return self.run("keypoint_detect", config)

keypoint_detect_run(run_id)

A detect run's reader (§26): its record, skeleton, parts, instances, coverage.

Source code in detail/api/recording.py
2857
2858
2859
2860
2861
def keypoint_detect_run(self, run_id: str):
    """A detect run's reader (§26): its record, skeleton, parts, instances, coverage."""
    from detail.storage.keypoint_runs import KeypointDetectRun

    return KeypointDetectRun(self.dir, run_id)

keypoint_instances(run_id, part_id)

Every pose instance a detect run placed in one video part, unassigned (§26 Analysis and export): {column: array} with frame_idx, t_ns, bbox, confidence, detection_row, points, point_scores, candidates / candidate_scores when kept and extras/<name>. Zero rows for a part where nothing was placed.

Raises:

Type Description
KeyError

part_id is not a video part of this recording.

Source code in detail/api/recording.py
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
def keypoint_instances(self, run_id: str, part_id: str) -> dict:
    """Every pose instance a detect run placed in one video part, unassigned (§26
    *Analysis and export*): ``{column: array}`` with ``frame_idx``, ``t_ns``, ``bbox``,
    ``confidence``, ``detection_row``, ``points``, ``point_scores``, ``candidates`` /
    ``candidate_scores`` when kept and ``extras/<name>``. Zero rows for a part where
    nothing was placed.

    Raises:
        KeyError: ``part_id`` is not a video part of this recording.
    """
    from detail.storage import keypoint_runs

    run = self.keypoint_detect_run(run_id)
    if part_id in run.part_ids():
        return run.rows(part_id)
    parts = [
        recording_store.part_stem(f)
        for f in recording_store.video_files(
            recording_store.read_recording(self.dir)
        )
    ]
    if part_id not in parts:
        raise KeyError(
            f"no video part {part_id!r} in recording {self.id!r}; parts: {parts}"
        )
    empty = keypoint_runs._instance_columns(
        len(run.meta["skeleton"]["names"]), run.n_candidates
    )
    del empty["row"]
    return empty

run_keypoint_track(detect, method=None, config=None, *, tracking=None, match_min_inside=None, match_mask_grow=None)

Give a detect run's instances to a tracking run's subjects and settle them over time (§26 keypoint_track).

detect is the keypoint detect run id; tracking the tracking run whose subjects the instances are assigned to — omitted, the one complete tracking run on the detect run's detection run (several are refused, named). match_min_inside / match_mask_grow left unset take the assignment's defaults. method omitted takes the detect run's method's own default (dinov3_match: temporal_decode); config holds the method's settings, every field of which is resolved and recorded. CPU only, seconds per recording. Thin wrapper over run.

Source code in detail/api/recording.py
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
def run_keypoint_track(
    self,
    detect: str,
    method: str | None = None,
    config: dict | None = None,
    *,
    tracking: str | None = None,
    match_min_inside: float | None = None,
    match_mask_grow: float | None = None,
) -> RunHandle:
    """Give a detect run's instances to a tracking run's subjects and settle them over
    time (§26 ``keypoint_track``).

    ``detect`` is the keypoint detect run id; ``tracking`` the tracking run whose
    subjects the instances are assigned to — omitted, the one complete tracking run on
    the detect run's detection run (several are refused, named). ``match_min_inside`` /
    ``match_mask_grow`` left unset take the assignment's defaults. ``method`` omitted
    takes the detect run's method's own default (``dinov3_match``: ``temporal_decode``);
    ``config`` holds the method's settings, every field of which is resolved and
    recorded. CPU only, seconds per recording. Thin wrapper over ``run``.
    """
    run_config = {
        "detect_run_id": detect,
        "tracking_run_id": tracking,
        "method": method,
        "config": dict(config or {}),
    }
    if match_min_inside is not None:
        run_config["match_min_inside"] = float(match_min_inside)
    if match_mask_grow is not None:
        run_config["match_mask_grow"] = float(match_mask_grow)
    return self.run("keypoint_track", run_config)

keypoint_track_run(run_id)

A track run's reader (§26): record, skeleton, parts, rows, coverage.

Source code in detail/api/recording.py
2928
2929
2930
2931
2932
def keypoint_track_run(self, run_id: str):
    """A track run's reader (§26): record, skeleton, parts, rows, coverage."""
    from detail.storage.keypoint_runs import KeypointTrackRun

    return KeypointTrackRun(self.dir, run_id)

keypoints(run_id, track_id)

The final points of one track, every part — {part_id: {frame_idx, t_ns, points, point_scores, changed}} (§26 Surfaces).

Source code in detail/api/recording.py
2934
2935
2936
2937
2938
2939
2940
def keypoints(self, run_id: str, track_id: int) -> dict[str, dict]:
    """The final points of one track, every part — ``{part_id: {frame_idx, t_ns, points,
    point_scores, changed}}`` (§26 *Surfaces*)."""
    run = self.keypoint_track_run(run_id)
    return {
        part_id: run.rows(track_id, part_id) for part_id in run.part_ids(track_id)
    }

Analysis runs

An analysis run is experiment-level, over a selection of recordings. AnalysisRun is the base every module's run handle shares; AuthoredRun adds the editable state that a run you keep working on needs.

detail.api.experiment.AnalysisRun

Bases: RunHandle

Run handle for an analysis run (§16); reconciles analysis.yaml's status to the executor's terminal status on wait (the runner writes the full record on success; a failure leaves the initial running record to fix up).

Source code in detail/api/experiment.py
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
class AnalysisRun(RunHandle):
    """Run handle for an analysis run (§16); reconciles ``analysis.yaml``'s status
    to the executor's terminal status on ``wait`` (the runner writes the full
    record on success; a failure leaves the initial ``running`` record to fix up)."""

    def __init__(self, inner: ExecutorRunHandle, experiment: "Experiment", run_id: str):
        self._inner = inner
        self._experiment = experiment
        self.id = run_id

    @property
    def status(self) -> str:
        return self._inner.status

    @property
    def error(self) -> str | None:
        return self._inner.error

    def progress(self):
        return self._inner.progress()

    def wait(self) -> "AnalysisRun":
        self._inner.wait()
        adir = analysis_store.analysis_dir(self._experiment.dir, self.id)
        # The runner writes the authoritative terminal status (complete / partial /
        # failed, with per-recording detail); `reconciled_status` says when the job
        # envelope overrides it — a record the runner never finalized, and any record
        # claiming something other than a failure over a failed envelope.
        status = reconciled_status(
            analysis_store.read_analysis_yaml(adir).get("status"), self._inner.status
        )
        if status is not None:
            analysis_store.set_analysis_status(adir, status, self._inner.error)
        return self

    def cancel(self) -> None:
        self._inner.cancel()

detail.api.authored_run.AuthoredRun

Bases: AnalysisRun

An analysis run whose result is authored in place after its compute finishes (§21).

inner (the executor handle) is present while the compute is in flight and None for a run reached later to work on; every authored operation works either way.

Source code in detail/api/authored_run.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
class AuthoredRun(AnalysisRun):
    """An analysis run whose result is authored in place after its compute finishes (§21).

    ``inner`` (the executor handle) is present while the compute is in flight and ``None`` for a
    run reached later to work on; every authored operation works either way.
    """

    #: What the run is called in a refusal message ("query run an_03 is finalized…").
    kind: str = "run"
    #: Whether this run's labels nest (§22: labels on tree nodes), so the audit addresses a label
    #: by its **path** and one judgment answers every level. A query's behaviors are flat ids.
    nested_labels: bool = False

    def __init__(self, inner, experiment: Experiment, run_id: str):
        super().__init__(inner, experiment, run_id)

    # — what a subclass supplies ---------------------------------------------------------

    def _read_state(self):
        """The run's authored state, as its own dataclass."""
        raise NotImplementedError

    def _write_state(self, state) -> None:
        """Rewrite the authored state atomically."""
        raise NotImplementedError

    def _log(self, entry: dict) -> None:
        """Append one operation to the run's history — provenance, never authoritative (§21)."""
        raise NotImplementedError

    def _project(self, *, progress=None, reuse: bool = False) -> None:
        """Rebuild the §19 artifact from the compute's stored output and the current state.

        ``reuse`` is an edit's projection (``behavior_artifact.write_artifact``): the intervals
        now, the frame views deferred to :meth:`bring_frame_views_current`.
        """
        raise NotImplementedError

    def _project_frames(self, *, progress=None) -> int:
        """Rebuild the frame views an edit deferred; the producer's ``project_frames``."""
        raise NotImplementedError

    def _recording_ids(self, state) -> list[str]:
        """The recordings this run reads, from its own state: a clustering run's fit selection,
        a query's searched recordings. The one per-kind fact :meth:`data_sources` needs.
        """
        raise NotImplementedError

    # — what it read ---------------------------------------------------------------------

    def data_sources(self) -> dict:
        """``{recording_ids, embed_run_ids, embed_run_id, track_id, method}`` — the same keys
        for every kind of authored run.

        ``embed_run_ids`` is each recording's own embedding run, which is what a reader must
        use; ``embed_run_id`` is set only when every recording's agrees.

        Here, once, rather than per kind: a clustering run names its recordings
        ``source_recording_ids`` and a query ``search_recording_ids``, and a surface shared by
        both (BROWSE) that asked the state by one of those names loaded nothing for the other.
        A kind answers only which recordings it read (:meth:`_recording_ids`);
        ``core.run_selection`` reads either shape of the embedding map.
        """
        state = self.state()
        recording_ids = list(self._recording_ids(state))
        return {
            "recording_ids": recording_ids,
            "embed_run_ids": run_selection.runs_by_recording(state, recording_ids),
            "embed_run_id": state.embed_run_id,
            "track_id": state.track_id,
            "method": state.method,
        }

    # — lifecycle ------------------------------------------------------------------------

    def _run_dir(self) -> Path:
        return analysis_store.analysis_dir(self._experiment.dir, self.id)

    @property
    def status(self) -> str:
        """The run's own status — ``open`` while it is being worked on, ``complete`` once
        finished.

        Read from the record rather than the executor handle, which only ever describes the
        *compute* job: a run whose compute finished perfectly is ``open``, because nobody has
        said they are done with it.
        """
        return analysis_store.read_analysis_yaml(self._run_dir()).get("status", "open")

    #: Whether this handle may write. ``True`` for a run, ``False`` for a snapshot view.
    #:
    #: Deliberately **not** ``status``. A finalized run is still editable — §21 calls finalize a
    #: statement rather than a lock and ``reopen()`` is one call away — while a snapshot view never
    #: is, whatever the run underneath it says. Two different reasons a control is dead, which is
    #: why a surface that conflates them tells a user who finished a run yesterday the same thing
    #: it tells one who is looking at a frozen copy.
    editable = True

    @property
    def error(self) -> str | None:
        return self._inner.error if self._inner is not None else None

    def progress(self):
        return self._inner.progress() if self._inner is not None else iter(())

    def wait(self):
        # Found by the scan in `tests/api/test_snapshot_view.py`, not by reasoning about it: this
        # reconciles a crashed compute by writing the run's status, which is a write like any
        # other. Waiting on a frozen copy is meaningless anyway — the compute it would wait for
        # belongs to the run.
        self._refuse_if_read_only("wait")
        if self._inner is None:
            return self
        self._inner.wait()
        # An "open" record is the runner's own statement (§21) — right up until the job it
        # was written from failed. `reconciled_status` draws that line: an `open` run whose
        # envelope says `complete` stays open, and one whose envelope says `failed` does not.
        # The runner writes `open` *before* projecting the artifact, so this is not a corner.
        run_dir = self._run_dir()
        status = reconciled_status(
            analysis_store.read_analysis_yaml(run_dir).get("status"), self._inner.status
        )
        if status is not None:
            analysis_store.set_analysis_status(run_dir, status, self._inner.error)
        return self

    def cancel(self) -> None:
        # A view built from a *launch* handle carries a live ``_inner``, so an unguarded cancel
        # would kill the run's compute from a screen opened only to read it. Inert on a reattach
        # handle (``_inner is None``), which is the only reason this was not a live bug.
        self._refuse_if_read_only("cancel")
        if self._inner is not None:
            self._inner.cancel()

    def finish_blocker(self) -> str | None:
        """Why this run cannot be finished yet, naming the fix, or ``None`` when it can.

        Finishing says the authoring is done, so a run whose result still lacks the decision it
        is made of — a behavior scan's cutoff, a clustering run's first label — refuses. Finished
        anyway, its AUDIT told the user to make that decision and to reopen the run, at once.

        The one wording of each kind's rule: :meth:`finalize` raises it, the CLI prints it, and
        a surface greys its **Finish** with it in words before it is pressed. A kind overrides
        this; ``tests/api/test_run_lifecycle_parity.py`` holds every kind to having decided.
        Cheap — one read of the run's state — because a surface asks it on the UI thread.
        """
        return None

    def finalize(self, *, progress=None):
        """Mark the run finished — the user's statement that they are done, and pin the artifact.

        The artifact is unchanged: it already says what the state says. What finalize adds is a
        **snapshot** of it (§21), because "I am done" is the moment a result is most likely to be
        cited, and ``reopen()`` is one call away — a statement that can move out from under a
        number somebody has already read is not a statement.

        Long when edits have deferred frame views (see :meth:`pin`), so it reports through
        ``progress(stage, fraction, detail)``.

        Raises:
            ReadOnlyRunError: on a snapshot view, before anything else is asked.
            ValueError: if the compute did not finish (``_refuse_if_incomplete``) — the deeper
                cause, which no authoring fixes, so it is asked before the decisions are.
            UserInputError: :meth:`finish_blocker`'s reason, before anything is pinned.
        """
        self._refuse_if_read_only("finalize")
        self._refuse_if_incomplete("be finalized")
        blocker = self.finish_blocker()
        if blocker is not None:
            raise UserInputError(blocker)
        self.pin(reason="finish", progress=progress)
        analysis_store.set_analysis_status(self._run_dir(), "complete")
        self._log({"op": "finalize"})
        return self

    def reopen(self):
        """Move a finalized run back to ``open`` so it can be worked on again.

        The counterpart to ``finalize`` being a statement rather than a lock (§21) — without it
        the soft lock would be a hard one.
        """
        self._refuse_if_read_only("reopen")
        analysis_store.set_analysis_status(self._run_dir(), "open")
        self._log({"op": "reopen"})
        return self

    # — snapshots (§21) ------------------------------------------------------------------

    def pin(self, *, reason: str, progress=None) -> str | None:
        """Freeze the working artifact and return the snapshot id.

        Returns the *existing* snapshot when the artifact has not changed since the last pin, so
        exporting the same run twice yields one snapshot rather than two, and ``None`` when the
        run has no artifact to pin (a fit whose granularity is unset — §21).

        Brings the frame views current first: a snapshot copies them and is never rewritten, so
        this is the last moment they can be. That rebuild is the long part, and the only one that
        reports through ``progress``.
        """
        self._refuse_if_read_only("pin")
        self._refuse_if_incomplete(f"be pinned for {reason}")
        self.bring_frame_views_current(progress=progress)
        return snapshots_store.pin(
            self._run_dir(),
            reason=reason,
            state=self._snapshot_state(),
            code_sha=provenance.code_version(),
        )

    def _snapshot_state(self) -> dict:
        """The authored decisions, as plain data for the snapshot record.

        A subclass whose state is not a dataclass overrides this; every one today is.
        """
        state = self._read_state()
        if dataclasses.is_dataclass(state):
            return dataclasses.asdict(state)
        return dict(getattr(state, "__dict__", {}))

    def snapshots(self) -> list[dict]:
        """Every pinned copy of this run's artifact, oldest first."""
        run_dir = self._run_dir()
        return dirscan.read_each(
            snapshots_store.discover_snapshots(run_dir),
            lambda sid: snapshots_store.read_snapshot(run_dir, sid),
        )

    def snapshot(self, snapshot_id: str) -> dict:
        """One snapshot's record — what it was taken for, and the state behind it."""
        return snapshots_store.read_snapshot(self._run_dir(), snapshot_id)

    #: The module's :class:`SnapshotViewMixin` subclass, or ``None`` where reading a snapshot back
    #: as an interpretation does not mean anything. ``None`` is a declaration, not an omission: it
    #: is what tells a surface to show the snapshot rows without a cue that opens them. Every
    #: module that authors an interpretation has one — Query included, whose cutoffs are as much an
    #: interpretation as a granularity is.
    snapshot_view_class = None

    def view(self, snapshot_id: str):
        """This run as it was when ``snapshot_id`` was pinned — read-only (§21).

        Everything that reads the run reads the frozen state and the frozen artifact instead; every
        write refuses. Returns ``None`` when the module declares no view class.

        Raises:
            FileNotFoundError: If the run has no such snapshot.
            ValueError: If the snapshot recorded no state. Snapshots pinned before a comparison
                pinned through the run handle carry ``state: {}``, so there is no granularity and
                no vocabulary to render — a fact worth saying plainly, since the alternative is a
                ``KeyError`` from the state dataclass.
        """
        if self.snapshot_view_class is None:
            return None
        record = self.snapshot(snapshot_id)
        if not (record.get("state") or {}):
            raise ValueError(
                f"snapshot {snapshot_id} of {self.id} recorded no settings, so there is no "
                "interpretation to show. It was pinned before snapshots carried the state behind "
                "them; its frozen instances are still readable with snapshot_artifact()."
            )
        return self.snapshot_view_class(self, snapshot_id, record)

    def snapshot_interpretation(self, record: dict) -> SnapshotInterpretation:
        """Summarize one snapshot record in this module's own terms.

        The default says nothing rather than guessing: a module that has not declared how it
        interprets a snapshot shows the columns every snapshot has (when, why, how many instances,
        what used it) and no invented ones. Overriding is how a module earns its own.
        """
        return SnapshotInterpretation(columns=(), cells=(), headline="")

    def instance_placements(self) -> dict | None:
        """``{cluster_id: {recording_id: [placement, ...]}}`` — where each instance was, **and
        which instance it was**, or ``None`` when this run has no positions at all.

        A placement is a dict with ``instance_id``, ``cx``, ``cy``, ``subject``, ``t_ns`` and
        ``end_t_ns`` — enough for a surface to turn a clicked dot back into the thing it stands
        for. :meth:`instance_positions` is the coordinates-only view of this, derived rather
        than read a second time.

        Identity is carried rather than recomputed on purpose. ``instance_id`` is a hash of
        ``(recording_id, subject, source_label, t_ns, end_t_ns)``, and for a **pose** run the
        artifact's ``end_t_ns`` is the end of the row *run* while ``member_clips`` reports the
        one row, ``end_t_ns == t_ns``. (It used to extend the row by its sampling period, as a
        preview "with duration" — which a player reading both ends inclusive turned into the
        row plus the next frame, and a thumbnail at the span's middle into the next frame
        alone.) Rebuilding the hash from a clip would therefore miss for pose and match for
        temporal, silently and only on one module.
        """
        output = self.artifact()
        if output.features is None:
            return None
        out: dict[int | str, dict[str, list]] = {}
        for row in behavior_output.bouts(output.instances):
            position = output.features.get(row.instance_id)
            if position is None or position[0] is None or position[1] is None:
                continue
            # The producer's label, as an `int` where it is one. Clustering labels its groups
            # `0`, `1`, `2` and its surfaces index a colour palette with them; Query labels its
            # behaviors `q01`, `q02` (`storage/query_runs.py::behavior_id`). This coerced
            # unconditionally and dropped what would not parse, under a comment claiming the row
            # belonged to another producer — so **every** query run reported no placements at
            # all, and `instance_positions` with it. A key that cannot hold one producer's
            # labels is not a filter, it is a hole.
            cluster = _as_label(row.source_label)
            out.setdefault(cluster, {}).setdefault(row.recording_id, []).append(
                {
                    "instance_id": row.instance_id,
                    "cx": float(position[0]),
                    "cy": float(position[1]),
                    "subject": int(row.subject),
                    "t_ns": int(row.t_ns),
                    "end_t_ns": int(row.end_t_ns),
                }
            )
        return out

    def instance_positions(self) -> dict | None:
        """``{cluster_id: {recording_id: [(cx_norm, cy_norm), ...]}}`` — where each instance was,
        or ``None`` when this run has no positions to report at all.

        On the base rather than on one run class, because every §19 producer writes the same
        artifact and the surfaces that read it are shared. It lived on ``TemporalClusteringRun``
        alone, and ``ClusterWorkspace`` — which pose and behavior clustering both use — reached
        for it with ``getattr(run, "instance_positions", None)``. A run type that never
        implemented it was then indistinguishable from a run that had no positions, and both
        silently hid the map: pose clustering shipped without the spatial map the other
        clustering pages had, and nothing anywhere said so.

        ``None`` is the actionable state — the run predates §14's ``kinematics/`` and
        ``recording backfill-kinematics`` fills it in. ``{}`` means there were positions but
        none landed in a cluster, which needs no action and no sentence.

        Grouped here rather than in the widget because it is a fact about this run's artifact,
        not about how a panel is laid out (§22: the method answers, the surface renders).
        """
        placements = self.instance_placements()
        if placements is None:
            return None
        return {
            cluster: {
                recording_id: [(p["cx"], p["cy"]) for p in placements_here]
                for recording_id, placements_here in by_recording.items()
            }
            for cluster, by_recording in placements.items()
        }

    def snapshot_artifact(self, snapshot_id: str):
        """The frozen §19 artifact a snapshot holds.

        Read from the snapshot rather than re-derived from its recorded state: re-deriving under
        later code is exactly what makes an old result unreproducible (§21).
        """
        return behavior_output.read_behavior_output(
            snapshots_store.snapshot_dir(self._run_dir(), snapshot_id)
        )

    def coverage_summary(self) -> list[dict]:
        """Per recording: how much of the video was analysed, and how much of that is labelled.

        ``{recording_id, video_ns, analysed_ns, in_instance_ns}`` — two ratios a user reads
        together, because one number cannot say *which* step lost a frame: ``analysed / video``
        is tracking and embedding, ``in_instance / analysed`` is this run. Read from
        :meth:`artifact`, so a snapshot view reports its frozen numbers.

        ``video_ns`` is ``None`` when the recording has no timestamp map. Instance time uses
        :func:`behavior_output.instance_ns`, the rule the cluster table and measures use, so the
        three agree.
        """
        from detail.storage import read_cache

        output = self.artifact()
        periods = behavior_output.period_by_recording(output.coverage)
        analysed: dict[str, int] = {}
        for row in output.coverage:
            analysed[row.recording_id] = analysed.get(row.recording_id, 0) + int(
                row.observed_ns
            )
        inside: dict[str, int] = {}
        for row in behavior_output.bouts(output.instances):
            inside[row.recording_id] = inside.get(
                row.recording_id, 0
            ) + behavior_output.instance_ns(row, periods)
        with read_cache.pinned():
            return [
                {
                    "recording_id": recording_id,
                    "video_ns": self._video_ns(recording_id),
                    "analysed_ns": analysed_ns,
                    "in_instance_ns": inside.get(recording_id, 0),
                }
                for recording_id, analysed_ns in analysed.items()
            ]

    def _video_ns(self, recording_id: str) -> int | None:
        """A recording's video length, from its timestamp maps (Tenet 8), not ``total_duration_s``."""
        from detail.storage import experiment as experiment_store
        from detail.storage import recording as recording_store
        from detail.storage import video as video_store

        recording_dir = experiment_store.recording_path(
            self._experiment.dir, recording_id
        )
        try:
            data = recording_store.read_recording(recording_dir)
            parts = data["video"]["files"]
            last = recording_store.load_active_timestamps_cached(
                recording_dir, data, len(parts) - 1
            )
        except (FileNotFoundError, KeyError, IndexError, ValueError):
            return None
        t_ns = last.values
        if not len(t_ns):
            return None
        return int(t_ns[0]) + video_store.part_duration_ns(t_ns, 0.0)

    @property
    def artifact_stale(self) -> bool:
        """Whether this run's §19 artifact is known not to match its authored state.

        Set while a reprojection is in flight and cleared when it lands, so a reprojection that
        dies — a transient share write, a kill — leaves the disagreement *recorded* instead of
        silent. :meth:`reproject` is the way back.
        """
        return analysis_store.artifact_stale(self._run_dir())

    def _set_stale(self, stale: bool) -> None:
        """Mark (or clear) the artifact-vs-state disagreement.

        The mark goes down **before** the work and never in an ``except``: a SIGKILL mid-write
        leaves exactly the disagreement an exception does, and nothing catches that.
        """
        self._refuse_if_read_only("mark its artifact stale")
        analysis_store.set_artifact_stale(self._run_dir(), stale)

    def reproject(self, *, progress=None):
        """Rebuild the §19 artifact from the stored compute output and the current state.

        Every edit already does this; it is public for the case where the artifact and the state
        disagree — a crash between the two writes — since §19's rule for a materialized view is
        to regenerate rather than to reconcile. Long (a shard read and a frame-view zarr per
        analyzed unit), so it reports through ``progress(stage, fraction, detail)``.
        """
        self._refuse_if_read_only("reproject")
        with _edit_lock(self._run_dir()):
            self._set_stale(True)
            self._project(progress=progress)
            self._set_stale(False)
        return self

    def bring_frame_views_current(self, *, progress=None) -> int:
        """Rebuild the frame views the last edits deferred; return how many were rebuilt.

        An edit writes the intervals and leaves the per-frame views, which are most of a
        reprojection's cost and read by none of the surfaces an edit refreshes (#325). Anything
        that reads them — measures, a pin, an export — calls this first, and a reader that did not
        gets ``FrameViewsPendingError`` rather than a stale view. Free when nothing is pending;
        otherwise one zarr per recording the edits actually moved, reported through
        ``progress(stage, fraction, detail)``.

        Under the edit lock, so it cannot interleave with an edit that is moving the intervals
        under it.

        Raises:
            ResultsOutOfDateError: the last edit was saved but its reprojection did not land
                (:attr:`artifact_stale`), so no view is current and :meth:`reproject` must run
                first. Every reader — a pin and so finalize, the exports and a comparison, and
                measures — calls this first, which is what makes it the one refusal.
        """
        self._refuse_if_read_only("bring_frame_views_current")
        # Every reader of the output passes through here first, so this is where a run whose last
        # rebuild failed refuses rather than hands out the old results as current (#24).
        analysis_store.refuse_if_stale(self._run_dir())
        # The free case asks nothing of the producer — not its state, not the lock — so every
        # reader can call this unconditionally, whatever state the run is otherwise in.
        if not frame_view.is_pending(self._run_dir()):
            return 0
        with _edit_lock(self._run_dir()):
            return self._project_frames(progress=progress)

    # — the operation --------------------------------------------------------------------

    def _edit(self, op: str, mutate, *, reproject: bool = True, progress=None):
        """Apply one authored edit: rewrite the state, log it, reproject if it changed what the
        instances are.

        Every edit funnels through here so the finalize check, the history entry and the
        reprojection cannot be forgotten by one of them — and, now, so that two of them cannot
        run at once (see :data:`_EDIT_LOCKS`). The read-modify-write and the reprojection are
        both inside the lock, because both break when they interleave.
        """
        self._refuse_if_read_only(op)
        with _edit_lock(self._run_dir()):
            self._refuse_if_finalized(op)
            state = self._read_state()
            entry = mutate(state)
            # Read before the mark below goes down. A clear flag is the statement that the frame
            # views on disk agree with `instances.csv`, which is the only thing that makes keeping
            # an unchanged unit's view safe; a run left stale by a killed edit is rebuilt whole.
            reuse = reproject and not self.artifact_stale
            if reproject:
                # Marked before the state is written, because from here until the reprojection
                # lands the two genuinely disagree. The old order — state, history, then the
                # work that makes them true — left a run saying `granularity: 138` over an
                # artifact saying `null`, with a history line asserting it had worked and no
                # surface able to tell. A durable commit ordered before the operation that
                # justifies it needs, at minimum, to record that it is not justified yet.
                self._set_stale(True)
            self._write_state(state)
            self._log({"op": op, **(entry or {})})
            if reproject:
                try:
                    self._project(progress=progress, reuse=reuse)
                except OperationCancelled:
                    raise
                except Exception as exc:
                    # Re-raised, not handled: the state is already written and the stale mark
                    # stays down, so the error has to say the change was saved (#24) — the bare
                    # cause ("no embedded rows for track 0") read as the edit having failed.
                    raise analysis_store.RebuildFailedError(self.id, exc) from exc
                self._set_stale(False)
        return self

    #: Every method on this class that writes to the run directory.
    #:
    #: Declared rather than inferred so a read-only view can refuse all of them at once, and so
    #: ``tests/api/test_snapshot_view.py`` can scan this module for a writer that was added without
    #: joining the list. ``finalize`` and ``pin`` are the ones that make the list necessary: neither
    #: goes through ``_edit``, and both write to ``self._run_dir()`` — the *live* run — so an
    #: unguarded ``finalize()`` on a view would finish the run somebody was only looking at.
    _WRITE_METHODS = (
        "_edit",
        "reproject",
        "bring_frame_views_current",
        "pin",
        "finalize",
        "reopen",
        "wait",
        "_record",
        "cancel",
        "_write_state",
        "_set_stale",
        "rebuild_node_cache",
    )

    def _audit_dir(self) -> Path:
        """Where the §19 reliability audit's decisions are **read** from.

        A seam, because a snapshot carries its own copy of ``audit.csv`` and the panel that reports
        precision has to read *that* one. Reading by run directory mixed a frozen numerator with
        live decisions: a snapshot whose own file said ``precision 1.00 (n=3)`` reported
        ``0.50 (n=6)`` after three more clips were judged on the live run — a number that was never
        true of anything.

        Writes are deliberately **not** routed through here. A review's writes
        (``finish_review``, the removals) keep addressing ``_run_dir()`` and keep being refused on
        a view; a snapshot's audit is evidence to read, never to add to.
        """
        return self._run_dir()

    def _refuse_if_read_only(self, op: str) -> None:
        """A snapshot view refuses every write, and names the way back.

        The whole guarantee is that what left a run cannot be changed by looking at it. A view
        addresses the *run's* directory for everything except its state and its artifact, so a
        write that slipped through would land on the live run rather than on the frozen copy --
        the failure would not even be local to the thing being looked at.
        """
        if not self.editable:
            raise ReadOnlyRunError(
                f"{self.kind} {self.id} is being read as it was at "
                f"{getattr(self, '_snapshot_id', 'a snapshot')}, so it will not {op}. Snapshots "
                "are frozen by design (§21); work on the run itself instead."
            )

    # -- the reliability audit (§19) ------------------------------------------------------

    def _audit_pool(self, label: str | None):
        """The instances an audit may sample from — the artifact's, by default.

        A subclass overrides this when its artifact is a *projection* of something larger.
        ``QueryRun`` does: ``instances.csv`` holds only what the current cutoff kept, so
        sampling it would make the sample a function of a decision the user is still making,
        and every adjustment would invalidate part of the evidence.
        """
        rows = list(self.artifact().instances)
        return [r for r in rows if label is None or r.source_label == label]

    def _audit_examples(self, rows) -> set[str]:
        """The ``instance_id``s among ``rows`` that the user's own clips overlap — never drawn and
        never counted (§19: an instance that fed the method cannot also score it).

        Empty here: a clustering run is given no clips. ``QueryRun`` overrides it.
        """
        return set()

    def _audit_edges(self, labels) -> dict | None:
        """``{source_label: edges}`` — where each label's scores are cut into audit bins.

        ``None`` here: a clustering run's instances carry no score, so there is nothing to bin.
        ``QueryRun`` overrides it.
        """
        return None

    def _audit_rows(self, label: str | None, cutoff: float | None):
        """``(rows, cutoff)`` an estimate is over: the instances it may count, and the cutoff the
        storage layer still has to apply to them.

        The artifact's instances here, cut at ``cutoff``. ``QueryRun`` hands back its candidates
        at no cutoff already cut at each behavior's own, because a query estimate is weighted
        by score bin and the bins are sized from the candidates, not from the artifact.
        """
        rows = [
            row
            for row in self.artifact().instances
            if label is None or row.source_label == label
        ]
        return rows, cutoff

    @staticmethod
    def _audit_scope(rows, path: str | None, *, own_only: bool = False) -> list:
        """The labelled rows an audit draws from, narrowed to ``path`` and what nests under it.

        For a run whose labels nest. A query's candidates are enumerated before any name is
        attached (``QueryRun._audit_pool``), so "has a label" would empty its pool.
        """
        from detail.storage import behavior_audit as audit

        return [
            row
            for row in rows
            if row.label
            and (path is None or audit.under(row.label_path or row.label, path))
            and (not own_only or (row.label_path or row.label) == path)
        ]

    def audit_labels(self) -> list[str]:
        """Every label path the audit can address — each label present, and each above it.

        A parent appears even when no instance reports it directly (every member sits under a
        sub-label), because its precision is still a question: it is scored over everything
        under it. Ordered so a parent precedes its sub-labels, which is how a surface nests them.
        """
        from detail.storage import behavior_output as bo

        paths: set[str] = set()
        for row in self.artifact().instances:
            if not row.label:
                continue
            parts = (row.label_path or row.label).split(bo.PATH_SEPARATOR)
            for depth in range(1, len(parts) + 1):
                paths.add(bo.PATH_SEPARATOR.join(parts[:depth]))
        return sorted(paths, key=lambda p: p.split(bo.PATH_SEPARATOR))

    def audit_precision(
        self,
        *,
        label: str | None = None,
        path: str | None = None,
        cutoff: float | None = None,
        own_only: bool = False,
    ) -> dict | None:
        """The precision the audit supports, with its interval, its ``n`` and its coverage.

        The reader of the earlier one-by-one audit (``audit.csv``), which nothing writes any
        more: the review of every clip replaced it (``review_precision``). Kept so a run audited
        before keeps the figure that audit bought.

        ``None`` when nothing has been audited — the caller says "no reliability estimate" and
        never substitutes one. A returned ``precision`` of ``None`` with a ``reason`` is the
        other refusal: the audit no longer covers enough of this run to speak for it
        (:func:`~detail.storage.behavior_audit.decision_coverage`).

        ``path`` asks about one label of a nested vocabulary, over every instance under it. Where
        the run's clusters are known (a clustering run with a node cache) the estimate is
        **stratified** by cluster — each cluster's precision weighted by its share of the label —
        because the draw gives undecided clusters more than their share. A label whose clusters
        changed after it was audited counts only judgments made since (``membership_changed_at``);
        the result says so in ``since``.

        Read from ``_audit_dir()``, so a snapshot reports its own frozen audit rather than the
        live run's — the mix that seam exists to prevent.
        """
        from detail.storage import behavior_audit as audit

        artifact = self.artifact()
        rows, storage_cutoff = self._audit_rows(label, cutoff)
        if own_only and path:
            # The label's own clusters only — its "other": instances reporting as plain *path*.
            rows = [row for row in rows if (row.label_path or row.label) == path]
        examples = self._audit_examples(rows)
        rows = [row for row in rows if row.instance_id not in examples]
        clusters = self._audit_clusters(self._audit_scope(rows, path)) if path else None
        since = self._label_changed_at(path)
        estimate = audit.precision_at_cutoff(
            self._audit_dir(),
            rows,
            cutoff=storage_cutoff,
            manifest=artifact.manifest,
            universe=self._audit_pool(None),
            target_path=path,
            stratum_of=clusters,
            since=since,
            edges=self._audit_edges({str(row.source_label) for row in rows}),
        )
        if estimate is not None:
            estimate["cutoff"] = cutoff
            estimate["since"] = since
            if path:
                estimate.update(self._audit_left(self._audit_scope(rows, path), since))
        return estimate

    def _audit_left(self, rows, since: str | None) -> dict:
        """``{"size", "remaining"}``: the scope's instances, and how many are still unjudged.

        A judgment from before ``since`` is set aside here exactly as the draw set it aside, so
        "nothing left" meant what the next draw would find.
        """
        from detail.storage import behavior_audit as audit

        decided = {
            row.instance_id
            for row in audit.latest_decisions(self._audit_dir())
            if row.decided and (since is None or (row.drawn_at or "") >= since)
        }
        bouts = list(behavior_output.bouts(rows))
        return {
            "size": len(bouts),
            "remaining": sum(1 for row in bouts if row.instance_id not in decided),
        }

    def _label_changed_at(self, path: str | None) -> str | None:
        """When the clusters of the label at ``path`` last changed, or ``None``."""
        if not path or not self.nested_labels:
            return None
        from detail.storage import run_labels

        state = self.state()
        label = run_labels.find(
            state.labels, path.split(behavior_output.PATH_SEPARATOR)[-1]
        )
        return (getattr(state, "membership_changed_at", {}) or {}).get(label)

    def _audit_clusters(self, rows) -> dict | None:
        """``{instance_id: node}`` — the labelled cluster holding most of each instance — or
        ``None`` where the run has no clusters to attribute to (a query, or a clustering run
        without its node cache)."""
        return None

    def audit_by_cluster(
        self,
        *,
        path: str | None = None,
        own_only: bool = False,
    ) -> list[dict]:
        """Each labelled cluster's precision with its 95% confidence interval (§19, clusters).

        ``[{node, label, path, size, share, estimate, answers}]`` — the question a user asked by
        picking the cluster: is it as pure as they thought? The audit reports the interval; the
        answer is the reader's. ``path`` is the label path the cluster carries; ``size`` its
        instances; ``share`` its part of its label's instances; ``answers`` counts what its judged
        clips were
        answered as, in the words of the buttons (``answer_text``), which is what says *what* an
        impure cluster is instead. The ``path`` argument limits it to clusters under one label;
        ``None`` gives every labelled cluster, which INTERPRET draws on its tree.

        Every judgment a cluster has counts here, before or after a label edit: the figure is about
        the cluster, and the cluster did not change. Empty where clusters are not known.
        """
        from detail.storage import behavior_audit as audit
        from detail.storage import run_labels

        rows = [row for row in self.artifact().instances if row.label]
        if path:
            rows = self._audit_scope(rows, path, own_only=own_only)
        clusters = self._audit_clusters(rows)
        if clusters is None:
            return []
        state = self.state()
        names = run_labels.node_names(state.labels, state.node_labels)
        decisions = {
            r.instance_id: r for r in audit.latest_decisions(self._audit_dir())
        }
        sizes: dict = {}
        decided: dict = {}
        judged: dict = {}
        answers: dict = {}
        label_size: dict = {}
        for row in behavior_output.bouts(rows):
            node = clusters.get(row.instance_id)
            if node is None:
                continue
            own = row.label_path or row.label
            sizes[node] = sizes.get(node, 0) + 1
            label_size[names.get(str(node), "")] = (
                label_size.get(names.get(str(node), ""), 0) + 1
            )
            decision = decisions.get(row.instance_id)
            if decision is None or not decision.decided:
                continue
            decided[node] = decided.get(node, 0) + 1
            node_path = state.resolved_paths.get(
                state.node_labels.get(str(node), ""), own
            )
            value = audit.verdict(decision, own, node_path)
            if value is not None:
                judged.setdefault(node, []).append(value)
            text = audit.answer_text(decision, own)
            answers.setdefault(node, {})
            answers[node][text] = answers[node].get(text, 0) + 1
        out = []
        for node in sorted(sizes, key=lambda n: (names.get(str(n), ""), -sizes[n])):
            label = names.get(str(node), "")
            out.append(
                {
                    "node": int(node),
                    "label": label,
                    "path": state.resolved_paths.get(
                        state.node_labels.get(str(node), ""), ""
                    ),
                    "size": sizes[node],
                    "share": sizes[node] / max(label_size.get(label, 1), 1),
                    "estimate": {
                        **audit.estimate(judged.get(node, [])),
                        "size": sizes[node],
                        "remaining": sizes[node] - decided.get(node, 0),
                    },
                    "answers": answers.get(node, {}),
                }
            )
        return out

    def audit_precision_by_recording(
        self,
        *,
        label: str | None = None,
        path: str | None = None,
        cutoff: float | None = None,
        own_only: bool = False,
    ) -> list[dict] | None:
        """The same estimate split per recording — where one cutoff behaves differently in
        different animals, which an overall figure hides completely (§20)."""
        from detail.storage import behavior_audit as audit

        artifact = self.artifact()
        rows, storage_cutoff = self._audit_rows(label, cutoff)
        examples = self._audit_examples(rows)
        rows = [
            row
            for row in rows
            if row.instance_id not in examples
            and (not (own_only and path) or (row.label_path or row.label) == path)
        ]
        return audit.precision_by_recording(
            self._audit_dir(),
            rows,
            cutoff=storage_cutoff,
            manifest=artifact.manifest,
            universe=self._audit_pool(None),
            target_path=path,
            edges=self._audit_edges({str(row.source_label) for row in rows}),
        )

    def audit_decisions(self) -> list:
        """Every standing decision — one row per instance, the most recent judgment about it.

        ``AuditRow.decided`` separates "judged unclear" from "never looked at"; both carry
        ``human_label`` of ``None``.
        """
        from detail.storage import behavior_audit as audit

        return audit.latest_decisions(self._audit_dir())

    def _record(self, op: str, entry: dict) -> None:
        """Refuse if finalized, then log — for an operation that writes no state.

        A review's census (``finish_review``) writes to ``clip_review.csv``, not to the run's
        state, and reprojects nothing: an answer is evidence *about* the instances rather than a
        change to them. So it cannot go through ``_edit``, which rewrites state and reprojects. It
        still has to make the same finalize check, and this is the one place that policy lives
        for those operations.

        **Finishing a review on a finalized run is refused today**, and that is a decision rather than an
        inevitability: nothing about the instances, the cutoff or the export moves when someone
        labels a clip, so a case exists for allowing it. It is refused because precision is a
        number a reader sees, and a finalized run whose reported precision shifts underneath
        them is the thing ``_refuse_if_finalized`` exists to prevent. ``reopen()`` is one call.
        If that trade is revisited, this method is the only place it has to change.
        """
        self._refuse_if_read_only(op)
        self._refuse_if_finalized(op)
        self._log({"op": op, **entry})

    #: Record statuses that say the compute did not finish. §19: such a run has no behavior
    #: output, because its coverage cannot honestly state what was analyzed.
    _INCOMPLETE_STATUSES = ("partial", "failed")

    def _refuse_if_incomplete(self, op: str) -> None:
        """A run whose compute did not finish refuses to leave as a result (finalize, a pin).

        ``finalize`` used to set ``complete`` on any run, so an interrupted ``partial`` run became
        ``complete`` on the user's say-so, and every number that leaves a run goes through
        ``pin``. Editing stays allowed: what the compute did reach is real, and calibrating it is
        how a user decides whether to re-run. A subclass that can name the missing work extends
        this (``QueryRun``).
        """
        status = self.status
        if status in self._INCOMPLETE_STATUSES:
            raise ValueError(
                f"{self.kind} {self.id} is {status!r}: its compute did not finish, so it will "
                f"not {op}. Re-run it to get a result that covers everything it was asked to."
            )

    def _refuse_if_finalized(self, op: str) -> None:
        """A finalized run refuses an edit and names the way back.

        §21 calls finalize "a statement by the user that they are done, not a lock", and this is
        not one: ``reopen()`` is a single call away. But a statement that can be silently
        overwritten is not a statement, so the run says no once rather than quietly moving under
        a result somebody has already read.
        """
        if self.status == "complete":
            raise ValueError(
                f"{self.kind} {self.id} is finalized, so it will not {op}. Call reopen() "
                "first if you meant to change it."
            )

status property

The run's own status — open while it is being worked on, complete once finished.

Read from the record rather than the executor handle, which only ever describes the compute job: a run whose compute finished perfectly is open, because nobody has said they are done with it.

artifact_stale property

Whether this run's §19 artifact is known not to match its authored state.

Set while a reprojection is in flight and cleared when it lands, so a reprojection that dies — a transient share write, a kill — leaves the disagreement recorded instead of silent. :meth:reproject is the way back.

data_sources()

{recording_ids, embed_run_ids, embed_run_id, track_id, method} — the same keys for every kind of authored run.

embed_run_ids is each recording's own embedding run, which is what a reader must use; embed_run_id is set only when every recording's agrees.

Here, once, rather than per kind: a clustering run names its recordings source_recording_ids and a query search_recording_ids, and a surface shared by both (BROWSE) that asked the state by one of those names loaded nothing for the other. A kind answers only which recordings it read (:meth:_recording_ids); core.run_selection reads either shape of the embedding map.

Source code in detail/api/authored_run.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
def data_sources(self) -> dict:
    """``{recording_ids, embed_run_ids, embed_run_id, track_id, method}`` — the same keys
    for every kind of authored run.

    ``embed_run_ids`` is each recording's own embedding run, which is what a reader must
    use; ``embed_run_id`` is set only when every recording's agrees.

    Here, once, rather than per kind: a clustering run names its recordings
    ``source_recording_ids`` and a query ``search_recording_ids``, and a surface shared by
    both (BROWSE) that asked the state by one of those names loaded nothing for the other.
    A kind answers only which recordings it read (:meth:`_recording_ids`);
    ``core.run_selection`` reads either shape of the embedding map.
    """
    state = self.state()
    recording_ids = list(self._recording_ids(state))
    return {
        "recording_ids": recording_ids,
        "embed_run_ids": run_selection.runs_by_recording(state, recording_ids),
        "embed_run_id": state.embed_run_id,
        "track_id": state.track_id,
        "method": state.method,
    }

finish_blocker()

Why this run cannot be finished yet, naming the fix, or None when it can.

Finishing says the authoring is done, so a run whose result still lacks the decision it is made of — a behavior scan's cutoff, a clustering run's first label — refuses. Finished anyway, its AUDIT told the user to make that decision and to reopen the run, at once.

The one wording of each kind's rule: :meth:finalize raises it, the CLI prints it, and a surface greys its Finish with it in words before it is pressed. A kind overrides this; tests/api/test_run_lifecycle_parity.py holds every kind to having decided. Cheap — one read of the run's state — because a surface asks it on the UI thread.

Source code in detail/api/authored_run.py
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
def finish_blocker(self) -> str | None:
    """Why this run cannot be finished yet, naming the fix, or ``None`` when it can.

    Finishing says the authoring is done, so a run whose result still lacks the decision it
    is made of — a behavior scan's cutoff, a clustering run's first label — refuses. Finished
    anyway, its AUDIT told the user to make that decision and to reopen the run, at once.

    The one wording of each kind's rule: :meth:`finalize` raises it, the CLI prints it, and
    a surface greys its **Finish** with it in words before it is pressed. A kind overrides
    this; ``tests/api/test_run_lifecycle_parity.py`` holds every kind to having decided.
    Cheap — one read of the run's state — because a surface asks it on the UI thread.
    """
    return None

finalize(*, progress=None)

Mark the run finished — the user's statement that they are done, and pin the artifact.

The artifact is unchanged: it already says what the state says. What finalize adds is a snapshot of it (§21), because "I am done" is the moment a result is most likely to be cited, and reopen() is one call away — a statement that can move out from under a number somebody has already read is not a statement.

Long when edits have deferred frame views (see :meth:pin), so it reports through progress(stage, fraction, detail).

Raises:

Type Description
ReadOnlyRunError

on a snapshot view, before anything else is asked.

ValueError

if the compute did not finish (_refuse_if_incomplete) — the deeper cause, which no authoring fixes, so it is asked before the decisions are.

UserInputError

:meth:finish_blocker's reason, before anything is pinned.

Source code in detail/api/authored_run.py
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
def finalize(self, *, progress=None):
    """Mark the run finished — the user's statement that they are done, and pin the artifact.

    The artifact is unchanged: it already says what the state says. What finalize adds is a
    **snapshot** of it (§21), because "I am done" is the moment a result is most likely to be
    cited, and ``reopen()`` is one call away — a statement that can move out from under a
    number somebody has already read is not a statement.

    Long when edits have deferred frame views (see :meth:`pin`), so it reports through
    ``progress(stage, fraction, detail)``.

    Raises:
        ReadOnlyRunError: on a snapshot view, before anything else is asked.
        ValueError: if the compute did not finish (``_refuse_if_incomplete``) — the deeper
            cause, which no authoring fixes, so it is asked before the decisions are.
        UserInputError: :meth:`finish_blocker`'s reason, before anything is pinned.
    """
    self._refuse_if_read_only("finalize")
    self._refuse_if_incomplete("be finalized")
    blocker = self.finish_blocker()
    if blocker is not None:
        raise UserInputError(blocker)
    self.pin(reason="finish", progress=progress)
    analysis_store.set_analysis_status(self._run_dir(), "complete")
    self._log({"op": "finalize"})
    return self

reopen()

Move a finalized run back to open so it can be worked on again.

The counterpart to finalize being a statement rather than a lock (§21) — without it the soft lock would be a hard one.

Source code in detail/api/authored_run.py
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
def reopen(self):
    """Move a finalized run back to ``open`` so it can be worked on again.

    The counterpart to ``finalize`` being a statement rather than a lock (§21) — without it
    the soft lock would be a hard one.
    """
    self._refuse_if_read_only("reopen")
    analysis_store.set_analysis_status(self._run_dir(), "open")
    self._log({"op": "reopen"})
    return self

pin(*, reason, progress=None)

Freeze the working artifact and return the snapshot id.

Returns the existing snapshot when the artifact has not changed since the last pin, so exporting the same run twice yields one snapshot rather than two, and None when the run has no artifact to pin (a fit whose granularity is unset — §21).

Brings the frame views current first: a snapshot copies them and is never rewritten, so this is the last moment they can be. That rebuild is the long part, and the only one that reports through progress.

Source code in detail/api/authored_run.py
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
def pin(self, *, reason: str, progress=None) -> str | None:
    """Freeze the working artifact and return the snapshot id.

    Returns the *existing* snapshot when the artifact has not changed since the last pin, so
    exporting the same run twice yields one snapshot rather than two, and ``None`` when the
    run has no artifact to pin (a fit whose granularity is unset — §21).

    Brings the frame views current first: a snapshot copies them and is never rewritten, so
    this is the last moment they can be. That rebuild is the long part, and the only one that
    reports through ``progress``.
    """
    self._refuse_if_read_only("pin")
    self._refuse_if_incomplete(f"be pinned for {reason}")
    self.bring_frame_views_current(progress=progress)
    return snapshots_store.pin(
        self._run_dir(),
        reason=reason,
        state=self._snapshot_state(),
        code_sha=provenance.code_version(),
    )

snapshots()

Every pinned copy of this run's artifact, oldest first.

Source code in detail/api/authored_run.py
1383
1384
1385
1386
1387
1388
1389
def snapshots(self) -> list[dict]:
    """Every pinned copy of this run's artifact, oldest first."""
    run_dir = self._run_dir()
    return dirscan.read_each(
        snapshots_store.discover_snapshots(run_dir),
        lambda sid: snapshots_store.read_snapshot(run_dir, sid),
    )

snapshot(snapshot_id)

One snapshot's record — what it was taken for, and the state behind it.

Source code in detail/api/authored_run.py
1391
1392
1393
def snapshot(self, snapshot_id: str) -> dict:
    """One snapshot's record — what it was taken for, and the state behind it."""
    return snapshots_store.read_snapshot(self._run_dir(), snapshot_id)

view(snapshot_id)

This run as it was when snapshot_id was pinned — read-only (§21).

Everything that reads the run reads the frozen state and the frozen artifact instead; every write refuses. Returns None when the module declares no view class.

Raises:

Type Description
FileNotFoundError

If the run has no such snapshot.

ValueError

If the snapshot recorded no state. Snapshots pinned before a comparison pinned through the run handle carry state: {}, so there is no granularity and no vocabulary to render — a fact worth saying plainly, since the alternative is a KeyError from the state dataclass.

Source code in detail/api/authored_run.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
def view(self, snapshot_id: str):
    """This run as it was when ``snapshot_id`` was pinned — read-only (§21).

    Everything that reads the run reads the frozen state and the frozen artifact instead; every
    write refuses. Returns ``None`` when the module declares no view class.

    Raises:
        FileNotFoundError: If the run has no such snapshot.
        ValueError: If the snapshot recorded no state. Snapshots pinned before a comparison
            pinned through the run handle carry ``state: {}``, so there is no granularity and
            no vocabulary to render — a fact worth saying plainly, since the alternative is a
            ``KeyError`` from the state dataclass.
    """
    if self.snapshot_view_class is None:
        return None
    record = self.snapshot(snapshot_id)
    if not (record.get("state") or {}):
        raise ValueError(
            f"snapshot {snapshot_id} of {self.id} recorded no settings, so there is no "
            "interpretation to show. It was pinned before snapshots carried the state behind "
            "them; its frozen instances are still readable with snapshot_artifact()."
        )
    return self.snapshot_view_class(self, snapshot_id, record)

snapshot_interpretation(record)

Summarize one snapshot record in this module's own terms.

The default says nothing rather than guessing: a module that has not declared how it interprets a snapshot shows the columns every snapshot has (when, why, how many instances, what used it) and no invented ones. Overriding is how a module earns its own.

Source code in detail/api/authored_run.py
1426
1427
1428
1429
1430
1431
1432
1433
def snapshot_interpretation(self, record: dict) -> SnapshotInterpretation:
    """Summarize one snapshot record in this module's own terms.

    The default says nothing rather than guessing: a module that has not declared how it
    interprets a snapshot shows the columns every snapshot has (when, why, how many instances,
    what used it) and no invented ones. Overriding is how a module earns its own.
    """
    return SnapshotInterpretation(columns=(), cells=(), headline="")

instance_placements()

{cluster_id: {recording_id: [placement, ...]}} — where each instance was, and which instance it was, or None when this run has no positions at all.

A placement is a dict with instance_id, cx, cy, subject, t_ns and end_t_ns — enough for a surface to turn a clicked dot back into the thing it stands for. :meth:instance_positions is the coordinates-only view of this, derived rather than read a second time.

Identity is carried rather than recomputed on purpose. instance_id is a hash of (recording_id, subject, source_label, t_ns, end_t_ns), and for a pose run the artifact's end_t_ns is the end of the row run while member_clips reports the one row, end_t_ns == t_ns. (It used to extend the row by its sampling period, as a preview "with duration" — which a player reading both ends inclusive turned into the row plus the next frame, and a thumbnail at the span's middle into the next frame alone.) Rebuilding the hash from a clip would therefore miss for pose and match for temporal, silently and only on one module.

Source code in detail/api/authored_run.py
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
def instance_placements(self) -> dict | None:
    """``{cluster_id: {recording_id: [placement, ...]}}`` — where each instance was, **and
    which instance it was**, or ``None`` when this run has no positions at all.

    A placement is a dict with ``instance_id``, ``cx``, ``cy``, ``subject``, ``t_ns`` and
    ``end_t_ns`` — enough for a surface to turn a clicked dot back into the thing it stands
    for. :meth:`instance_positions` is the coordinates-only view of this, derived rather
    than read a second time.

    Identity is carried rather than recomputed on purpose. ``instance_id`` is a hash of
    ``(recording_id, subject, source_label, t_ns, end_t_ns)``, and for a **pose** run the
    artifact's ``end_t_ns`` is the end of the row *run* while ``member_clips`` reports the
    one row, ``end_t_ns == t_ns``. (It used to extend the row by its sampling period, as a
    preview "with duration" — which a player reading both ends inclusive turned into the
    row plus the next frame, and a thumbnail at the span's middle into the next frame
    alone.) Rebuilding the hash from a clip would therefore miss for pose and match for
    temporal, silently and only on one module.
    """
    output = self.artifact()
    if output.features is None:
        return None
    out: dict[int | str, dict[str, list]] = {}
    for row in behavior_output.bouts(output.instances):
        position = output.features.get(row.instance_id)
        if position is None or position[0] is None or position[1] is None:
            continue
        # The producer's label, as an `int` where it is one. Clustering labels its groups
        # `0`, `1`, `2` and its surfaces index a colour palette with them; Query labels its
        # behaviors `q01`, `q02` (`storage/query_runs.py::behavior_id`). This coerced
        # unconditionally and dropped what would not parse, under a comment claiming the row
        # belonged to another producer — so **every** query run reported no placements at
        # all, and `instance_positions` with it. A key that cannot hold one producer's
        # labels is not a filter, it is a hole.
        cluster = _as_label(row.source_label)
        out.setdefault(cluster, {}).setdefault(row.recording_id, []).append(
            {
                "instance_id": row.instance_id,
                "cx": float(position[0]),
                "cy": float(position[1]),
                "subject": int(row.subject),
                "t_ns": int(row.t_ns),
                "end_t_ns": int(row.end_t_ns),
            }
        )
    return out

instance_positions()

{cluster_id: {recording_id: [(cx_norm, cy_norm), ...]}} — where each instance was, or None when this run has no positions to report at all.

On the base rather than on one run class, because every §19 producer writes the same artifact and the surfaces that read it are shared. It lived on TemporalClusteringRun alone, and ClusterWorkspace — which pose and behavior clustering both use — reached for it with getattr(run, "instance_positions", None). A run type that never implemented it was then indistinguishable from a run that had no positions, and both silently hid the map: pose clustering shipped without the spatial map the other clustering pages had, and nothing anywhere said so.

None is the actionable state — the run predates §14's kinematics/ and recording backfill-kinematics fills it in. {} means there were positions but none landed in a cluster, which needs no action and no sentence.

Grouped here rather than in the widget because it is a fact about this run's artifact, not about how a panel is laid out (§22: the method answers, the surface renders).

Source code in detail/api/authored_run.py
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
def instance_positions(self) -> dict | None:
    """``{cluster_id: {recording_id: [(cx_norm, cy_norm), ...]}}`` — where each instance was,
    or ``None`` when this run has no positions to report at all.

    On the base rather than on one run class, because every §19 producer writes the same
    artifact and the surfaces that read it are shared. It lived on ``TemporalClusteringRun``
    alone, and ``ClusterWorkspace`` — which pose and behavior clustering both use — reached
    for it with ``getattr(run, "instance_positions", None)``. A run type that never
    implemented it was then indistinguishable from a run that had no positions, and both
    silently hid the map: pose clustering shipped without the spatial map the other
    clustering pages had, and nothing anywhere said so.

    ``None`` is the actionable state — the run predates §14's ``kinematics/`` and
    ``recording backfill-kinematics`` fills it in. ``{}`` means there were positions but
    none landed in a cluster, which needs no action and no sentence.

    Grouped here rather than in the widget because it is a fact about this run's artifact,
    not about how a panel is laid out (§22: the method answers, the surface renders).
    """
    placements = self.instance_placements()
    if placements is None:
        return None
    return {
        cluster: {
            recording_id: [(p["cx"], p["cy"]) for p in placements_here]
            for recording_id, placements_here in by_recording.items()
        }
        for cluster, by_recording in placements.items()
    }

snapshot_artifact(snapshot_id)

The frozen §19 artifact a snapshot holds.

Read from the snapshot rather than re-derived from its recorded state: re-deriving under later code is exactly what makes an old result unreproducible (§21).

Source code in detail/api/authored_run.py
1511
1512
1513
1514
1515
1516
1517
1518
1519
def snapshot_artifact(self, snapshot_id: str):
    """The frozen §19 artifact a snapshot holds.

    Read from the snapshot rather than re-derived from its recorded state: re-deriving under
    later code is exactly what makes an old result unreproducible (§21).
    """
    return behavior_output.read_behavior_output(
        snapshots_store.snapshot_dir(self._run_dir(), snapshot_id)
    )

coverage_summary()

Per recording: how much of the video was analysed, and how much of that is labelled.

{recording_id, video_ns, analysed_ns, in_instance_ns} — two ratios a user reads together, because one number cannot say which step lost a frame: analysed / video is tracking and embedding, in_instance / analysed is this run. Read from :meth:artifact, so a snapshot view reports its frozen numbers.

video_ns is None when the recording has no timestamp map. Instance time uses :func:behavior_output.instance_ns, the rule the cluster table and measures use, so the three agree.

Source code in detail/api/authored_run.py
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
def coverage_summary(self) -> list[dict]:
    """Per recording: how much of the video was analysed, and how much of that is labelled.

    ``{recording_id, video_ns, analysed_ns, in_instance_ns}`` — two ratios a user reads
    together, because one number cannot say *which* step lost a frame: ``analysed / video``
    is tracking and embedding, ``in_instance / analysed`` is this run. Read from
    :meth:`artifact`, so a snapshot view reports its frozen numbers.

    ``video_ns`` is ``None`` when the recording has no timestamp map. Instance time uses
    :func:`behavior_output.instance_ns`, the rule the cluster table and measures use, so the
    three agree.
    """
    from detail.storage import read_cache

    output = self.artifact()
    periods = behavior_output.period_by_recording(output.coverage)
    analysed: dict[str, int] = {}
    for row in output.coverage:
        analysed[row.recording_id] = analysed.get(row.recording_id, 0) + int(
            row.observed_ns
        )
    inside: dict[str, int] = {}
    for row in behavior_output.bouts(output.instances):
        inside[row.recording_id] = inside.get(
            row.recording_id, 0
        ) + behavior_output.instance_ns(row, periods)
    with read_cache.pinned():
        return [
            {
                "recording_id": recording_id,
                "video_ns": self._video_ns(recording_id),
                "analysed_ns": analysed_ns,
                "in_instance_ns": inside.get(recording_id, 0),
            }
            for recording_id, analysed_ns in analysed.items()
        ]

reproject(*, progress=None)

Rebuild the §19 artifact from the stored compute output and the current state.

Every edit already does this; it is public for the case where the artifact and the state disagree — a crash between the two writes — since §19's rule for a materialized view is to regenerate rather than to reconcile. Long (a shard read and a frame-view zarr per analyzed unit), so it reports through progress(stage, fraction, detail).

Source code in detail/api/authored_run.py
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
def reproject(self, *, progress=None):
    """Rebuild the §19 artifact from the stored compute output and the current state.

    Every edit already does this; it is public for the case where the artifact and the state
    disagree — a crash between the two writes — since §19's rule for a materialized view is
    to regenerate rather than to reconcile. Long (a shard read and a frame-view zarr per
    analyzed unit), so it reports through ``progress(stage, fraction, detail)``.
    """
    self._refuse_if_read_only("reproject")
    with _edit_lock(self._run_dir()):
        self._set_stale(True)
        self._project(progress=progress)
        self._set_stale(False)
    return self

bring_frame_views_current(*, progress=None)

Rebuild the frame views the last edits deferred; return how many were rebuilt.

An edit writes the intervals and leaves the per-frame views, which are most of a reprojection's cost and read by none of the surfaces an edit refreshes (#325). Anything that reads them — measures, a pin, an export — calls this first, and a reader that did not gets FrameViewsPendingError rather than a stale view. Free when nothing is pending; otherwise one zarr per recording the edits actually moved, reported through progress(stage, fraction, detail).

Under the edit lock, so it cannot interleave with an edit that is moving the intervals under it.

Raises:

Type Description
ResultsOutOfDateError

the last edit was saved but its reprojection did not land (:attr:artifact_stale), so no view is current and :meth:reproject must run first. Every reader — a pin and so finalize, the exports and a comparison, and measures — calls this first, which is what makes it the one refusal.

Source code in detail/api/authored_run.py
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
def bring_frame_views_current(self, *, progress=None) -> int:
    """Rebuild the frame views the last edits deferred; return how many were rebuilt.

    An edit writes the intervals and leaves the per-frame views, which are most of a
    reprojection's cost and read by none of the surfaces an edit refreshes (#325). Anything
    that reads them — measures, a pin, an export — calls this first, and a reader that did not
    gets ``FrameViewsPendingError`` rather than a stale view. Free when nothing is pending;
    otherwise one zarr per recording the edits actually moved, reported through
    ``progress(stage, fraction, detail)``.

    Under the edit lock, so it cannot interleave with an edit that is moving the intervals
    under it.

    Raises:
        ResultsOutOfDateError: the last edit was saved but its reprojection did not land
            (:attr:`artifact_stale`), so no view is current and :meth:`reproject` must run
            first. Every reader — a pin and so finalize, the exports and a comparison, and
            measures — calls this first, which is what makes it the one refusal.
    """
    self._refuse_if_read_only("bring_frame_views_current")
    # Every reader of the output passes through here first, so this is where a run whose last
    # rebuild failed refuses rather than hands out the old results as current (#24).
    analysis_store.refuse_if_stale(self._run_dir())
    # The free case asks nothing of the producer — not its state, not the lock — so every
    # reader can call this unconditionally, whatever state the run is otherwise in.
    if not frame_view.is_pending(self._run_dir()):
        return 0
    with _edit_lock(self._run_dir()):
        return self._project_frames(progress=progress)

audit_labels()

Every label path the audit can address — each label present, and each above it.

A parent appears even when no instance reports it directly (every member sits under a sub-label), because its precision is still a question: it is scored over everything under it. Ordered so a parent precedes its sub-labels, which is how a surface nests them.

Source code in detail/api/authored_run.py
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
def audit_labels(self) -> list[str]:
    """Every label path the audit can address — each label present, and each above it.

    A parent appears even when no instance reports it directly (every member sits under a
    sub-label), because its precision is still a question: it is scored over everything
    under it. Ordered so a parent precedes its sub-labels, which is how a surface nests them.
    """
    from detail.storage import behavior_output as bo

    paths: set[str] = set()
    for row in self.artifact().instances:
        if not row.label:
            continue
        parts = (row.label_path or row.label).split(bo.PATH_SEPARATOR)
        for depth in range(1, len(parts) + 1):
            paths.add(bo.PATH_SEPARATOR.join(parts[:depth]))
    return sorted(paths, key=lambda p: p.split(bo.PATH_SEPARATOR))

audit_precision(*, label=None, path=None, cutoff=None, own_only=False)

The precision the audit supports, with its interval, its n and its coverage.

The reader of the earlier one-by-one audit (audit.csv), which nothing writes any more: the review of every clip replaced it (review_precision). Kept so a run audited before keeps the figure that audit bought.

None when nothing has been audited — the caller says "no reliability estimate" and never substitutes one. A returned precision of None with a reason is the other refusal: the audit no longer covers enough of this run to speak for it (:func:~detail.storage.behavior_audit.decision_coverage).

path asks about one label of a nested vocabulary, over every instance under it. Where the run's clusters are known (a clustering run with a node cache) the estimate is stratified by cluster — each cluster's precision weighted by its share of the label — because the draw gives undecided clusters more than their share. A label whose clusters changed after it was audited counts only judgments made since (membership_changed_at); the result says so in since.

Read from _audit_dir(), so a snapshot reports its own frozen audit rather than the live run's — the mix that seam exists to prevent.

Source code in detail/api/authored_run.py
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
def audit_precision(
    self,
    *,
    label: str | None = None,
    path: str | None = None,
    cutoff: float | None = None,
    own_only: bool = False,
) -> dict | None:
    """The precision the audit supports, with its interval, its ``n`` and its coverage.

    The reader of the earlier one-by-one audit (``audit.csv``), which nothing writes any
    more: the review of every clip replaced it (``review_precision``). Kept so a run audited
    before keeps the figure that audit bought.

    ``None`` when nothing has been audited — the caller says "no reliability estimate" and
    never substitutes one. A returned ``precision`` of ``None`` with a ``reason`` is the
    other refusal: the audit no longer covers enough of this run to speak for it
    (:func:`~detail.storage.behavior_audit.decision_coverage`).

    ``path`` asks about one label of a nested vocabulary, over every instance under it. Where
    the run's clusters are known (a clustering run with a node cache) the estimate is
    **stratified** by cluster — each cluster's precision weighted by its share of the label —
    because the draw gives undecided clusters more than their share. A label whose clusters
    changed after it was audited counts only judgments made since (``membership_changed_at``);
    the result says so in ``since``.

    Read from ``_audit_dir()``, so a snapshot reports its own frozen audit rather than the
    live run's — the mix that seam exists to prevent.
    """
    from detail.storage import behavior_audit as audit

    artifact = self.artifact()
    rows, storage_cutoff = self._audit_rows(label, cutoff)
    if own_only and path:
        # The label's own clusters only — its "other": instances reporting as plain *path*.
        rows = [row for row in rows if (row.label_path or row.label) == path]
    examples = self._audit_examples(rows)
    rows = [row for row in rows if row.instance_id not in examples]
    clusters = self._audit_clusters(self._audit_scope(rows, path)) if path else None
    since = self._label_changed_at(path)
    estimate = audit.precision_at_cutoff(
        self._audit_dir(),
        rows,
        cutoff=storage_cutoff,
        manifest=artifact.manifest,
        universe=self._audit_pool(None),
        target_path=path,
        stratum_of=clusters,
        since=since,
        edges=self._audit_edges({str(row.source_label) for row in rows}),
    )
    if estimate is not None:
        estimate["cutoff"] = cutoff
        estimate["since"] = since
        if path:
            estimate.update(self._audit_left(self._audit_scope(rows, path), since))
    return estimate

audit_by_cluster(*, path=None, own_only=False)

Each labelled cluster's precision with its 95% confidence interval (§19, clusters).

[{node, label, path, size, share, estimate, answers}] — the question a user asked by picking the cluster: is it as pure as they thought? The audit reports the interval; the answer is the reader's. path is the label path the cluster carries; size its instances; share its part of its label's instances; answers counts what its judged clips were answered as, in the words of the buttons (answer_text), which is what says what an impure cluster is instead. The path argument limits it to clusters under one label; None gives every labelled cluster, which INTERPRET draws on its tree.

Every judgment a cluster has counts here, before or after a label edit: the figure is about the cluster, and the cluster did not change. Empty where clusters are not known.

Source code in detail/api/authored_run.py
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
def audit_by_cluster(
    self,
    *,
    path: str | None = None,
    own_only: bool = False,
) -> list[dict]:
    """Each labelled cluster's precision with its 95% confidence interval (§19, clusters).

    ``[{node, label, path, size, share, estimate, answers}]`` — the question a user asked by
    picking the cluster: is it as pure as they thought? The audit reports the interval; the
    answer is the reader's. ``path`` is the label path the cluster carries; ``size`` its
    instances; ``share`` its part of its label's instances; ``answers`` counts what its judged
    clips were
    answered as, in the words of the buttons (``answer_text``), which is what says *what* an
    impure cluster is instead. The ``path`` argument limits it to clusters under one label;
    ``None`` gives every labelled cluster, which INTERPRET draws on its tree.

    Every judgment a cluster has counts here, before or after a label edit: the figure is about
    the cluster, and the cluster did not change. Empty where clusters are not known.
    """
    from detail.storage import behavior_audit as audit
    from detail.storage import run_labels

    rows = [row for row in self.artifact().instances if row.label]
    if path:
        rows = self._audit_scope(rows, path, own_only=own_only)
    clusters = self._audit_clusters(rows)
    if clusters is None:
        return []
    state = self.state()
    names = run_labels.node_names(state.labels, state.node_labels)
    decisions = {
        r.instance_id: r for r in audit.latest_decisions(self._audit_dir())
    }
    sizes: dict = {}
    decided: dict = {}
    judged: dict = {}
    answers: dict = {}
    label_size: dict = {}
    for row in behavior_output.bouts(rows):
        node = clusters.get(row.instance_id)
        if node is None:
            continue
        own = row.label_path or row.label
        sizes[node] = sizes.get(node, 0) + 1
        label_size[names.get(str(node), "")] = (
            label_size.get(names.get(str(node), ""), 0) + 1
        )
        decision = decisions.get(row.instance_id)
        if decision is None or not decision.decided:
            continue
        decided[node] = decided.get(node, 0) + 1
        node_path = state.resolved_paths.get(
            state.node_labels.get(str(node), ""), own
        )
        value = audit.verdict(decision, own, node_path)
        if value is not None:
            judged.setdefault(node, []).append(value)
        text = audit.answer_text(decision, own)
        answers.setdefault(node, {})
        answers[node][text] = answers[node].get(text, 0) + 1
    out = []
    for node in sorted(sizes, key=lambda n: (names.get(str(n), ""), -sizes[n])):
        label = names.get(str(node), "")
        out.append(
            {
                "node": int(node),
                "label": label,
                "path": state.resolved_paths.get(
                    state.node_labels.get(str(node), ""), ""
                ),
                "size": sizes[node],
                "share": sizes[node] / max(label_size.get(label, 1), 1),
                "estimate": {
                    **audit.estimate(judged.get(node, [])),
                    "size": sizes[node],
                    "remaining": sizes[node] - decided.get(node, 0),
                },
                "answers": answers.get(node, {}),
            }
        )
    return out

audit_precision_by_recording(*, label=None, path=None, cutoff=None, own_only=False)

The same estimate split per recording — where one cutoff behaves differently in different animals, which an overall figure hides completely (§20).

Source code in detail/api/authored_run.py
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
def audit_precision_by_recording(
    self,
    *,
    label: str | None = None,
    path: str | None = None,
    cutoff: float | None = None,
    own_only: bool = False,
) -> list[dict] | None:
    """The same estimate split per recording — where one cutoff behaves differently in
    different animals, which an overall figure hides completely (§20)."""
    from detail.storage import behavior_audit as audit

    artifact = self.artifact()
    rows, storage_cutoff = self._audit_rows(label, cutoff)
    examples = self._audit_examples(rows)
    rows = [
        row
        for row in rows
        if row.instance_id not in examples
        and (not (own_only and path) or (row.label_path or row.label) == path)
    ]
    return audit.precision_by_recording(
        self._audit_dir(),
        rows,
        cutoff=storage_cutoff,
        manifest=artifact.manifest,
        universe=self._audit_pool(None),
        target_path=path,
        edges=self._audit_edges({str(row.source_label) for row in rows}),
    )

audit_decisions()

Every standing decision — one row per instance, the most recent judgment about it.

AuditRow.decided separates "judged unclear" from "never looked at"; both carry human_label of None.

Source code in detail/api/authored_run.py
2027
2028
2029
2030
2031
2032
2033
2034
2035
def audit_decisions(self) -> list:
    """Every standing decision — one row per instance, the most recent judgment about it.

    ``AuditRow.decided`` separates "judged unclear" from "never looked at"; both carry
    ``human_label`` of ``None``.
    """
    from detail.storage import behavior_audit as audit

    return audit.latest_decisions(self._audit_dir())

detail.api.query.QueryRun

Bases: QueryReviewOperations, AuthoredRun

Handle for a Query run. inner (the executor handle) is present while the search is in flight and None for a run reached later to calibrate; every calibration operation works either way.

Source code in detail/api/query.py
 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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
class QueryRun(QueryReviewOperations, AuthoredRun):
    """Handle for a Query run. ``inner`` (the executor handle) is present while the search is
    in flight and ``None`` for a run reached later to calibrate; every calibration operation
    works either way."""

    #: ``AuthoredRun``'s writers and this run's own: the review's removals (through ``_edit``)
    #: and its census (through ``_record``), each refused on a snapshot view.
    _WRITE_METHODS = (
        *AuthoredRun._WRITE_METHODS,
        "take_out_clips",
        "put_back_clips",
        "finish_review",
    )

    def __init__(self, inner, experiment: Experiment, run_id: str):
        super().__init__(inner, experiment, run_id)
        # Loaded search results per behavior, warmed by `load_results`. On the *handle*
        # rather than module-level: a handle is what a calibration surface holds open while
        # someone works, and a process-wide cache would outlive the run it describes.
        self._results: dict[str, dict[tuple[str, int], object]] = {}
        # Each behavior's candidates at no cutoff (the audit's population), and each searched
        # unit's timeline they are placed on. Same lifetime as `_results`, for the same reason:
        # every audit figure on a surface reads them, and they move only when the search does.
        self._pools: dict[str, list] = {}
        self._timelines: dict[tuple[str, int], tuple] = {}

    kind = "query run"

    # -- what AuthoredRun needs from this module ------------------------------------------

    def snapshot_interpretation(self, record: dict) -> SnapshotInterpretation:
        """A snapshot of this run is its behaviors and the cutoff each was calibrated to (§20).

        A cutoff is what a Query run authors, the way a granularity is what a clustering run
        authors — "which cutoff did I ship?" is the question a pinned result has to answer. A
        behavior with `cutoff: None` has been searched and not calibrated, which is why the count
        of calibrated ones is its own column rather than folded into the total.
        """
        state = record.get("state") or {}
        behaviors = list(state.get("behaviors") or [])
        names = {
            str(b.get("id", i)): str(b.get("name") or "")
            for i, b in enumerate(behaviors)
            if b.get("name")
        }
        calibrated = [b for b in behaviors if b.get("cutoff") is not None]
        cutoffs = ", ".join(f"{float(b['cutoff']):.2f}" for b in calibrated[:4])
        vocabulary = snapshots_store.vocabulary(names)
        return SnapshotInterpretation(
            columns=("Behaviors", "Calibrated", "Cutoffs", "Vocabulary"),
            cells=(
                str(len(behaviors)),
                str(len(calibrated)),
                cutoffs or "—",
                vocabulary,
            ),
            headline=(
                f"{len(behaviors)} behaviors · {len(calibrated)} calibrated · {vocabulary}"
            ),
        )

    def _refuse_if_incomplete(self, op: str) -> None:
        """A search that did not reach every unit refuses to be finalized or exported, naming them.

        Two ways a unit goes unsearched: the search was cancelled before it (``partial``) or one
        behavior's search raised on it (``open``, with the behavior in ``behaviors_failed``).
        Either way the unit has no shard, and an export would write it as a header-only CSV —
        "searched, found nothing" — which is the one thing it is not.
        """
        record = analysis_store.read_analysis_yaml(self._run_dir())
        status = record.get("status", "open")
        failed = record.get("behaviors_failed") or {}
        if status not in self._INCOMPLETE_STATUSES and not failed:
            return
        missing = query_pipeline.missing_units(self._run_dir())
        detail = "; ".join(
            f"{behavior_id} on {', '.join(recordings)}"
            for behavior_id, recordings in sorted(missing.items())
        )
        reasons = "; ".join(f"{b}: {why}" for b, why in sorted(failed.items()))
        raise ValueError(
            f"{self.kind} {self.id} did not search every recording it was asked to "
            f"(status {status!r}), so it will not {op}. Missing: "
            f"{detail or 'units whose search failed'}"
            f"{f' ({reasons})' if reasons else ''}. Calibrating what was searched still works; "
            "re-run the search to cover the rest."
        )

    def finish_blocker(self) -> str | None:
        """Why this run cannot be finished yet, naming each behavior with no cutoff, or ``None``.

        ``AuthoredRun.finish_blocker`` for a behavior scan. Finishing says the calibration is
        done, and a behavior with no cutoff has none: it is absent from the artifact and its
        review has no clips to cover. A run finished that way showed an Audit telling the user
        to set a cutoff on Calibrate and to reopen the run, at once. ``AuthoredRun.finalize``
        raises it after the read-only and incomplete-search refusals. One read of ``query.yaml``.
        """
        uncut = [b for b in self.state().behaviors if b.cutoff is None]
        if not uncut:
            return None
        names = [b.name for b in uncut]
        listed = (
            names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}"
        )
        flags = " ".join(f"--cutoff {b.id}=CONFIDENCE" for b in uncut)
        return (
            f"{listed} {'has' if len(uncut) == 1 else 'have'} no cutoff yet, so this run "
            f"cannot be finished. Set a cutoff for {listed} on Calibrate (in the CLI, "
            f"`detail analysis query-calibrate --run {self.id} {flags}`), then finish it"
        )

    def _read_state(self) -> query_runs.QueryState:
        return query_runs.read_query_state(self._run_dir())

    def _write_state(self, state) -> None:
        query_runs.write_query_state(self._run_dir(), state)

    def _method(self):
        """The query method that wrote this run's search.

        Raises:
            UserInputError: this version no longer has it (``docs/removed_capabilities.md``),
                naming the method. Its search cannot be read — not calibrated, reviewed or
                audited — and saying so beats the bare registry error, which reached the CLI as a
                traceback.
        """
        from detail.core.registries import QUERY_METHODS
        from detail.query_methods import import_query_methods

        method_id = self.state().method
        import_query_methods()
        if method_id not in QUERY_METHODS:
            raise UserInputError(
                f"query run {self.id!r} was searched with the {method_id!r} method, which this "
                "version no longer has, so its search cannot be calibrated, reviewed or "
                "audited. The run record, its behavior output and its output folder are kept"
            )
        return query_pipeline.resolve_method(method_id)

    def _edit(self, op: str, mutate, *, reproject: bool = True, progress=None):
        """``AuthoredRun._edit``, refused first when the run's method is gone: every query edit
        reprojects through it, and finding that out inside the reprojection left the edit saved
        over results that were never rebuilt (#24 — a cutoff, a rename, a clip put back).
        """
        self._method()
        return super()._edit(op, mutate, reproject=reproject, progress=progress)

    def _log(self, entry: dict) -> None:
        query_pipeline.append_history(self._run_dir(), entry)

    def _project_frames(self, *, progress=None) -> int:
        return query_pipeline.project_frames(
            self._experiment.dir, self._run_dir(), progress=progress
        )

    def _project(self, *, progress=None, reuse: bool = False) -> None:
        # Handed whatever results this handle has already warmed, so a surface that loaded them
        # to draw a curve does not pay for them again on every commit.
        query_pipeline.project_artifact(
            self._experiment.dir,
            self._run_dir(),
            progress=progress,
            results=self._results or None,
            reuse=reuse,
        )

    # --- authored state (reads) ----------------------------------------------------------

    def state(self) -> query_runs.QueryState:
        """The whole authored state — behaviors, method, searched recordings.

        Through ``_read_state`` rather than reading the file, because that is the seam a snapshot
        view replaces (§21). Reading the run directory here bypassed it, so a pinned calibration
        rendered the *live* cutoffs and names under a banner saying "Read-only" — the frozen
        instance list beside them making it look internally consistent.
        """
        return self._read_state()

    def behaviors(self) -> list[query_runs.Behavior]:
        """The run's behaviors, each with its id, name, example clips and cutoff."""
        return self.state().behaviors

    def _recording_ids(self, state) -> list[str]:
        """The recordings the search ran over (``AuthoredRun.data_sources``)."""
        return list(state.search_recording_ids)

    def load_results(self, behavior_id: str, progress=None) -> dict:
        """Load this behavior's search results and extract their candidates, once.

        Returns ``{(recording_id, subject): SearchResult}`` for the units whose search
        completed; a unit whose shard is absent (its search failed or was interrupted) is
        simply not in the map, which is what lets the rest still be calibrated.

        **The extraction is forced here, not left to the first reader.** A method caches its
        candidate list on the result object, so whoever touches it first pays for the whole
        thing — and that is the one genuinely sized step in calibration. Doing it behind a
        named call with a ``progress`` callback is what lets a surface show a bar instead of
        freezing on whichever read happened to come first.

        ``progress(stage, fraction, detail)`` matches the synchronous long-op shape the CLI's
        ``_StageProgress`` and the GUI's ``run_progress`` both drive.
        """
        if behavior_id in self._results:
            return self._results[behavior_id]
        state = self.state()
        state.behavior(behavior_id)  # raises, naming the ids that exist
        method = self._method()
        recordings = list(state.search_recording_ids)
        loaded: dict[tuple[str, int], object] = {}
        for i, recording_id in enumerate(recordings):
            if progress is not None:
                progress("loading", i / max(len(recordings), 1), recording_id)
            path = query_runs.shard_path(
                self._run_dir(),
                behavior_id,
                recording_id,
                state.track_id,
                method.shard_suffix,
            )
            if not path.is_file():
                continue
            result = method.load(path)
            # Force the extraction while the caller is watching a bar, rather than on
            # whichever read touches it first.
            method.instances_at(result, 0.0, state.method_params)
            loaded[(recording_id, state.track_id)] = result
        if progress is not None:
            progress("loading", 1.0, "")
        self._results[behavior_id] = loaded
        return loaded

    def candidates_at(self, behavior_id: str, cutoff: float) -> dict:
        """``{(recording_id, subject): [QueryCandidate]}`` at ``cutoff`` — **without**
        committing it.

        What a calibration surface shows while the user is still deciding: the matches a
        setting would yield, read off the warmed results rather than by reprojecting. Keeping
        this on the handle is what stops a view from having to know where a shard lives or how
        a method is resolved.
        """
        state = self.state()
        method = self._method()
        return {
            unit: method.instances_at(result, float(cutoff), state.method_params)
            for unit, result in self.load_results(behavior_id).items()
        }

    def score_distribution(self, behavior_id: str, *, bins: int = 20) -> dict:
        """``{recording_id: (counts, edges)}`` over every candidate's confidence.

        §20 requires the per-recording distributions to be **always visible**, because a
        single cutoff that keeps most of one animal's behavior and little of another's biases
        the result along the very axis being compared — and a pooled curve cannot show it.
        Histograms of the candidates, not of the instances at some cutoff: the point is to see
        where each recording's mass sits before choosing one.

        Every searched recording gets an entry, including one whose search returned nothing —
        an absent row would read as "not searched", which is the distinction coverage exists
        to preserve.
        """
        import numpy as np

        edges = np.linspace(0.0, 1.0, bins + 1)
        out: dict[str, tuple] = {}
        for recording_id in self.state().search_recording_ids:
            out[recording_id] = (np.zeros(bins, dtype=np.int64), edges)
        for (recording_id, _subject), candidates in self.candidates_at(
            behavior_id, 0.0
        ).items():
            scores = np.array([c.confidence for c in candidates], dtype=float)
            counts, _ = np.histogram(scores, bins=edges)
            out[recording_id] = (counts, edges)
        return out

    def recording_duration_ns(self, recording_id: str) -> int:
        """Full video duration of a searched recording, in nanoseconds.

        The x-axis extent a timeline is drawn against, so a mark's position reflects where in
        the whole recording it falls rather than where it falls among the matches.
        """
        from detail.storage import experiment as experiment_store
        from detail.storage import recording as recording_store

        data = recording_store.read_recording(
            experiment_store.recording_path(self._experiment.dir, recording_id)
        )
        return int(float(data["video"]["total_duration_s"]) * 1e9)

    def frequency_curve(
        self, behavior_id: str, *, steps: int = 41, progress=None
    ) -> list[dict]:
        """How many instances each cutoff returns — the calibration view's whole basis.

        Without ground truth there is no score to optimize, so choosing a cutoff means looking
        at what each setting returns. This is that, as data: ``[{cutoff, n_instances, capped},
        ...]`` over ``steps`` evenly spaced cutoffs in ``[0, 1]``.

        **Instance count is not guaranteed monotonic** in the cutoff (§20): a method that
        re-forms extents can split one instance into two as the cutoff tightens. So this
        reports what it measures and no caller may assume a shape.

        ``capped`` says the method's own candidate limit bound that point. §20 requires it:
        "a curve that flattens because storage ran out looks exactly like a curve that
        flattens because the animal stopped."

        Cheap because ``instances_at`` is a slice of one cached extraction rather than a fresh
        search — before that it was quadratic per point and a slider drag cost minutes.

        Reads the results ``load_results`` warmed, so building the curve a second time (a
        second behavior, a redraw, a reopened view) costs no disk and no extraction.
        """
        state = self.state()
        method = self._method()
        cap = method.candidate_cap(state.method_params)
        results = list(self.load_results(behavior_id, progress=progress).values())

        curve: list[dict] = []
        for i in range(steps):
            cutoff = i / (steps - 1) if steps > 1 else 0.0
            counts = [
                len(method.instances_at(result, cutoff, state.method_params))
                for result in results
            ]
            curve.append(
                {
                    "cutoff": cutoff,
                    "n_instances": sum(counts),
                    "capped": cap is not None and any(n >= cap for n in counts),
                }
            )
        return curve

    def artifact(self) -> behavior_output.BehaviorOutput:
        """The §19 behavior artifact this run currently states.

        Raises:
            FileNotFoundError: If the search never completed, so there is nothing to state.
        """
        return behavior_output.read_behavior_output(self._run_dir())

    def _audit_pool(self, label: str | None):
        """Every candidate the search found, **at no cutoff at all** (§19/§20).

        Not ``instances.csv``. The artifact holds only what the current cutoff kept
        (``pipeline/query.py``'s projection), so sampling it would make the audit a function of
        a decision the user is still making: every adjustment would invalidate part of the
        evidence, and the flow would degenerate into set-cutoff, audit, re-set, re-audit.

        Enumerating at zero instead is what buys the property the audit exists for — **one
        audit serves every cutoff**. It is affordable because a cutoff-free set is small (583
        candidates for soft-kNN, and 716 for the since-removed dtw, on a 30-minute recording) and
        because ``instance_id`` is a content hash of the span, so a decision recorded here still
        attaches to its instance after the cutoff moves and the artifact is rebuilt.
        """
        from detail.api.run_preview import load_track_trajectory
        from detail.storage import experiment as experiment_store

        state = self.state()
        method = self._method()
        pool: list = []
        for behavior in state.behaviors:
            if label is not None and behavior.id != label:
                continue
            if behavior.id in self._pools:
                pool.extend(self._pools[behavior.id])
                continue
            mine: list = []
            for (recording_id, subject), result in self.load_results(
                behavior.id
            ).items():
                if (recording_id, subject) not in self._timelines:
                    recording_dir = experiment_store.recording_path(
                        self._experiment.dir, recording_id
                    )
                    self._require_searched_data(recording_dir, recording_id, state)
                    _emb, frame_idx, t_ns = load_track_trajectory(
                        recording_dir, state.embed_run_id, subject
                    )
                    self._timelines[(recording_id, subject)] = (t_ns, frame_idx)
                t_ns, frame_idx = self._timelines[(recording_id, subject)]
                mine.extend(
                    query_pipeline.instances_from(
                        method.instances_at(result, 0.0, state.method_params),
                        recording_id=recording_id,
                        subject=subject,
                        behavior_id=behavior.id,
                        t_ns=t_ns,
                        frame_idx=frame_idx,
                    )
                )
            self._pools[behavior.id] = mine
            pool.extend(mine)
        return pool

    def _require_searched_data(
        self, recording_dir: Path, recording_id: str, state
    ) -> None:
        """Refuse, naming it, a recording the search read whose data has since been deleted.

        The candidates are re-read from the recording's embedding, so a recording deleted
        after the search (or its embedding run) leaves nothing to read them from.

        Raises:
            UserInputError: the recording, or its embedding run, is no longer on disk.
        """
        what = None
        if not recording_dir.is_dir():
            what = f"recording {recording_id!r} it searched was deleted"
        elif not (recording_dir / "embeddings" / state.embed_run_id).is_dir():
            name = recording_store.read_recording(recording_dir).get(
                "name", recording_id
            )
            what = (
                f"embedding run {state.embed_run_id!r} of recording {name!r}, which it "
                "searched, was deleted"
            )
        if what is not None:
            raise UserInputError(
                f"query run {self.id!r} cannot read its candidates: the {what}. Run the "
                "query again over the recordings that are left"
            )

    def _audit_examples(self, rows) -> set[str]:
        """The candidates the user's own example or non-example clips overlap (§19).

        Those clips *defined* the behavior, so a candidate on top of one is the method finding
        its own input: judging it scores the answer key, and it is near-certain to be judged a
        yes. They stay in the run's counts and the export, marked ``is_example``; the audit
        never draws them and never counts a judgment of one.
        """
        return query_runs.example_instance_ids(self.state().behaviors, rows)

    def _audit_edges(self, labels) -> dict:
        """``{behavior id: edges}`` — each behavior's audit bins, from its candidates at no cutoff.

        Read from ``audit.yaml`` where the behavior has recorded bins (the earlier one-by-one
        audit recorded them at its first draw), else derived — the same edges, because they are
        a pure function of the candidates and the search results never change.
        """
        from detail.storage import behavior_audit as audit

        labels = sorted(str(label) for label in labels)
        stored = audit.read_bins(self._audit_dir())
        edges = {
            label: (
                stored[label]
                if label in stored
                else audit.bin_edges(
                    [
                        row.score
                        for row in behavior_output.bouts(self._audit_pool(label))
                        if row.score is not None
                    ]
                )
            )
            for label in labels
        }
        return edges

    def _audit_rows(self, label: str | None, cutoff: float | None):
        """Every behavior's candidates at no cutoff that its cutoff keeps — ``cutoff`` when one is
        given, else the behavior's own — and nothing left for storage to cut.

        Not the artifact. The estimate weights each score bin by how many instances the cutoff
        keeps in it, and a bin's instances below the committed cutoff are not in the artifact at
        all, so a cutoff lower than the committed one had no population to weight. For both
        query methods the candidates a cutoff keeps *are* the artifact's instances at it
        (``instances_at`` is a filter of one extraction), so nothing else moves. A behavior with
        no cutoff and none given is absent, as it is from the artifact.
        """
        from detail.storage import behavior_audit as audit

        direction = audit.score_direction(self.artifact().manifest)
        rows: list = []
        for behavior in self.state().behaviors:
            if label is not None and behavior.id != label:
                continue
            effective = behavior.cutoff if cutoff is None else float(cutoff)
            if effective is None:
                continue
            rows.extend(
                row
                for row in self._audit_pool(behavior.id)
                if audit.retained(row.score, effective, direction)
            )
        return rows, None

    # --- authored state (writes) ---------------------------------------------------------

    def set_cutoff(
        self, behavior_id: str, cutoff: float | None, *, progress=None
    ) -> "QueryRun":
        """Set (or clear, with ``None``) one behavior's confidence cutoff, and reproject.

        A cutoff of ``None`` is not zero. An uncalibrated behavior is **absent** from the
        artifact rather than present with no rows, because §19 reads a vocabulary entry with
        no rows inside coverage as a real zero — "we looked and it never happened" — which is
        a different claim from "nobody has chosen a threshold yet".

        Reprojects, which reads a shard and rewrites a frame-view zarr per searched unit —
        real work on a cohort, so ``progress(stage, fraction, detail)`` is driven throughout
        and every caller is expected to render it.

        Raises:
            ValueError: If the run is finalized, or the cutoff is outside ``[0, 1]``.
            KeyError: If no behavior carries that id.
        """
        if cutoff is not None and not 0.0 <= float(cutoff) <= 1.0:
            raise ValueError(
                f"cutoff must be a confidence in [0, 1], got {cutoff!r}. Confidence is "
                "canonical across query methods (§20), so this axis is method-independent."
            )

        def mutate(state: query_runs.QueryState) -> dict:
            behavior = state.behavior(behavior_id)
            behavior.cutoff = None if cutoff is None else float(cutoff)
            return {"behavior_id": behavior_id, "cutoff": behavior.cutoff}

        return self._edit("set_cutoff", mutate, progress=progress)

    def name_behavior(
        self, behavior_id: str, name: str, *, progress=None
    ) -> "QueryRun":
        """Rename one behavior, and reproject.

        The **id** never moves (§19 hashes it into every ``instance_id``, which audit decisions
        are keyed by), so a rename re-points the label and leaves every recorded judgment
        attached to what it was made about.

        Raises:
            ValueError: If the run is finalized, the name is blank, or another behavior in
                this run already carries it.
            KeyError: If no behavior carries that id.
        """
        cleaned = str(name).strip()
        if not cleaned:
            raise ValueError("a behavior name cannot be blank")

        def mutate(state: query_runs.QueryState) -> dict:
            behavior = state.behavior(behavior_id)
            clash = [
                b for b in state.behaviors if b.id != behavior_id and b.name == cleaned
            ]
            if clash:
                raise ValueError(
                    f"another behavior in this run is already called {cleaned!r} "
                    f"({clash[0].id}); names are what the artifact's vocabulary carries, so "
                    "two behaviors sharing one would pool into a single label"
                )
            behavior.name = cleaned
            return {"behavior_id": behavior_id, "name": cleaned}

        return self._edit("name_behavior", mutate, progress=progress)

    def export(self, out_dir: Path | str, *, progress=None) -> Path:
        """Write one per-recording behavior-stream CSV into a new folder under ``out_dir``;
        return that folder. Each export gets its own, so a second one never replaces the first.

        §19's deliberate, user-initiated re-ingest: the artifact is never auto-written into a
        recording's ``streams/``, because keeping the prediction/ground-truth boundary
        structural is what makes the leakage rule enforceable rather than remembered. Each row
        carries ``origin: predicted``, so re-importing one can never read back as ground truth.

        One CSV per searched recording, including recordings with no instances — an empty file
        is the honest statement for a recording that was searched and matched nothing.

        Raises:
            FileNotFoundError: If the run carries no artifact yet.
            ValueError: If the search did not reach every unit (cancelled, or a behavior's
                search failed on one) — the message names them; re-run the search.
            UserInputError: If no behavior has a cutoff yet (nothing is calibrated).

        The artifact is **pinned first** and the CSVs are written from the pinned copy (§21), so
        an exported file always corresponds to a snapshot still on disk: reopening the run and
        re-cutting it afterwards cannot leave the export describing something unfindable. Pinning
        brings deferred frame views current, the one long step, reported through ``progress``.
        """
        self._refuse_if_incomplete("be exported")
        if not any(b.cutoff is not None for b in self.state().behaviors):
            # A header-only file reads as "searched and matched nothing" (`docs/cli.md`), and
            # here nothing was calibrated: no behavior has a cutoff to cut the search at.
            raise UserInputError(
                "nothing is calibrated yet, so there is nothing to export: set a cutoff for "
                "at least one behavior (`detail analysis query-calibrate --cutoff q01=0.8`, "
                "or Calibrate in the app) first"
            )
        pinned = self.pin(reason="export", progress=progress)
        output = self.artifact() if pinned is None else self.snapshot_artifact(pinned)
        out_dir = exporters.new_export_folder(
            exporters.ExportSubject("analysis_run", self._experiment.dir, self.id),
            out_dir,
        )
        for recording_id in self.state().search_recording_ids:
            behavior_output.write_stream_csv(
                out_dir / f"{recording_id}.csv", output, recording_id
            )
        return out_dir

snapshot_interpretation(record)

A snapshot of this run is its behaviors and the cutoff each was calibrated to (§20).

A cutoff is what a Query run authors, the way a granularity is what a clustering run authors — "which cutoff did I ship?" is the question a pinned result has to answer. A behavior with cutoff: None has been searched and not calibrated, which is why the count of calibrated ones is its own column rather than folded into the total.

Source code in detail/api/query.py
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
def snapshot_interpretation(self, record: dict) -> SnapshotInterpretation:
    """A snapshot of this run is its behaviors and the cutoff each was calibrated to (§20).

    A cutoff is what a Query run authors, the way a granularity is what a clustering run
    authors — "which cutoff did I ship?" is the question a pinned result has to answer. A
    behavior with `cutoff: None` has been searched and not calibrated, which is why the count
    of calibrated ones is its own column rather than folded into the total.
    """
    state = record.get("state") or {}
    behaviors = list(state.get("behaviors") or [])
    names = {
        str(b.get("id", i)): str(b.get("name") or "")
        for i, b in enumerate(behaviors)
        if b.get("name")
    }
    calibrated = [b for b in behaviors if b.get("cutoff") is not None]
    cutoffs = ", ".join(f"{float(b['cutoff']):.2f}" for b in calibrated[:4])
    vocabulary = snapshots_store.vocabulary(names)
    return SnapshotInterpretation(
        columns=("Behaviors", "Calibrated", "Cutoffs", "Vocabulary"),
        cells=(
            str(len(behaviors)),
            str(len(calibrated)),
            cutoffs or "—",
            vocabulary,
        ),
        headline=(
            f"{len(behaviors)} behaviors · {len(calibrated)} calibrated · {vocabulary}"
        ),
    )

finish_blocker()

Why this run cannot be finished yet, naming each behavior with no cutoff, or None.

AuthoredRun.finish_blocker for a behavior scan. Finishing says the calibration is done, and a behavior with no cutoff has none: it is absent from the artifact and its review has no clips to cover. A run finished that way showed an Audit telling the user to set a cutoff on Calibrate and to reopen the run, at once. AuthoredRun.finalize raises it after the read-only and incomplete-search refusals. One read of query.yaml.

Source code in detail/api/query.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def finish_blocker(self) -> str | None:
    """Why this run cannot be finished yet, naming each behavior with no cutoff, or ``None``.

    ``AuthoredRun.finish_blocker`` for a behavior scan. Finishing says the calibration is
    done, and a behavior with no cutoff has none: it is absent from the artifact and its
    review has no clips to cover. A run finished that way showed an Audit telling the user
    to set a cutoff on Calibrate and to reopen the run, at once. ``AuthoredRun.finalize``
    raises it after the read-only and incomplete-search refusals. One read of ``query.yaml``.
    """
    uncut = [b for b in self.state().behaviors if b.cutoff is None]
    if not uncut:
        return None
    names = [b.name for b in uncut]
    listed = (
        names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}"
    )
    flags = " ".join(f"--cutoff {b.id}=CONFIDENCE" for b in uncut)
    return (
        f"{listed} {'has' if len(uncut) == 1 else 'have'} no cutoff yet, so this run "
        f"cannot be finished. Set a cutoff for {listed} on Calibrate (in the CLI, "
        f"`detail analysis query-calibrate --run {self.id} {flags}`), then finish it"
    )

state()

The whole authored state — behaviors, method, searched recordings.

Through _read_state rather than reading the file, because that is the seam a snapshot view replaces (§21). Reading the run directory here bypassed it, so a pinned calibration rendered the live cutoffs and names under a banner saying "Read-only" — the frozen instance list beside them making it look internally consistent.

Source code in detail/api/query.py
203
204
205
206
207
208
209
210
211
def state(self) -> query_runs.QueryState:
    """The whole authored state — behaviors, method, searched recordings.

    Through ``_read_state`` rather than reading the file, because that is the seam a snapshot
    view replaces (§21). Reading the run directory here bypassed it, so a pinned calibration
    rendered the *live* cutoffs and names under a banner saying "Read-only" — the frozen
    instance list beside them making it look internally consistent.
    """
    return self._read_state()

behaviors()

The run's behaviors, each with its id, name, example clips and cutoff.

Source code in detail/api/query.py
213
214
215
def behaviors(self) -> list[query_runs.Behavior]:
    """The run's behaviors, each with its id, name, example clips and cutoff."""
    return self.state().behaviors

load_results(behavior_id, progress=None)

Load this behavior's search results and extract their candidates, once.

Returns {(recording_id, subject): SearchResult} for the units whose search completed; a unit whose shard is absent (its search failed or was interrupted) is simply not in the map, which is what lets the rest still be calibrated.

The extraction is forced here, not left to the first reader. A method caches its candidate list on the result object, so whoever touches it first pays for the whole thing — and that is the one genuinely sized step in calibration. Doing it behind a named call with a progress callback is what lets a surface show a bar instead of freezing on whichever read happened to come first.

progress(stage, fraction, detail) matches the synchronous long-op shape the CLI's _StageProgress and the GUI's run_progress both drive.

Source code in detail/api/query.py
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
def load_results(self, behavior_id: str, progress=None) -> dict:
    """Load this behavior's search results and extract their candidates, once.

    Returns ``{(recording_id, subject): SearchResult}`` for the units whose search
    completed; a unit whose shard is absent (its search failed or was interrupted) is
    simply not in the map, which is what lets the rest still be calibrated.

    **The extraction is forced here, not left to the first reader.** A method caches its
    candidate list on the result object, so whoever touches it first pays for the whole
    thing — and that is the one genuinely sized step in calibration. Doing it behind a
    named call with a ``progress`` callback is what lets a surface show a bar instead of
    freezing on whichever read happened to come first.

    ``progress(stage, fraction, detail)`` matches the synchronous long-op shape the CLI's
    ``_StageProgress`` and the GUI's ``run_progress`` both drive.
    """
    if behavior_id in self._results:
        return self._results[behavior_id]
    state = self.state()
    state.behavior(behavior_id)  # raises, naming the ids that exist
    method = self._method()
    recordings = list(state.search_recording_ids)
    loaded: dict[tuple[str, int], object] = {}
    for i, recording_id in enumerate(recordings):
        if progress is not None:
            progress("loading", i / max(len(recordings), 1), recording_id)
        path = query_runs.shard_path(
            self._run_dir(),
            behavior_id,
            recording_id,
            state.track_id,
            method.shard_suffix,
        )
        if not path.is_file():
            continue
        result = method.load(path)
        # Force the extraction while the caller is watching a bar, rather than on
        # whichever read touches it first.
        method.instances_at(result, 0.0, state.method_params)
        loaded[(recording_id, state.track_id)] = result
    if progress is not None:
        progress("loading", 1.0, "")
    self._results[behavior_id] = loaded
    return loaded

candidates_at(behavior_id, cutoff)

{(recording_id, subject): [QueryCandidate]} at cutoff — without committing it.

What a calibration surface shows while the user is still deciding: the matches a setting would yield, read off the warmed results rather than by reprojecting. Keeping this on the handle is what stops a view from having to know where a shard lives or how a method is resolved.

Source code in detail/api/query.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def candidates_at(self, behavior_id: str, cutoff: float) -> dict:
    """``{(recording_id, subject): [QueryCandidate]}`` at ``cutoff`` — **without**
    committing it.

    What a calibration surface shows while the user is still deciding: the matches a
    setting would yield, read off the warmed results rather than by reprojecting. Keeping
    this on the handle is what stops a view from having to know where a shard lives or how
    a method is resolved.
    """
    state = self.state()
    method = self._method()
    return {
        unit: method.instances_at(result, float(cutoff), state.method_params)
        for unit, result in self.load_results(behavior_id).items()
    }

score_distribution(behavior_id, *, bins=20)

{recording_id: (counts, edges)} over every candidate's confidence.

§20 requires the per-recording distributions to be always visible, because a single cutoff that keeps most of one animal's behavior and little of another's biases the result along the very axis being compared — and a pooled curve cannot show it. Histograms of the candidates, not of the instances at some cutoff: the point is to see where each recording's mass sits before choosing one.

Every searched recording gets an entry, including one whose search returned nothing — an absent row would read as "not searched", which is the distinction coverage exists to preserve.

Source code in detail/api/query.py
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
def score_distribution(self, behavior_id: str, *, bins: int = 20) -> dict:
    """``{recording_id: (counts, edges)}`` over every candidate's confidence.

    §20 requires the per-recording distributions to be **always visible**, because a
    single cutoff that keeps most of one animal's behavior and little of another's biases
    the result along the very axis being compared — and a pooled curve cannot show it.
    Histograms of the candidates, not of the instances at some cutoff: the point is to see
    where each recording's mass sits before choosing one.

    Every searched recording gets an entry, including one whose search returned nothing —
    an absent row would read as "not searched", which is the distinction coverage exists
    to preserve.
    """
    import numpy as np

    edges = np.linspace(0.0, 1.0, bins + 1)
    out: dict[str, tuple] = {}
    for recording_id in self.state().search_recording_ids:
        out[recording_id] = (np.zeros(bins, dtype=np.int64), edges)
    for (recording_id, _subject), candidates in self.candidates_at(
        behavior_id, 0.0
    ).items():
        scores = np.array([c.confidence for c in candidates], dtype=float)
        counts, _ = np.histogram(scores, bins=edges)
        out[recording_id] = (counts, edges)
    return out

recording_duration_ns(recording_id)

Full video duration of a searched recording, in nanoseconds.

The x-axis extent a timeline is drawn against, so a mark's position reflects where in the whole recording it falls rather than where it falls among the matches.

Source code in detail/api/query.py
309
310
311
312
313
314
315
316
317
318
319
320
321
def recording_duration_ns(self, recording_id: str) -> int:
    """Full video duration of a searched recording, in nanoseconds.

    The x-axis extent a timeline is drawn against, so a mark's position reflects where in
    the whole recording it falls rather than where it falls among the matches.
    """
    from detail.storage import experiment as experiment_store
    from detail.storage import recording as recording_store

    data = recording_store.read_recording(
        experiment_store.recording_path(self._experiment.dir, recording_id)
    )
    return int(float(data["video"]["total_duration_s"]) * 1e9)

frequency_curve(behavior_id, *, steps=41, progress=None)

How many instances each cutoff returns — the calibration view's whole basis.

Without ground truth there is no score to optimize, so choosing a cutoff means looking at what each setting returns. This is that, as data: [{cutoff, n_instances, capped}, ...] over steps evenly spaced cutoffs in [0, 1].

Instance count is not guaranteed monotonic in the cutoff (§20): a method that re-forms extents can split one instance into two as the cutoff tightens. So this reports what it measures and no caller may assume a shape.

capped says the method's own candidate limit bound that point. §20 requires it: "a curve that flattens because storage ran out looks exactly like a curve that flattens because the animal stopped."

Cheap because instances_at is a slice of one cached extraction rather than a fresh search — before that it was quadratic per point and a slider drag cost minutes.

Reads the results load_results warmed, so building the curve a second time (a second behavior, a redraw, a reopened view) costs no disk and no extraction.

Source code in detail/api/query.py
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
def frequency_curve(
    self, behavior_id: str, *, steps: int = 41, progress=None
) -> list[dict]:
    """How many instances each cutoff returns — the calibration view's whole basis.

    Without ground truth there is no score to optimize, so choosing a cutoff means looking
    at what each setting returns. This is that, as data: ``[{cutoff, n_instances, capped},
    ...]`` over ``steps`` evenly spaced cutoffs in ``[0, 1]``.

    **Instance count is not guaranteed monotonic** in the cutoff (§20): a method that
    re-forms extents can split one instance into two as the cutoff tightens. So this
    reports what it measures and no caller may assume a shape.

    ``capped`` says the method's own candidate limit bound that point. §20 requires it:
    "a curve that flattens because storage ran out looks exactly like a curve that
    flattens because the animal stopped."

    Cheap because ``instances_at`` is a slice of one cached extraction rather than a fresh
    search — before that it was quadratic per point and a slider drag cost minutes.

    Reads the results ``load_results`` warmed, so building the curve a second time (a
    second behavior, a redraw, a reopened view) costs no disk and no extraction.
    """
    state = self.state()
    method = self._method()
    cap = method.candidate_cap(state.method_params)
    results = list(self.load_results(behavior_id, progress=progress).values())

    curve: list[dict] = []
    for i in range(steps):
        cutoff = i / (steps - 1) if steps > 1 else 0.0
        counts = [
            len(method.instances_at(result, cutoff, state.method_params))
            for result in results
        ]
        curve.append(
            {
                "cutoff": cutoff,
                "n_instances": sum(counts),
                "capped": cap is not None and any(n >= cap for n in counts),
            }
        )
    return curve

artifact()

The §19 behavior artifact this run currently states.

Raises:

Type Description
FileNotFoundError

If the search never completed, so there is nothing to state.

Source code in detail/api/query.py
367
368
369
370
371
372
373
def artifact(self) -> behavior_output.BehaviorOutput:
    """The §19 behavior artifact this run currently states.

    Raises:
        FileNotFoundError: If the search never completed, so there is nothing to state.
    """
    return behavior_output.read_behavior_output(self._run_dir())

set_cutoff(behavior_id, cutoff, *, progress=None)

Set (or clear, with None) one behavior's confidence cutoff, and reproject.

A cutoff of None is not zero. An uncalibrated behavior is absent from the artifact rather than present with no rows, because §19 reads a vocabulary entry with no rows inside coverage as a real zero — "we looked and it never happened" — which is a different claim from "nobody has chosen a threshold yet".

Reprojects, which reads a shard and rewrites a frame-view zarr per searched unit — real work on a cohort, so progress(stage, fraction, detail) is driven throughout and every caller is expected to render it.

Raises:

Type Description
ValueError

If the run is finalized, or the cutoff is outside [0, 1].

KeyError

If no behavior carries that id.

Source code in detail/api/query.py
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
def set_cutoff(
    self, behavior_id: str, cutoff: float | None, *, progress=None
) -> "QueryRun":
    """Set (or clear, with ``None``) one behavior's confidence cutoff, and reproject.

    A cutoff of ``None`` is not zero. An uncalibrated behavior is **absent** from the
    artifact rather than present with no rows, because §19 reads a vocabulary entry with
    no rows inside coverage as a real zero — "we looked and it never happened" — which is
    a different claim from "nobody has chosen a threshold yet".

    Reprojects, which reads a shard and rewrites a frame-view zarr per searched unit —
    real work on a cohort, so ``progress(stage, fraction, detail)`` is driven throughout
    and every caller is expected to render it.

    Raises:
        ValueError: If the run is finalized, or the cutoff is outside ``[0, 1]``.
        KeyError: If no behavior carries that id.
    """
    if cutoff is not None and not 0.0 <= float(cutoff) <= 1.0:
        raise ValueError(
            f"cutoff must be a confidence in [0, 1], got {cutoff!r}. Confidence is "
            "canonical across query methods (§20), so this axis is method-independent."
        )

    def mutate(state: query_runs.QueryState) -> dict:
        behavior = state.behavior(behavior_id)
        behavior.cutoff = None if cutoff is None else float(cutoff)
        return {"behavior_id": behavior_id, "cutoff": behavior.cutoff}

    return self._edit("set_cutoff", mutate, progress=progress)

name_behavior(behavior_id, name, *, progress=None)

Rename one behavior, and reproject.

The id never moves (§19 hashes it into every instance_id, which audit decisions are keyed by), so a rename re-points the label and leaves every recorded judgment attached to what it was made about.

Raises:

Type Description
ValueError

If the run is finalized, the name is blank, or another behavior in this run already carries it.

KeyError

If no behavior carries that id.

Source code in detail/api/query.py
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
def name_behavior(
    self, behavior_id: str, name: str, *, progress=None
) -> "QueryRun":
    """Rename one behavior, and reproject.

    The **id** never moves (§19 hashes it into every ``instance_id``, which audit decisions
    are keyed by), so a rename re-points the label and leaves every recorded judgment
    attached to what it was made about.

    Raises:
        ValueError: If the run is finalized, the name is blank, or another behavior in
            this run already carries it.
        KeyError: If no behavior carries that id.
    """
    cleaned = str(name).strip()
    if not cleaned:
        raise ValueError("a behavior name cannot be blank")

    def mutate(state: query_runs.QueryState) -> dict:
        behavior = state.behavior(behavior_id)
        clash = [
            b for b in state.behaviors if b.id != behavior_id and b.name == cleaned
        ]
        if clash:
            raise ValueError(
                f"another behavior in this run is already called {cleaned!r} "
                f"({clash[0].id}); names are what the artifact's vocabulary carries, so "
                "two behaviors sharing one would pool into a single label"
            )
        behavior.name = cleaned
        return {"behavior_id": behavior_id, "name": cleaned}

    return self._edit("name_behavior", mutate, progress=progress)

export(out_dir, *, progress=None)

Write one per-recording behavior-stream CSV into a new folder under out_dir; return that folder. Each export gets its own, so a second one never replaces the first.

§19's deliberate, user-initiated re-ingest: the artifact is never auto-written into a recording's streams/, because keeping the prediction/ground-truth boundary structural is what makes the leakage rule enforceable rather than remembered. Each row carries origin: predicted, so re-importing one can never read back as ground truth.

One CSV per searched recording, including recordings with no instances — an empty file is the honest statement for a recording that was searched and matched nothing.

Raises:

Type Description
FileNotFoundError

If the run carries no artifact yet.

ValueError

If the search did not reach every unit (cancelled, or a behavior's search failed on one) — the message names them; re-run the search.

UserInputError

If no behavior has a cutoff yet (nothing is calibrated).

The artifact is pinned first and the CSVs are written from the pinned copy (§21), so an exported file always corresponds to a snapshot still on disk: reopening the run and re-cutting it afterwards cannot leave the export describing something unfindable. Pinning brings deferred frame views current, the one long step, reported through progress.

Source code in detail/api/query.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def export(self, out_dir: Path | str, *, progress=None) -> Path:
    """Write one per-recording behavior-stream CSV into a new folder under ``out_dir``;
    return that folder. Each export gets its own, so a second one never replaces the first.

    §19's deliberate, user-initiated re-ingest: the artifact is never auto-written into a
    recording's ``streams/``, because keeping the prediction/ground-truth boundary
    structural is what makes the leakage rule enforceable rather than remembered. Each row
    carries ``origin: predicted``, so re-importing one can never read back as ground truth.

    One CSV per searched recording, including recordings with no instances — an empty file
    is the honest statement for a recording that was searched and matched nothing.

    Raises:
        FileNotFoundError: If the run carries no artifact yet.
        ValueError: If the search did not reach every unit (cancelled, or a behavior's
            search failed on one) — the message names them; re-run the search.
        UserInputError: If no behavior has a cutoff yet (nothing is calibrated).

    The artifact is **pinned first** and the CSVs are written from the pinned copy (§21), so
    an exported file always corresponds to a snapshot still on disk: reopening the run and
    re-cutting it afterwards cannot leave the export describing something unfindable. Pinning
    brings deferred frame views current, the one long step, reported through ``progress``.
    """
    self._refuse_if_incomplete("be exported")
    if not any(b.cutoff is not None for b in self.state().behaviors):
        # A header-only file reads as "searched and matched nothing" (`docs/cli.md`), and
        # here nothing was calibrated: no behavior has a cutoff to cut the search at.
        raise UserInputError(
            "nothing is calibrated yet, so there is nothing to export: set a cutoff for "
            "at least one behavior (`detail analysis query-calibrate --cutoff q01=0.8`, "
            "or Calibrate in the app) first"
        )
    pinned = self.pin(reason="export", progress=progress)
    output = self.artifact() if pinned is None else self.snapshot_artifact(pinned)
    out_dir = exporters.new_export_folder(
        exporters.ExportSubject("analysis_run", self._experiment.dir, self.id),
        out_dir,
    )
    for recording_id in self.state().search_recording_ids:
        behavior_output.write_stream_csv(
            out_dir / f"{recording_id}.csv", output, recording_id
        )
    return out_dir

detail.api.temporal_clustering.TemporalClusteringRun

Bases: ClipReviewOperations, ClipEditOperations, LabelOperations, NodeCacheMixin, AuthoredRun

Handle for a temporal-clustering run.

inner (the executor handle) is present while the fit is in flight and None for a run reached later to interpret; every interpretation operation works either way.

Source code in detail/api/temporal_clustering.py
 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
class TemporalClusteringRun(
    ClipReviewOperations,
    ClipEditOperations,
    LabelOperations,
    NodeCacheMixin,
    AuthoredRun,
):
    """Handle for a temporal-clustering run.

    ``inner`` (the executor handle) is present while the fit is in flight and ``None`` for a run
    reached later to interpret; every interpretation operation works either way.
    """

    #: The launch config.
    config_model = TemporalClusteringConfig

    def __init__(self, inner, experiment: Experiment, run_id: str):
        super().__init__(inner, experiment, run_id)
        # The loaded fit, warmed on first use. On the *handle* rather than module-level: a handle
        # is what an interpretation surface holds open while someone works, and a process-wide
        # cache would outlive the run it describes. It matters more here than for pose — the fit
        # is a dense K×K matrix, so re-reading it per interaction is both slow and large.
        self._fit = None

    kind = "temporal-clustering run"
    nested_labels = True

    #: ``AuthoredRun``'s writers and this run's own: the clip edits (through ``_edit``) and the
    #: clip review (through ``_record``), each refused on a snapshot view.
    _WRITE_METHODS = (
        *AuthoredRun._WRITE_METHODS,
        "take_out_clips",
        "put_back_clips",
        "finish_review",
    )

    # -- what AuthoredRun needs from this module ------------------------------------------

    snapshot_view_class = None  # set below, once the view class exists

    def snapshot_interpretation(self, record: dict) -> SnapshotInterpretation:
        """A snapshot of this run is the labels it carried (§22)."""
        return label_interpretation(record)

    def _read_state(self) -> temporal_runs.TemporalClusteringState:
        return temporal_runs.read_temporal_state(self._run_dir())

    def _write_state(self, state) -> None:
        temporal_runs.write_temporal_state(self._run_dir(), state)

    def _log(self, entry: dict) -> None:
        temporal_pipeline.append_history(self._run_dir(), entry)

    def _project_frames(self, *, progress=None) -> int:
        return temporal_pipeline.project_frames(
            self._experiment.dir, self._run_dir(), progress=progress
        )

    def _project(self, *, progress=None, reuse: bool = False) -> None:
        temporal_pipeline.project_artifact(
            self._experiment.dir,
            self._run_dir(),
            progress=progress,
            fit=self._fit,
            reuse=reuse,
        )

    # --- reads ---------------------------------------------------------------------------

    def state(self) -> temporal_runs.TemporalClusteringState:
        """The whole authored state: labels, the cache floor, and the fit's resolved inputs."""
        self._require_fit()
        return self._read_state()

    def _recording_ids(self, state) -> list[str]:
        """The recordings the fit read (``AuthoredRun.data_sources``)."""
        return list(state.source_recording_ids)

    def finish_blocker(self) -> str | None:
        """Why this run cannot be finished yet — no behavior carries a label — or ``None``.

        ``AuthoredRun.finish_blocker`` for a clustering run. A fit is a tree nobody has read
        until a node is labelled: no instance in the output carries a label, so AUDIT has
        nothing to review and BROWSE nothing to show. A run finished that way showed an AUDIT
        saying "label a node on INTERPRET" over an INTERPRET saying "this run is finished,
        reopen it".

        Counted from the stored resolution (``named_count``), which a run written before labels
        lived on nodes reports too, so a legacy run with names is not refused. One read of the
        state file, no fit.

        Worded in the screen's noun: INTERPRET calls a node of this tree a **behavior**
        (``TEMPORAL_TERMS``), and ``tests/gui/test_temporal_workspace.py`` holds every word it
        shows to that, this sentence included.
        """
        if self.state().named_count():
            return None
        return (
            "No behavior is labelled yet, so this run cannot be finished. Label one on "
            f"Interpret (in the CLI, `detail analysis temporal-interpret --run {self.id} "
            "--name-node NODE=NAME`; `--tree` lists the nodes), then finish it"
        )

    def subsample_note(self) -> str | None:
        """What the fit left out, in a sentence, or ``None`` if it compared every bout.

        §22 requires the interpretation surface to state a subsample. A fit capped by
        ``max_segments`` looks exactly like a full one — same clusters, same table, same
        confident-looking scatter — so this is the only thing standing between a user and a
        vocabulary quietly built on a fraction of their data.
        """
        return self._method().subsample_note(self._load_fit())

    def instances(self) -> list:
        """Every instance the current interpretation yields.

        Reads the projected artifact rather than recomputing: the artifact is what every other
        reader sees, so a browse list built from a second computation could disagree with it.
        """
        return list(self.artifact().instances)

    def artifact(self) -> behavior_output.BehaviorOutput:
        """The §19 behavior output this run currently projects."""
        return behavior_output.read_behavior_output(self._run_dir())

    # --- edits ---------------------------------------------------------------------------

    def _tree(self):
        """This fit's merge tree — the id space names live in."""
        return self._method().hierarchy_of(self._load_fit())

    def _reresolve(self, state) -> dict:
        """Recompute the label resolution; see ``authored_run.reresolve_labels``."""
        return authored.reresolve_labels(
            state, self._tree(), self._load_fit().labels_at
        )

    def hierarchy(self):
        """This fit's merge tree — the :class:`ClusterTree` a surface draws (§22).

        Asked of the handle rather than reached for past it, which is the layering §22 states
        ("the module never looks inside a fit"). ``node_view`` is what a surface reads a node
        through; this is the bare tree it indexes.
        """
        return self._tree()

    def export(self, out_dir: Path | str, *, progress=None) -> Path:
        """Write one per-recording behavior-stream CSV into a new folder under ``out_dir``;
        return that folder. Each export gets its own, so a second one never replaces the first.

        §19's deliberate, user-initiated re-ingest: the artifact is never auto-written into a
        recording's ``streams/``. Each row carries ``origin: predicted``, so re-importing one can
        never read back as ground truth.

        The artifact is **pinned first** and the CSVs are written from the pinned copy (§21), so
        an exported file always corresponds to a snapshot still on disk: reopening the run and
        re-cutting it afterwards cannot leave the export describing something unfindable. Pinning
        brings deferred frame views current, the one long step, reported through ``progress``.
        """
        pinned = self.pin(reason="export", progress=progress)
        output = self.artifact() if pinned is None else self.snapshot_artifact(pinned)
        out_dir = exporters.new_export_folder(
            exporters.ExportSubject("analysis_run", self._experiment.dir, self.id),
            out_dir,
        )
        for recording_id in self.state().source_recording_ids:
            behavior_output.write_stream_csv(
                out_dir / f"{recording_id}.csv", output, recording_id
            )
        return out_dir

    # --- internals -----------------------------------------------------------------------

    def _state_file(self) -> Path:
        return temporal_runs.temporal_yaml_path(self._run_dir())

    def _fit_path(self) -> Path:
        return temporal_runs.fit_path(self._run_dir(), self._method().shard_suffix)

    def _member_resolver(self, method, fit):
        return temporal_pipeline.member_resolver(method, fit)

    def _require_fit(self) -> None:
        if not temporal_runs.has_temporal_state(self._run_dir()):
            raise FileNotFoundError(
                f"analysis run {self.id} has no temporal-clustering state; it is either a "
                "different kind of run or its fit did not finish"
            )

    def _method(self):
        return temporal_pipeline.resolve_method(self.state().method)

    def _load_fit(self):
        if self._fit is None:
            method = temporal_pipeline.resolve_method(
                temporal_runs.read_temporal_state(self._run_dir()).method
            )
            self._fit = method.load(
                temporal_runs.fit_path(self._run_dir(), method.shard_suffix)
            )
        return self._fit

snapshot_interpretation(record)

A snapshot of this run is the labels it carried (§22).

Source code in detail/api/temporal_clustering.py
74
75
76
def snapshot_interpretation(self, record: dict) -> SnapshotInterpretation:
    """A snapshot of this run is the labels it carried (§22)."""
    return label_interpretation(record)

state()

The whole authored state: labels, the cache floor, and the fit's resolved inputs.

Source code in detail/api/temporal_clustering.py
103
104
105
106
def state(self) -> temporal_runs.TemporalClusteringState:
    """The whole authored state: labels, the cache floor, and the fit's resolved inputs."""
    self._require_fit()
    return self._read_state()

finish_blocker()

Why this run cannot be finished yet — no behavior carries a label — or None.

AuthoredRun.finish_blocker for a clustering run. A fit is a tree nobody has read until a node is labelled: no instance in the output carries a label, so AUDIT has nothing to review and BROWSE nothing to show. A run finished that way showed an AUDIT saying "label a node on INTERPRET" over an INTERPRET saying "this run is finished, reopen it".

Counted from the stored resolution (named_count), which a run written before labels lived on nodes reports too, so a legacy run with names is not refused. One read of the state file, no fit.

Worded in the screen's noun: INTERPRET calls a node of this tree a behavior (TEMPORAL_TERMS), and tests/gui/test_temporal_workspace.py holds every word it shows to that, this sentence included.

Source code in detail/api/temporal_clustering.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def finish_blocker(self) -> str | None:
    """Why this run cannot be finished yet — no behavior carries a label — or ``None``.

    ``AuthoredRun.finish_blocker`` for a clustering run. A fit is a tree nobody has read
    until a node is labelled: no instance in the output carries a label, so AUDIT has
    nothing to review and BROWSE nothing to show. A run finished that way showed an AUDIT
    saying "label a node on INTERPRET" over an INTERPRET saying "this run is finished,
    reopen it".

    Counted from the stored resolution (``named_count``), which a run written before labels
    lived on nodes reports too, so a legacy run with names is not refused. One read of the
    state file, no fit.

    Worded in the screen's noun: INTERPRET calls a node of this tree a **behavior**
    (``TEMPORAL_TERMS``), and ``tests/gui/test_temporal_workspace.py`` holds every word it
    shows to that, this sentence included.
    """
    if self.state().named_count():
        return None
    return (
        "No behavior is labelled yet, so this run cannot be finished. Label one on "
        f"Interpret (in the CLI, `detail analysis temporal-interpret --run {self.id} "
        "--name-node NODE=NAME`; `--tree` lists the nodes), then finish it"
    )

subsample_note()

What the fit left out, in a sentence, or None if it compared every bout.

§22 requires the interpretation surface to state a subsample. A fit capped by max_segments looks exactly like a full one — same clusters, same table, same confident-looking scatter — so this is the only thing standing between a user and a vocabulary quietly built on a fraction of their data.

Source code in detail/api/temporal_clustering.py
137
138
139
140
141
142
143
144
145
def subsample_note(self) -> str | None:
    """What the fit left out, in a sentence, or ``None`` if it compared every bout.

    §22 requires the interpretation surface to state a subsample. A fit capped by
    ``max_segments`` looks exactly like a full one — same clusters, same table, same
    confident-looking scatter — so this is the only thing standing between a user and a
    vocabulary quietly built on a fraction of their data.
    """
    return self._method().subsample_note(self._load_fit())

instances()

Every instance the current interpretation yields.

Reads the projected artifact rather than recomputing: the artifact is what every other reader sees, so a browse list built from a second computation could disagree with it.

Source code in detail/api/temporal_clustering.py
147
148
149
150
151
152
153
def instances(self) -> list:
    """Every instance the current interpretation yields.

    Reads the projected artifact rather than recomputing: the artifact is what every other
    reader sees, so a browse list built from a second computation could disagree with it.
    """
    return list(self.artifact().instances)

artifact()

The §19 behavior output this run currently projects.

Source code in detail/api/temporal_clustering.py
155
156
157
def artifact(self) -> behavior_output.BehaviorOutput:
    """The §19 behavior output this run currently projects."""
    return behavior_output.read_behavior_output(self._run_dir())

hierarchy()

This fit's merge tree — the :class:ClusterTree a surface draws (§22).

Asked of the handle rather than reached for past it, which is the layering §22 states ("the module never looks inside a fit"). node_view is what a surface reads a node through; this is the bare tree it indexes.

Source code in detail/api/temporal_clustering.py
171
172
173
174
175
176
177
178
def hierarchy(self):
    """This fit's merge tree — the :class:`ClusterTree` a surface draws (§22).

    Asked of the handle rather than reached for past it, which is the layering §22 states
    ("the module never looks inside a fit"). ``node_view`` is what a surface reads a node
    through; this is the bare tree it indexes.
    """
    return self._tree()

export(out_dir, *, progress=None)

Write one per-recording behavior-stream CSV into a new folder under out_dir; return that folder. Each export gets its own, so a second one never replaces the first.

§19's deliberate, user-initiated re-ingest: the artifact is never auto-written into a recording's streams/. Each row carries origin: predicted, so re-importing one can never read back as ground truth.

The artifact is pinned first and the CSVs are written from the pinned copy (§21), so an exported file always corresponds to a snapshot still on disk: reopening the run and re-cutting it afterwards cannot leave the export describing something unfindable. Pinning brings deferred frame views current, the one long step, reported through progress.

Source code in detail/api/temporal_clustering.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def export(self, out_dir: Path | str, *, progress=None) -> Path:
    """Write one per-recording behavior-stream CSV into a new folder under ``out_dir``;
    return that folder. Each export gets its own, so a second one never replaces the first.

    §19's deliberate, user-initiated re-ingest: the artifact is never auto-written into a
    recording's ``streams/``. Each row carries ``origin: predicted``, so re-importing one can
    never read back as ground truth.

    The artifact is **pinned first** and the CSVs are written from the pinned copy (§21), so
    an exported file always corresponds to a snapshot still on disk: reopening the run and
    re-cutting it afterwards cannot leave the export describing something unfindable. Pinning
    brings deferred frame views current, the one long step, reported through ``progress``.
    """
    pinned = self.pin(reason="export", progress=progress)
    output = self.artifact() if pinned is None else self.snapshot_artifact(pinned)
    out_dir = exporters.new_export_folder(
        exporters.ExportSubject("analysis_run", self._experiment.dir, self.id),
        out_dir,
    )
    for recording_id in self.state().source_recording_ids:
        behavior_output.write_stream_csv(
            out_dir / f"{recording_id}.csv", output, recording_id
        )
    return out_dir

Results

detail.api.measures.Measures

The measures of one analysis run's behavior artifact.

Source code in detail/api/measures.py
 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
class Measures:
    """The measures of one analysis run's behavior artifact."""

    def __init__(self, experiment, run_id: str) -> None:
        self._experiment = experiment
        self.id = run_id

    def _run_dir(self) -> Path:
        run_dir = analysis_store.analysis_dir(Path(self._experiment.dir), self.id)
        if not behavior_output.has_behavior_output(run_dir):
            raise MeasuresError(
                f"run {self.id!r} has no behavior output to measure. Measures read the §19 "
                f"artifact (instances + coverage + manifest), which only a producing module "
                f"writes."
            )
        return run_dir

    def _current_run_dir(self, progress=None) -> Path:
        """The run directory, with any frame views an authored edit deferred rebuilt first.

        A windowed measure reads the frame view, and an edit leaves it to be brought current by
        whoever reads next (§21) — which is here, before a single view is opened. Long only then,
        and it reports through ``progress``.
        """
        run_dir = self._run_dir()
        run = self._experiment.authored_run(self.id)
        if run is not None:
            run.bring_frame_views_current(progress=progress)
        return run_dir

    def table(
        self,
        *,
        windows: WindowSpec | None = None,
        measures: list[str] | None = None,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> list[dict]:
        """The tidy table: one row per ``(recording, subject, label, window, measure)``.

        ``windows`` defaults to the whole coverage span. A sub-window needs the producer's frame
        view -- ``coverage.csv`` says how much time was observed and not *where* -- and
        ``measure_run`` refuses rather than dividing by the recording's total.

        ``progress(stage, fraction, detail)`` reports the one long step: rebuilding frame views
        that edits since the last read deferred.
        """
        spec = windows or WindowSpec()
        return measures_lib.measure_run(
            self._current_run_dir(progress),
            windows_for=spec.windows_for_coverage,
            measures=measures,
        )

    def export(
        self,
        out_dir: Path | str,
        *,
        windows: WindowSpec | None = None,
        measures: list[str] | None = None,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> Path:
        """Write ``measures.csv``, ``frames.csv`` and ``measures.yaml`` into a new folder under
        ``out_dir``; return that folder. Each export gets its own, so a second one — another
        window rule, another run — never replaces the first (#29).

        The frame table is the reason this is an export rather than a single file: the frame view
        is zarr, so a per-frame classification is not otherwise readable outside this tool. The
        instance table is deliberately **not** copied -- the artifact already writes one beside
        the run, and a second copy is two files that can disagree.
        """
        from detail.api import exporters

        run_dir = self._current_run_dir(progress)
        out = exporters.new_export_folder(
            exporters.ExportSubject(
                "analysis_run", Path(self._experiment.dir), self.id
            ),
            out_dir,
            what="measures",
        )
        spec = windows or WindowSpec()

        def report(stage: str, fraction: float, detail: str = "") -> None:
            if progress is not None:
                progress(stage, fraction, detail)

        report("measuring", 0.0, self.id)
        rows = measures_lib.measure_run(
            run_dir,
            windows_for=spec.windows_for_coverage,
            measures=measures,
        )
        measures_lib.write_measures(out / MEASURES_FILENAME, rows)
        report("measuring", 1.0, f"{len(rows)} row(s)")

        report("expanding frames", 0.0, "")
        self._write_frames(run_dir, out / FRAMES_FILENAME, progress=progress)
        report("expanding frames", 1.0, "")

        (out / MANIFEST_FILENAME).write_text(
            yaml.dump(
                {
                    "schema_version": SCHEMA_VERSION,
                    "run_id": self.id,
                    "windows": spec.model_dump(),
                    "measures": measures,
                    "files": [MEASURES_FILENAME, FRAMES_FILENAME],
                },
                sort_keys=False,
            ),
            encoding="utf-8",
        )
        return out

    def _write_frames(self, run_dir: Path, path: Path, *, progress=None) -> None:
        """The frame view as CSV: one row per observed-or-not frame, with what was active on it."""
        import csv

        artifact = behavior_output.read_behavior_output(run_dir)
        names = {
            source: labels
            for source, labels in (artifact.manifest.get("names") or {}).items()
        }
        units = frame_view.discover_frame_views(run_dir)
        with open(path, "w", newline="", encoding="utf-8") as handle:
            writer = csv.DictWriter(handle, fieldnames=FRAME_COLUMNS)
            writer.writeheader()
            for index, (recording_id, subject) in enumerate(units):
                if progress is not None:
                    progress(
                        "expanding frames",
                        index / max(len(units), 1),
                        recording_id,
                    )
                view = frame_view.read_frame_view(run_dir, recording_id, subject)
                t_ns = view.t_ns[:]
                observed = view.observed[:]
                columns = {
                    source: view.root[source][:] for source in view.source_labels
                }
                for row in range(len(t_ns)):
                    active = [s for s, col in columns.items() if col[row]]
                    writer.writerow(
                        {
                            "recording_id": recording_id,
                            "subject": "" if subject is None else subject,
                            "t_ns": int(t_ns[row]),
                            "observed": int(bool(observed[row])),
                            "source_label": "|".join(active),
                            "label": "|".join(
                                name
                                for source in active
                                for name in names.get(source, [])
                            ),
                        }
                    )

table(*, windows=None, measures=None, progress=None)

The tidy table: one row per (recording, subject, label, window, measure).

windows defaults to the whole coverage span. A sub-window needs the producer's frame view -- coverage.csv says how much time was observed and not where -- and measure_run refuses rather than dividing by the recording's total.

progress(stage, fraction, detail) reports the one long step: rebuilding frame views that edits since the last read deferred.

Source code in detail/api/measures.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def table(
    self,
    *,
    windows: WindowSpec | None = None,
    measures: list[str] | None = None,
    progress: Callable[[str, float, str], None] | None = None,
) -> list[dict]:
    """The tidy table: one row per ``(recording, subject, label, window, measure)``.

    ``windows`` defaults to the whole coverage span. A sub-window needs the producer's frame
    view -- ``coverage.csv`` says how much time was observed and not *where* -- and
    ``measure_run`` refuses rather than dividing by the recording's total.

    ``progress(stage, fraction, detail)`` reports the one long step: rebuilding frame views
    that edits since the last read deferred.
    """
    spec = windows or WindowSpec()
    return measures_lib.measure_run(
        self._current_run_dir(progress),
        windows_for=spec.windows_for_coverage,
        measures=measures,
    )

export(out_dir, *, windows=None, measures=None, progress=None)

Write measures.csv, frames.csv and measures.yaml into a new folder under out_dir; return that folder. Each export gets its own, so a second one — another window rule, another run — never replaces the first (#29).

The frame table is the reason this is an export rather than a single file: the frame view is zarr, so a per-frame classification is not otherwise readable outside this tool. The instance table is deliberately not copied -- the artifact already writes one beside the run, and a second copy is two files that can disagree.

Source code in detail/api/measures.py
 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
def export(
    self,
    out_dir: Path | str,
    *,
    windows: WindowSpec | None = None,
    measures: list[str] | None = None,
    progress: Callable[[str, float, str], None] | None = None,
) -> Path:
    """Write ``measures.csv``, ``frames.csv`` and ``measures.yaml`` into a new folder under
    ``out_dir``; return that folder. Each export gets its own, so a second one — another
    window rule, another run — never replaces the first (#29).

    The frame table is the reason this is an export rather than a single file: the frame view
    is zarr, so a per-frame classification is not otherwise readable outside this tool. The
    instance table is deliberately **not** copied -- the artifact already writes one beside
    the run, and a second copy is two files that can disagree.
    """
    from detail.api import exporters

    run_dir = self._current_run_dir(progress)
    out = exporters.new_export_folder(
        exporters.ExportSubject(
            "analysis_run", Path(self._experiment.dir), self.id
        ),
        out_dir,
        what="measures",
    )
    spec = windows or WindowSpec()

    def report(stage: str, fraction: float, detail: str = "") -> None:
        if progress is not None:
            progress(stage, fraction, detail)

    report("measuring", 0.0, self.id)
    rows = measures_lib.measure_run(
        run_dir,
        windows_for=spec.windows_for_coverage,
        measures=measures,
    )
    measures_lib.write_measures(out / MEASURES_FILENAME, rows)
    report("measuring", 1.0, f"{len(rows)} row(s)")

    report("expanding frames", 0.0, "")
    self._write_frames(run_dir, out / FRAMES_FILENAME, progress=progress)
    report("expanding frames", 1.0, "")

    (out / MANIFEST_FILENAME).write_text(
        yaml.dump(
            {
                "schema_version": SCHEMA_VERSION,
                "run_id": self.id,
                "windows": spec.model_dump(),
                "measures": measures,
                "files": [MEASURES_FILENAME, FRAMES_FILENAME],
            },
            sort_keys=False,
        ),
        encoding="utf-8",
    )
    return out

detail.api.comparison.Comparison

Handle for a saved comparison: read its record, check drift, export tables and figures.

Source code in detail/api/comparison.py
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
class Comparison:
    """Handle for a saved comparison: read its record, check drift, export tables and figures."""

    def __init__(self, experiment, comparison_id: str) -> None:
        self._experiment = experiment
        self._id = comparison_id

    @property
    def id(self) -> str:
        return self._id

    @property
    def dir(self) -> Path:
        return comparisons_store.comparison_dir(self._experiment.dir, self._id)

    def record(self) -> dict:
        """The saved record.

        Raises:
            UserInputError: no comparison with this id (a mistyped ``cmp_NN``).
        """
        if not (self.dir / comparisons_store.COMPARISON_FILENAME).is_file():
            raise UserInputError(
                f"no comparison {self._id!r} in this experiment; "
                "`detail comparison list` shows the saved ones"
            )
        return comparisons_store.read_comparison_yaml(self.dir)

    def ranking(self):
        """This comparison's ranking with its floor, re-ranked from its stored observations
        through `comparison_report.rank_record` — the one record → ranking mapping (§22) — or
        ``None`` where there is nothing to rank. Seconds over a large family: call it off the
        UI thread."""
        from detail.analysis import comparison_report

        obs = comparison_report._observations(comparison_report._read_stats(self.dir))
        return comparison_report.rank_record(
            obs, self.record(), comparison_report.read_hierarchy(self.dir)
        )

    def kept_nodes(self, alpha: float | None = None) -> list[int]:
        """The node ids a node screen kept, in rank order — what the filter dock turns into
        leaves — at the strictness ``alpha``, or its own floor. Empty for a labels comparison,
        or a screen that kept nothing. Ranks; a caller already holding :meth:`ranking` passes
        it to :func:`kept_nodes_of` instead."""
        return kept_nodes_of(self.ranking(), alpha)

    def _current_source(self, record: dict) -> dict | None:
        """Where the source is *now* — the run's current artifact, or its current node cache."""
        source_run_id = record.get("source_run_id")
        if not source_run_id:
            return None
        experiment_dir = Path(self._experiment.dir)
        if record.get("source") == "nodes":
            run = self._experiment.authored_run(source_run_id)
            if run is None or not getattr(run, "has_node_cache", lambda: False)():
                return {"run_id": source_run_id}
            return {
                "run_id": source_run_id,
                "content_hash": node_source_hash(run.node_view().built_from),
            }
        if record.get("source") == "locations":
            run_dir = analysis_store.analysis_dir(experiment_dir, source_run_id)
            if not (run_dir / "analysis.yaml").is_file():
                return {"run_id": source_run_id}
            compared = sorted(record.get("provenance", {}).get("recordings", {}))
            return {
                "run_id": source_run_id,
                "content_hash": location_source_hash(run_dir, compared),
            }
        return {
            "run_id": source_run_id,
            "content_hash": snapshots_store.artifact_hash(
                analysis_store.analysis_dir(experiment_dir, source_run_id)
            ),
        }

    def drift(self) -> list[str]:
        """What changed since this was run — edited labels, a swapped video, moved code, or the
        source analysis being re-interpreted.

        A stale comparison is indistinguishable from a current one by looking at it, which is why
        every surface that renders these numbers checks (§18.5). None of it means the stored
        numbers are wrong: they were measured from a pinned snapshot and stay exactly reproducible
        (§21). What drift says is that a re-run would not match them.
        """
        record = self.record()
        experiment_dir = Path(self._experiment.dir)
        current = provenance.capture(
            experiment_dir,
            recording_ids=sorted(record["provenance"].get("recordings", {})),
            members=[],
            # Deliberately the **run's current** artifact, not the snapshot this comparison read:
            # the question drift answers is whether the run has moved on since.
            source=self._current_source(record),
        )
        return provenance.drift(record.get("provenance", {}), current)

    def export(
        self,
        out_dir: Path | str | None = None,
        *,
        formats: tuple[str, ...] = DEFAULT_FORMATS,
        style: "FigureStyle | None" = None,
        theme: str | None = None,
        progress: Callable[[str, float, str], None] | None = None,
    ) -> dict:
        """Write the publication tree (tables + figures + summary + manifest); return the manifest.

        Defaults into the comparison's own directory, because §24 makes a comparison a saved object
        *holding its outputs* rather than a record pointing at a separate export.

        Args:
            out_dir: where to write; the comparison's own folder when omitted.
            formats: the figure formats to write.
            style: the figure style (default :data:`detail.report.style.DEFAULT_STYLE`).
            theme: ``"light"`` (white, for print — the default) or ``"dark"`` (for slides).
                Overrides ``style``'s theme when given; recorded in the manifest.
            progress: ``(stage, fraction, detail)``, reported through the render — one
                matplotlib figure per measurement, minutes on a large comparison.

        Raises:
            ValueError: If ``theme`` is not ``"light"`` or ``"dark"``.
        """
        from detail.analysis.comparison_report import export_comparison
        from detail.report.style import DEFAULT_STYLE

        out = Path(out_dir) if out_dir is not None else self.dir
        style = style or DEFAULT_STYLE
        if theme is not None:
            style = style.with_theme(theme)
        return export_comparison(
            Path(self._experiment.dir),
            self.record(),
            out,
            formats=formats,
            style=style,
            progress=progress,
        )

record()

The saved record.

Raises:

Type Description
UserInputError

no comparison with this id (a mistyped cmp_NN).

Source code in detail/api/comparison.py
910
911
912
913
914
915
916
917
918
919
920
921
def record(self) -> dict:
    """The saved record.

    Raises:
        UserInputError: no comparison with this id (a mistyped ``cmp_NN``).
    """
    if not (self.dir / comparisons_store.COMPARISON_FILENAME).is_file():
        raise UserInputError(
            f"no comparison {self._id!r} in this experiment; "
            "`detail comparison list` shows the saved ones"
        )
    return comparisons_store.read_comparison_yaml(self.dir)

ranking()

This comparison's ranking with its floor, re-ranked from its stored observations through comparison_report.rank_record — the one record → ranking mapping (§22) — or None where there is nothing to rank. Seconds over a large family: call it off the UI thread.

Source code in detail/api/comparison.py
923
924
925
926
927
928
929
930
931
932
933
def ranking(self):
    """This comparison's ranking with its floor, re-ranked from its stored observations
    through `comparison_report.rank_record` — the one record → ranking mapping (§22) — or
    ``None`` where there is nothing to rank. Seconds over a large family: call it off the
    UI thread."""
    from detail.analysis import comparison_report

    obs = comparison_report._observations(comparison_report._read_stats(self.dir))
    return comparison_report.rank_record(
        obs, self.record(), comparison_report.read_hierarchy(self.dir)
    )

kept_nodes(alpha=None)

The node ids a node screen kept, in rank order — what the filter dock turns into leaves — at the strictness alpha, or its own floor. Empty for a labels comparison, or a screen that kept nothing. Ranks; a caller already holding :meth:ranking passes it to :func:kept_nodes_of instead.

Source code in detail/api/comparison.py
935
936
937
938
939
940
def kept_nodes(self, alpha: float | None = None) -> list[int]:
    """The node ids a node screen kept, in rank order — what the filter dock turns into
    leaves — at the strictness ``alpha``, or its own floor. Empty for a labels comparison,
    or a screen that kept nothing. Ranks; a caller already holding :meth:`ranking` passes
    it to :func:`kept_nodes_of` instead."""
    return kept_nodes_of(self.ranking(), alpha)

drift()

What changed since this was run — edited labels, a swapped video, moved code, or the source analysis being re-interpreted.

A stale comparison is indistinguishable from a current one by looking at it, which is why every surface that renders these numbers checks (§18.5). None of it means the stored numbers are wrong: they were measured from a pinned snapshot and stay exactly reproducible (§21). What drift says is that a re-run would not match them.

Source code in detail/api/comparison.py
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def drift(self) -> list[str]:
    """What changed since this was run — edited labels, a swapped video, moved code, or the
    source analysis being re-interpreted.

    A stale comparison is indistinguishable from a current one by looking at it, which is why
    every surface that renders these numbers checks (§18.5). None of it means the stored
    numbers are wrong: they were measured from a pinned snapshot and stay exactly reproducible
    (§21). What drift says is that a re-run would not match them.
    """
    record = self.record()
    experiment_dir = Path(self._experiment.dir)
    current = provenance.capture(
        experiment_dir,
        recording_ids=sorted(record["provenance"].get("recordings", {})),
        members=[],
        # Deliberately the **run's current** artifact, not the snapshot this comparison read:
        # the question drift answers is whether the run has moved on since.
        source=self._current_source(record),
    )
    return provenance.drift(record.get("provenance", {}), current)

export(out_dir=None, *, formats=DEFAULT_FORMATS, style=None, theme=None, progress=None)

Write the publication tree (tables + figures + summary + manifest); return the manifest.

Defaults into the comparison's own directory, because §24 makes a comparison a saved object holding its outputs rather than a record pointing at a separate export.

Parameters:

Name Type Description Default
out_dir Path | str | None

where to write; the comparison's own folder when omitted.

None
formats tuple[str, ...]

the figure formats to write.

DEFAULT_FORMATS
style FigureStyle | None

the figure style (default :data:detail.report.style.DEFAULT_STYLE).

None
theme str | None

"light" (white, for print — the default) or "dark" (for slides). Overrides style's theme when given; recorded in the manifest.

None
progress Callable[[str, float, str], None] | None

(stage, fraction, detail), reported through the render — one matplotlib figure per measurement, minutes on a large comparison.

None

Raises:

Type Description
ValueError

If theme is not "light" or "dark".

Source code in detail/api/comparison.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
def export(
    self,
    out_dir: Path | str | None = None,
    *,
    formats: tuple[str, ...] = DEFAULT_FORMATS,
    style: "FigureStyle | None" = None,
    theme: str | None = None,
    progress: Callable[[str, float, str], None] | None = None,
) -> dict:
    """Write the publication tree (tables + figures + summary + manifest); return the manifest.

    Defaults into the comparison's own directory, because §24 makes a comparison a saved object
    *holding its outputs* rather than a record pointing at a separate export.

    Args:
        out_dir: where to write; the comparison's own folder when omitted.
        formats: the figure formats to write.
        style: the figure style (default :data:`detail.report.style.DEFAULT_STYLE`).
        theme: ``"light"`` (white, for print — the default) or ``"dark"`` (for slides).
            Overrides ``style``'s theme when given; recorded in the manifest.
        progress: ``(stage, fraction, detail)``, reported through the render — one
            matplotlib figure per measurement, minutes on a large comparison.

    Raises:
        ValueError: If ``theme`` is not ``"light"`` or ``"dark"``.
    """
    from detail.analysis.comparison_report import export_comparison
    from detail.report.style import DEFAULT_STYLE

    out = Path(out_dir) if out_dir is not None else self.dir
    style = style or DEFAULT_STYLE
    if theme is not None:
        style = style.with_theme(theme)
    return export_comparison(
        Path(self._experiment.dir),
        self.record(),
        out,
        formats=formats,
        style=style,
        progress=progress,
    )

Machine-global catalogs

These take no experiment: the model catalog is per machine, and a tool run is saved outside any experiment.

detail.api.models

Experiment-independent machine-global model catalog (Section 5).

Built-in models (the MODELS / EMBEDDING_MODELS registries) and machine-global imported weights are not experiment state — readiness, install, and the imported catalog are all shared across experiments. This is the experiment-free surface the GUI's top-level Models tab uses; Experiment's model methods delegate here. Backend imports stay lazy (Tenet 13): importing this module pulls in no torch / ultralytics / sam3.

list_models()

All machine-global models — built-in (every role in MODEL_REGISTRIES) + imported.

Source code in detail/api/models.py
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
def list_models() -> list[GlobalModelRow]:
    """All machine-global models — built-in (every role in ``MODEL_REGISTRIES``) + imported."""
    _ensure_registered()
    rows: list[GlobalModelRow] = []
    for role, registry in MODEL_REGISTRIES:
        for mid in sorted(registry):
            cls = registry[mid]
            if getattr(cls, "shares_weights_with", None):
                # Nothing of its own to install: the backbone's row carries the capability
                # (§14), so one download is listed once. The id still resolves (all_models).
                continue
            capabilities = [role]
            if issubclass(cls, PatchFeatures):
                capabilities.append("patch features")
            rows.append(
                GlobalModelRow(
                    id=mid,
                    role=role,
                    architecture=getattr(cls, "architecture", "—"),
                    source="built-in",
                    variants=cls.variants(),
                    classes=[],  # built-ins: open-vocab / embedding — no fixed classes
                    gated=getattr(cls, "gated", False),
                    input_size=getattr(cls, "input_size", None),
                    output_dim=getattr(cls, "output_dim", None),
                    capabilities=capabilities,
                )
            )
    for rec in imported_store.list_records():
        role = _catalog_role(rec)
        rows.append(
            GlobalModelRow(
                id=rec["id"],
                role=role,
                architecture=rec.get("model_family", "—"),
                source=rec.get("source", "imported"),  # "imported" | "distilled" (§12)
                variants=[],
                classes=[c["name"] for c in rec.get("classes", [])],
                gated=False,
                provenance=rec.get("provenance"),
                capabilities=[role],
            )
        )
    return rows

model_readiness(model_id, variant=None)

Proactive readiness for a model — drives the 'check access' UI. Imported models are on disk by definition (no repo/token), so they are always ready; only built-ins consult their cache/credentials.

variant selects the size to answer for (the model's default when omitted).

Source code in detail/api/models.py
325
326
327
328
329
330
331
332
333
334
335
336
def model_readiness(model_id: str, variant: str | None = None) -> ModelReadiness:
    """Proactive readiness for a model — drives the 'check access' UI. Imported
    models are on disk by definition (no repo/token), so they are always ready;
    only built-ins consult their cache/credentials.

    ``variant`` selects the size to answer for (the model's default when omitted)."""
    _ensure_registered()
    if model_id in imported_store.discover():
        return ModelReadiness(
            ready=True, reason="ok", message="", action_url=None, repo_id=None
        )
    return _model(model_id, variant).readiness()

is_installed(model_id, variant=None)

Whether a model's weights are on this machine — a cheap, no-network check, and the authoritative one: a run's pre-flight gates on it, because load() will not download. Imported models are on disk by definition; every built-in answers for itself via DetectionModel/EmbeddingModel.is_installed (§5).

Answers for variant (the model's default when omitted) — the run gates on the variant it was configured with, so a variant-blind answer here is a false green.

Source code in detail/api/models.py
353
354
355
356
357
358
359
360
361
362
363
364
def is_installed(model_id: str, variant: str | None = None) -> bool:
    """Whether a model's weights are on this machine — a cheap, **no-network** check,
    and the authoritative one: a run's pre-flight gates on it, because ``load()`` will
    not download. Imported models are on disk by definition; every built-in answers
    for itself via ``DetectionModel/EmbeddingModel.is_installed`` (§5).

    Answers for ``variant`` (the model's default when omitted) — the run gates on the
    variant it was configured with, so a variant-blind answer here is a false green."""
    _ensure_registered()
    if model_id in imported_store.discover():
        return True
    return _model(model_id, variant).is_installed()

install_model(model_id, progress_cb=None, *, variant=None)

Ensure a built-in model's weights are present; raises ModelNotReadyError if blocked.

variant picks the size to download. Each variant is a separate download, so installing one leaves the others absent — installing the default does not make a run configured for another size runnable.

Source code in detail/api/models.py
339
340
341
342
343
344
345
346
347
348
349
350
def install_model(
    model_id: str,
    progress_cb: Callable[[InstallProgress], None] | None = None,
    *,
    variant: str | None = None,
) -> None:
    """Ensure a built-in model's weights are present; raises ModelNotReadyError if blocked.

    ``variant`` picks the size to download. Each variant is a separate download, so
    installing one leaves the others absent — installing the default does not make a
    run configured for another size runnable."""
    _model(model_id, variant).install(progress_cb)

import_model(weights_path, *, family=None, skeleton=None, name=None, made_by=None, description=None, notes=None, preview=None)

Import an external Ultralytics checkpoint into the machine-global catalog (usable in any experiment). Class names and the task are read from the checkpoint; the task decides whether it lands as a detection or a keypoint model (§12 Keypoint models in the catalog). family is optional and, when given, is checked against the task.

A pose checkpoint needs skeleton — a preset id, a library id, a skeleton YAML, a Skeleton or its dict — with the checkpoint's number of points and left/right pairs matching its flip_idx; it is added to the skeleton library unless one with its digest is there. made_by / description / notes / preview are captured so the model isn't 'lost in a folder' (§12). Returns the assigned id.

Raises:

Type Description
FileNotFoundError

weights_path (or preview) does not exist.

UserInputError

weights_path is not a YOLO .pt checkpoint.

ValueError

Unknown family or one that disagrees with the task, an unknown skeleton, a pose checkpoint without a fitting skeleton, a skeleton for a detection checkpoint, a class-less checkpoint, or an id collision.

Source code in detail/api/models.py
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
def import_model(
    weights_path: Path | str,
    *,
    family: str | None = None,
    skeleton=None,
    name: str | None = None,
    made_by: str | None = None,
    description: str | None = None,
    notes: str | None = None,
    preview: Path | str | None = None,
) -> str:
    """Import an external Ultralytics checkpoint into the machine-global catalog (usable in
    any experiment). Class names and the task are read from the checkpoint; the task decides
    whether it lands as a detection or a keypoint model (§12 *Keypoint models in the
    catalog*). ``family`` is optional and, when given, is checked against the task.

    A pose checkpoint needs ``skeleton`` — a preset id, a library id, a skeleton YAML, a
    ``Skeleton`` or its dict — with the checkpoint's number of points and left/right pairs
    matching its ``flip_idx``; it is added to the skeleton library unless one with its digest
    is there. ``made_by`` / ``description`` / ``notes`` / ``preview`` are captured so the
    model isn't 'lost in a folder' (§12). Returns the assigned id.

    Raises:
        FileNotFoundError: ``weights_path`` (or ``preview``) does not exist.
        UserInputError: ``weights_path`` is not a YOLO ``.pt`` checkpoint.
        ValueError: Unknown family or one that disagrees with the task, an unknown skeleton,
            a pose checkpoint without a fitting skeleton, a skeleton for a detection
            checkpoint, a class-less checkpoint, or an id collision.
    """
    _ensure_registered()  # populate TRAINED_LOADERS + MODELS for the family loader
    resolved = None if skeleton is None else skeletons_api.resolve_skeleton(skeleton)
    skeleton_name = (
        None if skeleton is None else skeletons_api.skeleton_source_name(skeleton)
    )
    return imported_store.import_model(
        weights_path,
        family=family,
        skeleton=resolved,
        skeleton_name=skeleton_name,
        name=name,
        made_by=made_by,
        description=description,
        notes=notes,
        preview=preview,
    )

remove_imported_model(model_id)

Delete a machine-global imported model (raises if absent).

Also deletes a catalog folder an import cut short left behind (no model.yaml, :func:imported.unfinished): it is no model, but it blocks its name, and nothing else could delete it. Only a name in either listing is deleted, so an id is never a path.

Source code in detail/api/models.py
738
739
740
741
742
743
744
745
746
747
748
749
750
def remove_imported_model(model_id: str) -> None:
    """Delete a machine-global imported model (raises if absent).

    Also deletes a catalog folder an import cut short left behind (no ``model.yaml``,
    :func:`imported.unfinished`): it is no model, but it blocks its name, and nothing else
    could delete it. Only a name in either listing is deleted, so an id is never a path.
    """
    if (
        model_id not in imported_store.discover()
        and model_id not in imported_store.unfinished()
    ):
        raise FileNotFoundError(f"no imported model {model_id!r}")
    imported_store.remove(model_id)

detail.api.tools

Machine-global Tools API (§27) — the experiment-free entry point for one-off runs.

A tool runs synchronously and saves a managed run under the machine-global tools workspace (storage/tool_runs.py). This module is the surface the CLI and GUI both drive: it resolves the tool, allocates a run directory, runs it (recording running → complete/failed on the manifest), and lists / reads / deletes past runs. Experiment-free, so it is a module of functions (like api/models.py), not a class.

list_tools()

Every registered tool, ordered by id.

Source code in detail/api/tools.py
32
33
34
35
36
37
38
def list_tools() -> list[ToolInfo]:
    """Every registered tool, ordered by id."""
    import_tools()
    return [
        ToolInfo(t.tool_id, t.label, t.description, t.category)
        for t in (TOOLS[k] for k in sorted(TOOLS))
    ]

run_tool(tool_id, config, *, progress=None, stop_check=None)

Run a tool and record its managed run; return the final manifest.

The manifest is written running before the work starts (so a crash leaves a visible record), then complete with the result — stopped when the user ended it early (the partial output is still there and still openable), or failed with the error, re-raised for the caller to surface.

Raises:

Type Description
ValueError

Unknown tool_id.

Source code in detail/api/tools.py
 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
def run_tool(
    tool_id: str,
    config: dict,
    *,
    progress: Callable[[str, float, str], None] | None = None,
    stop_check: Callable[[], bool] | None = None,
) -> dict:
    """Run a tool and record its managed run; return the final manifest.

    The manifest is written ``running`` before the work starts (so a crash leaves a
    visible record), then ``complete`` with the result — ``stopped`` when the user ended
    it early (the partial output is still there and still openable), or ``failed`` with
    the error, re-raised for the caller to surface.

    Raises:
        ValueError: Unknown ``tool_id``.
    """
    import_tools()
    tool_cls = TOOLS.get(tool_id)
    if tool_cls is None:
        raise ValueError(f"unknown tool {tool_id!r}; available: {sorted(TOOLS)}")
    tool = tool_cls()

    run_id = tool_runs.next_run_id(tool_id)
    out_dir = tool_runs.tool_run_dir(tool_id, run_id)
    out_dir.mkdir(parents=True, exist_ok=True)
    # Plural inputs with a singular alias: a run may span several clips and compare
    # several prompts, but ``source_video`` / ``prompt`` stay populated with the first so
    # manifests written before this — and anything reading them — keep working.
    videos = [Path(v) for v in (config.get("videos") or [config["video"]])]
    prompts = list(config.get("prompts") or [config["prompt"]])
    record = {
        "id": run_id,
        "tool_id": tool_id,
        "label": tool.label,
        "source_video": str(videos[0].resolve()),
        "source_videos": [str(v.resolve()) for v in videos],
        "model_id": config.get("model_id"),
        "model_variant": config.get("model_variant"),
        "prompt": prompts[0].to_dict(),
        "prompts": [p.to_dict() for p in prompts],
        "compute": config["compute"].to_dict(),
        # The tool's config model is the single source for its scalar parameters, so the
        # manifest records exactly those rather than a hand-listed subset that drifts.
        "config": {
            name: config[name]
            for name in tool.config_model.model_fields
            if name in config
        },
        "status": "running",
        "created_at": utc_timestamp(),
    }
    tool_runs.write_tool_run(tool_id, run_id, record)

    try:
        result = tool.run(config, out_dir, progress, stop_check)
    except Exception as exc:  # noqa: BLE001 — record the failure, then re-raise
        record["status"] = "failed"
        record["error"] = str(exc)
        tool_runs.write_tool_run(tool_id, run_id, record)
        raise
    record["status"] = "stopped" if result.stopped else "complete"
    record["result"] = result.to_dict()
    tool_runs.write_tool_run(tool_id, run_id, record)
    return record

list_tool_runs(tool_id=None)

All tool-run manifests (one tool or every tool), ordered by run id.

Source code in detail/api/tools.py
128
129
130
def list_tool_runs(tool_id: str | None = None) -> list[dict]:
    """All tool-run manifests (one tool or every tool), ordered by run id."""
    return tool_runs.list_tool_runs(tool_id)

read_tool_run(run_id)

One tool-run manifest by id (raises FileNotFoundError if absent).

Source code in detail/api/tools.py
133
134
135
def read_tool_run(run_id: str) -> dict:
    """One tool-run manifest by id (raises ``FileNotFoundError`` if absent)."""
    return tool_runs.read_tool_run(run_id)

delete_tool_run(run_id)

Delete a tool run by id (idempotent).

Source code in detail/api/tools.py
138
139
140
def delete_tool_run(run_id: str) -> None:
    """Delete a tool run by id (idempotent)."""
    tool_runs.delete_tool_run(run_id)