Skip to content

canvod.store API Reference

Versioned data storage using Icechunk.

Package

canvod-store: Icechunk storage for GNSS VOD data.

This package provides versioned storage for GNSS VOD data using Icechunk. Manages both RINEX observation storage and VOD analysis results.

MyIcechunkStore

Core Icechunk store manager for GNSS data.

This class encapsulates all operations on a single Icechunk repository, providing a clean interface for GNSS data storage and retrieval with integrated logging and proper resource management.

Features: - Automatic repository creation/connection - Group management with validation - Session management with context managers - Integrated logging with file contexts - Configurable compression and chunking

Note on "metadata"

This class manages two distinct things both historically called "metadata":

  • File registry ({group}/metadata/table): per-file ingest ledger tracking hashes, temporal ranges, filenames, and paths. Managed by append_metadata(), load_metadata(), backup_metadata_table(), etc.

  • Store metadata (canvod.store_metadata package): store-level provenance (identity, creator, environment, compliance). Written to Zarr root attrs by the orchestrator. See canvod-store-metadata.

Parameters

store_path : Path Path to the Icechunk store directory. store_type : str, default "rinex_store" Type of store ("rinex_store" or "vod_store"). compression_level : int | None, optional Override default compression level. compression_algorithm : str | None, optional Override default compression algorithm.

Attributes

store_path : Path Path to the Icechunk store directory. store_type : str Type of store ("rinex_store" or "vod_store"). compression_level : int Compression level (1-9). compression_algorithm : icechunk.CompressionAlgorithm Compression algorithm enum. repo : icechunk.Repository The Icechunk repository instance.

Source code in packages/canvod-store/src/canvod/store/store.py
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 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
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
@add_rich_display_to_store
class MyIcechunkStore:
    """
    Core Icechunk store manager for GNSS data.

    This class encapsulates all operations on a single Icechunk repository,
    providing a clean interface for GNSS data storage and retrieval with
    integrated logging and proper resource management.

    Features:
    - Automatic repository creation/connection
    - Group management with validation
    - Session management with context managers
    - Integrated logging with file contexts
    - Configurable compression and chunking

    Note on "metadata"
    ------------------
    This class manages two distinct things both historically called "metadata":

    - **File registry** (``{group}/metadata/table``): per-file ingest ledger
      tracking hashes, temporal ranges, filenames, and paths. Managed by
      ``append_metadata()``, ``load_metadata()``, ``backup_metadata_table()``, etc.

    - **Store metadata** (``canvod.store_metadata`` package): store-level
      provenance (identity, creator, environment, compliance). Written to
      Zarr root attrs by the orchestrator. See ``canvod-store-metadata``.

    Parameters
    ----------
    store_path : Path
        Path to the Icechunk store directory.
    store_type : str, default "rinex_store"
        Type of store ("rinex_store" or "vod_store").
    compression_level : int | None, optional
        Override default compression level.
    compression_algorithm : str | None, optional
        Override default compression algorithm.

    Attributes
    ----------
    store_path : Path
        Path to the Icechunk store directory.
    store_type : str
        Type of store ("rinex_store" or "vod_store").
    compression_level : int
        Compression level (1-9).
    compression_algorithm : icechunk.CompressionAlgorithm
        Compression algorithm enum.
    repo : icechunk.Repository
        The Icechunk repository instance.
    """

    def __init__(
        self,
        store_path: Path,
        store_type: str = "rinex_store",
        compression_level: int | None = None,
        compression_algorithm: str | None = None,
    ) -> None:
        """Initialize the Icechunk store manager.

        Parameters
        ----------
        store_path : Path
            Path to the Icechunk store directory.
        store_type : str, default "rinex_store"
            Type of store ("rinex_store" or "vod_store").
        compression_level : int | None, optional
            Override default compression level.
        compression_algorithm : str | None, optional
            Override default compression algorithm.
        """
        from canvod.utils.config import load_config

        cfg = load_config()
        ic_cfg = cfg.processing.icechunk
        st_cfg = cfg.processing.storage

        self.store_path = Path(store_path)
        self.store_type = store_type
        # Site name is parent directory name
        self.site_name = self.store_path.parent.name

        # Compression
        self.compression_level = compression_level or ic_cfg.compression_level
        compression_alg = compression_algorithm or ic_cfg.compression_algorithm
        self.compression_algorithm = getattr(
            icechunk.CompressionAlgorithm, compression_alg.capitalize()
        )

        # Chunk strategy
        chunk_strategies = {
            k: {"epoch": v.epoch, "sid": v.sid}
            for k, v in ic_cfg.chunk_strategies.items()
        }
        self.chunk_strategy = chunk_strategies.get(store_type, {})

        # Storage config cached for metadata rows
        self._rinex_store_strategy = st_cfg.rinex_store_strategy
        self._rinex_store_expire_days = st_cfg.rinex_store_expire_days
        self._vod_store_strategy = st_cfg.vod_store_strategy

        # Configure repository
        self.config = icechunk.RepositoryConfig.default()
        self.config.compression = icechunk.CompressionConfig(
            level=self.compression_level, algorithm=self.compression_algorithm
        )
        self.config.inline_chunk_threshold_bytes = ic_cfg.inline_threshold
        self.config.get_partial_values_concurrency = ic_cfg.get_concurrency

        if ic_cfg.manifest_preload_enabled:
            self.config.manifest = icechunk.ManifestConfig(
                preload=icechunk.ManifestPreloadConfig(
                    max_total_refs=ic_cfg.manifest_preload_max_refs,
                    preload_if=icechunk.ManifestPreloadCondition.name_matches(
                        ic_cfg.manifest_preload_pattern
                    ),
                )
            )
            self._logger.info(
                f"Manifest preload enabled: {ic_cfg.manifest_preload_pattern}"
            )

        self._repo = None
        self._logger = get_logger(__name__)

        # Remove .DS_Store files that corrupt icechunk ref listing on macOS
        self._clean_ds_store()
        self._ensure_store_exists()

    def _clean_ds_store(self) -> None:
        """Remove .DS_Store files from the store directory tree.

        macOS creates these files automatically and they corrupt icechunk's
        ref listing, causing 'invalid ref type `.DS_Store`' errors.
        """
        if not self.store_path.exists():
            return
        for ds_store in self.store_path.rglob(".DS_Store"):
            ds_store.unlink()
            self._logger.debug(f"Removed {ds_store}")

    def _normalize_encodings(self, ds: xr.Dataset) -> xr.Dataset:
        """Normalize dataset encodings for Icechunk.

        Parameters
        ----------
        ds : xr.Dataset
            Dataset to normalize.

        Returns
        -------
        xr.Dataset
            Dataset with normalized encodings.
        """
        for v in ds.data_vars:
            if "dtype" in ds[v].encoding:
                ds[v].encoding["dtype"] = np.dtype(ds[v].dtype)
        return ds

    def _ensure_store_exists(self) -> None:
        """Ensure the store exists, creating if necessary."""
        storage = icechunk.local_filesystem_storage(str(self.store_path))

        if self.store_path.exists() and any(self.store_path.iterdir()):
            self._logger.info(f"Opening existing Icechunk store at {self.store_path}")
            self._repo = icechunk.Repository.open(storage=storage, config=self.config)
        else:
            self._logger.info(f"Creating new Icechunk store at {self.store_path}")
            self.store_path.mkdir(parents=True, exist_ok=True)
            self._repo = icechunk.Repository.create(storage=storage, config=self.config)

    @property
    def repo(self) -> icechunk.Repository:
        """Get the repository instance."""
        if self._repo is None:
            self._ensure_store_exists()
        return self._repo

    @contextlib.contextmanager
    def readonly_session(
        self,
        branch: str = "main",
    ) -> Generator[icechunk.ReadonlySession]:
        """Context manager for readonly sessions.

        Parameters
        ----------
        branch : str, default "main"
            Branch name.

        Returns
        -------
        Generator[icechunk.ReadonlySession, None, None]
            Readonly session context manager.
        """
        session = self.repo.readonly_session(branch)
        try:
            self._logger.debug(f"Opened readonly session for branch '{branch}'")
            yield session
        finally:
            self._logger.debug(f"Closed readonly session for branch '{branch}'")

    @contextlib.contextmanager
    def writable_session(
        self,
        branch: str = "main",
    ) -> Generator[icechunk.WritableSession]:
        """Context manager for writable sessions.

        Parameters
        ----------
        branch : str, default "main"
            Branch name.

        Returns
        -------
        Generator[icechunk.WritableSession, None, None]
            Writable session context manager.
        """
        session = self.repo.writable_session(branch)
        try:
            self._logger.debug(f"Opened writable session for branch '{branch}'")
            yield session
        finally:
            self._logger.debug(f"Closed writable session for branch '{branch}'")

    # ── Root-level store attributes ────────────────────────────────────────────

    def set_root_attrs(self, attrs: dict[str, Any], branch: str = "main") -> str:
        """Set root-level Zarr attributes on the store.

        Parameters
        ----------
        attrs : dict[str, Any]
            Key-value pairs to merge into root attrs.
        branch : str, default "main"
            Branch to write to.

        Returns
        -------
        str
            Snapshot ID from the commit.
        """
        with self.writable_session(branch) as session:
            try:
                root = zarr.open_group(session.store, mode="r+")
            except zarr.errors.GroupNotFoundError:
                root = zarr.open_group(session.store, mode="w")
            root.attrs.update(attrs)
            return session.commit(f"Set root attrs: {list(attrs.keys())}")

    def get_root_attrs(self, branch: str = "main") -> dict[str, Any]:
        """Read root-level Zarr attributes from the store.

        Returns
        -------
        dict[str, Any]
            Root attributes (empty dict if none set).
        """
        try:
            with self.readonly_session(branch) as session:
                root = zarr.open_group(session.store, mode="r")
                return dict(root.attrs)
        except Exception:
            return {}

    @property
    def source_format(self) -> str | None:
        """Return the ``source_format`` root attribute, or None."""
        return self.get_root_attrs().get("source_format")

    def get_branch_names(self) -> list[str]:
        """
        List all branches in the store.

        Returns
        -------
        list[str]
            List of branch names.
        """
        try:
            storage_config = icechunk.local_filesystem_storage(self.store_path)
            repo = icechunk.Repository.open(
                storage=storage_config,
            )

            return list(repo.list_branches())
        except Exception as e:
            self._logger.warning(f"Failed to list branches in {self!r}: {e}")
            warnings.warn(f"Failed to list branches in {self!r}: {e}", stacklevel=2)
            return []

    def get_group_names(self, branch: str | None = None) -> dict[str, list[str]]:
        """
        List all groups in the store.

        Parameters
        ----------
        branch: Optional[str]
            Repository branch to examine. Defaults to listing groups from all branches.

        Returns
        -------
        dict[str, list[str]]
            Dictionary mapping branch names to lists of group names.

        """
        try:
            if not branch:
                branches = self.get_branch_names()
            else:
                branches = [branch]

            storage_config = icechunk.local_filesystem_storage(self.store_path)
            repo = icechunk.Repository.open(
                storage=storage_config,
            )

            group_dict = {}
            for br in branches:
                with self.readonly_session(br) as session:
                    session = repo.readonly_session(br)
                    root = zarr.open(session.store, mode="r")
                    group_dict[br] = list(root.group_keys())

            return group_dict

        except Exception as e:
            self._logger.warning(f"Failed to list groups in {self!r}: {e}")
            return {}

    def list_groups(self, branch: str = "main") -> list[str]:
        """
        List all groups in a branch.

        Parameters
        ----------
        branch : str
            Branch name (default: "main")

        Returns
        -------
        list[str]
            List of group names in the branch
        """
        group_dict = self.get_group_names(branch=branch)
        if branch in group_dict:
            return group_dict[branch]
        return []

    @property
    def tree(self) -> None:
        """
        Display hierarchical tree of all branches, groups, and subgroups.
        """
        self.print_tree(max_depth=None)

    def print_tree(self, max_depth: int | None = None) -> None:
        """
        Display hierarchical tree of all branches, groups, and subgroups.

        Parameters
        ----------
        max_depth : int | None
            Maximum depth to display. None for unlimited depth.
            - 0: Only show branches
            - 1: Show branches and top-level groups
            - 2: Show branches, groups, and first level of subgroups/arrays
            - etc.
        """
        try:
            branches = self.get_branch_names()

            for i, branch in enumerate(branches):
                is_last_branch = i == len(branches) - 1
                branch_prefix = "└── " if is_last_branch else "├── "

                if max_depth is not None and max_depth < 1:
                    continue

                session = self.repo.readonly_session(branch)
                root = zarr.open(session.store, mode="r")

                if i == 0:
                    sys.stdout.write(f"{self.store_path}\n")

                sys.stdout.write(f"{branch_prefix}{branch}\n")
                # Build tree recursively
                branch_indent = "    " if is_last_branch else "│   "
                self._build_tree(root, branch_indent, max_depth, current_depth=1)

        except Exception as e:
            self._logger.warning(f"Failed to generate tree for {self!r}: {e}")
            sys.stdout.write(f"Error generating tree: {e}\n")

    def _build_tree(
        self,
        group: zarr.Group,
        prefix: str,
        max_depth: int | None,
        current_depth: int = 0,
    ) -> None:
        """Recursively build a tree structure.

        Parameters
        ----------
        group : zarr.Group
            Root group to traverse.
        prefix : str
            Prefix string for tree formatting.
        max_depth : int | None
            Maximum depth to display. None for unlimited.
        current_depth : int, default 0
            Current recursion depth.

        Returns
        -------
        None
        """
        if max_depth is not None and current_depth >= max_depth:
            return

        # Get all groups and arrays
        groups = list(group.group_keys())
        arrays = list(group.array_keys())
        items = groups + arrays

        for i, item_name in enumerate(items):
            is_last = i == len(items) - 1
            connector = "└── " if is_last else "├── "

            if item_name in groups:
                # It's a group
                sys.stdout.write(f"{prefix}{connector}{item_name}\n")

                # Recurse into subgroup
                subgroup = group[item_name]
                new_prefix = prefix + ("    " if is_last else "│   ")
                self._build_tree(subgroup, new_prefix, max_depth, current_depth + 1)
            else:
                # It's an array
                arr = group[item_name]
                shape_str = str(arr.shape)
                dtype_str = str(arr.dtype)
                sys.stdout.write(
                    f"{prefix}{connector}{item_name} {shape_str} {dtype_str}\n"
                )

    def group_exists(self, group_name: str, branch: str = "main") -> bool:
        """
        Check if a group exists.

        Parameters
        ----------
        group_name : str
            Name of the group to check.
        branch : str, default "main"
            Repository branch to examine.

        Returns
        -------
        bool
            True if the group exists, False otherwise.
        """
        group_dict = self.get_group_names(branch)

        # get_group_names returns dict like {'main': ['canopy_01', ...]}
        if branch in group_dict:
            exists = group_name in group_dict[branch]
        else:
            exists = False

        self._logger.debug(
            f"Group '{group_name}' exists on branch '{branch}': {exists}"
        )
        return exists

    def read_group(
        self,
        group_name: str,
        branch: str = "main",
        time_slice: slice | None = None,
        date: str | None = None,
        chunks: dict[str, Any] | None = None,
    ) -> xr.Dataset:
        """
        Read data from a group.

        Parameters
        ----------
        group_name : str
            Name of the group to read.
        branch : str, default "main"
            Repository branch.
        time_slice : slice | None, optional
            Optional label-based time slice for filtering (passed to ``ds.sel``).
        date : str | None, optional
            YYYYDOY string (e.g. ``"2025001"``) selecting a single calendar day.
            Converted to a ``time_slice``; mutually exclusive with ``time_slice``.
        chunks : dict[str, Any] | None, optional
            Chunking specification (uses config defaults if None).

        Returns
        -------
        xr.Dataset
            Dataset from the group.
        """
        self._logger.info(f"Reading group '{group_name}' from branch '{branch}'")

        if date is not None:
            from canvod.utils.tools.date_utils import YYYYDOY

            _d = YYYYDOY.from_str(date).date
            time_slice = slice(str(_d), str(_d + timedelta(days=1)))

        with self.readonly_session(branch) as session:
            # Use default chunking strategy if none provided
            if chunks is None:
                chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

            ds = xr.open_zarr(
                session.store,
                group=group_name,
                chunks=chunks,
                consolidated=False,
            )

            if time_slice is not None:
                ds = ds.sel(epoch=time_slice)
                self._logger.debug(f"Applied time slice: {time_slice}")

            self._logger.info(
                f"Successfully read group '{group_name}' - shape: {dict(ds.sizes)}"
            )
            return ds

    def read_group_deduplicated(
        self,
        group_name: str,
        branch: str = "main",
        keep: str = "last",
        time_slice: slice | None = None,
        chunks: dict[str, Any] | None = None,
    ) -> xr.Dataset:
        """
        Read data from a group with automatic deduplication.

        This method calls read_group() then removes duplicates using metadata table
        intelligence when available, falling back to simple epoch deduplication.

        Parameters
        ----------
        group_name : str
            Name of the group to read.
        branch : str, default "main"
            Repository branch.
        keep : str, default "last"
            Deduplication strategy for duplicate epochs.
        time_slice : slice | None, optional
            Optional time slice for filtering.
        chunks : dict[str, Any] | None, optional
            Chunking specification (uses config defaults if None).

        Returns
        -------
        xr.Dataset
            Dataset with duplicates removed (latest data only).
        """

        if keep not in ["last"]:
            raise ValueError("Currently only 'last' is supported for keep parameter.")

        self._logger.info(f"Reading group '{group_name}' with deduplication")

        # First, read the raw data
        ds = self.read_group(
            group_name, branch=branch, time_slice=time_slice, chunks=chunks
        )

        # Then deduplicate using metadata table intelligence
        with self.readonly_session(branch) as session:
            try:
                zmeta = zarr.open_group(session.store, mode="r")[
                    f"{group_name}/metadata/table"
                ]

                # Load metadata and get latest entries for each time range
                data = {col: zmeta[col][:] for col in zmeta.array_keys()}
                df = pl.DataFrame(data)

                # Ensure datetime dtypes
                df = df.with_columns(
                    [
                        pl.col("start").cast(pl.Datetime("ns")),
                        pl.col("end").cast(pl.Datetime("ns")),
                    ]
                )

                # Get latest entry for each unique (start, end) combination
                latest_entries = df.sort("written_at").unique(
                    subset=["start", "end"], keep=keep
                )

                if latest_entries.height > 0:
                    # Create time masks for latest data only
                    time_masks = []
                    for row in latest_entries.iter_rows(named=True):
                        start_time = np.datetime64(row["start"], "ns")
                        end_time = np.datetime64(row["end"], "ns")
                        mask = (ds.epoch >= start_time) & (ds.epoch <= end_time)
                        time_masks.append(mask)

                    # Combine all masks with OR logic
                    if time_masks:
                        combined_mask = time_masks[0]
                        for mask in time_masks[1:]:
                            combined_mask = combined_mask | mask
                        ds = ds.isel(epoch=combined_mask)

                        self._logger.info(
                            "Deduplicated using metadata table: kept "
                            f"{len(latest_entries)} time ranges"
                        )

            except Exception as e:
                # Fall back to simple deduplication
                self._logger.warning(
                    f"Metadata-based deduplication failed, using simple approach: {e}"
                )
                ds = ds.drop_duplicates("epoch", keep="last")
                self._logger.info("Applied simple epoch deduplication (keep='last')")

        return ds

    def _cleanse_dataset_attrs(self, dataset: xr.Dataset) -> xr.Dataset:
        """Remove any attributes that might interfere with Icechunk storage."""

        attrs_to_remove = [
            "Created",
            "File Path",
            "File Type",
            "Date",
            "institution",
            "Time of First Observation",
            "GLONASS COD",
            "GLONASS PHS",
            "GLONASS BIS",
            "Leap Seconds",
        ]
        for attr in attrs_to_remove:
            if attr in dataset.attrs:
                del dataset.attrs[attr]
        return dataset

    def write_dataset(
        self,
        dataset: xr.Dataset,
        group_name: str,
        session: Any,
        mode: str = "a",
        chunks: dict[str, int] | None = None,
    ) -> None:
        """
        Write a dataset to Icechunk with proper chunking.

        Parameters
        ----------
        dataset : xr.Dataset
            Dataset to write
        group_name : str
            Group path in store
        session : Any
            Active writable session or store handle.
        mode : str
            Write mode: 'w' (overwrite) or 'a' (append)
        chunks : dict[str, int] | None
            Chunking spec. If None, uses store's chunk_strategy.
            Example: {'epoch': 34560, 'sid': -1}
        """
        # Use explicit chunks, or fall back to store's chunk strategy
        if chunks is None:
            chunks = self.chunk_strategy

        # Apply chunking if strategy defined
        if chunks:
            dataset = dataset.chunk(chunks)
            self._logger.info(f"Rechunked to {dict(dataset.chunks)} before write")

        # Normalize encodings
        dataset = self._normalize_encodings(dataset)

        # Calculate dataset metrics for tracing
        dataset_size_mb = dataset.nbytes / 1024 / 1024
        num_variables = len(dataset.data_vars)

        # Write to Icechunk with OpenTelemetry tracing
        try:
            from canvodpy.utils.telemetry import trace_icechunk_write

            with trace_icechunk_write(
                group_name=group_name,
                dataset_size_mb=dataset_size_mb,
                num_variables=num_variables,
            ):
                to_icechunk(dataset, session, group=group_name, mode=mode)
        except ImportError:
            # Fallback if telemetry not available
            to_icechunk(dataset, session, group=group_name, mode=mode)

        self._logger.info(f"Wrote dataset to group '{group_name}' (mode={mode})")

    def write_initial_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        branch: str = "main",
        commit_message: str | None = None,
    ) -> None:
        """Write initial data to a new group."""
        if self.group_exists(group_name, branch):
            raise ValueError(
                f"Group '{group_name}' already exists. Use append_to_group() instead."
            )

        with self.writable_session(branch) as session:
            dataset = self._normalize_encodings(dataset)

            rinex_hash = dataset.attrs.get("File Hash")
            if rinex_hash is None:
                raise ValueError("Dataset missing 'File Hash' attribute")
            start = dataset.epoch.min().values
            end = dataset.epoch.max().values

            to_icechunk(dataset, session, group=group_name, mode="w")

            if commit_message is None:
                version = get_version_from_pyproject()
                commit_message = f"[v{version}] Initial commit to group '{group_name}'"

            snapshot_id = session.commit(commit_message)

            self.append_metadata(
                group_name=group_name,
                rinex_hash=rinex_hash,
                start=start,
                end=end,
                snapshot_id=snapshot_id,
                action="write",  # Correct action for initial data
                commit_msg=commit_message,
                dataset_attrs=dataset.attrs,
            )

        self._logger.info(
            f"Created group '{group_name}' with {len(dataset.epoch)} epochs, "
            f"hash={rinex_hash}"
        )

    def backup_metadata_table(
        self,
        group_name: str,
        session: Any,
    ) -> pl.DataFrame | None:
        """Backup the metadata table to a Polars DataFrame.

        Parameters
        ----------
        group_name : str
            Group name.
        session : Any
            Active session for reading.

        Returns
        -------
        pl.DataFrame | None
            DataFrame with metadata rows, or None if missing.
        """
        try:
            zroot = zarr.open_group(session.store, mode="r")
            meta_group_path = f"{group_name}/metadata/table"

            if (
                "metadata" not in zroot[group_name]
                or "table" not in zroot[group_name]["metadata"]
            ):
                self._logger.info(
                    "No metadata table found for group "
                    f"'{group_name}' - nothing to backup"
                )
                return None

            zmeta = zroot[meta_group_path]

            # Load all columns into a dictionary
            data = {}
            for col_name in zmeta.array_keys():
                data[col_name] = zmeta[col_name][:]

            # Convert to Polars DataFrame
            df = pl.DataFrame(data)

            self._logger.info(
                "Backed up metadata table with "
                f"{df.height} rows for group '{group_name}'"
            )
            return df

        except Exception as e:
            self._logger.warning(
                f"Failed to backup metadata table for group '{group_name}': {e}"
            )
            return None

    def restore_metadata_table(
        self,
        group_name: str,
        df: pl.DataFrame,
        session: Any,
    ) -> None:
        """Restore the metadata table from a Polars DataFrame.

        This recreates the full Zarr structure for the metadata table.

        Parameters
        ----------
        group_name : str
            Group name.
        df : pl.DataFrame
            Metadata table to restore.
        session : Any
            Active session for writing.

        Returns
        -------
        None
        """
        if df is None or df.height == 0:
            self._logger.info(f"No metadata to restore for group '{group_name}'")
            return

        try:
            zroot = zarr.open_group(session.store, mode="a")
            meta_group_path = f"{group_name}/metadata/table"

            # Create the metadata subgroup
            zmeta = zroot.require_group(meta_group_path)

            # Create all arrays from the DataFrame
            for col_name in df.columns:
                col_data = df[col_name]

                if col_name == "index":
                    # Index column as int64
                    arr = col_data.to_numpy().astype("i8")
                    dtype = "i8"
                elif col_name in ("start", "end"):
                    # Datetime columns
                    arr = col_data.to_numpy().astype("datetime64[ns]")
                    dtype = "M8[ns]"
                else:
                    # String columns - use VariableLengthUTF8
                    arr = col_data.to_list()  # Convert to list for VariableLengthUTF8
                    dtype = VariableLengthUTF8()

                # Create the array
                zmeta.create_array(
                    name=col_name,
                    shape=(len(arr),),
                    dtype=dtype,
                    chunks=(1024,),
                    overwrite=True,
                )

                # Write the data
                zmeta[col_name][:] = arr

            self._logger.info(
                "Restored metadata table with "
                f"{df.height} rows for group '{group_name}'"
            )

        except Exception as e:
            self._logger.error(
                f"Failed to restore metadata table for group '{group_name}': {e}"
            )
            raise RuntimeError(
                f"Critical error: could not restore metadata table: {e}"
            ) from e

    def overwrite_file_in_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        rinex_hash: str,
        start: np.datetime64,
        end: np.datetime64,
        branch: str = "main",
        commit_message: str | None = None,
    ) -> None:
        """Overwrite a file's contribution to the group (same hash, new epoch range)."""

        dataset = self._normalize_encodings(dataset)

        # --- Step 3: rewrite store ---
        with self.writable_session(branch) as session:
            ds_from_store = xr.open_zarr(
                session.store, group=group_name, consolidated=False
            ).compute(
                scheduler="synchronous"
            )  # synchronous avoids Dask serialization error

            # Backup the existing metadata table
            metadata_backup = self.backup_metadata_table(group_name, session)

            mask = (ds_from_store.epoch.values < start) | (
                ds_from_store.epoch.values > end
            )
            ds_from_store_cleansed = ds_from_store.isel(epoch=mask)
            ds_from_store_cleansed = self._normalize_encodings(ds_from_store_cleansed)

            # Check if any epochs remain after cleansing, then write leftovers.
            if ds_from_store_cleansed.sizes.get("epoch", 0) > 0:
                to_icechunk(ds_from_store_cleansed, session, group=group_name, mode="w")
            # no epochs left, reset group to empty
            else:
                to_icechunk(dataset.isel(epoch=[]), session, group=group_name, mode="w")

            # write back the backed up metadata table
            self.restore_metadata_table(group_name, metadata_backup, session)

            # Append the new dataset
            to_icechunk(dataset, session, group=group_name, append_dim="epoch")

            if commit_message is None:
                version = get_version_from_pyproject()
                commit_message = (
                    f"[v{version}] Overwrote file {rinex_hash} in group '{group_name}'"
                )

            snapshot_id = session.commit(commit_message)

            self.append_metadata(
                group_name=group_name,
                rinex_hash=rinex_hash,
                start=start,
                end=end,
                snapshot_id=snapshot_id,
                action="overwrite",
                commit_msg=commit_message,
                dataset_attrs=dataset.attrs,
            )

    def get_group_info(self, group_name: str, branch: str = "main") -> dict[str, Any]:
        """
        Get metadata about a group.

        Parameters
        ----------
        group_name : str
            Name of the group.
        branch : str, default "main"
            Repository branch to examine.

        Returns
        -------
        dict[str, Any]
            Group metadata.

        Raises
        ------
        ValueError
            If the group does not exist.
        """
        if not self.group_exists(group_name, branch):
            raise ValueError(f"Group '{group_name}' does not exist")

        ds = self.read_group(group_name, branch)

        info = {
            "group_name": group_name,
            "store_type": self.store_type,
            "dimensions": dict(ds.sizes),
            "variables": list(ds.data_vars.keys()),
            "coordinates": list(ds.coords.keys()),
            "attributes": dict(ds.attrs),
        }

        # Add temporal information if epoch dimension exists
        if "epoch" in ds.sizes:
            info["temporal_info"] = {
                "start": str(ds.epoch.min().values),
                "end": str(ds.epoch.max().values),
                "count": ds.sizes["epoch"],
                "resolution": str(ds.epoch.diff("epoch").median().values),
            }

        return info

    # ── Generic metadata datasets ─────────────────────────────────────────────

    def metadata_dataset_exists(
        self, group_name: str, name: str, branch: str = "main"
    ) -> bool:
        """Return True if a metadata dataset *name* exists for *group_name*."""
        path = f"{group_name}/metadata/{name}"
        try:
            with self.readonly_session(branch) as session:
                zarr.open_group(session.store, mode="r", path=path)
                return True
        except Exception:
            return False

    def write_metadata_dataset(
        self,
        meta_ds: xr.Dataset,
        group_name: str,
        name: str,
        branch: str = "main",
    ) -> str:
        """Write a pre-concatenated metadata dataset to *{group_name}/metadata/{name}*.

        Always writes with ``mode="w"`` (full overwrite for the day).

        Parameters
        ----------
        meta_ds : xr.Dataset
            Pre-concatenated ``(epoch, sid)`` metadata dataset.
        group_name : str
            Target group (receiver name).
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch to write to.

        Returns
        -------
        str
            Icechunk snapshot ID.
        """
        version = get_version_from_pyproject()
        path = f"{group_name}/metadata/{name}"
        ds = self._normalize_encodings(meta_ds)
        ds = self._cleanse_dataset_attrs(ds)
        with self.writable_session(branch) as session:
            to_icechunk(ds, session, group=path, mode="w")
            return session.commit(f"[v{version}] metadata/{name} for {group_name}")

    def append_metadata_datasets(
        self,
        parts: list[xr.Dataset],
        group_name: str,
        name: str,
        branch: str = "main",
    ) -> str:
        """Write metadata datasets incrementally — no in-memory concat.

        The first dataset initialises the group (``mode="w"``), subsequent
        datasets are appended along ``epoch``.  All writes happen inside a
        single session/commit so the operation is atomic.

        Parameters
        ----------
        parts : list[xr.Dataset]
            Individual per-file metadata datasets with an ``epoch`` dim.
        group_name : str
            Target group (receiver name).
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch to write to.

        Returns
        -------
        str
            Icechunk snapshot ID.
        """
        if not parts:
            msg = "parts list is empty"
            raise ValueError(msg)

        version = get_version_from_pyproject()
        path = f"{group_name}/metadata/{name}"
        total_epochs = 0

        with self.writable_session(branch) as session:
            for i, part in enumerate(parts):
                ds = self._normalize_encodings(part)
                ds = self._cleanse_dataset_attrs(ds)
                if i == 0:
                    to_icechunk(ds, session, group=path, mode="w")
                else:
                    to_icechunk(ds, session, group=path, append_dim="epoch")
                total_epochs += ds.sizes.get("epoch", 0)

            return session.commit(
                f"[v{version}] metadata/{name} for {group_name} ({total_epochs} epochs)"
            )

    def read_metadata_dataset(
        self,
        group_name: str,
        name: str,
        branch: str = "main",
        chunks: dict | None = None,
    ) -> xr.Dataset:
        """Read a metadata dataset *name* for *group_name*.

        Parameters
        ----------
        group_name : str
            Group (receiver) name.
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch.
        chunks : dict | None, optional
            Dask chunk specification.  Defaults to
            ``{"epoch": 34560, "sid": -1}``.

        Returns
        -------
        xr.Dataset
            Lazy ``(epoch, sid)`` metadata dataset.
        """
        path = f"{group_name}/metadata/{name}"
        with self.readonly_session(branch) as session:
            return xr.open_zarr(
                session.store,
                group=path,
                chunks=chunks or self.chunk_strategy or {"epoch": 34560, "sid": -1},
                consolidated=False,
            )

    def get_metadata_dataset_info(
        self,
        group_name: str,
        name: str,
        branch: str = "main",
    ) -> dict[str, Any]:
        """Get info about metadata dataset *name* for *group_name*.

        Parameters
        ----------
        group_name : str
            Group (receiver) name.
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch.

        Returns
        -------
        dict[str, Any]
            Info dict with the same structure as ``get_group_info()``.

        Raises
        ------
        ValueError
            If the metadata dataset does not exist.
        """
        if not self.metadata_dataset_exists(group_name, name, branch):
            raise ValueError(f"No metadata dataset '{name}' for group '{group_name}'")
        ds = self.read_metadata_dataset(group_name, name, branch, chunks={})
        info: dict[str, Any] = {
            "group_name": group_name,
            "store_path": f"{group_name}/metadata/{name}",
            "store_type": f"metadata/{name}",
            "dimensions": dict(ds.sizes),
            "variables": list(ds.data_vars.keys()),
            "coordinates": list(ds.coords.keys()),
            "attributes": dict(ds.attrs),
        }
        if "epoch" in ds.sizes:
            info["temporal_info"] = {
                "start": str(ds.epoch.min().values),
                "end": str(ds.epoch.max().values),
                "count": ds.sizes["epoch"],
                "resolution": str(ds.epoch.diff("epoch").median().values),
            }
        return info

    # Convenience aliases (SBF)
    def sbf_metadata_exists(self, group_name: str, branch: str = "main") -> bool:
        """Return True if an SBF metadata dataset exists for *group_name*."""
        return self.metadata_dataset_exists(group_name, "sbf_obs", branch)

    def write_sbf_metadata(
        self, meta_ds: xr.Dataset, group_name: str, branch: str = "main"
    ) -> str:
        """Write SBF metadata dataset."""
        return self.write_metadata_dataset(meta_ds, group_name, "sbf_obs", branch)

    def read_sbf_metadata(
        self, group_name: str, branch: str = "main", chunks: dict | None = None
    ) -> xr.Dataset:
        """Read SBF metadata dataset."""
        return self.read_metadata_dataset(group_name, "sbf_obs", branch, chunks)

    def get_sbf_metadata_info(
        self, group_name: str, branch: str = "main"
    ) -> dict[str, Any]:
        """Get SBF metadata info."""
        return self.get_metadata_dataset_info(group_name, "sbf_obs", branch)

    def rel_path_for_commit(self, file_path: Path) -> str:
        """
        Generate relative path for commit messages.

        Parameters
        ----------
        file_path : Path
            Full file path.

        Returns
        -------
        str
            Relative path string with log_path_depth parts.
        """
        depth = load_config().processing.logging.log_path_depth
        return str(Path(*file_path.parts[-depth:]))

    def get_store_stats(self) -> dict[str, Any]:
        """
        Get statistics about the store.

        Returns
        -------
        dict[str, Any]
            Store statistics.
        """
        groups = self.get_group_names()
        stats = {
            "store_path": str(self.store_path),
            "store_type": self.store_type,
            "compression_level": self.compression_level,
            "compression_algorithm": self.compression_algorithm.name,
            "total_groups": len(groups),
            "groups": groups,
        }

        # Add group-specific stats
        for group_name in groups:
            try:
                info = self.get_group_info(group_name)
                stats[f"group_{group_name}"] = {
                    "dimensions": info["dimensions"],
                    "variables_count": len(info["variables"]),
                    "has_temporal_data": "temporal_info" in info,
                }
            except Exception as e:
                self._logger.warning(
                    f"Failed to get stats for group '{group_name}': {e}"
                )

        return stats

    def append_to_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        append_dim: str = "epoch",
        branch: str = "main",
        action: str = "write",
        commit_message: str | None = None,
    ) -> None:
        """Append data to an existing group."""
        if not self.group_exists(group_name, branch):
            raise ValueError(
                f"Group '{group_name}' does not exist. Use write_initial_group() first."
            )

        dataset = self._normalize_encodings(dataset)

        rinex_hash = dataset.attrs.get("File Hash")
        if rinex_hash is None:
            raise ValueError("Dataset missing 'File Hash' attribute")
        start = dataset.epoch.min().values
        end = dataset.epoch.max().values

        # Guard: check hash + temporal overlap before appending
        exists, matches = self.metadata_row_exists(
            group_name, rinex_hash, start, end, branch
        )
        if exists and action != "overwrite":
            self._logger.warning(
                "append_blocked_by_guardrail",
                group=group_name,
                hash=rinex_hash[:16],
                range=f"{start}{end}",
                reason="hash_or_temporal_overlap",
                matching_files=matches.height if not matches.is_empty() else 0,
            )
            return

        with self.writable_session(branch) as session:
            to_icechunk(dataset, session, group=group_name, append_dim=append_dim)

            if commit_message is None and action == "write":
                version = get_version_from_pyproject()
                commit_message = f"[v{version}] Wrote to group '{group_name}'"
            elif commit_message is None and action != "append":
                version = get_version_from_pyproject()
                commit_message = f"[v{version}] Appended to group '{group_name}'"

            snapshot_id = session.commit(commit_message)

            self.append_metadata(
                group_name=group_name,
                rinex_hash=rinex_hash,
                start=start,
                end=end,
                snapshot_id=snapshot_id,
                action=action,
                commit_msg=commit_message,
                dataset_attrs=dataset.attrs,
            )

        if action == "append":
            self._logger.info(
                f"Appended {len(dataset.epoch)} epochs to group '{group_name}', "
                f"hash={rinex_hash}"
            )
        elif action == "write":
            self._logger.info(
                f"Wrote {len(dataset.epoch)} epochs to group '{group_name}', "
                f"hash={rinex_hash}"
            )
        else:
            self._logger.info(
                f"Action '{action}' completed for group '{group_name}', "
                f"hash={rinex_hash}"
            )

    def write_or_append_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        append_dim: str = "epoch",
        branch: str = "main",
        commit_message: str | None = None,
        dedup: bool = False,
    ) -> bool:
        """Write or append a dataset to a group.

        By default (``dedup=False``) no guardrails are applied — suitable for
        VOD stores and other derived-data stores where rinex-style dedup does
        not apply.

        When ``dedup=True`` the method runs a full hash-match + temporal-overlap
        check (via :meth:`should_skip_file`) **before** opening a write session.
        This makes the store the authoritative final gate for RINEX/SBF ingest
        paths, backstopping any pre-checks in the caller.

        If the group does not exist, creates it (``mode='w'``).
        If it exists, appends along ``append_dim``.

        Parameters
        ----------
        dataset : xr.Dataset
            Dataset to write or append.
        group_name : str
            Target Icechunk group.
        append_dim : str, default "epoch"
            Dimension along which to append when the group already exists.
        branch : str, default "main"
            Icechunk branch to write to.
        commit_message : str or None
            Commit message.  Auto-generated if ``None``.
        dedup : bool, default False
            When ``True``, check for duplicate hash or temporal overlap before
            writing.  If the dataset would be a duplicate, the write is skipped,
            a warning is logged, and ``False`` is returned.  Set to ``True`` for
            RINEX/SBF ingest; leave ``False`` for VOD and derived-data stores.

        Returns
        -------
        bool
            ``True`` if the dataset was written, ``False`` if skipped
            (only possible when ``dedup=True``).
        """
        if dedup:
            file_hash = dataset.attrs.get("File Hash")
            time_start = dataset.epoch.min().values
            time_end = dataset.epoch.max().values
            skip, reason = self.should_skip_file(
                group_name=group_name,
                file_hash=file_hash,
                time_start=time_start,
                time_end=time_end,
                branch=branch,
            )
            if skip:
                self._logger.warning(
                    "write_or_append_group skipped duplicate",
                    group=group_name,
                    reason=reason,
                    file_hash=file_hash,
                )
                return False

        dataset = self._normalize_encodings(dataset)

        if self.group_exists(group_name, branch):
            with self.writable_session(branch) as session:
                to_icechunk(dataset, session, group=group_name, append_dim=append_dim)
                if commit_message is None:
                    commit_message = f"Appended to group '{group_name}'"
                session.commit(commit_message)
            self._logger.info(
                f"Appended {len(dataset.epoch)} epochs to group '{group_name}'"
            )
        else:
            with self.writable_session(branch) as session:
                to_icechunk(dataset, session, group=group_name, mode="w")
                if commit_message is None:
                    commit_message = f"Created group '{group_name}'"
                session.commit(commit_message)
            self._logger.info(
                f"Created group '{group_name}' with {len(dataset.epoch)} epochs"
            )
        return True

    def append_metadata(
        self,
        group_name: str,
        rinex_hash: str,
        start: np.datetime64,
        end: np.datetime64,
        snapshot_id: str,
        action: str,
        commit_msg: str,
        dataset_attrs: dict,
        branch: str = "main",
        canonical_name: str | None = None,
        physical_path: str | None = None,
    ) -> None:
        """
        Append a metadata row into the group_name/metadata/table.

        Schema:
            index           int64 (continuous row id)
            rinex_hash      str   (UTF-8, VariableLengthUTF8)
            start           datetime64[ns]
            end             datetime64[ns]
            snapshot_id     str   (UTF-8)
            action          str   (UTF-8, e.g. "insert"|"append"|"overwrite"|"skip")
            commit_msg      str   (UTF-8)
            written_at      str   (UTF-8, ISO8601 with timezone)
            write_strategy  str   (UTF-8, RINEX_STORE_STRATEGY or VOD_STORE_STRATEGY)
            attrs           str   (UTF-8, JSON dump of dataset attrs)
        """
        written_at = datetime.now().astimezone().isoformat()

        row = {
            "rinex_hash": str(rinex_hash),
            "start": np.datetime64(start, "ns"),
            "end": np.datetime64(end, "ns"),
            "snapshot_id": str(snapshot_id),
            "action": str(action),
            "commit_msg": str(commit_msg),
            "written_at": written_at,
            "write_strategy": str(self._rinex_store_strategy)
            if self.store_type == "rinex_store"
            else str(self._vod_store_strategy),
            "attrs": json.dumps(dataset_attrs, default=str),
            "canonical_name": str(canonical_name) if canonical_name else "",
            "physical_path": str(physical_path) if physical_path else "",
        }
        df_row = pl.DataFrame([row])

        with self.writable_session(branch) as session:
            zroot = zarr.open_group(session.store, mode="a")
            meta_group_path = f"{group_name}/metadata/table"

            if (
                "metadata" not in zroot[group_name]
                or "table" not in zroot[group_name]["metadata"]
            ):
                # --- First time: create arrays with correct dtypes ---
                zmeta = zroot.require_group(meta_group_path)

                # index counter
                zmeta.create_array(
                    name="index", shape=(0,), dtype="i8", chunks=(1024,), overwrite=True
                )
                zmeta["index"].append([0])

                for col in df_row.columns:
                    if col in ("start", "end"):
                        dtype = "M8[ns]"
                        arr = np.array(df_row[col].to_numpy(), dtype=dtype)
                    else:
                        dtype = VariableLengthUTF8()
                        arr = df_row[col].to_list()

                    zmeta.create_array(
                        name=col,
                        shape=(0,),
                        dtype=dtype,
                        chunks=(1024,),
                        overwrite=True,
                    )
                    zmeta[col].append(arr)

            else:
                # --- Append to existing ---
                zmeta = zroot[meta_group_path]

                # index increment
                current_len = zmeta["index"].shape[0]
                next_idx = current_len
                zmeta["index"].append([next_idx])

                for col in df_row.columns:
                    if col in ("start", "end"):
                        arr = np.array(df_row[col].to_numpy(), dtype="M8[ns]")
                    else:
                        arr = df_row[col].to_list()
                    zmeta[col].append(arr)

            session.commit(f"Appended metadata row for {group_name}, hash={rinex_hash}")

        self._logger.info(
            f"Metadata appended for group '{group_name}': "
            f"hash={rinex_hash}, snapshot={snapshot_id}, action={action}"
        )

    def append_metadata_bulk(
        self,
        group_name: str,
        rows: list[dict[str, Any]],
        session: icechunk.WritableSession | None = None,
    ) -> None:
        """
        Append multiple metadata rows in one commit.

        Parameters
        ----------
        group_name : str
            Group name (e.g. "canopy", "reference")
        rows : list[dict[str, Any]]
            List of metadata records matching the schema used in
            append_metadata().
        session : icechunk.WritableSession, optional
            If provided, rows are written into this session (caller commits later).
            If None, this method opens its own writable session and commits once.
        """
        if not rows:
            self._logger.info(f"No metadata rows to append for group '{group_name}'")
            return

        # Ensure datetime conversions for consistency
        for row in rows:
            if isinstance(row.get("start"), str):
                row["start"] = np.datetime64(row["start"])
            if isinstance(row.get("end"), str):
                row["end"] = np.datetime64(row["end"])
            if "written_at" not in row:
                row["written_at"] = datetime.now(UTC).isoformat()

        # Prepare the Polars DataFrame
        df = pl.DataFrame(rows)

        def _do_append(session_obj: icechunk.WritableSession) -> None:
            """Append metadata rows to a writable session.

            Parameters
            ----------
            session_obj : icechunk.WritableSession
                Writable session to update.

            Returns
            -------
            None
            """
            zroot = zarr.open_group(session_obj.store, mode="a")
            meta_group_path = f"{group_name}/metadata/table"
            zmeta = zroot.require_group(meta_group_path)

            start_index = 0
            if "index" in zmeta:
                existing_len = zmeta["index"].shape[0]
                start_index = (
                    int(zmeta["index"][-1].item()) + 1 if existing_len > 0 else 0
                )

            # Assign sequential indices
            df_with_index = df.with_columns(
                (pl.arange(start_index, start_index + df.height)).alias("index")
            )

            # Write each column
            for col_name in df_with_index.columns:
                col_data = df_with_index[col_name]

                if col_name == "index":
                    dtype = "i8"
                    arr = col_data.to_numpy().astype(dtype)
                elif col_name in ("start", "end"):
                    dtype = "M8[ns]"
                    arr = col_data.to_numpy().astype(dtype)
                else:
                    # strings / jsons / ids
                    dtype = VariableLengthUTF8()
                    arr = col_data.to_list()

                if col_name not in zmeta:
                    # Create array if it doesn't exist
                    zmeta.create_array(
                        name=col_name,
                        shape=(0,),
                        dtype=dtype,
                        chunks=(1024,),
                        overwrite=True,
                    )

                # Resize and append
                old_len = zmeta[col_name].shape[0]
                new_len = old_len + len(arr)
                zmeta[col_name].resize(new_len)
                zmeta[col_name][old_len:new_len] = arr

            self._logger.info(
                f"Appended {df_with_index.height} metadata rows to group '{group_name}'"
            )

        if session is not None:
            _do_append(session)
        else:
            with self.writable_session() as sess:
                _do_append(sess)
                sess.commit(f"Bulk metadata append for {group_name}")

    def load_metadata(self, store: Any, group_name: str) -> pl.DataFrame:
        """Load metadata directly from Zarr into a Polars DataFrame.

        Parameters
        ----------
        store : Any
            Zarr store or session store handle.
        group_name : str
            Group name.

        Returns
        -------
        pl.DataFrame
            Metadata table.
        """
        zroot = zarr.open_group(store, mode="r")
        zmeta = zroot[f"{group_name}/metadata/table"]

        # Read all columns into a dict of numpy arrays
        data = {col: zmeta[col][...] for col in zmeta.array_keys()}

        # Build Polars DataFrame
        df = pl.DataFrame(data)

        # Convert numeric datetime64 columns back to proper Polars datetimes
        if df["start"].dtype in (pl.Int64, pl.Float64):
            df = df.with_columns(pl.col("start").cast(pl.Datetime("ns")))
        if df["end"].dtype in (pl.Int64, pl.Float64):
            df = df.with_columns(pl.col("end").cast(pl.Datetime("ns")))
        if df["written_at"].dtype == pl.Utf8:
            df = df.with_columns(pl.col("written_at").str.to_datetime("%+"))
        return df

    def read_metadata_table(self, session: Any, group_name: str) -> pl.DataFrame:
        """Read the metadata table from a session.

        Parameters
        ----------
        session : Any
            Active session for reading.
        group_name : str
            Group name.

        Returns
        -------
        pl.DataFrame
            Metadata table.
        """
        zmeta = zarr.open_group(
            session.store,
            mode="r",
        )[f"{group_name}/metadata/table"]

        data = {col: zmeta[col][:] for col in zmeta.array_keys()}
        df = pl.DataFrame(data)

        # Ensure start/end are proper datetime
        df = df.with_columns(
            [
                pl.col("start").cast(pl.Datetime("ns")),
                pl.col("end").cast(pl.Datetime("ns")),
            ]
        )
        return df

    def metadata_row_exists(
        self,
        group_name: str,
        rinex_hash: str,
        start: np.datetime64,
        end: np.datetime64,
        branch: str = "main",
    ) -> tuple[bool, pl.DataFrame]:
        """
        Check whether a file already exists or temporally overlaps existing data.

        Performs two checks in order:

        1. **Hash match** — if ``rinex_hash`` already appears in the metadata
           table, the file was previously ingested (exact duplicate).
        2. **Temporal overlap** — if the incoming ``[start, end]`` interval
           overlaps any existing metadata interval, the file covers a time
           range that is already (partially) present in the store.  This
           catches cases like a daily concatenation file coexisting with the
           sub-daily files it was built from.

        Parameters
        ----------
        group_name : str
            Icechunk group name.
        rinex_hash : str
            Hash of the current GNSS dataset.
        start : np.datetime64
            Start epoch of the incoming file.
        end : np.datetime64
            End epoch of the incoming file.
        branch : str, default "main"
            Branch name in the Icechunk repository.

        Returns
        -------
        tuple[bool, pl.DataFrame]
            ``(True, overlapping_rows)`` when the file should be skipped,
            ``(False, empty_df)`` when it is safe to ingest.
        """
        with self.readonly_session(branch) as session:
            try:
                zmeta = zarr.open_group(session.store, mode="r")[
                    f"{group_name}/metadata/table"
                ]
            except Exception:
                return False, pl.DataFrame()

            data = {col: zmeta[col][:] for col in zmeta.array_keys()}
            df = pl.DataFrame(data)

            df = df.with_columns(
                [
                    pl.col("start").cast(pl.Datetime("ns")),
                    pl.col("end").cast(pl.Datetime("ns")),
                ]
            )

            # --- Check 1: exact hash match (file already ingested) ---
            hash_matches = df.filter(pl.col("rinex_hash") == rinex_hash)
            if not hash_matches.is_empty():
                return True, hash_matches

            # --- Check 2: temporal overlap ---
            # Two intervals [A.start, A.end] and [B.start, B.end] overlap
            # iff A.start <= B.end AND A.end >= B.start
            start_ns = np.datetime64(start, "ns")
            end_ns = np.datetime64(end, "ns")

            overlaps = df.filter(
                (pl.col("start") <= end_ns) & (pl.col("end") >= start_ns)
            )

            if not overlaps.is_empty():
                n = overlaps.height
                existing_range = f"{overlaps['start'].min()}{overlaps['end'].max()}"
                self._logger.warning(
                    "temporal_overlap_detected",
                    group=group_name,
                    incoming_hash=rinex_hash,
                    incoming_range=f"{start}{end}",
                    existing_range=existing_range,
                    overlapping_files=n,
                )
                return True, overlaps

            return False, pl.DataFrame()

    def should_skip_file(
        self,
        group_name: str,
        file_hash: str | None,
        time_start: np.datetime64,
        time_end: np.datetime64,
        branch: str = "main",
    ) -> tuple[bool, str]:
        """Check whether a file should be skipped before processing and writing.

        Thin public wrapper around :meth:`metadata_row_exists` that returns a
        simple ``(skip, reason)`` pair instead of a DataFrame, suitable for use
        in Airflow task functions as an early-exit optimisation.

        This method is an early-exit optimisation: it avoids opening a write
        session for files that are already present.  Pass ``dedup=True`` to
        :meth:`write_or_append_group` to make the store the authoritative
        final gate (runs the same check again before writing).

        Checks performed (in order):

        1. **Hash match** — file was previously ingested (exact duplicate).
        2. **Temporal overlap** — incoming time range overlaps existing epochs.

        Layer 3 (intra-batch overlap) is not applicable here because task
        functions process files one at a time.

        Parameters
        ----------
        group_name : str
            Icechunk group name.
        file_hash : str or None
            Hash from ``dataset.attrs["File Hash"]``.  When ``None`` the check
            is skipped and ``(False, "")`` is returned.
        time_start : np.datetime64
            First epoch of the incoming dataset.
        time_end : np.datetime64
            Last epoch of the incoming dataset.
        branch : str, default "main"
            Branch name in the Icechunk repository.

        Returns
        -------
        tuple[bool, str]
            ``(True, "hash_match")`` — exact duplicate, skip.
            ``(True, "temporal_overlap")`` — overlapping time range, skip.
            ``(False, "")`` — safe to ingest.
        """
        if file_hash is None:
            return False, ""

        exists, matches = self.metadata_row_exists(
            group_name, file_hash, time_start, time_end, branch
        )
        if not exists:
            return False, ""

        if not matches.is_empty() and (matches["rinex_hash"] == file_hash).any():
            return True, "hash_match"
        return True, "temporal_overlap"

    def batch_check_existing(self, group_name: str, file_hashes: list[str]) -> set[str]:
        """Check which file hashes already exist in metadata."""

        try:
            with self.readonly_session("main") as session:
                df = self.load_metadata(session.store, group_name)

                # Filter to matching hashes
                existing = df.filter(pl.col("rinex_hash").is_in(file_hashes))
                return set(existing["rinex_hash"].to_list())

        except KeyError, zarr.errors.GroupNotFoundError, Exception:
            # Branch/group/metadata doesn't exist yet (fresh store)
            return set()

    def check_temporal_overlaps(
        self,
        group_name: str,
        file_intervals: list[tuple[str, np.datetime64, np.datetime64]],
        branch: str = "main",
    ) -> set[str]:
        """Check which files temporally overlap existing metadata intervals.

        Parameters
        ----------
        group_name : str
            Icechunk group name.
        file_intervals : list[tuple[str, np.datetime64, np.datetime64]]
            List of ``(rinex_hash, start, end)`` tuples for incoming files.
        branch : str, default "main"
            Branch name in the Icechunk repository.

        Returns
        -------
        set[str]
            Hashes of files whose ``[start, end]`` overlaps any existing
            metadata interval.  Files whose hash already exists in the store
            are NOT included (use ``batch_check_existing`` for those).
        """
        if not file_intervals:
            return set()

        try:
            with self.readonly_session(branch) as session:
                df = self.load_metadata(session.store, group_name)
        except KeyError, zarr.errors.GroupNotFoundError, Exception:
            return set()

        if df.is_empty():
            return set()

        df = df.with_columns(
            [
                pl.col("start").cast(pl.Datetime("ns")),
                pl.col("end").cast(pl.Datetime("ns")),
            ]
        )

        overlapping: set[str] = set()
        for rinex_hash, start, end in file_intervals:
            start_ns = np.datetime64(start, "ns")
            end_ns = np.datetime64(end, "ns")

            hits = df.filter((pl.col("start") <= end_ns) & (pl.col("end") >= start_ns))
            if not hits.is_empty():
                self._logger.warning(
                    "temporal_overlap_detected",
                    group=group_name,
                    incoming_hash=rinex_hash[:16],
                    incoming_range=f"{start}{end}",
                    existing_files=hits.height,
                )
                overlapping.add(rinex_hash)

        return overlapping

    def append_metadata_bulk_store(
        self,
        group_name: str,
        rows: list[dict[str, Any]],
        store: Any,
    ) -> None:
        """
        Append metadata rows into an open transaction store.

        Parameters
        ----------
        group_name : str
            Group name (e.g. "canopy", "reference").
        rows : list[dict[str, Any]]
            Metadata rows to append.
        store : Any
            Open Icechunk transaction store.
        """
        if not rows:
            return

        zroot = zarr.open_group(store, mode="a")
        zmeta = zroot.require_group(f"{group_name}/metadata/table")

        # Find next index
        start_index = 0
        if "index" in zmeta:
            start_index = (
                int(zmeta["index"][-1]) + 1 if zmeta["index"].shape[0] > 0 else 0
            )

        for i, row in enumerate(rows, start=start_index):
            row["index"] = i

        import polars as pl

        df = pl.DataFrame(rows)

        for col in df.columns:
            list_only_cols = {
                "attrs",
                "commit_msg",
                "action",
                "write_strategy",
                "rinex_hash",
                "snapshot_id",
            }
            if col in list_only_cols:
                values = df[col].to_list()
            else:
                values = df[col].to_numpy()

            if col == "index":
                dtype = "i8"
            elif col in ("start", "end"):
                dtype = "M8[ns]"
            else:
                dtype = VariableLengthUTF8()

            if col not in zmeta:
                zmeta.create_array(
                    name=col, shape=(0,), dtype=dtype, chunks=(1024,), overwrite=True
                )

            arr = zmeta[col]
            old_len = arr.shape[0]
            new_len = old_len + len(values)
            arr.resize(new_len)
            arr[old_len:new_len] = values

        self._logger.info(f"Appended {df.height} metadata rows to group '{group_name}'")

    def expire_old_snapshots(
        self,
        days: int | None = None,
        branch: str = "main",
        delete_expired_branches: bool = True,
        delete_expired_tags: bool = True,
    ) -> set[str]:
        """
        Expire and garbage-collect snapshots older than the given retention period.

        Parameters
        ----------
        days : int | None, optional
            Number of days to retain snapshots. Defaults to config value.
        branch : str, default "main"
            Branch to apply expiration on.
        delete_expired_branches : bool, default True
            Whether to delete branches pointing to expired snapshots.
        delete_expired_tags : bool, default True
            Whether to delete tags pointing to expired snapshots.

        Returns
        -------
        set[str]
            Expired snapshot IDs.
        """
        if days is None:
            days = self._rinex_store_expire_days
        cutoff = datetime.now(UTC) - timedelta(days=days)

        # cutoff = datetime(2025, 10, 3, 16, 44, 1, tzinfo=timezone.utc)
        self._logger.info(
            f"Running expiration on store '{self.store_type}' "
            f"(branch '{branch}') with cutoff {cutoff.isoformat()}"
        )

        # Expire snapshots older than cutoff
        expired_ids = self.repo.expire_snapshots(
            older_than=cutoff,
            delete_expired_branches=delete_expired_branches,
            delete_expired_tags=delete_expired_tags,
        )

        if expired_ids:
            self._logger.info(
                f"Expired {len(expired_ids)} snapshots: {sorted(expired_ids)}"
            )
        else:
            self._logger.info("No snapshots to expire.")

        # Garbage-collect expired objects to reclaim storage
        summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
        self._logger.info(
            f"Garbage collection summary: "
            f"deleted_bytes={summary.bytes_deleted}, "
            f"deleted_chunks={summary.chunks_deleted}, "
            f"deleted_manifests={summary.manifests_deleted}, "
            f"deleted_snapshots={summary.snapshots_deleted}, "
            f"deleted_attributes={summary.attributes_deleted}, "
            f"deleted_transaction_logs={summary.transaction_logs_deleted}"
        )

        return expired_ids

    def get_history(self, branch: str = "main", limit: int | None = None) -> list[dict]:
        """
        Return commit ancestry (history) for a branch.

        Parameters
        ----------
        branch : str, default "main"
            Branch name.
        limit : int | None, optional
            Maximum number of commits to return.

        Returns
        -------
        list[dict]
            Commit info dictionaries (id, message, written_at, parent_ids).
        """
        self._logger.info(f"Fetching ancestry for branch '{branch}'")

        history = []
        for i, ancestor in enumerate(self.repo.ancestry(branch=branch)):
            history.append(
                {
                    "snapshot_id": ancestor.id,
                    "commit_msg": ancestor.message,
                    "written_at": ancestor.written_at,
                    "parent_ids": ancestor.parent_id,
                }
            )
            if limit is not None and i + 1 >= limit:
                break

        return history

    def print_history(self, branch: str = "main", limit: int | None = 100) -> None:
        """
        Pretty-print the ancestry for quick inspection.
        """
        for entry in self.get_history(branch=branch, limit=limit):
            ts = entry["written_at"].strftime("%Y-%m-%d %H:%M:%S")
            print(f"{ts} {entry['snapshot_id'][:8]} {entry['commit_msg']}")

    def __repr__(self) -> str:
        """Return the developer-facing representation.

        Returns
        -------
        str
            Representation string.
        """
        display_names = {"rinex_store": "GNSS Store", "vod_store": "VOD Store"}
        display = display_names.get(self.store_type, self.store_type)
        return f"MyIcechunkStore(store_path={self.store_path}, store_type={display})"

    def __str__(self) -> str:
        """Return a human-readable summary.

        Returns
        -------
        str
            Summary string.
        """

        # Capture tree output
        old_stdout = sys.stdout
        sys.stdout = buffer = io.StringIO()

        try:
            self.print_tree()
            tree_output = buffer.getvalue()
        finally:
            sys.stdout = old_stdout

        branches = self.get_branch_names()
        group_dict = self.get_group_names()
        total_groups = sum(len(groups) for groups in group_dict.values())

        return (
            f"MyIcechunkStore: {self.store_path}\n"
            f"Branches: {len(branches)} | Total Groups: {total_groups}\n\n"
            f"{tree_output}"
        )

    def rechunk_group(
        self,
        group_name: str,
        chunks: dict[str, int],
        source_branch: str = "main",
        temp_branch: str | None = None,
        promote_to_main: bool = True,
        delete_temp_branch: bool = True,
    ) -> str:
        """
        Rechunk a group with optimal chunk sizes.

        Parameters
        ----------
        group_name : str
            Name of the group to rechunk
        chunks : dict[str, int]
            Chunking specification, e.g. {'epoch': 34560, 'sid': -1}
        source_branch : str
            Branch to read original data from (default: "main")
        temp_branch : str | None
            Temporary branch name for rechunked data. If None, uses
            "{group_name}_rechunked".
        promote_to_main : bool
            If True, reset main branch to rechunked snapshot after writing
        delete_temp_branch : bool
            If True, delete temporary branch after promotion (only if
            promote_to_main=True).

        Returns
        -------
        str
            Snapshot ID of the rechunked data
        """
        if temp_branch is None:
            temp_branch = f"{group_name}_rechunked_temp"

        self._logger.info(
            f"Starting rechunk of group '{group_name}' with chunks={chunks}"
        )

        # Get CURRENT snapshot from source branch to preserve all other groups
        current_snapshot = next(self.repo.ancestry(branch=source_branch)).id

        # Create temp branch from current snapshot (preserves all existing groups)
        try:
            self.repo.create_branch(temp_branch, current_snapshot)
            self._logger.info(
                f"Created temporary branch '{temp_branch}' from current {source_branch}"
            )
        except Exception as e:
            self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

        # Read original data
        ds_original = self.read_group(group_name, branch=source_branch)
        self._logger.info(f"Original chunks: {ds_original.chunks}")

        # Rechunk
        ds_rechunked = ds_original.chunk(chunks)
        self._logger.info(f"New chunks: {ds_rechunked.chunks}")

        # Clear encoding to avoid conflicts
        for var in ds_rechunked.data_vars:
            ds_rechunked[var].encoding = {}

        # Write rechunked data (overwrites only this group)
        with self.writable_session(temp_branch) as session:
            to_icechunk(ds_rechunked, session, group=group_name, mode="w")
            snapshot_id = session.commit(f"Rechunked {group_name} with chunks={chunks}")

        self._logger.info(
            f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
        )

        # Promote to main if requested
        if promote_to_main:
            rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
            self.repo.reset_branch(source_branch, rechunked_snapshot)
            self._logger.info(
                f"Reset branch '{source_branch}' to rechunked snapshot "
                f"{rechunked_snapshot}"
            )

            # Delete temp branch if requested
            if delete_temp_branch:
                self.repo.delete_branch(temp_branch)
                self._logger.info(f"Deleted temporary branch '{temp_branch}'")

        return snapshot_id

    def rechunk_group_verbose(
        self,
        group_name: str,
        chunks: dict[str, int] | None = None,
        source_branch: str = "main",
        temp_branch: str | None = None,
        promote_to_main: bool = True,
        delete_temp_branch: bool = True,
    ) -> str:
        """
        Rechunk a group with optimal chunk sizes.

        Parameters
        ----------
        group_name : str
            Name of the group to rechunk
        chunks : dict[str, int] | None
            Chunking specification, e.g. {'epoch': 34560, 'sid': -1}. Defaults
            to `gnnsvodpy.globals.ICECHUNK_CHUNK_STRATEGIES`.
        source_branch : str
            Branch to read original data from (default: "main")
        temp_branch : str | None
            Temporary branch name for rechunked data. If None, uses
            "{group_name}_rechunked".
        promote_to_main : bool
            If True, reset main branch to rechunked snapshot after writing
        delete_temp_branch : bool
            If True, delete temporary branch after promotion (only if
            promote_to_main=True).

        Returns
        -------
        str
            Snapshot ID of the rechunked data
        """
        if temp_branch is None:
            temp_branch = f"{group_name}_rechunked_temp"

        if chunks is None:
            chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

        print(f"\n{'=' * 60}")
        print(f"Starting rechunk of group '{group_name}'")
        print(f"Target chunks: {chunks}")
        print(f"{'=' * 60}\n")

        self._logger.info(
            f"Starting rechunk of group '{group_name}' with chunks={chunks}"
        )

        # Get CURRENT snapshot from source branch to preserve all other groups
        print(f"[1/7] Getting current snapshot from branch '{source_branch}'...")
        current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
        print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

        # Create temp branch from current snapshot (preserves all existing groups)
        print(f"\n[2/7] Creating temporary branch '{temp_branch}'...")
        try:
            self.repo.create_branch(temp_branch, current_snapshot)
            print(f"      ✓ Branch '{temp_branch}' created")
            self._logger.info(
                f"Created temporary branch '{temp_branch}' from current {source_branch}"
            )
        except Exception as e:
            print(
                f"      ⚠ Branch '{temp_branch}' already exists, using existing branch"
            )
            self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

        # Read original data
        print(f"\n[3/7] Reading original data from '{group_name}'...")
        ds_original = self.read_group(group_name, branch=source_branch)

        # Unify chunks if inconsistent
        try:
            ds_original = ds_original.unify_chunks()
            print("      ✓ Unified inconsistent chunks")
        except TypeError, ValueError:
            pass  # Chunks are already consistent

        print(f"      ✓ Data shape: {dict(ds_original.sizes)}")
        print(f"      ✓ Original chunks: {ds_original.chunks}")
        self._logger.info(f"Original chunks: {ds_original.chunks}")

        # Rechunk
        print("\n[4/7] Rechunking data...")
        ds_rechunked = ds_original.chunk(chunks)
        ds_rechunked = ds_rechunked.unify_chunks()
        print(f"      ✓ New chunks: {ds_rechunked.chunks}")
        self._logger.info(f"New chunks: {ds_rechunked.chunks}")

        # Clear encoding to avoid conflicts
        for var in ds_rechunked.data_vars:
            ds_rechunked[var].encoding = {}
        for coord in ds_rechunked.coords:
            if "chunks" in ds_rechunked[coord].encoding:
                del ds_rechunked[coord].encoding["chunks"]

        # Write rechunked data first (overwrites entire group)
        print(f"\n[5/7] Writing rechunked data to branch '{temp_branch}'...")
        print("      This may take several minutes for large datasets...")
        with self.writable_session(temp_branch) as session:
            to_icechunk(ds_rechunked, session, group=group_name, mode="w")
            session.commit(f"Wrote rechunked data for {group_name}")
        print("      ✓ Data written successfully")

        # Copy subgroups after writing rechunked data
        print(f"\n[6/7] Copying subgroups from '{group_name}'...")
        with self.writable_session(temp_branch) as session:
            with self.readonly_session(source_branch) as icsession:
                source_group = zarr.open_group(icsession.store, mode="r")[group_name]
            target_group = zarr.open_group(session.store, mode="a")[group_name]

            subgroup_count = 0
            for subgroup_name in source_group.group_keys():
                print(f"      ✓ Copying subgroup '{subgroup_name}'...")
                source_subgroup = source_group[subgroup_name]
                target_subgroup = target_group.create_group(
                    subgroup_name, overwrite=True
                )

                # Copy arrays from subgroup
                for array_name in source_subgroup.array_keys():
                    source_array = source_subgroup[array_name]
                    target_array = target_subgroup.create_array(
                        array_name,
                        shape=source_array.shape,
                        dtype=source_array.dtype,
                        chunks=source_array.chunks,
                        overwrite=True,
                    )
                    target_array[:] = source_array[:]

                # Copy subgroup attributes
                target_subgroup.attrs.update(source_subgroup.attrs)
                subgroup_count += 1

            if subgroup_count > 0:
                snapshot_id = session.commit(
                    f"Rechunked {group_name} with chunks={chunks}"
                )
                print(f"      ✓ {subgroup_count} subgroups copied")
            else:
                snapshot_id = next(self.repo.ancestry(branch=temp_branch)).id
                print("      ✓ No subgroups to copy")

        print(f"      ✓ Snapshot ID: {snapshot_id[:12]}")
        self._logger.info(
            f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
        )

        # Promote to main if requested
        if promote_to_main:
            print(f"\n[7/7] Promoting to '{source_branch}' branch...")
            rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
            self.repo.reset_branch(source_branch, rechunked_snapshot)
            print(
                f"      ✓ Branch '{source_branch}' reset to {rechunked_snapshot[:12]}"
            )
            self._logger.info(
                f"Reset branch '{source_branch}' to rechunked snapshot "
                f"{rechunked_snapshot}"
            )

            # Delete temp branch if requested
            if delete_temp_branch:
                print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
                self.delete_branch(temp_branch)
                print("      ✓ Temporary branch deleted")
                self._logger.info(f"Deleted temporary branch '{temp_branch}'")
        else:
            print("\n[7/7] Skipping promotion (promote_to_main=False)")
            print(f"      Rechunked data available on branch '{temp_branch}'")

        print(f"\n{'=' * 60}")
        print(f"✓ Rechunking complete for '{group_name}'")
        print(f"{'=' * 60}\n")

        return snapshot_id

    def create_release_tag(self, tag_name: str, snapshot_id: str | None = None) -> None:
        """
        Create an immutable tag for an important version.

        Parameters
        ----------
        tag_name : str
            Name for the tag (e.g., "v2024_complete", "before_reprocess")
        snapshot_id : str | None
            Snapshot to tag. If None, uses current tip of main branch.
        """
        if snapshot_id is None:
            # Tag current main branch tip
            snapshot_id = next(self.repo.ancestry(branch="main")).id

        self.repo.create_tag(tag_name, snapshot_id)
        self._logger.info(f"Created tag '{tag_name}' at snapshot {snapshot_id[:8]}")

    def list_tags(self) -> list[str]:
        """List all tags in the repository."""
        return list(self.repo.list_tags())

    def delete_tag(self, tag_name: str) -> None:
        """Delete a tag (use with caution - tags are meant to be permanent)."""
        self.repo.delete_tag(tag_name)
        self._logger.warning(f"Deleted tag '{tag_name}'")

    def plot_commit_graph(self, max_commits: int = 100) -> Figure:
        """
        Visualize commit history as an interactive git-like graph.

        Creates an interactive visualization showing:
        - Branches with different colors
        - Chronological commit ordering
        - Branch divergence points
        - Commit messages on hover
        - Click to see commit details

        Parameters
        ----------
        max_commits : int
            Maximum number of commits to display (default: 100).

        Returns
        -------
        Figure
            Interactive plotly figure (works in marimo and Jupyter).
        """
        from collections import defaultdict
        from datetime import datetime

        import plotly.graph_objects as go

        # Collect all commits with full metadata
        commit_map = {}  # id -> commit data
        branch_tips = {}  # branch -> latest commit id

        for branch in self.repo.list_branches():
            ancestors = list(self.repo.ancestry(branch=branch))
            if ancestors:
                branch_tips[branch] = ancestors[0].id

            for ancestor in ancestors:
                if ancestor.id not in commit_map:
                    commit_map[ancestor.id] = {
                        "id": ancestor.id,
                        "parent_id": ancestor.parent_id,
                        "message": ancestor.message,
                        "written_at": ancestor.written_at,
                        "branches": [branch],
                    }
                else:
                    # Multiple branches point to same commit
                    commit_map[ancestor.id]["branches"].append(branch)

                if len(commit_map) >= max_commits:
                    break
            if len(commit_map) >= max_commits:
                break

        # Build parent-child relationships
        commits_list = list(commit_map.values())
        commits_list.sort(key=lambda c: c["written_at"])  # Oldest first

        # Assign horizontal positions (chronological)
        commit_x_positions = {}
        for idx, commit in enumerate(commits_list):
            commit["x"] = idx
            commit_x_positions[commit["id"]] = idx

        # Assign vertical positions: commits shared by branches stay on same Y
        # Only diverge when branches have different commits
        branch_names = sorted(
            self.repo.list_branches(), key=lambda b: (b != "main", b)
        )  # main first

        # Build a set of all commit IDs for each branch
        branch_commits = {}
        for branch in branch_names:
            history = list(self.repo.ancestry(branch=branch))
            branch_commits[branch] = {h.id for h in history if h.id in commit_map}

        # Find where branches diverge
        def branches_share_commit(
            commit_id: str,
            branches: list[str],
        ) -> list[str]:
            """Return branches that contain a commit.

            Parameters
            ----------
            commit_id : str
                Commit identifier to check.
            branches : list[str]
                Branch names to search.

            Returns
            -------
            list[str]
                Branches that contain the commit.
            """
            return [b for b in branches if commit_id in branch_commits[b]]

        # Assign Y position: all commits on a single horizontal line initially
        # We'll use vertical offset for parallel branch indicators
        for commit in commits_list:
            commit["y"] = 0  # All on same timeline
            commit["branch_set"] = frozenset(commit["branches"])

        # Color palette for branches
        colors = [
            "#4a9a4a",  # green (main)
            "#5580c8",  # blue
            "#d97643",  # orange
            "#9b59b6",  # purple
            "#e74c3c",  # red
            "#1abc9c",  # turquoise
            "#f39c12",  # yellow
            "#34495e",  # dark gray
        ]
        branch_colors = {b: colors[i % len(colors)] for i, b in enumerate(branch_names)}

        # Build edges: draw parallel lines for shared commits (metro-style)
        edges_by_branch = defaultdict(list)  # branch -> list of edge dicts

        for commit in commits_list:
            if commit["parent_id"] and commit["parent_id"] in commit_map:
                parent = commit_map[commit["parent_id"]]

                # Find which branches share both this commit and its parent
                shared_branches = [
                    b for b in commit["branches"] if b in parent["branches"]
                ]

                for branch in shared_branches:
                    edges_by_branch[branch].append(
                        {
                            "x0": parent["x"],
                            "y0": parent["y"],
                            "x1": commit["x"],
                            "y1": commit["y"],
                        }
                    )

        # Create plotly figure
        fig = go.Figure()

        # Draw edges grouped by branch (parallel lines for shared paths)
        for branch_idx, branch in enumerate(branch_names):
            if branch not in edges_by_branch:
                continue

            color = branch_colors[branch]

            # Draw each edge as a separate line
            for edge in edges_by_branch[branch]:
                # Vertical offset for parallel lines (metro-style)
                offset = (branch_idx - (len(branch_names) - 1) / 2) * 0.15

                fig.add_trace(
                    go.Scatter(
                        x=[edge["x0"], edge["x1"]],
                        y=[edge["y0"] + offset, edge["y1"] + offset],
                        mode="lines",
                        line=dict(color=color, width=3),
                        hoverinfo="skip",
                        showlegend=False,
                        opacity=0.7,
                    )
                )

        # Draw commits (nodes) - one trace per unique commit
        # Color by which branches include it
        x_vals = [c["x"] for c in commits_list]
        y_vals = [c["y"] for c in commits_list]

        # Format hover text
        hover_texts = []
        marker_colors = []
        marker_symbols = []

        for c in commits_list:
            # Handle both string and datetime objects
            if isinstance(c["written_at"], str):
                time_str = datetime.fromisoformat(c["written_at"]).strftime(
                    "%Y-%m-%d %H:%M"
                )
            else:
                time_str = c["written_at"].strftime("%Y-%m-%d %H:%M")

            branches_str = ", ".join(c["branches"])
            hover_texts.append(
                f"<b>{c['message'] or 'No message'}</b><br>"
                f"Commit: {c['id'][:12]}<br>"
                f"Branches: {branches_str}<br>"
                f"Time: {time_str}"
            )

            # Color by first branch (priority: main)
            if "main" in c["branches"]:
                marker_colors.append(branch_colors["main"])
            else:
                marker_colors.append(branch_colors[c["branches"][0]])

            # Star for branch tips
            if c["id"] in branch_tips.values():
                marker_symbols.append("star")
            else:
                marker_symbols.append("circle")

        fig.add_trace(
            go.Scatter(
                x=x_vals,
                y=y_vals,
                mode="markers",
                name="Commits",
                marker=dict(
                    size=14,
                    color=marker_colors,
                    symbol=marker_symbols,
                    line=dict(color="white", width=2),
                ),
                hovertext=hover_texts,
                hoverinfo="text",
                showlegend=False,
            )
        )

        # Add legend traces (invisible points just for legend)
        for branch_idx, branch in enumerate(branch_names):
            fig.add_trace(
                go.Scatter(
                    x=[None],
                    y=[None],
                    mode="markers",
                    name=branch,
                    marker=dict(
                        size=10,
                        color=branch_colors[branch],
                        line=dict(color="white", width=2),
                    ),
                    showlegend=True,
                )
            )

        # Layout styling
        title_text = (
            f"Commit Graph: {self.site_name} ({len(commits_list)} commits, "
            f"{len(branch_names)} branches)"
        )
        fig.update_layout(
            title=dict(
                text=title_text,
                font=dict(size=16, color="#e5e5e5"),
            ),
            xaxis=dict(
                title="Time (oldest ← → newest)",
                showticklabels=False,
                showgrid=True,
                gridcolor="rgba(255,255,255,0.1)",
                zeroline=False,
            ),
            yaxis=dict(
                title="",
                showticklabels=False,
                showgrid=False,
                zeroline=False,
                range=[-1, 1],  # Fixed range for single timeline
            ),
            plot_bgcolor="#1a1a1a",
            paper_bgcolor="#1a1a1a",
            font=dict(color="#e5e5e5"),
            hovermode="closest",
            height=400,
            width=max(800, len(commits_list) * 50),
            legend=dict(
                title="Branches",
                orientation="h",
                x=0,
                y=-0.15,
                bgcolor="rgba(30,30,30,0.8)",
                bordercolor="rgba(255,255,255,0.2)",
                borderwidth=1,
            ),
        )

        return fig

    def cleanup_stale_branches(
        self, keep_patterns: list[str] | None = None
    ) -> list[str]:
        """
        Delete stale temporary branches (e.g., from failed rechunking).

        Parameters
        ----------
        keep_patterns : list[str] | None
            Patterns to preserve. Default: ["main", "dev"]

        Returns
        -------
        list[str]
            Names of deleted branches
        """
        if keep_patterns is None:
            keep_patterns = ["main", "dev"]

        deleted = []

        for branch in self.repo.list_branches():
            # Keep if matches any pattern
            should_keep = any(pattern in branch for pattern in keep_patterns)

            if not should_keep:
                # Check if it's a temp branch from rechunking
                if "_rechunked_temp" in branch or "_temp" in branch:
                    try:
                        self.repo.delete_branch(branch)
                        deleted.append(branch)
                        self._logger.info(f"Deleted stale branch: {branch}")
                    except Exception as e:
                        self._logger.warning(f"Failed to delete branch {branch}: {e}")

        return deleted

    def delete_branch(self, branch_name: str) -> None:
        """Delete a branch."""
        if branch_name == "main":
            raise ValueError("Cannot delete 'main' branch")

        self.repo.delete_branch(branch_name)
        self._logger.info(f"Deleted branch '{branch_name}'")

    def get_snapshot_info(self, snapshot_id: str) -> dict:
        """
        Get detailed information about a specific snapshot.

        Parameters
        ----------
        snapshot_id : str
            Snapshot ID to inspect

        Returns
        -------
        dict
            Snapshot metadata and statistics
        """
        # Find the snapshot in ancestry
        for ancestor in self.repo.ancestry(branch="main"):
            if ancestor.id == snapshot_id or ancestor.id.startswith(snapshot_id):
                info = {
                    "snapshot_id": ancestor.id,
                    "message": ancestor.message,
                    "written_at": ancestor.written_at,
                    "parent_id": ancestor.parent_id,
                }

                # Try to get groups at this snapshot
                try:
                    session = self.repo.readonly_session(snapshot_id=ancestor.id)
                    root = zarr.open(session.store, mode="r")
                    info["groups"] = list(root.group_keys())
                    info["arrays"] = list(root.array_keys())
                except Exception as e:
                    self._logger.warning(f"Could not inspect snapshot contents: {e}")

                return info

        raise ValueError(f"Snapshot {snapshot_id} not found in history")

    def compare_snapshots(self, snapshot_id_1: str, snapshot_id_2: str) -> dict:
        """
        Compare two snapshots to see what changed.

        Parameters
        ----------
        snapshot_id_1 : str
            First snapshot (older)
        snapshot_id_2 : str
            Second snapshot (newer)

        Returns
        -------
        dict
            Comparison results showing added/removed/modified groups
        """
        info_1 = self.get_snapshot_info(snapshot_id_1)
        info_2 = self.get_snapshot_info(snapshot_id_2)

        groups_1 = set(info_1.get("groups", []))
        groups_2 = set(info_2.get("groups", []))

        return {
            "snapshot_1": snapshot_id_1[:8],
            "snapshot_2": snapshot_id_2[:8],
            "added_groups": list(groups_2 - groups_1),
            "removed_groups": list(groups_1 - groups_2),
            "common_groups": list(groups_1 & groups_2),
            "time_diff": (info_2["written_at"] - info_1["written_at"]).total_seconds(),
        }

    def maintenance(
        self, expire_days: int = 7, cleanup_branches: bool = True, run_gc: bool = True
    ) -> dict:
        """
        Run full maintenance on the store.

        Parameters
        ----------
        expire_days : int
            Days of snapshot history to keep
        cleanup_branches : bool
            Remove stale temporary branches
        run_gc : bool
            Run garbage collection after expiration

        Returns
        -------
        dict
            Summary of maintenance actions
        """
        self._logger.info(f"Starting maintenance on {self.store_type}")

        results = {"expired_snapshots": 0, "deleted_branches": [], "gc_summary": None}

        # Expire old snapshots
        expired_ids = self.expire_old_snapshots(days=expire_days)
        results["expired_snapshots"] = len(expired_ids)

        # Cleanup stale branches
        if cleanup_branches:
            deleted_branches = self.cleanup_stale_branches()
            results["deleted_branches"] = deleted_branches

        # Garbage collection
        if run_gc:
            from datetime import datetime, timedelta

            cutoff = datetime.now(UTC) - timedelta(days=expire_days)
            gc_summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
            results["gc_summary"] = {
                "bytes_deleted": gc_summary.bytes_deleted,
                "chunks_deleted": gc_summary.chunks_deleted,
                "manifests_deleted": gc_summary.manifests_deleted,
            }

        self._logger.info(f"Maintenance complete: {results}")
        return results

    def sanitize_store(
        self,
        source_branch: str = "main",
        temp_branch: str = "sanitize_temp",
        promote_to_main: bool = True,
        delete_temp_branch: bool = True,
    ) -> str:
        """
        Sanitize all groups by removing NaN-only SIDs and cleaning coordinates.

        Creates a temporary branch, applies sanitization to all groups, then
        optionally promotes to main and cleans up.

        Parameters
        ----------
        source_branch : str, default "main"
            Branch to read original data from.
        temp_branch : str, default "sanitize_temp"
            Temporary branch name for sanitized data.
        promote_to_main : bool, default True
            If True, reset main branch to sanitized snapshot after writing.
        delete_temp_branch : bool, default True
            If True, delete temporary branch after promotion.

        Returns
        -------
        str
            Snapshot ID of the sanitized data.
        """
        import time

        from icechunk.xarray import to_icechunk

        print(f"\n{'=' * 60}")
        print("Starting store sanitization")
        print(f"{'=' * 60}\n")

        # Step 1: Get current snapshot
        print(f"[1/6] Getting current snapshot from '{source_branch}'...")
        current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
        print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

        # Step 2: Create temp branch
        print(f"\n[2/6] Creating temporary branch '{temp_branch}'...")
        try:
            self.repo.create_branch(temp_branch, current_snapshot)
            print(f"      ✓ Branch '{temp_branch}' created")
        except Exception:
            print("      ⚠ Branch exists, deleting and recreating...")
            self.delete_branch(temp_branch)
            self.repo.create_branch(temp_branch, current_snapshot)
            print(f"      ✓ Branch '{temp_branch}' created")

        # Step 3: Get all groups
        print("\n[3/6] Discovering groups...")
        groups = self.list_groups()
        print(f"      ✓ Found {len(groups)} groups: {groups}")

        # Step 4: Sanitize each group
        print("\n[4/6] Sanitizing groups...")
        sanitized_count = 0

        for group_name in groups:
            print(f"\n      Processing '{group_name}'...")
            t_start = time.time()

            try:
                # Read original data
                ds_original = self.read_group(group_name, branch=source_branch)
                original_sids = len(ds_original.sid)
                print(f"        • Original: {original_sids} SIDs")

                # Sanitize: remove SIDs with all-NaN data
                ds_sanitized = self._sanitize_dataset(ds_original)
                sanitized_sids = len(ds_sanitized.sid)
                removed_sids = original_sids - sanitized_sids

                print(
                    f"        • Sanitized: {sanitized_sids} SIDs "
                    f"(removed {removed_sids})"
                )

                # Write sanitized data
                with self.writable_session(temp_branch) as session:
                    to_icechunk(ds_sanitized, session, group=group_name, mode="w")

                    # Copy metadata subgroups if they exist
                    try:
                        with self.readonly_session(source_branch) as read_session:
                            source_group = zarr.open_group(
                                read_session.store, mode="r"
                            )[group_name]
                            if "metadata" in source_group.group_keys():
                                # Copy entire metadata subgroup
                                dest_group = zarr.open_group(session.store)[group_name]
                                zarr.copy(
                                    source_group["metadata"],
                                    dest_group,
                                    name="metadata",
                                )
                                print("        • Copied metadata subgroup")
                    except Exception as e:
                        print(f"        ⚠ Could not copy metadata: {e}")

                    session.commit(
                        f"Sanitized {group_name}: removed {removed_sids} empty SIDs"
                    )

                t_elapsed = time.time() - t_start
                print(f"        ✓ Completed in {t_elapsed:.2f}s")
                sanitized_count += 1

            except Exception as e:
                print(f"        ✗ Failed: {e}")
                continue

        print(f"\n      ✓ Sanitized {sanitized_count}/{len(groups)} groups")

        # Step 5: Get final snapshot
        print("\n[5/6] Getting sanitized snapshot...")
        sanitized_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
        print(f"      ✓ Snapshot: {sanitized_snapshot[:12]}")

        # Step 6: Promote to main
        if promote_to_main:
            print(f"\n[6/6] Promoting to '{source_branch}' branch...")
            self.repo.reset_branch(source_branch, sanitized_snapshot)
            print(
                f"      ✓ Branch '{source_branch}' reset to {sanitized_snapshot[:12]}"
            )

            if delete_temp_branch:
                print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
                self.delete_branch(temp_branch)
                print("      ✓ Temporary branch deleted")
        else:
            print("\n[6/6] Skipping promotion (promote_to_main=False)")
            print(f"      Sanitized data available on branch '{temp_branch}'")

        print(f"\n{'=' * 60}")
        print("✓ Sanitization complete")
        print(f"{'=' * 60}\n")

        return sanitized_snapshot

    def _sanitize_dataset(self, ds: xr.Dataset) -> xr.Dataset:
        """
        Remove SIDs that have all-NaN data and clean coordinate metadata.

        Parameters
        ----------
        ds : xr.Dataset
            Dataset to sanitize

        Returns
        -------
        xr.Dataset
            Sanitized dataset with NaN-only SIDs removed
        """
        # Find SIDs that have at least some non-NaN data across all variables
        has_data = ds.to_array().notnull().any(dim=["variable", "epoch"])

        # Keep only SIDs with data
        sids_with_data = ds.sid.values[has_data.values]
        ds_clean = ds.sel(sid=sids_with_data)

        # Clean coordinate metadata - remove NaN values from string coordinates
        for coord in ["band", "system", "code", "sv"]:
            if coord in ds_clean.coords:
                coord_values = ds_clean[coord].values
                # Convert object arrays, handling NaN
                if coord_values.dtype == object:
                    clean_values = []
                    for val in coord_values:
                        if isinstance(val, float) and np.isnan(val):
                            clean_values.append("")
                        elif val is None or (isinstance(val, str) and val == "nan"):
                            clean_values.append("")
                        else:
                            clean_values.append(str(val))
                    ds_clean = ds_clean.assign_coords({coord: ("sid", clean_values)})

        # Numeric coordinates can keep NaN if needed
        for coord in ["freq_center", "freq_min", "freq_max"]:
            if coord in ds_clean.coords:
                # These are fine as-is since they're numeric
                pass

        return ds_clean

    def safe_temporal_aggregate(
        self,
        group: str,
        freq: str = "1D",
        vars_to_aggregate: Sequence[str] = ("VOD",),
        geometry_vars: Sequence[str] = ("phi", "theta"),
        drop_empty: bool = True,
        branch: str = "main",
    ) -> xr.Dataset:
        """Aggregate temporally irregular VOD data per SID.

        Each satellite (SID) is aggregated independently within each
        time bin.  Mixing observations across satellites is physically
        meaningless because each observes a different part of the canopy
        from a different sky position.

        .. note::

           For production use, prefer ``canvod.ops.TemporalAggregate``
           which uses Polars groupby and handles all coordinate types
           explicitly.  This method is a convenience wrapper for quick
           interactive exploration.

        Parameters
        ----------
        group : str
            Group name to aggregate.
        freq : str, default "1D"
            Resample frequency string.
        vars_to_aggregate : Sequence[str], optional
            Variables to aggregate using mean.
        geometry_vars : Sequence[str], optional
            Geometry variables to aggregate using mean (centroid of
            contributing sky positions).
        drop_empty : bool, default True
            Drop empty epochs after aggregation.
        branch : str, default "main"
            Branch name to read from.

        Returns
        -------
        xr.Dataset
            Aggregated dataset with independent per-SID aggregation.
        """
        log = get_logger(__name__)

        with self.readonly_session(branch=branch) as session:
            ds = xr.open_zarr(session.store, group=group, consolidated=False)

            log.info(
                "Aggregating group",
                group=group,
                branch=branch,
                freq=freq,
            )

            # Aggregate data and geometry vars with mean (per SID
            # independently — resample preserves the sid dimension).
            all_vars = list(vars_to_aggregate) + list(geometry_vars)
            merged_vars = []
            for var in all_vars:
                if var in ds:
                    merged_vars.append(ds[var].resample(epoch=freq).mean())
                else:
                    log.warning("Skipping missing variable", var=var)
            ds_agg = xr.merge(merged_vars)

            # Preserve sid-only coordinates (sv, band, code, etc.)
            for coord in ds.coords:
                if coord in ds_agg.coords or coord == "epoch":
                    continue
                coord_dims = ds.coords[coord].dims
                # Only copy coords whose dims all survive in ds_agg
                if all(d in ds_agg.dims for d in coord_dims):
                    ds_agg[coord] = ds[coord]

            # Drop all-NaN epochs if requested
            if drop_empty and "VOD" in ds_agg:
                valid_mask = ds_agg["VOD"].notnull().any(dim="sid").compute()
                ds_agg = ds_agg.isel(epoch=valid_mask)

            log.info("Aggregation done", sizes=dict(ds_agg.sizes))
            return ds_agg

    def safe_temporal_aggregate_to_branch(
        self,
        source_group: str,
        target_group: str,
        target_branch: str,
        freq: str = "1D",
        overwrite: bool = False,
        **kwargs: Any,
    ) -> xr.Dataset:
        """Aggregate a group and save to a new Icechunk branch/group.

        Parameters
        ----------
        source_group : str
            Source group name.
        target_group : str
            Target group name.
        target_branch : str
            Target branch name.
        freq : str, default "1D"
            Resample frequency string.
        overwrite : bool, default False
            Whether to overwrite an existing branch.
        **kwargs : Any
            Additional keyword args passed to safe_temporal_aggregate().

        Returns
        -------
        xr.Dataset
            Aggregated dataset written to the target branch.
        """

        print(
            f"🚀 Creating new aggregated branch '{target_branch}' at '{target_group}'"
        )

        # Compute safe aggregation
        ds_agg = self.safe_temporal_aggregate(
            group=source_group,
            freq=freq,
            **kwargs,
        )

        # Write to new branch
        current_snapshot = next(self.repo.ancestry(branch="main")).id
        self.delete_branch(target_branch)
        self.repo.create_branch(target_branch, current_snapshot)
        with self.writable_session(target_branch) as session:
            to_icechunk(
                obj=ds_agg,
                session=session,
                group=target_group,
                mode="w",
            )
            session.commit(f"Saved aggregated data to {target_group} at freq={freq}")

        print(
            f"✅ Saved aggregated dataset to branch '{target_branch}' "
            f"(group '{target_group}')"
        )
        return ds_agg

repo property

Get the repository instance.

source_format property

Return the source_format root attribute, or None.

tree property

Display hierarchical tree of all branches, groups, and subgroups.

__init__(store_path, store_type='rinex_store', compression_level=None, compression_algorithm=None)

Initialize the Icechunk store manager.

Parameters

store_path : Path Path to the Icechunk store directory. store_type : str, default "rinex_store" Type of store ("rinex_store" or "vod_store"). compression_level : int | None, optional Override default compression level. compression_algorithm : str | None, optional Override default compression algorithm.

Source code in packages/canvod-store/src/canvod/store/store.py
 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
def __init__(
    self,
    store_path: Path,
    store_type: str = "rinex_store",
    compression_level: int | None = None,
    compression_algorithm: str | None = None,
) -> None:
    """Initialize the Icechunk store manager.

    Parameters
    ----------
    store_path : Path
        Path to the Icechunk store directory.
    store_type : str, default "rinex_store"
        Type of store ("rinex_store" or "vod_store").
    compression_level : int | None, optional
        Override default compression level.
    compression_algorithm : str | None, optional
        Override default compression algorithm.
    """
    from canvod.utils.config import load_config

    cfg = load_config()
    ic_cfg = cfg.processing.icechunk
    st_cfg = cfg.processing.storage

    self.store_path = Path(store_path)
    self.store_type = store_type
    # Site name is parent directory name
    self.site_name = self.store_path.parent.name

    # Compression
    self.compression_level = compression_level or ic_cfg.compression_level
    compression_alg = compression_algorithm or ic_cfg.compression_algorithm
    self.compression_algorithm = getattr(
        icechunk.CompressionAlgorithm, compression_alg.capitalize()
    )

    # Chunk strategy
    chunk_strategies = {
        k: {"epoch": v.epoch, "sid": v.sid}
        for k, v in ic_cfg.chunk_strategies.items()
    }
    self.chunk_strategy = chunk_strategies.get(store_type, {})

    # Storage config cached for metadata rows
    self._rinex_store_strategy = st_cfg.rinex_store_strategy
    self._rinex_store_expire_days = st_cfg.rinex_store_expire_days
    self._vod_store_strategy = st_cfg.vod_store_strategy

    # Configure repository
    self.config = icechunk.RepositoryConfig.default()
    self.config.compression = icechunk.CompressionConfig(
        level=self.compression_level, algorithm=self.compression_algorithm
    )
    self.config.inline_chunk_threshold_bytes = ic_cfg.inline_threshold
    self.config.get_partial_values_concurrency = ic_cfg.get_concurrency

    if ic_cfg.manifest_preload_enabled:
        self.config.manifest = icechunk.ManifestConfig(
            preload=icechunk.ManifestPreloadConfig(
                max_total_refs=ic_cfg.manifest_preload_max_refs,
                preload_if=icechunk.ManifestPreloadCondition.name_matches(
                    ic_cfg.manifest_preload_pattern
                ),
            )
        )
        self._logger.info(
            f"Manifest preload enabled: {ic_cfg.manifest_preload_pattern}"
        )

    self._repo = None
    self._logger = get_logger(__name__)

    # Remove .DS_Store files that corrupt icechunk ref listing on macOS
    self._clean_ds_store()
    self._ensure_store_exists()

readonly_session(branch='main')

Context manager for readonly sessions.

Parameters

branch : str, default "main" Branch name.

Returns

Generator[icechunk.ReadonlySession, None, None] Readonly session context manager.

Source code in packages/canvod-store/src/canvod/store/store.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@contextlib.contextmanager
def readonly_session(
    self,
    branch: str = "main",
) -> Generator[icechunk.ReadonlySession]:
    """Context manager for readonly sessions.

    Parameters
    ----------
    branch : str, default "main"
        Branch name.

    Returns
    -------
    Generator[icechunk.ReadonlySession, None, None]
        Readonly session context manager.
    """
    session = self.repo.readonly_session(branch)
    try:
        self._logger.debug(f"Opened readonly session for branch '{branch}'")
        yield session
    finally:
        self._logger.debug(f"Closed readonly session for branch '{branch}'")

writable_session(branch='main')

Context manager for writable sessions.

Parameters

branch : str, default "main" Branch name.

Returns

Generator[icechunk.WritableSession, None, None] Writable session context manager.

Source code in packages/canvod-store/src/canvod/store/store.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
@contextlib.contextmanager
def writable_session(
    self,
    branch: str = "main",
) -> Generator[icechunk.WritableSession]:
    """Context manager for writable sessions.

    Parameters
    ----------
    branch : str, default "main"
        Branch name.

    Returns
    -------
    Generator[icechunk.WritableSession, None, None]
        Writable session context manager.
    """
    session = self.repo.writable_session(branch)
    try:
        self._logger.debug(f"Opened writable session for branch '{branch}'")
        yield session
    finally:
        self._logger.debug(f"Closed writable session for branch '{branch}'")

set_root_attrs(attrs, branch='main')

Set root-level Zarr attributes on the store.

Parameters

attrs : dict[str, Any] Key-value pairs to merge into root attrs. branch : str, default "main" Branch to write to.

Returns

str Snapshot ID from the commit.

Source code in packages/canvod-store/src/canvod/store/store.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def set_root_attrs(self, attrs: dict[str, Any], branch: str = "main") -> str:
    """Set root-level Zarr attributes on the store.

    Parameters
    ----------
    attrs : dict[str, Any]
        Key-value pairs to merge into root attrs.
    branch : str, default "main"
        Branch to write to.

    Returns
    -------
    str
        Snapshot ID from the commit.
    """
    with self.writable_session(branch) as session:
        try:
            root = zarr.open_group(session.store, mode="r+")
        except zarr.errors.GroupNotFoundError:
            root = zarr.open_group(session.store, mode="w")
        root.attrs.update(attrs)
        return session.commit(f"Set root attrs: {list(attrs.keys())}")

get_root_attrs(branch='main')

Read root-level Zarr attributes from the store.

Returns

dict[str, Any] Root attributes (empty dict if none set).

Source code in packages/canvod-store/src/canvod/store/store.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def get_root_attrs(self, branch: str = "main") -> dict[str, Any]:
    """Read root-level Zarr attributes from the store.

    Returns
    -------
    dict[str, Any]
        Root attributes (empty dict if none set).
    """
    try:
        with self.readonly_session(branch) as session:
            root = zarr.open_group(session.store, mode="r")
            return dict(root.attrs)
    except Exception:
        return {}

get_branch_names()

List all branches in the store.

Returns

list[str] List of branch names.

Source code in packages/canvod-store/src/canvod/store/store.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def get_branch_names(self) -> list[str]:
    """
    List all branches in the store.

    Returns
    -------
    list[str]
        List of branch names.
    """
    try:
        storage_config = icechunk.local_filesystem_storage(self.store_path)
        repo = icechunk.Repository.open(
            storage=storage_config,
        )

        return list(repo.list_branches())
    except Exception as e:
        self._logger.warning(f"Failed to list branches in {self!r}: {e}")
        warnings.warn(f"Failed to list branches in {self!r}: {e}", stacklevel=2)
        return []

get_group_names(branch=None)

List all groups in the store.

Parameters

branch: Optional[str] Repository branch to examine. Defaults to listing groups from all branches.

Returns

dict[str, list[str]] Dictionary mapping branch names to lists of group names.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_group_names(self, branch: str | None = None) -> dict[str, list[str]]:
    """
    List all groups in the store.

    Parameters
    ----------
    branch: Optional[str]
        Repository branch to examine. Defaults to listing groups from all branches.

    Returns
    -------
    dict[str, list[str]]
        Dictionary mapping branch names to lists of group names.

    """
    try:
        if not branch:
            branches = self.get_branch_names()
        else:
            branches = [branch]

        storage_config = icechunk.local_filesystem_storage(self.store_path)
        repo = icechunk.Repository.open(
            storage=storage_config,
        )

        group_dict = {}
        for br in branches:
            with self.readonly_session(br) as session:
                session = repo.readonly_session(br)
                root = zarr.open(session.store, mode="r")
                group_dict[br] = list(root.group_keys())

        return group_dict

    except Exception as e:
        self._logger.warning(f"Failed to list groups in {self!r}: {e}")
        return {}

list_groups(branch='main')

List all groups in a branch.

Parameters

branch : str Branch name (default: "main")

Returns

list[str] List of group names in the branch

Source code in packages/canvod-store/src/canvod/store/store.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def list_groups(self, branch: str = "main") -> list[str]:
    """
    List all groups in a branch.

    Parameters
    ----------
    branch : str
        Branch name (default: "main")

    Returns
    -------
    list[str]
        List of group names in the branch
    """
    group_dict = self.get_group_names(branch=branch)
    if branch in group_dict:
        return group_dict[branch]
    return []

print_tree(max_depth=None)

Display hierarchical tree of all branches, groups, and subgroups.

Parameters

max_depth : int | None Maximum depth to display. None for unlimited depth. - 0: Only show branches - 1: Show branches and top-level groups - 2: Show branches, groups, and first level of subgroups/arrays - etc.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def print_tree(self, max_depth: int | None = None) -> None:
    """
    Display hierarchical tree of all branches, groups, and subgroups.

    Parameters
    ----------
    max_depth : int | None
        Maximum depth to display. None for unlimited depth.
        - 0: Only show branches
        - 1: Show branches and top-level groups
        - 2: Show branches, groups, and first level of subgroups/arrays
        - etc.
    """
    try:
        branches = self.get_branch_names()

        for i, branch in enumerate(branches):
            is_last_branch = i == len(branches) - 1
            branch_prefix = "└── " if is_last_branch else "├── "

            if max_depth is not None and max_depth < 1:
                continue

            session = self.repo.readonly_session(branch)
            root = zarr.open(session.store, mode="r")

            if i == 0:
                sys.stdout.write(f"{self.store_path}\n")

            sys.stdout.write(f"{branch_prefix}{branch}\n")
            # Build tree recursively
            branch_indent = "    " if is_last_branch else "│   "
            self._build_tree(root, branch_indent, max_depth, current_depth=1)

    except Exception as e:
        self._logger.warning(f"Failed to generate tree for {self!r}: {e}")
        sys.stdout.write(f"Error generating tree: {e}\n")

group_exists(group_name, branch='main')

Check if a group exists.

Parameters

group_name : str Name of the group to check. branch : str, default "main" Repository branch to examine.

Returns

bool True if the group exists, False otherwise.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def group_exists(self, group_name: str, branch: str = "main") -> bool:
    """
    Check if a group exists.

    Parameters
    ----------
    group_name : str
        Name of the group to check.
    branch : str, default "main"
        Repository branch to examine.

    Returns
    -------
    bool
        True if the group exists, False otherwise.
    """
    group_dict = self.get_group_names(branch)

    # get_group_names returns dict like {'main': ['canopy_01', ...]}
    if branch in group_dict:
        exists = group_name in group_dict[branch]
    else:
        exists = False

    self._logger.debug(
        f"Group '{group_name}' exists on branch '{branch}': {exists}"
    )
    return exists

read_group(group_name, branch='main', time_slice=None, date=None, chunks=None)

Read data from a group.

Parameters

group_name : str Name of the group to read. branch : str, default "main" Repository branch. time_slice : slice | None, optional Optional label-based time slice for filtering (passed to ds.sel). date : str | None, optional YYYYDOY string (e.g. "2025001") selecting a single calendar day. Converted to a time_slice; mutually exclusive with time_slice. chunks : dict[str, Any] | None, optional Chunking specification (uses config defaults if None).

Returns

xr.Dataset Dataset from the group.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_group(
    self,
    group_name: str,
    branch: str = "main",
    time_slice: slice | None = None,
    date: str | None = None,
    chunks: dict[str, Any] | None = None,
) -> xr.Dataset:
    """
    Read data from a group.

    Parameters
    ----------
    group_name : str
        Name of the group to read.
    branch : str, default "main"
        Repository branch.
    time_slice : slice | None, optional
        Optional label-based time slice for filtering (passed to ``ds.sel``).
    date : str | None, optional
        YYYYDOY string (e.g. ``"2025001"``) selecting a single calendar day.
        Converted to a ``time_slice``; mutually exclusive with ``time_slice``.
    chunks : dict[str, Any] | None, optional
        Chunking specification (uses config defaults if None).

    Returns
    -------
    xr.Dataset
        Dataset from the group.
    """
    self._logger.info(f"Reading group '{group_name}' from branch '{branch}'")

    if date is not None:
        from canvod.utils.tools.date_utils import YYYYDOY

        _d = YYYYDOY.from_str(date).date
        time_slice = slice(str(_d), str(_d + timedelta(days=1)))

    with self.readonly_session(branch) as session:
        # Use default chunking strategy if none provided
        if chunks is None:
            chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

        ds = xr.open_zarr(
            session.store,
            group=group_name,
            chunks=chunks,
            consolidated=False,
        )

        if time_slice is not None:
            ds = ds.sel(epoch=time_slice)
            self._logger.debug(f"Applied time slice: {time_slice}")

        self._logger.info(
            f"Successfully read group '{group_name}' - shape: {dict(ds.sizes)}"
        )
        return ds

read_group_deduplicated(group_name, branch='main', keep='last', time_slice=None, chunks=None)

Read data from a group with automatic deduplication.

This method calls read_group() then removes duplicates using metadata table intelligence when available, falling back to simple epoch deduplication.

Parameters

group_name : str Name of the group to read. branch : str, default "main" Repository branch. keep : str, default "last" Deduplication strategy for duplicate epochs. time_slice : slice | None, optional Optional time slice for filtering. chunks : dict[str, Any] | None, optional Chunking specification (uses config defaults if None).

Returns

xr.Dataset Dataset with duplicates removed (latest data only).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_group_deduplicated(
    self,
    group_name: str,
    branch: str = "main",
    keep: str = "last",
    time_slice: slice | None = None,
    chunks: dict[str, Any] | None = None,
) -> xr.Dataset:
    """
    Read data from a group with automatic deduplication.

    This method calls read_group() then removes duplicates using metadata table
    intelligence when available, falling back to simple epoch deduplication.

    Parameters
    ----------
    group_name : str
        Name of the group to read.
    branch : str, default "main"
        Repository branch.
    keep : str, default "last"
        Deduplication strategy for duplicate epochs.
    time_slice : slice | None, optional
        Optional time slice for filtering.
    chunks : dict[str, Any] | None, optional
        Chunking specification (uses config defaults if None).

    Returns
    -------
    xr.Dataset
        Dataset with duplicates removed (latest data only).
    """

    if keep not in ["last"]:
        raise ValueError("Currently only 'last' is supported for keep parameter.")

    self._logger.info(f"Reading group '{group_name}' with deduplication")

    # First, read the raw data
    ds = self.read_group(
        group_name, branch=branch, time_slice=time_slice, chunks=chunks
    )

    # Then deduplicate using metadata table intelligence
    with self.readonly_session(branch) as session:
        try:
            zmeta = zarr.open_group(session.store, mode="r")[
                f"{group_name}/metadata/table"
            ]

            # Load metadata and get latest entries for each time range
            data = {col: zmeta[col][:] for col in zmeta.array_keys()}
            df = pl.DataFrame(data)

            # Ensure datetime dtypes
            df = df.with_columns(
                [
                    pl.col("start").cast(pl.Datetime("ns")),
                    pl.col("end").cast(pl.Datetime("ns")),
                ]
            )

            # Get latest entry for each unique (start, end) combination
            latest_entries = df.sort("written_at").unique(
                subset=["start", "end"], keep=keep
            )

            if latest_entries.height > 0:
                # Create time masks for latest data only
                time_masks = []
                for row in latest_entries.iter_rows(named=True):
                    start_time = np.datetime64(row["start"], "ns")
                    end_time = np.datetime64(row["end"], "ns")
                    mask = (ds.epoch >= start_time) & (ds.epoch <= end_time)
                    time_masks.append(mask)

                # Combine all masks with OR logic
                if time_masks:
                    combined_mask = time_masks[0]
                    for mask in time_masks[1:]:
                        combined_mask = combined_mask | mask
                    ds = ds.isel(epoch=combined_mask)

                    self._logger.info(
                        "Deduplicated using metadata table: kept "
                        f"{len(latest_entries)} time ranges"
                    )

        except Exception as e:
            # Fall back to simple deduplication
            self._logger.warning(
                f"Metadata-based deduplication failed, using simple approach: {e}"
            )
            ds = ds.drop_duplicates("epoch", keep="last")
            self._logger.info("Applied simple epoch deduplication (keep='last')")

    return ds

write_dataset(dataset, group_name, session, mode='a', chunks=None)

Write a dataset to Icechunk with proper chunking.

Parameters

dataset : xr.Dataset Dataset to write group_name : str Group path in store session : Any Active writable session or store handle. mode : str Write mode: 'w' (overwrite) or 'a' (append) chunks : dict[str, int] | None Chunking spec. If None, uses store's chunk_strategy. Example: {'epoch': 34560, 'sid': -1}

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_dataset(
    self,
    dataset: xr.Dataset,
    group_name: str,
    session: Any,
    mode: str = "a",
    chunks: dict[str, int] | None = None,
) -> None:
    """
    Write a dataset to Icechunk with proper chunking.

    Parameters
    ----------
    dataset : xr.Dataset
        Dataset to write
    group_name : str
        Group path in store
    session : Any
        Active writable session or store handle.
    mode : str
        Write mode: 'w' (overwrite) or 'a' (append)
    chunks : dict[str, int] | None
        Chunking spec. If None, uses store's chunk_strategy.
        Example: {'epoch': 34560, 'sid': -1}
    """
    # Use explicit chunks, or fall back to store's chunk strategy
    if chunks is None:
        chunks = self.chunk_strategy

    # Apply chunking if strategy defined
    if chunks:
        dataset = dataset.chunk(chunks)
        self._logger.info(f"Rechunked to {dict(dataset.chunks)} before write")

    # Normalize encodings
    dataset = self._normalize_encodings(dataset)

    # Calculate dataset metrics for tracing
    dataset_size_mb = dataset.nbytes / 1024 / 1024
    num_variables = len(dataset.data_vars)

    # Write to Icechunk with OpenTelemetry tracing
    try:
        from canvodpy.utils.telemetry import trace_icechunk_write

        with trace_icechunk_write(
            group_name=group_name,
            dataset_size_mb=dataset_size_mb,
            num_variables=num_variables,
        ):
            to_icechunk(dataset, session, group=group_name, mode=mode)
    except ImportError:
        # Fallback if telemetry not available
        to_icechunk(dataset, session, group=group_name, mode=mode)

    self._logger.info(f"Wrote dataset to group '{group_name}' (mode={mode})")

write_initial_group(dataset, group_name, branch='main', commit_message=None)

Write initial data to a new group.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_initial_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    branch: str = "main",
    commit_message: str | None = None,
) -> None:
    """Write initial data to a new group."""
    if self.group_exists(group_name, branch):
        raise ValueError(
            f"Group '{group_name}' already exists. Use append_to_group() instead."
        )

    with self.writable_session(branch) as session:
        dataset = self._normalize_encodings(dataset)

        rinex_hash = dataset.attrs.get("File Hash")
        if rinex_hash is None:
            raise ValueError("Dataset missing 'File Hash' attribute")
        start = dataset.epoch.min().values
        end = dataset.epoch.max().values

        to_icechunk(dataset, session, group=group_name, mode="w")

        if commit_message is None:
            version = get_version_from_pyproject()
            commit_message = f"[v{version}] Initial commit to group '{group_name}'"

        snapshot_id = session.commit(commit_message)

        self.append_metadata(
            group_name=group_name,
            rinex_hash=rinex_hash,
            start=start,
            end=end,
            snapshot_id=snapshot_id,
            action="write",  # Correct action for initial data
            commit_msg=commit_message,
            dataset_attrs=dataset.attrs,
        )

    self._logger.info(
        f"Created group '{group_name}' with {len(dataset.epoch)} epochs, "
        f"hash={rinex_hash}"
    )

backup_metadata_table(group_name, session)

Backup the metadata table to a Polars DataFrame.

Parameters

group_name : str Group name. session : Any Active session for reading.

Returns

pl.DataFrame | None DataFrame with metadata rows, or None if missing.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def backup_metadata_table(
    self,
    group_name: str,
    session: Any,
) -> pl.DataFrame | None:
    """Backup the metadata table to a Polars DataFrame.

    Parameters
    ----------
    group_name : str
        Group name.
    session : Any
        Active session for reading.

    Returns
    -------
    pl.DataFrame | None
        DataFrame with metadata rows, or None if missing.
    """
    try:
        zroot = zarr.open_group(session.store, mode="r")
        meta_group_path = f"{group_name}/metadata/table"

        if (
            "metadata" not in zroot[group_name]
            or "table" not in zroot[group_name]["metadata"]
        ):
            self._logger.info(
                "No metadata table found for group "
                f"'{group_name}' - nothing to backup"
            )
            return None

        zmeta = zroot[meta_group_path]

        # Load all columns into a dictionary
        data = {}
        for col_name in zmeta.array_keys():
            data[col_name] = zmeta[col_name][:]

        # Convert to Polars DataFrame
        df = pl.DataFrame(data)

        self._logger.info(
            "Backed up metadata table with "
            f"{df.height} rows for group '{group_name}'"
        )
        return df

    except Exception as e:
        self._logger.warning(
            f"Failed to backup metadata table for group '{group_name}': {e}"
        )
        return None

restore_metadata_table(group_name, df, session)

Restore the metadata table from a Polars DataFrame.

This recreates the full Zarr structure for the metadata table.

Parameters

group_name : str Group name. df : pl.DataFrame Metadata table to restore. session : Any Active session for writing.

Returns

None

Source code in packages/canvod-store/src/canvod/store/store.py
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
def restore_metadata_table(
    self,
    group_name: str,
    df: pl.DataFrame,
    session: Any,
) -> None:
    """Restore the metadata table from a Polars DataFrame.

    This recreates the full Zarr structure for the metadata table.

    Parameters
    ----------
    group_name : str
        Group name.
    df : pl.DataFrame
        Metadata table to restore.
    session : Any
        Active session for writing.

    Returns
    -------
    None
    """
    if df is None or df.height == 0:
        self._logger.info(f"No metadata to restore for group '{group_name}'")
        return

    try:
        zroot = zarr.open_group(session.store, mode="a")
        meta_group_path = f"{group_name}/metadata/table"

        # Create the metadata subgroup
        zmeta = zroot.require_group(meta_group_path)

        # Create all arrays from the DataFrame
        for col_name in df.columns:
            col_data = df[col_name]

            if col_name == "index":
                # Index column as int64
                arr = col_data.to_numpy().astype("i8")
                dtype = "i8"
            elif col_name in ("start", "end"):
                # Datetime columns
                arr = col_data.to_numpy().astype("datetime64[ns]")
                dtype = "M8[ns]"
            else:
                # String columns - use VariableLengthUTF8
                arr = col_data.to_list()  # Convert to list for VariableLengthUTF8
                dtype = VariableLengthUTF8()

            # Create the array
            zmeta.create_array(
                name=col_name,
                shape=(len(arr),),
                dtype=dtype,
                chunks=(1024,),
                overwrite=True,
            )

            # Write the data
            zmeta[col_name][:] = arr

        self._logger.info(
            "Restored metadata table with "
            f"{df.height} rows for group '{group_name}'"
        )

    except Exception as e:
        self._logger.error(
            f"Failed to restore metadata table for group '{group_name}': {e}"
        )
        raise RuntimeError(
            f"Critical error: could not restore metadata table: {e}"
        ) from e

overwrite_file_in_group(dataset, group_name, rinex_hash, start, end, branch='main', commit_message=None)

Overwrite a file's contribution to the group (same hash, new epoch range).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def overwrite_file_in_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    rinex_hash: str,
    start: np.datetime64,
    end: np.datetime64,
    branch: str = "main",
    commit_message: str | None = None,
) -> None:
    """Overwrite a file's contribution to the group (same hash, new epoch range)."""

    dataset = self._normalize_encodings(dataset)

    # --- Step 3: rewrite store ---
    with self.writable_session(branch) as session:
        ds_from_store = xr.open_zarr(
            session.store, group=group_name, consolidated=False
        ).compute(
            scheduler="synchronous"
        )  # synchronous avoids Dask serialization error

        # Backup the existing metadata table
        metadata_backup = self.backup_metadata_table(group_name, session)

        mask = (ds_from_store.epoch.values < start) | (
            ds_from_store.epoch.values > end
        )
        ds_from_store_cleansed = ds_from_store.isel(epoch=mask)
        ds_from_store_cleansed = self._normalize_encodings(ds_from_store_cleansed)

        # Check if any epochs remain after cleansing, then write leftovers.
        if ds_from_store_cleansed.sizes.get("epoch", 0) > 0:
            to_icechunk(ds_from_store_cleansed, session, group=group_name, mode="w")
        # no epochs left, reset group to empty
        else:
            to_icechunk(dataset.isel(epoch=[]), session, group=group_name, mode="w")

        # write back the backed up metadata table
        self.restore_metadata_table(group_name, metadata_backup, session)

        # Append the new dataset
        to_icechunk(dataset, session, group=group_name, append_dim="epoch")

        if commit_message is None:
            version = get_version_from_pyproject()
            commit_message = (
                f"[v{version}] Overwrote file {rinex_hash} in group '{group_name}'"
            )

        snapshot_id = session.commit(commit_message)

        self.append_metadata(
            group_name=group_name,
            rinex_hash=rinex_hash,
            start=start,
            end=end,
            snapshot_id=snapshot_id,
            action="overwrite",
            commit_msg=commit_message,
            dataset_attrs=dataset.attrs,
        )

get_group_info(group_name, branch='main')

Get metadata about a group.

Parameters

group_name : str Name of the group. branch : str, default "main" Repository branch to examine.

Returns

dict[str, Any] Group metadata.

Raises

ValueError If the group does not exist.

Source code in packages/canvod-store/src/canvod/store/store.py
 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
def get_group_info(self, group_name: str, branch: str = "main") -> dict[str, Any]:
    """
    Get metadata about a group.

    Parameters
    ----------
    group_name : str
        Name of the group.
    branch : str, default "main"
        Repository branch to examine.

    Returns
    -------
    dict[str, Any]
        Group metadata.

    Raises
    ------
    ValueError
        If the group does not exist.
    """
    if not self.group_exists(group_name, branch):
        raise ValueError(f"Group '{group_name}' does not exist")

    ds = self.read_group(group_name, branch)

    info = {
        "group_name": group_name,
        "store_type": self.store_type,
        "dimensions": dict(ds.sizes),
        "variables": list(ds.data_vars.keys()),
        "coordinates": list(ds.coords.keys()),
        "attributes": dict(ds.attrs),
    }

    # Add temporal information if epoch dimension exists
    if "epoch" in ds.sizes:
        info["temporal_info"] = {
            "start": str(ds.epoch.min().values),
            "end": str(ds.epoch.max().values),
            "count": ds.sizes["epoch"],
            "resolution": str(ds.epoch.diff("epoch").median().values),
        }

    return info

metadata_dataset_exists(group_name, name, branch='main')

Return True if a metadata dataset name exists for group_name.

Source code in packages/canvod-store/src/canvod/store/store.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
def metadata_dataset_exists(
    self, group_name: str, name: str, branch: str = "main"
) -> bool:
    """Return True if a metadata dataset *name* exists for *group_name*."""
    path = f"{group_name}/metadata/{name}"
    try:
        with self.readonly_session(branch) as session:
            zarr.open_group(session.store, mode="r", path=path)
            return True
    except Exception:
        return False

write_metadata_dataset(meta_ds, group_name, name, branch='main')

Write a pre-concatenated metadata dataset to {group_name}/metadata/{name}.

Always writes with mode="w" (full overwrite for the day).

Parameters

meta_ds : xr.Dataset Pre-concatenated (epoch, sid) metadata dataset. group_name : str Target group (receiver name). name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch to write to.

Returns

str Icechunk snapshot ID.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_metadata_dataset(
    self,
    meta_ds: xr.Dataset,
    group_name: str,
    name: str,
    branch: str = "main",
) -> str:
    """Write a pre-concatenated metadata dataset to *{group_name}/metadata/{name}*.

    Always writes with ``mode="w"`` (full overwrite for the day).

    Parameters
    ----------
    meta_ds : xr.Dataset
        Pre-concatenated ``(epoch, sid)`` metadata dataset.
    group_name : str
        Target group (receiver name).
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch to write to.

    Returns
    -------
    str
        Icechunk snapshot ID.
    """
    version = get_version_from_pyproject()
    path = f"{group_name}/metadata/{name}"
    ds = self._normalize_encodings(meta_ds)
    ds = self._cleanse_dataset_attrs(ds)
    with self.writable_session(branch) as session:
        to_icechunk(ds, session, group=path, mode="w")
        return session.commit(f"[v{version}] metadata/{name} for {group_name}")

append_metadata_datasets(parts, group_name, name, branch='main')

Write metadata datasets incrementally — no in-memory concat.

The first dataset initialises the group (mode="w"), subsequent datasets are appended along epoch. All writes happen inside a single session/commit so the operation is atomic.

Parameters

parts : list[xr.Dataset] Individual per-file metadata datasets with an epoch dim. group_name : str Target group (receiver name). name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch to write to.

Returns

str Icechunk snapshot ID.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata_datasets(
    self,
    parts: list[xr.Dataset],
    group_name: str,
    name: str,
    branch: str = "main",
) -> str:
    """Write metadata datasets incrementally — no in-memory concat.

    The first dataset initialises the group (``mode="w"``), subsequent
    datasets are appended along ``epoch``.  All writes happen inside a
    single session/commit so the operation is atomic.

    Parameters
    ----------
    parts : list[xr.Dataset]
        Individual per-file metadata datasets with an ``epoch`` dim.
    group_name : str
        Target group (receiver name).
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch to write to.

    Returns
    -------
    str
        Icechunk snapshot ID.
    """
    if not parts:
        msg = "parts list is empty"
        raise ValueError(msg)

    version = get_version_from_pyproject()
    path = f"{group_name}/metadata/{name}"
    total_epochs = 0

    with self.writable_session(branch) as session:
        for i, part in enumerate(parts):
            ds = self._normalize_encodings(part)
            ds = self._cleanse_dataset_attrs(ds)
            if i == 0:
                to_icechunk(ds, session, group=path, mode="w")
            else:
                to_icechunk(ds, session, group=path, append_dim="epoch")
            total_epochs += ds.sizes.get("epoch", 0)

        return session.commit(
            f"[v{version}] metadata/{name} for {group_name} ({total_epochs} epochs)"
        )

read_metadata_dataset(group_name, name, branch='main', chunks=None)

Read a metadata dataset name for group_name.

Parameters

group_name : str Group (receiver) name. name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch. chunks : dict | None, optional Dask chunk specification. Defaults to {"epoch": 34560, "sid": -1}.

Returns

xr.Dataset Lazy (epoch, sid) metadata dataset.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_metadata_dataset(
    self,
    group_name: str,
    name: str,
    branch: str = "main",
    chunks: dict | None = None,
) -> xr.Dataset:
    """Read a metadata dataset *name* for *group_name*.

    Parameters
    ----------
    group_name : str
        Group (receiver) name.
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch.
    chunks : dict | None, optional
        Dask chunk specification.  Defaults to
        ``{"epoch": 34560, "sid": -1}``.

    Returns
    -------
    xr.Dataset
        Lazy ``(epoch, sid)`` metadata dataset.
    """
    path = f"{group_name}/metadata/{name}"
    with self.readonly_session(branch) as session:
        return xr.open_zarr(
            session.store,
            group=path,
            chunks=chunks or self.chunk_strategy or {"epoch": 34560, "sid": -1},
            consolidated=False,
        )

get_metadata_dataset_info(group_name, name, branch='main')

Get info about metadata dataset name for group_name.

Parameters

group_name : str Group (receiver) name. name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch.

Returns

dict[str, Any] Info dict with the same structure as get_group_info().

Raises

ValueError If the metadata dataset does not exist.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_metadata_dataset_info(
    self,
    group_name: str,
    name: str,
    branch: str = "main",
) -> dict[str, Any]:
    """Get info about metadata dataset *name* for *group_name*.

    Parameters
    ----------
    group_name : str
        Group (receiver) name.
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch.

    Returns
    -------
    dict[str, Any]
        Info dict with the same structure as ``get_group_info()``.

    Raises
    ------
    ValueError
        If the metadata dataset does not exist.
    """
    if not self.metadata_dataset_exists(group_name, name, branch):
        raise ValueError(f"No metadata dataset '{name}' for group '{group_name}'")
    ds = self.read_metadata_dataset(group_name, name, branch, chunks={})
    info: dict[str, Any] = {
        "group_name": group_name,
        "store_path": f"{group_name}/metadata/{name}",
        "store_type": f"metadata/{name}",
        "dimensions": dict(ds.sizes),
        "variables": list(ds.data_vars.keys()),
        "coordinates": list(ds.coords.keys()),
        "attributes": dict(ds.attrs),
    }
    if "epoch" in ds.sizes:
        info["temporal_info"] = {
            "start": str(ds.epoch.min().values),
            "end": str(ds.epoch.max().values),
            "count": ds.sizes["epoch"],
            "resolution": str(ds.epoch.diff("epoch").median().values),
        }
    return info

sbf_metadata_exists(group_name, branch='main')

Return True if an SBF metadata dataset exists for group_name.

Source code in packages/canvod-store/src/canvod/store/store.py
1211
1212
1213
def sbf_metadata_exists(self, group_name: str, branch: str = "main") -> bool:
    """Return True if an SBF metadata dataset exists for *group_name*."""
    return self.metadata_dataset_exists(group_name, "sbf_obs", branch)

write_sbf_metadata(meta_ds, group_name, branch='main')

Write SBF metadata dataset.

Source code in packages/canvod-store/src/canvod/store/store.py
1215
1216
1217
1218
1219
def write_sbf_metadata(
    self, meta_ds: xr.Dataset, group_name: str, branch: str = "main"
) -> str:
    """Write SBF metadata dataset."""
    return self.write_metadata_dataset(meta_ds, group_name, "sbf_obs", branch)

read_sbf_metadata(group_name, branch='main', chunks=None)

Read SBF metadata dataset.

Source code in packages/canvod-store/src/canvod/store/store.py
1221
1222
1223
1224
1225
def read_sbf_metadata(
    self, group_name: str, branch: str = "main", chunks: dict | None = None
) -> xr.Dataset:
    """Read SBF metadata dataset."""
    return self.read_metadata_dataset(group_name, "sbf_obs", branch, chunks)

get_sbf_metadata_info(group_name, branch='main')

Get SBF metadata info.

Source code in packages/canvod-store/src/canvod/store/store.py
1227
1228
1229
1230
1231
def get_sbf_metadata_info(
    self, group_name: str, branch: str = "main"
) -> dict[str, Any]:
    """Get SBF metadata info."""
    return self.get_metadata_dataset_info(group_name, "sbf_obs", branch)

rel_path_for_commit(file_path)

Generate relative path for commit messages.

Parameters

file_path : Path Full file path.

Returns

str Relative path string with log_path_depth parts.

Source code in packages/canvod-store/src/canvod/store/store.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
def rel_path_for_commit(self, file_path: Path) -> str:
    """
    Generate relative path for commit messages.

    Parameters
    ----------
    file_path : Path
        Full file path.

    Returns
    -------
    str
        Relative path string with log_path_depth parts.
    """
    depth = load_config().processing.logging.log_path_depth
    return str(Path(*file_path.parts[-depth:]))

get_store_stats()

Get statistics about the store.

Returns

dict[str, Any] Store statistics.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_store_stats(self) -> dict[str, Any]:
    """
    Get statistics about the store.

    Returns
    -------
    dict[str, Any]
        Store statistics.
    """
    groups = self.get_group_names()
    stats = {
        "store_path": str(self.store_path),
        "store_type": self.store_type,
        "compression_level": self.compression_level,
        "compression_algorithm": self.compression_algorithm.name,
        "total_groups": len(groups),
        "groups": groups,
    }

    # Add group-specific stats
    for group_name in groups:
        try:
            info = self.get_group_info(group_name)
            stats[f"group_{group_name}"] = {
                "dimensions": info["dimensions"],
                "variables_count": len(info["variables"]),
                "has_temporal_data": "temporal_info" in info,
            }
        except Exception as e:
            self._logger.warning(
                f"Failed to get stats for group '{group_name}': {e}"
            )

    return stats

append_to_group(dataset, group_name, append_dim='epoch', branch='main', action='write', commit_message=None)

Append data to an existing group.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_to_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    append_dim: str = "epoch",
    branch: str = "main",
    action: str = "write",
    commit_message: str | None = None,
) -> None:
    """Append data to an existing group."""
    if not self.group_exists(group_name, branch):
        raise ValueError(
            f"Group '{group_name}' does not exist. Use write_initial_group() first."
        )

    dataset = self._normalize_encodings(dataset)

    rinex_hash = dataset.attrs.get("File Hash")
    if rinex_hash is None:
        raise ValueError("Dataset missing 'File Hash' attribute")
    start = dataset.epoch.min().values
    end = dataset.epoch.max().values

    # Guard: check hash + temporal overlap before appending
    exists, matches = self.metadata_row_exists(
        group_name, rinex_hash, start, end, branch
    )
    if exists and action != "overwrite":
        self._logger.warning(
            "append_blocked_by_guardrail",
            group=group_name,
            hash=rinex_hash[:16],
            range=f"{start}{end}",
            reason="hash_or_temporal_overlap",
            matching_files=matches.height if not matches.is_empty() else 0,
        )
        return

    with self.writable_session(branch) as session:
        to_icechunk(dataset, session, group=group_name, append_dim=append_dim)

        if commit_message is None and action == "write":
            version = get_version_from_pyproject()
            commit_message = f"[v{version}] Wrote to group '{group_name}'"
        elif commit_message is None and action != "append":
            version = get_version_from_pyproject()
            commit_message = f"[v{version}] Appended to group '{group_name}'"

        snapshot_id = session.commit(commit_message)

        self.append_metadata(
            group_name=group_name,
            rinex_hash=rinex_hash,
            start=start,
            end=end,
            snapshot_id=snapshot_id,
            action=action,
            commit_msg=commit_message,
            dataset_attrs=dataset.attrs,
        )

    if action == "append":
        self._logger.info(
            f"Appended {len(dataset.epoch)} epochs to group '{group_name}', "
            f"hash={rinex_hash}"
        )
    elif action == "write":
        self._logger.info(
            f"Wrote {len(dataset.epoch)} epochs to group '{group_name}', "
            f"hash={rinex_hash}"
        )
    else:
        self._logger.info(
            f"Action '{action}' completed for group '{group_name}', "
            f"hash={rinex_hash}"
        )

write_or_append_group(dataset, group_name, append_dim='epoch', branch='main', commit_message=None, dedup=False)

Write or append a dataset to a group.

By default (dedup=False) no guardrails are applied — suitable for VOD stores and other derived-data stores where rinex-style dedup does not apply.

When dedup=True the method runs a full hash-match + temporal-overlap check (via :meth:should_skip_file) before opening a write session. This makes the store the authoritative final gate for RINEX/SBF ingest paths, backstopping any pre-checks in the caller.

If the group does not exist, creates it (mode='w'). If it exists, appends along append_dim.

Parameters

dataset : xr.Dataset Dataset to write or append. group_name : str Target Icechunk group. append_dim : str, default "epoch" Dimension along which to append when the group already exists. branch : str, default "main" Icechunk branch to write to. commit_message : str or None Commit message. Auto-generated if None. dedup : bool, default False When True, check for duplicate hash or temporal overlap before writing. If the dataset would be a duplicate, the write is skipped, a warning is logged, and False is returned. Set to True for RINEX/SBF ingest; leave False for VOD and derived-data stores.

Returns

bool True if the dataset was written, False if skipped (only possible when dedup=True).

Source code in packages/canvod-store/src/canvod/store/store.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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
def write_or_append_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    append_dim: str = "epoch",
    branch: str = "main",
    commit_message: str | None = None,
    dedup: bool = False,
) -> bool:
    """Write or append a dataset to a group.

    By default (``dedup=False``) no guardrails are applied — suitable for
    VOD stores and other derived-data stores where rinex-style dedup does
    not apply.

    When ``dedup=True`` the method runs a full hash-match + temporal-overlap
    check (via :meth:`should_skip_file`) **before** opening a write session.
    This makes the store the authoritative final gate for RINEX/SBF ingest
    paths, backstopping any pre-checks in the caller.

    If the group does not exist, creates it (``mode='w'``).
    If it exists, appends along ``append_dim``.

    Parameters
    ----------
    dataset : xr.Dataset
        Dataset to write or append.
    group_name : str
        Target Icechunk group.
    append_dim : str, default "epoch"
        Dimension along which to append when the group already exists.
    branch : str, default "main"
        Icechunk branch to write to.
    commit_message : str or None
        Commit message.  Auto-generated if ``None``.
    dedup : bool, default False
        When ``True``, check for duplicate hash or temporal overlap before
        writing.  If the dataset would be a duplicate, the write is skipped,
        a warning is logged, and ``False`` is returned.  Set to ``True`` for
        RINEX/SBF ingest; leave ``False`` for VOD and derived-data stores.

    Returns
    -------
    bool
        ``True`` if the dataset was written, ``False`` if skipped
        (only possible when ``dedup=True``).
    """
    if dedup:
        file_hash = dataset.attrs.get("File Hash")
        time_start = dataset.epoch.min().values
        time_end = dataset.epoch.max().values
        skip, reason = self.should_skip_file(
            group_name=group_name,
            file_hash=file_hash,
            time_start=time_start,
            time_end=time_end,
            branch=branch,
        )
        if skip:
            self._logger.warning(
                "write_or_append_group skipped duplicate",
                group=group_name,
                reason=reason,
                file_hash=file_hash,
            )
            return False

    dataset = self._normalize_encodings(dataset)

    if self.group_exists(group_name, branch):
        with self.writable_session(branch) as session:
            to_icechunk(dataset, session, group=group_name, append_dim=append_dim)
            if commit_message is None:
                commit_message = f"Appended to group '{group_name}'"
            session.commit(commit_message)
        self._logger.info(
            f"Appended {len(dataset.epoch)} epochs to group '{group_name}'"
        )
    else:
        with self.writable_session(branch) as session:
            to_icechunk(dataset, session, group=group_name, mode="w")
            if commit_message is None:
                commit_message = f"Created group '{group_name}'"
            session.commit(commit_message)
        self._logger.info(
            f"Created group '{group_name}' with {len(dataset.epoch)} epochs"
        )
    return True

append_metadata(group_name, rinex_hash, start, end, snapshot_id, action, commit_msg, dataset_attrs, branch='main', canonical_name=None, physical_path=None)

Append a metadata row into the group_name/metadata/table.

Schema

index int64 (continuous row id) rinex_hash str (UTF-8, VariableLengthUTF8) start datetime64[ns] end datetime64[ns] snapshot_id str (UTF-8) action str (UTF-8, e.g. "insert"|"append"|"overwrite"|"skip") commit_msg str (UTF-8) written_at str (UTF-8, ISO8601 with timezone) write_strategy str (UTF-8, RINEX_STORE_STRATEGY or VOD_STORE_STRATEGY) attrs str (UTF-8, JSON dump of dataset attrs)

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata(
    self,
    group_name: str,
    rinex_hash: str,
    start: np.datetime64,
    end: np.datetime64,
    snapshot_id: str,
    action: str,
    commit_msg: str,
    dataset_attrs: dict,
    branch: str = "main",
    canonical_name: str | None = None,
    physical_path: str | None = None,
) -> None:
    """
    Append a metadata row into the group_name/metadata/table.

    Schema:
        index           int64 (continuous row id)
        rinex_hash      str   (UTF-8, VariableLengthUTF8)
        start           datetime64[ns]
        end             datetime64[ns]
        snapshot_id     str   (UTF-8)
        action          str   (UTF-8, e.g. "insert"|"append"|"overwrite"|"skip")
        commit_msg      str   (UTF-8)
        written_at      str   (UTF-8, ISO8601 with timezone)
        write_strategy  str   (UTF-8, RINEX_STORE_STRATEGY or VOD_STORE_STRATEGY)
        attrs           str   (UTF-8, JSON dump of dataset attrs)
    """
    written_at = datetime.now().astimezone().isoformat()

    row = {
        "rinex_hash": str(rinex_hash),
        "start": np.datetime64(start, "ns"),
        "end": np.datetime64(end, "ns"),
        "snapshot_id": str(snapshot_id),
        "action": str(action),
        "commit_msg": str(commit_msg),
        "written_at": written_at,
        "write_strategy": str(self._rinex_store_strategy)
        if self.store_type == "rinex_store"
        else str(self._vod_store_strategy),
        "attrs": json.dumps(dataset_attrs, default=str),
        "canonical_name": str(canonical_name) if canonical_name else "",
        "physical_path": str(physical_path) if physical_path else "",
    }
    df_row = pl.DataFrame([row])

    with self.writable_session(branch) as session:
        zroot = zarr.open_group(session.store, mode="a")
        meta_group_path = f"{group_name}/metadata/table"

        if (
            "metadata" not in zroot[group_name]
            or "table" not in zroot[group_name]["metadata"]
        ):
            # --- First time: create arrays with correct dtypes ---
            zmeta = zroot.require_group(meta_group_path)

            # index counter
            zmeta.create_array(
                name="index", shape=(0,), dtype="i8", chunks=(1024,), overwrite=True
            )
            zmeta["index"].append([0])

            for col in df_row.columns:
                if col in ("start", "end"):
                    dtype = "M8[ns]"
                    arr = np.array(df_row[col].to_numpy(), dtype=dtype)
                else:
                    dtype = VariableLengthUTF8()
                    arr = df_row[col].to_list()

                zmeta.create_array(
                    name=col,
                    shape=(0,),
                    dtype=dtype,
                    chunks=(1024,),
                    overwrite=True,
                )
                zmeta[col].append(arr)

        else:
            # --- Append to existing ---
            zmeta = zroot[meta_group_path]

            # index increment
            current_len = zmeta["index"].shape[0]
            next_idx = current_len
            zmeta["index"].append([next_idx])

            for col in df_row.columns:
                if col in ("start", "end"):
                    arr = np.array(df_row[col].to_numpy(), dtype="M8[ns]")
                else:
                    arr = df_row[col].to_list()
                zmeta[col].append(arr)

        session.commit(f"Appended metadata row for {group_name}, hash={rinex_hash}")

    self._logger.info(
        f"Metadata appended for group '{group_name}': "
        f"hash={rinex_hash}, snapshot={snapshot_id}, action={action}"
    )

append_metadata_bulk(group_name, rows, session=None)

Append multiple metadata rows in one commit.

Parameters

group_name : str Group name (e.g. "canopy", "reference") rows : list[dict[str, Any]] List of metadata records matching the schema used in append_metadata(). session : icechunk.WritableSession, optional If provided, rows are written into this session (caller commits later). If None, this method opens its own writable session and commits once.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata_bulk(
    self,
    group_name: str,
    rows: list[dict[str, Any]],
    session: icechunk.WritableSession | None = None,
) -> None:
    """
    Append multiple metadata rows in one commit.

    Parameters
    ----------
    group_name : str
        Group name (e.g. "canopy", "reference")
    rows : list[dict[str, Any]]
        List of metadata records matching the schema used in
        append_metadata().
    session : icechunk.WritableSession, optional
        If provided, rows are written into this session (caller commits later).
        If None, this method opens its own writable session and commits once.
    """
    if not rows:
        self._logger.info(f"No metadata rows to append for group '{group_name}'")
        return

    # Ensure datetime conversions for consistency
    for row in rows:
        if isinstance(row.get("start"), str):
            row["start"] = np.datetime64(row["start"])
        if isinstance(row.get("end"), str):
            row["end"] = np.datetime64(row["end"])
        if "written_at" not in row:
            row["written_at"] = datetime.now(UTC).isoformat()

    # Prepare the Polars DataFrame
    df = pl.DataFrame(rows)

    def _do_append(session_obj: icechunk.WritableSession) -> None:
        """Append metadata rows to a writable session.

        Parameters
        ----------
        session_obj : icechunk.WritableSession
            Writable session to update.

        Returns
        -------
        None
        """
        zroot = zarr.open_group(session_obj.store, mode="a")
        meta_group_path = f"{group_name}/metadata/table"
        zmeta = zroot.require_group(meta_group_path)

        start_index = 0
        if "index" in zmeta:
            existing_len = zmeta["index"].shape[0]
            start_index = (
                int(zmeta["index"][-1].item()) + 1 if existing_len > 0 else 0
            )

        # Assign sequential indices
        df_with_index = df.with_columns(
            (pl.arange(start_index, start_index + df.height)).alias("index")
        )

        # Write each column
        for col_name in df_with_index.columns:
            col_data = df_with_index[col_name]

            if col_name == "index":
                dtype = "i8"
                arr = col_data.to_numpy().astype(dtype)
            elif col_name in ("start", "end"):
                dtype = "M8[ns]"
                arr = col_data.to_numpy().astype(dtype)
            else:
                # strings / jsons / ids
                dtype = VariableLengthUTF8()
                arr = col_data.to_list()

            if col_name not in zmeta:
                # Create array if it doesn't exist
                zmeta.create_array(
                    name=col_name,
                    shape=(0,),
                    dtype=dtype,
                    chunks=(1024,),
                    overwrite=True,
                )

            # Resize and append
            old_len = zmeta[col_name].shape[0]
            new_len = old_len + len(arr)
            zmeta[col_name].resize(new_len)
            zmeta[col_name][old_len:new_len] = arr

        self._logger.info(
            f"Appended {df_with_index.height} metadata rows to group '{group_name}'"
        )

    if session is not None:
        _do_append(session)
    else:
        with self.writable_session() as sess:
            _do_append(sess)
            sess.commit(f"Bulk metadata append for {group_name}")

load_metadata(store, group_name)

Load metadata directly from Zarr into a Polars DataFrame.

Parameters

store : Any Zarr store or session store handle. group_name : str Group name.

Returns

pl.DataFrame Metadata table.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def load_metadata(self, store: Any, group_name: str) -> pl.DataFrame:
    """Load metadata directly from Zarr into a Polars DataFrame.

    Parameters
    ----------
    store : Any
        Zarr store or session store handle.
    group_name : str
        Group name.

    Returns
    -------
    pl.DataFrame
        Metadata table.
    """
    zroot = zarr.open_group(store, mode="r")
    zmeta = zroot[f"{group_name}/metadata/table"]

    # Read all columns into a dict of numpy arrays
    data = {col: zmeta[col][...] for col in zmeta.array_keys()}

    # Build Polars DataFrame
    df = pl.DataFrame(data)

    # Convert numeric datetime64 columns back to proper Polars datetimes
    if df["start"].dtype in (pl.Int64, pl.Float64):
        df = df.with_columns(pl.col("start").cast(pl.Datetime("ns")))
    if df["end"].dtype in (pl.Int64, pl.Float64):
        df = df.with_columns(pl.col("end").cast(pl.Datetime("ns")))
    if df["written_at"].dtype == pl.Utf8:
        df = df.with_columns(pl.col("written_at").str.to_datetime("%+"))
    return df

read_metadata_table(session, group_name)

Read the metadata table from a session.

Parameters

session : Any Active session for reading. group_name : str Group name.

Returns

pl.DataFrame Metadata table.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_metadata_table(self, session: Any, group_name: str) -> pl.DataFrame:
    """Read the metadata table from a session.

    Parameters
    ----------
    session : Any
        Active session for reading.
    group_name : str
        Group name.

    Returns
    -------
    pl.DataFrame
        Metadata table.
    """
    zmeta = zarr.open_group(
        session.store,
        mode="r",
    )[f"{group_name}/metadata/table"]

    data = {col: zmeta[col][:] for col in zmeta.array_keys()}
    df = pl.DataFrame(data)

    # Ensure start/end are proper datetime
    df = df.with_columns(
        [
            pl.col("start").cast(pl.Datetime("ns")),
            pl.col("end").cast(pl.Datetime("ns")),
        ]
    )
    return df

metadata_row_exists(group_name, rinex_hash, start, end, branch='main')

Check whether a file already exists or temporally overlaps existing data.

Performs two checks in order:

  1. Hash match — if rinex_hash already appears in the metadata table, the file was previously ingested (exact duplicate).
  2. Temporal overlap — if the incoming [start, end] interval overlaps any existing metadata interval, the file covers a time range that is already (partially) present in the store. This catches cases like a daily concatenation file coexisting with the sub-daily files it was built from.
Parameters

group_name : str Icechunk group name. rinex_hash : str Hash of the current GNSS dataset. start : np.datetime64 Start epoch of the incoming file. end : np.datetime64 End epoch of the incoming file. branch : str, default "main" Branch name in the Icechunk repository.

Returns

tuple[bool, pl.DataFrame] (True, overlapping_rows) when the file should be skipped, (False, empty_df) when it is safe to ingest.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def metadata_row_exists(
    self,
    group_name: str,
    rinex_hash: str,
    start: np.datetime64,
    end: np.datetime64,
    branch: str = "main",
) -> tuple[bool, pl.DataFrame]:
    """
    Check whether a file already exists or temporally overlaps existing data.

    Performs two checks in order:

    1. **Hash match** — if ``rinex_hash`` already appears in the metadata
       table, the file was previously ingested (exact duplicate).
    2. **Temporal overlap** — if the incoming ``[start, end]`` interval
       overlaps any existing metadata interval, the file covers a time
       range that is already (partially) present in the store.  This
       catches cases like a daily concatenation file coexisting with the
       sub-daily files it was built from.

    Parameters
    ----------
    group_name : str
        Icechunk group name.
    rinex_hash : str
        Hash of the current GNSS dataset.
    start : np.datetime64
        Start epoch of the incoming file.
    end : np.datetime64
        End epoch of the incoming file.
    branch : str, default "main"
        Branch name in the Icechunk repository.

    Returns
    -------
    tuple[bool, pl.DataFrame]
        ``(True, overlapping_rows)`` when the file should be skipped,
        ``(False, empty_df)`` when it is safe to ingest.
    """
    with self.readonly_session(branch) as session:
        try:
            zmeta = zarr.open_group(session.store, mode="r")[
                f"{group_name}/metadata/table"
            ]
        except Exception:
            return False, pl.DataFrame()

        data = {col: zmeta[col][:] for col in zmeta.array_keys()}
        df = pl.DataFrame(data)

        df = df.with_columns(
            [
                pl.col("start").cast(pl.Datetime("ns")),
                pl.col("end").cast(pl.Datetime("ns")),
            ]
        )

        # --- Check 1: exact hash match (file already ingested) ---
        hash_matches = df.filter(pl.col("rinex_hash") == rinex_hash)
        if not hash_matches.is_empty():
            return True, hash_matches

        # --- Check 2: temporal overlap ---
        # Two intervals [A.start, A.end] and [B.start, B.end] overlap
        # iff A.start <= B.end AND A.end >= B.start
        start_ns = np.datetime64(start, "ns")
        end_ns = np.datetime64(end, "ns")

        overlaps = df.filter(
            (pl.col("start") <= end_ns) & (pl.col("end") >= start_ns)
        )

        if not overlaps.is_empty():
            n = overlaps.height
            existing_range = f"{overlaps['start'].min()}{overlaps['end'].max()}"
            self._logger.warning(
                "temporal_overlap_detected",
                group=group_name,
                incoming_hash=rinex_hash,
                incoming_range=f"{start}{end}",
                existing_range=existing_range,
                overlapping_files=n,
            )
            return True, overlaps

        return False, pl.DataFrame()

should_skip_file(group_name, file_hash, time_start, time_end, branch='main')

Check whether a file should be skipped before processing and writing.

Thin public wrapper around :meth:metadata_row_exists that returns a simple (skip, reason) pair instead of a DataFrame, suitable for use in Airflow task functions as an early-exit optimisation.

This method is an early-exit optimisation: it avoids opening a write session for files that are already present. Pass dedup=True to :meth:write_or_append_group to make the store the authoritative final gate (runs the same check again before writing).

Checks performed (in order):

  1. Hash match — file was previously ingested (exact duplicate).
  2. Temporal overlap — incoming time range overlaps existing epochs.

Layer 3 (intra-batch overlap) is not applicable here because task functions process files one at a time.

Parameters

group_name : str Icechunk group name. file_hash : str or None Hash from dataset.attrs["File Hash"]. When None the check is skipped and (False, "") is returned. time_start : np.datetime64 First epoch of the incoming dataset. time_end : np.datetime64 Last epoch of the incoming dataset. branch : str, default "main" Branch name in the Icechunk repository.

Returns

tuple[bool, str] (True, "hash_match") — exact duplicate, skip. (True, "temporal_overlap") — overlapping time range, skip. (False, "") — safe to ingest.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def should_skip_file(
    self,
    group_name: str,
    file_hash: str | None,
    time_start: np.datetime64,
    time_end: np.datetime64,
    branch: str = "main",
) -> tuple[bool, str]:
    """Check whether a file should be skipped before processing and writing.

    Thin public wrapper around :meth:`metadata_row_exists` that returns a
    simple ``(skip, reason)`` pair instead of a DataFrame, suitable for use
    in Airflow task functions as an early-exit optimisation.

    This method is an early-exit optimisation: it avoids opening a write
    session for files that are already present.  Pass ``dedup=True`` to
    :meth:`write_or_append_group` to make the store the authoritative
    final gate (runs the same check again before writing).

    Checks performed (in order):

    1. **Hash match** — file was previously ingested (exact duplicate).
    2. **Temporal overlap** — incoming time range overlaps existing epochs.

    Layer 3 (intra-batch overlap) is not applicable here because task
    functions process files one at a time.

    Parameters
    ----------
    group_name : str
        Icechunk group name.
    file_hash : str or None
        Hash from ``dataset.attrs["File Hash"]``.  When ``None`` the check
        is skipped and ``(False, "")`` is returned.
    time_start : np.datetime64
        First epoch of the incoming dataset.
    time_end : np.datetime64
        Last epoch of the incoming dataset.
    branch : str, default "main"
        Branch name in the Icechunk repository.

    Returns
    -------
    tuple[bool, str]
        ``(True, "hash_match")`` — exact duplicate, skip.
        ``(True, "temporal_overlap")`` — overlapping time range, skip.
        ``(False, "")`` — safe to ingest.
    """
    if file_hash is None:
        return False, ""

    exists, matches = self.metadata_row_exists(
        group_name, file_hash, time_start, time_end, branch
    )
    if not exists:
        return False, ""

    if not matches.is_empty() and (matches["rinex_hash"] == file_hash).any():
        return True, "hash_match"
    return True, "temporal_overlap"

batch_check_existing(group_name, file_hashes)

Check which file hashes already exist in metadata.

Source code in packages/canvod-store/src/canvod/store/store.py
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def batch_check_existing(self, group_name: str, file_hashes: list[str]) -> set[str]:
    """Check which file hashes already exist in metadata."""

    try:
        with self.readonly_session("main") as session:
            df = self.load_metadata(session.store, group_name)

            # Filter to matching hashes
            existing = df.filter(pl.col("rinex_hash").is_in(file_hashes))
            return set(existing["rinex_hash"].to_list())

    except KeyError, zarr.errors.GroupNotFoundError, Exception:
        # Branch/group/metadata doesn't exist yet (fresh store)
        return set()

check_temporal_overlaps(group_name, file_intervals, branch='main')

Check which files temporally overlap existing metadata intervals.

Parameters

group_name : str Icechunk group name. file_intervals : list[tuple[str, np.datetime64, np.datetime64]] List of (rinex_hash, start, end) tuples for incoming files. branch : str, default "main" Branch name in the Icechunk repository.

Returns

set[str] Hashes of files whose [start, end] overlaps any existing metadata interval. Files whose hash already exists in the store are NOT included (use batch_check_existing for those).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def check_temporal_overlaps(
    self,
    group_name: str,
    file_intervals: list[tuple[str, np.datetime64, np.datetime64]],
    branch: str = "main",
) -> set[str]:
    """Check which files temporally overlap existing metadata intervals.

    Parameters
    ----------
    group_name : str
        Icechunk group name.
    file_intervals : list[tuple[str, np.datetime64, np.datetime64]]
        List of ``(rinex_hash, start, end)`` tuples for incoming files.
    branch : str, default "main"
        Branch name in the Icechunk repository.

    Returns
    -------
    set[str]
        Hashes of files whose ``[start, end]`` overlaps any existing
        metadata interval.  Files whose hash already exists in the store
        are NOT included (use ``batch_check_existing`` for those).
    """
    if not file_intervals:
        return set()

    try:
        with self.readonly_session(branch) as session:
            df = self.load_metadata(session.store, group_name)
    except KeyError, zarr.errors.GroupNotFoundError, Exception:
        return set()

    if df.is_empty():
        return set()

    df = df.with_columns(
        [
            pl.col("start").cast(pl.Datetime("ns")),
            pl.col("end").cast(pl.Datetime("ns")),
        ]
    )

    overlapping: set[str] = set()
    for rinex_hash, start, end in file_intervals:
        start_ns = np.datetime64(start, "ns")
        end_ns = np.datetime64(end, "ns")

        hits = df.filter((pl.col("start") <= end_ns) & (pl.col("end") >= start_ns))
        if not hits.is_empty():
            self._logger.warning(
                "temporal_overlap_detected",
                group=group_name,
                incoming_hash=rinex_hash[:16],
                incoming_range=f"{start}{end}",
                existing_files=hits.height,
            )
            overlapping.add(rinex_hash)

    return overlapping

append_metadata_bulk_store(group_name, rows, store)

Append metadata rows into an open transaction store.

Parameters

group_name : str Group name (e.g. "canopy", "reference"). rows : list[dict[str, Any]] Metadata rows to append. store : Any Open Icechunk transaction store.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata_bulk_store(
    self,
    group_name: str,
    rows: list[dict[str, Any]],
    store: Any,
) -> None:
    """
    Append metadata rows into an open transaction store.

    Parameters
    ----------
    group_name : str
        Group name (e.g. "canopy", "reference").
    rows : list[dict[str, Any]]
        Metadata rows to append.
    store : Any
        Open Icechunk transaction store.
    """
    if not rows:
        return

    zroot = zarr.open_group(store, mode="a")
    zmeta = zroot.require_group(f"{group_name}/metadata/table")

    # Find next index
    start_index = 0
    if "index" in zmeta:
        start_index = (
            int(zmeta["index"][-1]) + 1 if zmeta["index"].shape[0] > 0 else 0
        )

    for i, row in enumerate(rows, start=start_index):
        row["index"] = i

    import polars as pl

    df = pl.DataFrame(rows)

    for col in df.columns:
        list_only_cols = {
            "attrs",
            "commit_msg",
            "action",
            "write_strategy",
            "rinex_hash",
            "snapshot_id",
        }
        if col in list_only_cols:
            values = df[col].to_list()
        else:
            values = df[col].to_numpy()

        if col == "index":
            dtype = "i8"
        elif col in ("start", "end"):
            dtype = "M8[ns]"
        else:
            dtype = VariableLengthUTF8()

        if col not in zmeta:
            zmeta.create_array(
                name=col, shape=(0,), dtype=dtype, chunks=(1024,), overwrite=True
            )

        arr = zmeta[col]
        old_len = arr.shape[0]
        new_len = old_len + len(values)
        arr.resize(new_len)
        arr[old_len:new_len] = values

    self._logger.info(f"Appended {df.height} metadata rows to group '{group_name}'")

expire_old_snapshots(days=None, branch='main', delete_expired_branches=True, delete_expired_tags=True)

Expire and garbage-collect snapshots older than the given retention period.

Parameters

days : int | None, optional Number of days to retain snapshots. Defaults to config value. branch : str, default "main" Branch to apply expiration on. delete_expired_branches : bool, default True Whether to delete branches pointing to expired snapshots. delete_expired_tags : bool, default True Whether to delete tags pointing to expired snapshots.

Returns

set[str] Expired snapshot IDs.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def expire_old_snapshots(
    self,
    days: int | None = None,
    branch: str = "main",
    delete_expired_branches: bool = True,
    delete_expired_tags: bool = True,
) -> set[str]:
    """
    Expire and garbage-collect snapshots older than the given retention period.

    Parameters
    ----------
    days : int | None, optional
        Number of days to retain snapshots. Defaults to config value.
    branch : str, default "main"
        Branch to apply expiration on.
    delete_expired_branches : bool, default True
        Whether to delete branches pointing to expired snapshots.
    delete_expired_tags : bool, default True
        Whether to delete tags pointing to expired snapshots.

    Returns
    -------
    set[str]
        Expired snapshot IDs.
    """
    if days is None:
        days = self._rinex_store_expire_days
    cutoff = datetime.now(UTC) - timedelta(days=days)

    # cutoff = datetime(2025, 10, 3, 16, 44, 1, tzinfo=timezone.utc)
    self._logger.info(
        f"Running expiration on store '{self.store_type}' "
        f"(branch '{branch}') with cutoff {cutoff.isoformat()}"
    )

    # Expire snapshots older than cutoff
    expired_ids = self.repo.expire_snapshots(
        older_than=cutoff,
        delete_expired_branches=delete_expired_branches,
        delete_expired_tags=delete_expired_tags,
    )

    if expired_ids:
        self._logger.info(
            f"Expired {len(expired_ids)} snapshots: {sorted(expired_ids)}"
        )
    else:
        self._logger.info("No snapshots to expire.")

    # Garbage-collect expired objects to reclaim storage
    summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
    self._logger.info(
        f"Garbage collection summary: "
        f"deleted_bytes={summary.bytes_deleted}, "
        f"deleted_chunks={summary.chunks_deleted}, "
        f"deleted_manifests={summary.manifests_deleted}, "
        f"deleted_snapshots={summary.snapshots_deleted}, "
        f"deleted_attributes={summary.attributes_deleted}, "
        f"deleted_transaction_logs={summary.transaction_logs_deleted}"
    )

    return expired_ids

get_history(branch='main', limit=None)

Return commit ancestry (history) for a branch.

Parameters

branch : str, default "main" Branch name. limit : int | None, optional Maximum number of commits to return.

Returns

list[dict] Commit info dictionaries (id, message, written_at, parent_ids).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_history(self, branch: str = "main", limit: int | None = None) -> list[dict]:
    """
    Return commit ancestry (history) for a branch.

    Parameters
    ----------
    branch : str, default "main"
        Branch name.
    limit : int | None, optional
        Maximum number of commits to return.

    Returns
    -------
    list[dict]
        Commit info dictionaries (id, message, written_at, parent_ids).
    """
    self._logger.info(f"Fetching ancestry for branch '{branch}'")

    history = []
    for i, ancestor in enumerate(self.repo.ancestry(branch=branch)):
        history.append(
            {
                "snapshot_id": ancestor.id,
                "commit_msg": ancestor.message,
                "written_at": ancestor.written_at,
                "parent_ids": ancestor.parent_id,
            }
        )
        if limit is not None and i + 1 >= limit:
            break

    return history

print_history(branch='main', limit=100)

Pretty-print the ancestry for quick inspection.

Source code in packages/canvod-store/src/canvod/store/store.py
2121
2122
2123
2124
2125
2126
2127
def print_history(self, branch: str = "main", limit: int | None = 100) -> None:
    """
    Pretty-print the ancestry for quick inspection.
    """
    for entry in self.get_history(branch=branch, limit=limit):
        ts = entry["written_at"].strftime("%Y-%m-%d %H:%M:%S")
        print(f"{ts} {entry['snapshot_id'][:8]} {entry['commit_msg']}")

__repr__()

Return the developer-facing representation.

Returns

str Representation string.

Source code in packages/canvod-store/src/canvod/store/store.py
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
def __repr__(self) -> str:
    """Return the developer-facing representation.

    Returns
    -------
    str
        Representation string.
    """
    display_names = {"rinex_store": "GNSS Store", "vod_store": "VOD Store"}
    display = display_names.get(self.store_type, self.store_type)
    return f"MyIcechunkStore(store_path={self.store_path}, store_type={display})"

__str__()

Return a human-readable summary.

Returns

str Summary string.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def __str__(self) -> str:
    """Return a human-readable summary.

    Returns
    -------
    str
        Summary string.
    """

    # Capture tree output
    old_stdout = sys.stdout
    sys.stdout = buffer = io.StringIO()

    try:
        self.print_tree()
        tree_output = buffer.getvalue()
    finally:
        sys.stdout = old_stdout

    branches = self.get_branch_names()
    group_dict = self.get_group_names()
    total_groups = sum(len(groups) for groups in group_dict.values())

    return (
        f"MyIcechunkStore: {self.store_path}\n"
        f"Branches: {len(branches)} | Total Groups: {total_groups}\n\n"
        f"{tree_output}"
    )

rechunk_group(group_name, chunks, source_branch='main', temp_branch=None, promote_to_main=True, delete_temp_branch=True)

Rechunk a group with optimal chunk sizes.

Parameters

group_name : str Name of the group to rechunk chunks : dict[str, int] Chunking specification, e.g. {'epoch': 34560, 'sid': -1} source_branch : str Branch to read original data from (default: "main") temp_branch : str | None Temporary branch name for rechunked data. If None, uses "{group_name}_rechunked". promote_to_main : bool If True, reset main branch to rechunked snapshot after writing delete_temp_branch : bool If True, delete temporary branch after promotion (only if promote_to_main=True).

Returns

str Snapshot ID of the rechunked data

Source code in packages/canvod-store/src/canvod/store/store.py
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
def rechunk_group(
    self,
    group_name: str,
    chunks: dict[str, int],
    source_branch: str = "main",
    temp_branch: str | None = None,
    promote_to_main: bool = True,
    delete_temp_branch: bool = True,
) -> str:
    """
    Rechunk a group with optimal chunk sizes.

    Parameters
    ----------
    group_name : str
        Name of the group to rechunk
    chunks : dict[str, int]
        Chunking specification, e.g. {'epoch': 34560, 'sid': -1}
    source_branch : str
        Branch to read original data from (default: "main")
    temp_branch : str | None
        Temporary branch name for rechunked data. If None, uses
        "{group_name}_rechunked".
    promote_to_main : bool
        If True, reset main branch to rechunked snapshot after writing
    delete_temp_branch : bool
        If True, delete temporary branch after promotion (only if
        promote_to_main=True).

    Returns
    -------
    str
        Snapshot ID of the rechunked data
    """
    if temp_branch is None:
        temp_branch = f"{group_name}_rechunked_temp"

    self._logger.info(
        f"Starting rechunk of group '{group_name}' with chunks={chunks}"
    )

    # Get CURRENT snapshot from source branch to preserve all other groups
    current_snapshot = next(self.repo.ancestry(branch=source_branch)).id

    # Create temp branch from current snapshot (preserves all existing groups)
    try:
        self.repo.create_branch(temp_branch, current_snapshot)
        self._logger.info(
            f"Created temporary branch '{temp_branch}' from current {source_branch}"
        )
    except Exception as e:
        self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

    # Read original data
    ds_original = self.read_group(group_name, branch=source_branch)
    self._logger.info(f"Original chunks: {ds_original.chunks}")

    # Rechunk
    ds_rechunked = ds_original.chunk(chunks)
    self._logger.info(f"New chunks: {ds_rechunked.chunks}")

    # Clear encoding to avoid conflicts
    for var in ds_rechunked.data_vars:
        ds_rechunked[var].encoding = {}

    # Write rechunked data (overwrites only this group)
    with self.writable_session(temp_branch) as session:
        to_icechunk(ds_rechunked, session, group=group_name, mode="w")
        snapshot_id = session.commit(f"Rechunked {group_name} with chunks={chunks}")

    self._logger.info(
        f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
    )

    # Promote to main if requested
    if promote_to_main:
        rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
        self.repo.reset_branch(source_branch, rechunked_snapshot)
        self._logger.info(
            f"Reset branch '{source_branch}' to rechunked snapshot "
            f"{rechunked_snapshot}"
        )

        # Delete temp branch if requested
        if delete_temp_branch:
            self.repo.delete_branch(temp_branch)
            self._logger.info(f"Deleted temporary branch '{temp_branch}'")

    return snapshot_id

rechunk_group_verbose(group_name, chunks=None, source_branch='main', temp_branch=None, promote_to_main=True, delete_temp_branch=True)

Rechunk a group with optimal chunk sizes.

Parameters

group_name : str Name of the group to rechunk chunks : dict[str, int] | None Chunking specification, e.g. {'epoch': 34560, 'sid': -1}. Defaults to gnnsvodpy.globals.ICECHUNK_CHUNK_STRATEGIES. source_branch : str Branch to read original data from (default: "main") temp_branch : str | None Temporary branch name for rechunked data. If None, uses "{group_name}_rechunked". promote_to_main : bool If True, reset main branch to rechunked snapshot after writing delete_temp_branch : bool If True, delete temporary branch after promotion (only if promote_to_main=True).

Returns

str Snapshot ID of the rechunked data

Source code in packages/canvod-store/src/canvod/store/store.py
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
def rechunk_group_verbose(
    self,
    group_name: str,
    chunks: dict[str, int] | None = None,
    source_branch: str = "main",
    temp_branch: str | None = None,
    promote_to_main: bool = True,
    delete_temp_branch: bool = True,
) -> str:
    """
    Rechunk a group with optimal chunk sizes.

    Parameters
    ----------
    group_name : str
        Name of the group to rechunk
    chunks : dict[str, int] | None
        Chunking specification, e.g. {'epoch': 34560, 'sid': -1}. Defaults
        to `gnnsvodpy.globals.ICECHUNK_CHUNK_STRATEGIES`.
    source_branch : str
        Branch to read original data from (default: "main")
    temp_branch : str | None
        Temporary branch name for rechunked data. If None, uses
        "{group_name}_rechunked".
    promote_to_main : bool
        If True, reset main branch to rechunked snapshot after writing
    delete_temp_branch : bool
        If True, delete temporary branch after promotion (only if
        promote_to_main=True).

    Returns
    -------
    str
        Snapshot ID of the rechunked data
    """
    if temp_branch is None:
        temp_branch = f"{group_name}_rechunked_temp"

    if chunks is None:
        chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

    print(f"\n{'=' * 60}")
    print(f"Starting rechunk of group '{group_name}'")
    print(f"Target chunks: {chunks}")
    print(f"{'=' * 60}\n")

    self._logger.info(
        f"Starting rechunk of group '{group_name}' with chunks={chunks}"
    )

    # Get CURRENT snapshot from source branch to preserve all other groups
    print(f"[1/7] Getting current snapshot from branch '{source_branch}'...")
    current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
    print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

    # Create temp branch from current snapshot (preserves all existing groups)
    print(f"\n[2/7] Creating temporary branch '{temp_branch}'...")
    try:
        self.repo.create_branch(temp_branch, current_snapshot)
        print(f"      ✓ Branch '{temp_branch}' created")
        self._logger.info(
            f"Created temporary branch '{temp_branch}' from current {source_branch}"
        )
    except Exception as e:
        print(
            f"      ⚠ Branch '{temp_branch}' already exists, using existing branch"
        )
        self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

    # Read original data
    print(f"\n[3/7] Reading original data from '{group_name}'...")
    ds_original = self.read_group(group_name, branch=source_branch)

    # Unify chunks if inconsistent
    try:
        ds_original = ds_original.unify_chunks()
        print("      ✓ Unified inconsistent chunks")
    except TypeError, ValueError:
        pass  # Chunks are already consistent

    print(f"      ✓ Data shape: {dict(ds_original.sizes)}")
    print(f"      ✓ Original chunks: {ds_original.chunks}")
    self._logger.info(f"Original chunks: {ds_original.chunks}")

    # Rechunk
    print("\n[4/7] Rechunking data...")
    ds_rechunked = ds_original.chunk(chunks)
    ds_rechunked = ds_rechunked.unify_chunks()
    print(f"      ✓ New chunks: {ds_rechunked.chunks}")
    self._logger.info(f"New chunks: {ds_rechunked.chunks}")

    # Clear encoding to avoid conflicts
    for var in ds_rechunked.data_vars:
        ds_rechunked[var].encoding = {}
    for coord in ds_rechunked.coords:
        if "chunks" in ds_rechunked[coord].encoding:
            del ds_rechunked[coord].encoding["chunks"]

    # Write rechunked data first (overwrites entire group)
    print(f"\n[5/7] Writing rechunked data to branch '{temp_branch}'...")
    print("      This may take several minutes for large datasets...")
    with self.writable_session(temp_branch) as session:
        to_icechunk(ds_rechunked, session, group=group_name, mode="w")
        session.commit(f"Wrote rechunked data for {group_name}")
    print("      ✓ Data written successfully")

    # Copy subgroups after writing rechunked data
    print(f"\n[6/7] Copying subgroups from '{group_name}'...")
    with self.writable_session(temp_branch) as session:
        with self.readonly_session(source_branch) as icsession:
            source_group = zarr.open_group(icsession.store, mode="r")[group_name]
        target_group = zarr.open_group(session.store, mode="a")[group_name]

        subgroup_count = 0
        for subgroup_name in source_group.group_keys():
            print(f"      ✓ Copying subgroup '{subgroup_name}'...")
            source_subgroup = source_group[subgroup_name]
            target_subgroup = target_group.create_group(
                subgroup_name, overwrite=True
            )

            # Copy arrays from subgroup
            for array_name in source_subgroup.array_keys():
                source_array = source_subgroup[array_name]
                target_array = target_subgroup.create_array(
                    array_name,
                    shape=source_array.shape,
                    dtype=source_array.dtype,
                    chunks=source_array.chunks,
                    overwrite=True,
                )
                target_array[:] = source_array[:]

            # Copy subgroup attributes
            target_subgroup.attrs.update(source_subgroup.attrs)
            subgroup_count += 1

        if subgroup_count > 0:
            snapshot_id = session.commit(
                f"Rechunked {group_name} with chunks={chunks}"
            )
            print(f"      ✓ {subgroup_count} subgroups copied")
        else:
            snapshot_id = next(self.repo.ancestry(branch=temp_branch)).id
            print("      ✓ No subgroups to copy")

    print(f"      ✓ Snapshot ID: {snapshot_id[:12]}")
    self._logger.info(
        f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
    )

    # Promote to main if requested
    if promote_to_main:
        print(f"\n[7/7] Promoting to '{source_branch}' branch...")
        rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
        self.repo.reset_branch(source_branch, rechunked_snapshot)
        print(
            f"      ✓ Branch '{source_branch}' reset to {rechunked_snapshot[:12]}"
        )
        self._logger.info(
            f"Reset branch '{source_branch}' to rechunked snapshot "
            f"{rechunked_snapshot}"
        )

        # Delete temp branch if requested
        if delete_temp_branch:
            print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
            self.delete_branch(temp_branch)
            print("      ✓ Temporary branch deleted")
            self._logger.info(f"Deleted temporary branch '{temp_branch}'")
    else:
        print("\n[7/7] Skipping promotion (promote_to_main=False)")
        print(f"      Rechunked data available on branch '{temp_branch}'")

    print(f"\n{'=' * 60}")
    print(f"✓ Rechunking complete for '{group_name}'")
    print(f"{'=' * 60}\n")

    return snapshot_id

create_release_tag(tag_name, snapshot_id=None)

Create an immutable tag for an important version.

Parameters

tag_name : str Name for the tag (e.g., "v2024_complete", "before_reprocess") snapshot_id : str | None Snapshot to tag. If None, uses current tip of main branch.

Source code in packages/canvod-store/src/canvod/store/store.py
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
def create_release_tag(self, tag_name: str, snapshot_id: str | None = None) -> None:
    """
    Create an immutable tag for an important version.

    Parameters
    ----------
    tag_name : str
        Name for the tag (e.g., "v2024_complete", "before_reprocess")
    snapshot_id : str | None
        Snapshot to tag. If None, uses current tip of main branch.
    """
    if snapshot_id is None:
        # Tag current main branch tip
        snapshot_id = next(self.repo.ancestry(branch="main")).id

    self.repo.create_tag(tag_name, snapshot_id)
    self._logger.info(f"Created tag '{tag_name}' at snapshot {snapshot_id[:8]}")

list_tags()

List all tags in the repository.

Source code in packages/canvod-store/src/canvod/store/store.py
2458
2459
2460
def list_tags(self) -> list[str]:
    """List all tags in the repository."""
    return list(self.repo.list_tags())

delete_tag(tag_name)

Delete a tag (use with caution - tags are meant to be permanent).

Source code in packages/canvod-store/src/canvod/store/store.py
2462
2463
2464
2465
def delete_tag(self, tag_name: str) -> None:
    """Delete a tag (use with caution - tags are meant to be permanent)."""
    self.repo.delete_tag(tag_name)
    self._logger.warning(f"Deleted tag '{tag_name}'")

plot_commit_graph(max_commits=100)

Visualize commit history as an interactive git-like graph.

Creates an interactive visualization showing: - Branches with different colors - Chronological commit ordering - Branch divergence points - Commit messages on hover - Click to see commit details

Parameters

max_commits : int Maximum number of commits to display (default: 100).

Returns

Figure Interactive plotly figure (works in marimo and Jupyter).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def plot_commit_graph(self, max_commits: int = 100) -> Figure:
    """
    Visualize commit history as an interactive git-like graph.

    Creates an interactive visualization showing:
    - Branches with different colors
    - Chronological commit ordering
    - Branch divergence points
    - Commit messages on hover
    - Click to see commit details

    Parameters
    ----------
    max_commits : int
        Maximum number of commits to display (default: 100).

    Returns
    -------
    Figure
        Interactive plotly figure (works in marimo and Jupyter).
    """
    from collections import defaultdict
    from datetime import datetime

    import plotly.graph_objects as go

    # Collect all commits with full metadata
    commit_map = {}  # id -> commit data
    branch_tips = {}  # branch -> latest commit id

    for branch in self.repo.list_branches():
        ancestors = list(self.repo.ancestry(branch=branch))
        if ancestors:
            branch_tips[branch] = ancestors[0].id

        for ancestor in ancestors:
            if ancestor.id not in commit_map:
                commit_map[ancestor.id] = {
                    "id": ancestor.id,
                    "parent_id": ancestor.parent_id,
                    "message": ancestor.message,
                    "written_at": ancestor.written_at,
                    "branches": [branch],
                }
            else:
                # Multiple branches point to same commit
                commit_map[ancestor.id]["branches"].append(branch)

            if len(commit_map) >= max_commits:
                break
        if len(commit_map) >= max_commits:
            break

    # Build parent-child relationships
    commits_list = list(commit_map.values())
    commits_list.sort(key=lambda c: c["written_at"])  # Oldest first

    # Assign horizontal positions (chronological)
    commit_x_positions = {}
    for idx, commit in enumerate(commits_list):
        commit["x"] = idx
        commit_x_positions[commit["id"]] = idx

    # Assign vertical positions: commits shared by branches stay on same Y
    # Only diverge when branches have different commits
    branch_names = sorted(
        self.repo.list_branches(), key=lambda b: (b != "main", b)
    )  # main first

    # Build a set of all commit IDs for each branch
    branch_commits = {}
    for branch in branch_names:
        history = list(self.repo.ancestry(branch=branch))
        branch_commits[branch] = {h.id for h in history if h.id in commit_map}

    # Find where branches diverge
    def branches_share_commit(
        commit_id: str,
        branches: list[str],
    ) -> list[str]:
        """Return branches that contain a commit.

        Parameters
        ----------
        commit_id : str
            Commit identifier to check.
        branches : list[str]
            Branch names to search.

        Returns
        -------
        list[str]
            Branches that contain the commit.
        """
        return [b for b in branches if commit_id in branch_commits[b]]

    # Assign Y position: all commits on a single horizontal line initially
    # We'll use vertical offset for parallel branch indicators
    for commit in commits_list:
        commit["y"] = 0  # All on same timeline
        commit["branch_set"] = frozenset(commit["branches"])

    # Color palette for branches
    colors = [
        "#4a9a4a",  # green (main)
        "#5580c8",  # blue
        "#d97643",  # orange
        "#9b59b6",  # purple
        "#e74c3c",  # red
        "#1abc9c",  # turquoise
        "#f39c12",  # yellow
        "#34495e",  # dark gray
    ]
    branch_colors = {b: colors[i % len(colors)] for i, b in enumerate(branch_names)}

    # Build edges: draw parallel lines for shared commits (metro-style)
    edges_by_branch = defaultdict(list)  # branch -> list of edge dicts

    for commit in commits_list:
        if commit["parent_id"] and commit["parent_id"] in commit_map:
            parent = commit_map[commit["parent_id"]]

            # Find which branches share both this commit and its parent
            shared_branches = [
                b for b in commit["branches"] if b in parent["branches"]
            ]

            for branch in shared_branches:
                edges_by_branch[branch].append(
                    {
                        "x0": parent["x"],
                        "y0": parent["y"],
                        "x1": commit["x"],
                        "y1": commit["y"],
                    }
                )

    # Create plotly figure
    fig = go.Figure()

    # Draw edges grouped by branch (parallel lines for shared paths)
    for branch_idx, branch in enumerate(branch_names):
        if branch not in edges_by_branch:
            continue

        color = branch_colors[branch]

        # Draw each edge as a separate line
        for edge in edges_by_branch[branch]:
            # Vertical offset for parallel lines (metro-style)
            offset = (branch_idx - (len(branch_names) - 1) / 2) * 0.15

            fig.add_trace(
                go.Scatter(
                    x=[edge["x0"], edge["x1"]],
                    y=[edge["y0"] + offset, edge["y1"] + offset],
                    mode="lines",
                    line=dict(color=color, width=3),
                    hoverinfo="skip",
                    showlegend=False,
                    opacity=0.7,
                )
            )

    # Draw commits (nodes) - one trace per unique commit
    # Color by which branches include it
    x_vals = [c["x"] for c in commits_list]
    y_vals = [c["y"] for c in commits_list]

    # Format hover text
    hover_texts = []
    marker_colors = []
    marker_symbols = []

    for c in commits_list:
        # Handle both string and datetime objects
        if isinstance(c["written_at"], str):
            time_str = datetime.fromisoformat(c["written_at"]).strftime(
                "%Y-%m-%d %H:%M"
            )
        else:
            time_str = c["written_at"].strftime("%Y-%m-%d %H:%M")

        branches_str = ", ".join(c["branches"])
        hover_texts.append(
            f"<b>{c['message'] or 'No message'}</b><br>"
            f"Commit: {c['id'][:12]}<br>"
            f"Branches: {branches_str}<br>"
            f"Time: {time_str}"
        )

        # Color by first branch (priority: main)
        if "main" in c["branches"]:
            marker_colors.append(branch_colors["main"])
        else:
            marker_colors.append(branch_colors[c["branches"][0]])

        # Star for branch tips
        if c["id"] in branch_tips.values():
            marker_symbols.append("star")
        else:
            marker_symbols.append("circle")

    fig.add_trace(
        go.Scatter(
            x=x_vals,
            y=y_vals,
            mode="markers",
            name="Commits",
            marker=dict(
                size=14,
                color=marker_colors,
                symbol=marker_symbols,
                line=dict(color="white", width=2),
            ),
            hovertext=hover_texts,
            hoverinfo="text",
            showlegend=False,
        )
    )

    # Add legend traces (invisible points just for legend)
    for branch_idx, branch in enumerate(branch_names):
        fig.add_trace(
            go.Scatter(
                x=[None],
                y=[None],
                mode="markers",
                name=branch,
                marker=dict(
                    size=10,
                    color=branch_colors[branch],
                    line=dict(color="white", width=2),
                ),
                showlegend=True,
            )
        )

    # Layout styling
    title_text = (
        f"Commit Graph: {self.site_name} ({len(commits_list)} commits, "
        f"{len(branch_names)} branches)"
    )
    fig.update_layout(
        title=dict(
            text=title_text,
            font=dict(size=16, color="#e5e5e5"),
        ),
        xaxis=dict(
            title="Time (oldest ← → newest)",
            showticklabels=False,
            showgrid=True,
            gridcolor="rgba(255,255,255,0.1)",
            zeroline=False,
        ),
        yaxis=dict(
            title="",
            showticklabels=False,
            showgrid=False,
            zeroline=False,
            range=[-1, 1],  # Fixed range for single timeline
        ),
        plot_bgcolor="#1a1a1a",
        paper_bgcolor="#1a1a1a",
        font=dict(color="#e5e5e5"),
        hovermode="closest",
        height=400,
        width=max(800, len(commits_list) * 50),
        legend=dict(
            title="Branches",
            orientation="h",
            x=0,
            y=-0.15,
            bgcolor="rgba(30,30,30,0.8)",
            bordercolor="rgba(255,255,255,0.2)",
            borderwidth=1,
        ),
    )

    return fig

cleanup_stale_branches(keep_patterns=None)

Delete stale temporary branches (e.g., from failed rechunking).

Parameters

keep_patterns : list[str] | None Patterns to preserve. Default: ["main", "dev"]

Returns

list[str] Names of deleted branches

Source code in packages/canvod-store/src/canvod/store/store.py
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
def cleanup_stale_branches(
    self, keep_patterns: list[str] | None = None
) -> list[str]:
    """
    Delete stale temporary branches (e.g., from failed rechunking).

    Parameters
    ----------
    keep_patterns : list[str] | None
        Patterns to preserve. Default: ["main", "dev"]

    Returns
    -------
    list[str]
        Names of deleted branches
    """
    if keep_patterns is None:
        keep_patterns = ["main", "dev"]

    deleted = []

    for branch in self.repo.list_branches():
        # Keep if matches any pattern
        should_keep = any(pattern in branch for pattern in keep_patterns)

        if not should_keep:
            # Check if it's a temp branch from rechunking
            if "_rechunked_temp" in branch or "_temp" in branch:
                try:
                    self.repo.delete_branch(branch)
                    deleted.append(branch)
                    self._logger.info(f"Deleted stale branch: {branch}")
                except Exception as e:
                    self._logger.warning(f"Failed to delete branch {branch}: {e}")

    return deleted

delete_branch(branch_name)

Delete a branch.

Source code in packages/canvod-store/src/canvod/store/store.py
2785
2786
2787
2788
2789
2790
2791
def delete_branch(self, branch_name: str) -> None:
    """Delete a branch."""
    if branch_name == "main":
        raise ValueError("Cannot delete 'main' branch")

    self.repo.delete_branch(branch_name)
    self._logger.info(f"Deleted branch '{branch_name}'")

get_snapshot_info(snapshot_id)

Get detailed information about a specific snapshot.

Parameters

snapshot_id : str Snapshot ID to inspect

Returns

dict Snapshot metadata and statistics

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_snapshot_info(self, snapshot_id: str) -> dict:
    """
    Get detailed information about a specific snapshot.

    Parameters
    ----------
    snapshot_id : str
        Snapshot ID to inspect

    Returns
    -------
    dict
        Snapshot metadata and statistics
    """
    # Find the snapshot in ancestry
    for ancestor in self.repo.ancestry(branch="main"):
        if ancestor.id == snapshot_id or ancestor.id.startswith(snapshot_id):
            info = {
                "snapshot_id": ancestor.id,
                "message": ancestor.message,
                "written_at": ancestor.written_at,
                "parent_id": ancestor.parent_id,
            }

            # Try to get groups at this snapshot
            try:
                session = self.repo.readonly_session(snapshot_id=ancestor.id)
                root = zarr.open(session.store, mode="r")
                info["groups"] = list(root.group_keys())
                info["arrays"] = list(root.array_keys())
            except Exception as e:
                self._logger.warning(f"Could not inspect snapshot contents: {e}")

            return info

    raise ValueError(f"Snapshot {snapshot_id} not found in history")

compare_snapshots(snapshot_id_1, snapshot_id_2)

Compare two snapshots to see what changed.

Parameters

snapshot_id_1 : str First snapshot (older) snapshot_id_2 : str Second snapshot (newer)

Returns

dict Comparison results showing added/removed/modified groups

Source code in packages/canvod-store/src/canvod/store/store.py
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
def compare_snapshots(self, snapshot_id_1: str, snapshot_id_2: str) -> dict:
    """
    Compare two snapshots to see what changed.

    Parameters
    ----------
    snapshot_id_1 : str
        First snapshot (older)
    snapshot_id_2 : str
        Second snapshot (newer)

    Returns
    -------
    dict
        Comparison results showing added/removed/modified groups
    """
    info_1 = self.get_snapshot_info(snapshot_id_1)
    info_2 = self.get_snapshot_info(snapshot_id_2)

    groups_1 = set(info_1.get("groups", []))
    groups_2 = set(info_2.get("groups", []))

    return {
        "snapshot_1": snapshot_id_1[:8],
        "snapshot_2": snapshot_id_2[:8],
        "added_groups": list(groups_2 - groups_1),
        "removed_groups": list(groups_1 - groups_2),
        "common_groups": list(groups_1 & groups_2),
        "time_diff": (info_2["written_at"] - info_1["written_at"]).total_seconds(),
    }

maintenance(expire_days=7, cleanup_branches=True, run_gc=True)

Run full maintenance on the store.

Parameters

expire_days : int Days of snapshot history to keep cleanup_branches : bool Remove stale temporary branches run_gc : bool Run garbage collection after expiration

Returns

dict Summary of maintenance actions

Source code in packages/canvod-store/src/canvod/store/store.py
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
def maintenance(
    self, expire_days: int = 7, cleanup_branches: bool = True, run_gc: bool = True
) -> dict:
    """
    Run full maintenance on the store.

    Parameters
    ----------
    expire_days : int
        Days of snapshot history to keep
    cleanup_branches : bool
        Remove stale temporary branches
    run_gc : bool
        Run garbage collection after expiration

    Returns
    -------
    dict
        Summary of maintenance actions
    """
    self._logger.info(f"Starting maintenance on {self.store_type}")

    results = {"expired_snapshots": 0, "deleted_branches": [], "gc_summary": None}

    # Expire old snapshots
    expired_ids = self.expire_old_snapshots(days=expire_days)
    results["expired_snapshots"] = len(expired_ids)

    # Cleanup stale branches
    if cleanup_branches:
        deleted_branches = self.cleanup_stale_branches()
        results["deleted_branches"] = deleted_branches

    # Garbage collection
    if run_gc:
        from datetime import datetime, timedelta

        cutoff = datetime.now(UTC) - timedelta(days=expire_days)
        gc_summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
        results["gc_summary"] = {
            "bytes_deleted": gc_summary.bytes_deleted,
            "chunks_deleted": gc_summary.chunks_deleted,
            "manifests_deleted": gc_summary.manifests_deleted,
        }

    self._logger.info(f"Maintenance complete: {results}")
    return results

sanitize_store(source_branch='main', temp_branch='sanitize_temp', promote_to_main=True, delete_temp_branch=True)

Sanitize all groups by removing NaN-only SIDs and cleaning coordinates.

Creates a temporary branch, applies sanitization to all groups, then optionally promotes to main and cleans up.

Parameters

source_branch : str, default "main" Branch to read original data from. temp_branch : str, default "sanitize_temp" Temporary branch name for sanitized data. promote_to_main : bool, default True If True, reset main branch to sanitized snapshot after writing. delete_temp_branch : bool, default True If True, delete temporary branch after promotion.

Returns

str Snapshot ID of the sanitized data.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def sanitize_store(
    self,
    source_branch: str = "main",
    temp_branch: str = "sanitize_temp",
    promote_to_main: bool = True,
    delete_temp_branch: bool = True,
) -> str:
    """
    Sanitize all groups by removing NaN-only SIDs and cleaning coordinates.

    Creates a temporary branch, applies sanitization to all groups, then
    optionally promotes to main and cleans up.

    Parameters
    ----------
    source_branch : str, default "main"
        Branch to read original data from.
    temp_branch : str, default "sanitize_temp"
        Temporary branch name for sanitized data.
    promote_to_main : bool, default True
        If True, reset main branch to sanitized snapshot after writing.
    delete_temp_branch : bool, default True
        If True, delete temporary branch after promotion.

    Returns
    -------
    str
        Snapshot ID of the sanitized data.
    """
    import time

    from icechunk.xarray import to_icechunk

    print(f"\n{'=' * 60}")
    print("Starting store sanitization")
    print(f"{'=' * 60}\n")

    # Step 1: Get current snapshot
    print(f"[1/6] Getting current snapshot from '{source_branch}'...")
    current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
    print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

    # Step 2: Create temp branch
    print(f"\n[2/6] Creating temporary branch '{temp_branch}'...")
    try:
        self.repo.create_branch(temp_branch, current_snapshot)
        print(f"      ✓ Branch '{temp_branch}' created")
    except Exception:
        print("      ⚠ Branch exists, deleting and recreating...")
        self.delete_branch(temp_branch)
        self.repo.create_branch(temp_branch, current_snapshot)
        print(f"      ✓ Branch '{temp_branch}' created")

    # Step 3: Get all groups
    print("\n[3/6] Discovering groups...")
    groups = self.list_groups()
    print(f"      ✓ Found {len(groups)} groups: {groups}")

    # Step 4: Sanitize each group
    print("\n[4/6] Sanitizing groups...")
    sanitized_count = 0

    for group_name in groups:
        print(f"\n      Processing '{group_name}'...")
        t_start = time.time()

        try:
            # Read original data
            ds_original = self.read_group(group_name, branch=source_branch)
            original_sids = len(ds_original.sid)
            print(f"        • Original: {original_sids} SIDs")

            # Sanitize: remove SIDs with all-NaN data
            ds_sanitized = self._sanitize_dataset(ds_original)
            sanitized_sids = len(ds_sanitized.sid)
            removed_sids = original_sids - sanitized_sids

            print(
                f"        • Sanitized: {sanitized_sids} SIDs "
                f"(removed {removed_sids})"
            )

            # Write sanitized data
            with self.writable_session(temp_branch) as session:
                to_icechunk(ds_sanitized, session, group=group_name, mode="w")

                # Copy metadata subgroups if they exist
                try:
                    with self.readonly_session(source_branch) as read_session:
                        source_group = zarr.open_group(
                            read_session.store, mode="r"
                        )[group_name]
                        if "metadata" in source_group.group_keys():
                            # Copy entire metadata subgroup
                            dest_group = zarr.open_group(session.store)[group_name]
                            zarr.copy(
                                source_group["metadata"],
                                dest_group,
                                name="metadata",
                            )
                            print("        • Copied metadata subgroup")
                except Exception as e:
                    print(f"        ⚠ Could not copy metadata: {e}")

                session.commit(
                    f"Sanitized {group_name}: removed {removed_sids} empty SIDs"
                )

            t_elapsed = time.time() - t_start
            print(f"        ✓ Completed in {t_elapsed:.2f}s")
            sanitized_count += 1

        except Exception as e:
            print(f"        ✗ Failed: {e}")
            continue

    print(f"\n      ✓ Sanitized {sanitized_count}/{len(groups)} groups")

    # Step 5: Get final snapshot
    print("\n[5/6] Getting sanitized snapshot...")
    sanitized_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
    print(f"      ✓ Snapshot: {sanitized_snapshot[:12]}")

    # Step 6: Promote to main
    if promote_to_main:
        print(f"\n[6/6] Promoting to '{source_branch}' branch...")
        self.repo.reset_branch(source_branch, sanitized_snapshot)
        print(
            f"      ✓ Branch '{source_branch}' reset to {sanitized_snapshot[:12]}"
        )

        if delete_temp_branch:
            print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
            self.delete_branch(temp_branch)
            print("      ✓ Temporary branch deleted")
    else:
        print("\n[6/6] Skipping promotion (promote_to_main=False)")
        print(f"      Sanitized data available on branch '{temp_branch}'")

    print(f"\n{'=' * 60}")
    print("✓ Sanitization complete")
    print(f"{'=' * 60}\n")

    return sanitized_snapshot

safe_temporal_aggregate(group, freq='1D', vars_to_aggregate=('VOD',), geometry_vars=('phi', 'theta'), drop_empty=True, branch='main')

Aggregate temporally irregular VOD data per SID.

Each satellite (SID) is aggregated independently within each time bin. Mixing observations across satellites is physically meaningless because each observes a different part of the canopy from a different sky position.

.. note::

For production use, prefer canvod.ops.TemporalAggregate which uses Polars groupby and handles all coordinate types explicitly. This method is a convenience wrapper for quick interactive exploration.

Parameters

group : str Group name to aggregate. freq : str, default "1D" Resample frequency string. vars_to_aggregate : Sequence[str], optional Variables to aggregate using mean. geometry_vars : Sequence[str], optional Geometry variables to aggregate using mean (centroid of contributing sky positions). drop_empty : bool, default True Drop empty epochs after aggregation. branch : str, default "main" Branch name to read from.

Returns

xr.Dataset Aggregated dataset with independent per-SID aggregation.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def safe_temporal_aggregate(
    self,
    group: str,
    freq: str = "1D",
    vars_to_aggregate: Sequence[str] = ("VOD",),
    geometry_vars: Sequence[str] = ("phi", "theta"),
    drop_empty: bool = True,
    branch: str = "main",
) -> xr.Dataset:
    """Aggregate temporally irregular VOD data per SID.

    Each satellite (SID) is aggregated independently within each
    time bin.  Mixing observations across satellites is physically
    meaningless because each observes a different part of the canopy
    from a different sky position.

    .. note::

       For production use, prefer ``canvod.ops.TemporalAggregate``
       which uses Polars groupby and handles all coordinate types
       explicitly.  This method is a convenience wrapper for quick
       interactive exploration.

    Parameters
    ----------
    group : str
        Group name to aggregate.
    freq : str, default "1D"
        Resample frequency string.
    vars_to_aggregate : Sequence[str], optional
        Variables to aggregate using mean.
    geometry_vars : Sequence[str], optional
        Geometry variables to aggregate using mean (centroid of
        contributing sky positions).
    drop_empty : bool, default True
        Drop empty epochs after aggregation.
    branch : str, default "main"
        Branch name to read from.

    Returns
    -------
    xr.Dataset
        Aggregated dataset with independent per-SID aggregation.
    """
    log = get_logger(__name__)

    with self.readonly_session(branch=branch) as session:
        ds = xr.open_zarr(session.store, group=group, consolidated=False)

        log.info(
            "Aggregating group",
            group=group,
            branch=branch,
            freq=freq,
        )

        # Aggregate data and geometry vars with mean (per SID
        # independently — resample preserves the sid dimension).
        all_vars = list(vars_to_aggregate) + list(geometry_vars)
        merged_vars = []
        for var in all_vars:
            if var in ds:
                merged_vars.append(ds[var].resample(epoch=freq).mean())
            else:
                log.warning("Skipping missing variable", var=var)
        ds_agg = xr.merge(merged_vars)

        # Preserve sid-only coordinates (sv, band, code, etc.)
        for coord in ds.coords:
            if coord in ds_agg.coords or coord == "epoch":
                continue
            coord_dims = ds.coords[coord].dims
            # Only copy coords whose dims all survive in ds_agg
            if all(d in ds_agg.dims for d in coord_dims):
                ds_agg[coord] = ds[coord]

        # Drop all-NaN epochs if requested
        if drop_empty and "VOD" in ds_agg:
            valid_mask = ds_agg["VOD"].notnull().any(dim="sid").compute()
            ds_agg = ds_agg.isel(epoch=valid_mask)

        log.info("Aggregation done", sizes=dict(ds_agg.sizes))
        return ds_agg

safe_temporal_aggregate_to_branch(source_group, target_group, target_branch, freq='1D', overwrite=False, **kwargs)

Aggregate a group and save to a new Icechunk branch/group.

Parameters

source_group : str Source group name. target_group : str Target group name. target_branch : str Target branch name. freq : str, default "1D" Resample frequency string. overwrite : bool, default False Whether to overwrite an existing branch. **kwargs : Any Additional keyword args passed to safe_temporal_aggregate().

Returns

xr.Dataset Aggregated dataset written to the target branch.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def safe_temporal_aggregate_to_branch(
    self,
    source_group: str,
    target_group: str,
    target_branch: str,
    freq: str = "1D",
    overwrite: bool = False,
    **kwargs: Any,
) -> xr.Dataset:
    """Aggregate a group and save to a new Icechunk branch/group.

    Parameters
    ----------
    source_group : str
        Source group name.
    target_group : str
        Target group name.
    target_branch : str
        Target branch name.
    freq : str, default "1D"
        Resample frequency string.
    overwrite : bool, default False
        Whether to overwrite an existing branch.
    **kwargs : Any
        Additional keyword args passed to safe_temporal_aggregate().

    Returns
    -------
    xr.Dataset
        Aggregated dataset written to the target branch.
    """

    print(
        f"🚀 Creating new aggregated branch '{target_branch}' at '{target_group}'"
    )

    # Compute safe aggregation
    ds_agg = self.safe_temporal_aggregate(
        group=source_group,
        freq=freq,
        **kwargs,
    )

    # Write to new branch
    current_snapshot = next(self.repo.ancestry(branch="main")).id
    self.delete_branch(target_branch)
    self.repo.create_branch(target_branch, current_snapshot)
    with self.writable_session(target_branch) as session:
        to_icechunk(
            obj=ds_agg,
            session=session,
            group=target_group,
            mode="w",
        )
        session.commit(f"Saved aggregated data to {target_group} at freq={freq}")

    print(
        f"✅ Saved aggregated dataset to branch '{target_branch}' "
        f"(group '{target_group}')"
    )
    return ds_agg

GnssResearchSite

High-level manager for a GNSS research site with dual Icechunk stores.

This class coordinates between RINEX data storage (Level 1) and VOD analysis storage (Level 2), providing a unified interface for site-wide operations.

Architecture: - RINEX Store: Raw/standardized observations per receiver - VOD Store: Analysis products comparing receiver pairs

Features: - Automatic store initialization from config - Receiver management and validation - Analysis workflow coordination - Unified logging and error handling

Parameters

site_name : str Name of the research site (must exist in config).

Raises

KeyError If site_name is not found in the RESEARCH_SITES config.

Source code in packages/canvod-store/src/canvod/store/manager.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
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
class GnssResearchSite:
    """
    High-level manager for a GNSS research site with dual Icechunk stores.

    This class coordinates between RINEX data storage (Level 1) and
    VOD analysis storage (Level 2), providing a unified interface
    for site-wide operations.

    Architecture:
    - RINEX Store: Raw/standardized observations per receiver
    - VOD Store: Analysis products comparing receiver pairs

    Features:
    - Automatic store initialization from config
    - Receiver management and validation
    - Analysis workflow coordination
    - Unified logging and error handling

    Parameters
    ----------
    site_name : str
        Name of the research site (must exist in config).

    Raises
    ------
    KeyError
        If ``site_name`` is not found in the RESEARCH_SITES config.
    """

    def __init__(self, site_name: str) -> None:
        """Initialize the site manager.

        Parameters
        ----------
        site_name : str
            Name of the research site.
        """
        from canvod.utils.config import load_config

        config = load_config()
        sites = config.sites.sites

        if site_name not in sites:
            available_sites = list(sites.keys())
            raise KeyError(
                f"Site '{site_name}' not found in config. "
                f"Available sites: {available_sites}"
            )

        self.site_name = site_name
        self._site_config = sites[site_name]
        self._logger = get_logger(__name__).bind(site=site_name)

        rinex_store_path = config.processing.storage.get_rinex_store_path(site_name)
        vod_store_path = config.processing.storage.get_vod_store_path(site_name)

        # Initialize stores using paths from processing.yaml
        self.rinex_store = create_rinex_store(rinex_store_path)
        self.vod_store = create_vod_store(vod_store_path)

        self._logger.info(
            f"Initialized GNSS research site: {site_name}",
            rinex_store=str(rinex_store_path),
            vod_store=str(vod_store_path),
        )

    @property
    def site_config(self) -> dict[str, Any]:
        """Get the site configuration as a dictionary."""
        return self._site_config.model_dump()

    @property
    def receivers(self) -> dict[str, dict[str, Any]]:
        """Get all configured receivers for this site."""
        return {
            name: cfg.model_dump() for name, cfg in self._site_config.receivers.items()
        }

    @property
    def active_receivers(self) -> dict[str, dict[str, Any]]:
        """Get only active receivers for this site."""
        return {
            name: config
            for name, config in self.receivers.items()
            if config.get("active", True)
        }

    @property
    def vod_analyses(self) -> dict[str, VodAnalysisConfig]:
        """Get all configured VOD analyses for this site.

        Returns auto-derived analyses from scs_from if no explicit
        vod_analyses are configured.
        """
        if self._site_config.vod_analyses is not None:
            return dict(self._site_config.vod_analyses)
        return self.get_auto_vod_analyses()

    @property
    def active_vod_analyses(self) -> dict[str, VodAnalysisConfig]:
        """Get only active VOD analyses for this site."""
        return {
            name: config
            for name, config in self.vod_analyses.items()
            if getattr(config, "active", True)
        }

    def get_receiver_metadata(
        self, receiver_name: str
    ) -> dict[str, str | int | float | bool] | None:
        """Get freeform metadata for a receiver.

        Returns the ``metadata`` dict from ``ReceiverConfig`` in
        ``sites.yaml``, or ``None`` if not configured.

        Parameters
        ----------
        receiver_name : str
            Name of the receiver.

        Returns
        -------
        dict or None
            Receiver metadata dict, or None.
        """
        cfg = self._site_config.receivers.get(receiver_name)
        if cfg is None:
            return None
        return cfg.metadata

    @classmethod
    def from_rinex_store_path(
        cls,
        rinex_store_path: Path,
    ) -> GnssResearchSite:
        """
        Create a GnssResearchSite instance from a RINEX store path.

        Parameters
        ----------
        rinex_store_path : Path
            Path to the RINEX Icechunk store.

        Returns
        -------
        GnssResearchSite
            Initialized research site manager.

        Raises
        ------
        ValueError
            If no matching site is found for the given path.
        """
        # Load config to get store paths
        from canvod.utils.config import load_config

        config = load_config()

        # Try to match against each site's expected rinex store path
        for site_name in config.sites.sites.keys():
            expected_path = config.processing.storage.get_rinex_store_path(site_name)
            if expected_path == rinex_store_path:
                return cls(site_name)

        raise ValueError(
            f"No research site found for RINEX store path: {rinex_store_path}"
        )

    def get_reference_canopy_pairs(self) -> list[tuple[str, str]]:
        """Expand scs_from into (reference_name, canopy_name) pairs.

        Returns
        -------
        list[tuple[str, str]]
            List of (reference_name, canopy_name) pairs.
        """
        return self._site_config.get_reference_canopy_pairs()

    def get_auto_vod_analyses(self) -> dict[str, VodAnalysisConfig]:
        """Derive VOD analysis pairs from scs_from configuration.

        Creates one VOD pair per (canopy, reference_for_that_canopy) combination.

        Returns
        -------
        dict[str, VodAnalysisConfig]
            Auto-derived VOD analyses keyed by analysis name.
        """
        analyses: dict[str, VodAnalysisConfig] = {}
        for ref_name, canopy_name in self.get_reference_canopy_pairs():
            analysis_name = f"{canopy_name}_vs_{ref_name}"
            analyses[analysis_name] = VodAnalysisConfig(
                canopy_receiver=canopy_name,
                reference_receiver=f"{ref_name}_{canopy_name}",
                description=f"VOD analysis {canopy_name} vs {ref_name}",
            )
        return analyses

    def validate_site_config(self) -> bool:
        """
        Validate that the site configuration is consistent.

        Returns
        -------
        bool
            True if configuration is valid.

        Raises
        ------
        ValueError
            If configuration is invalid.
        """
        # Check that all VOD analyses reference valid receivers
        # Build set of valid reference store groups (e.g. reference_01_canopy_01)
        valid_ref_groups = {
            f"{ref}_{canopy}" for ref, canopy in self.get_reference_canopy_pairs()
        }

        for analysis_name, analysis_config in self.vod_analyses.items():
            canopy_rx = analysis_config.canopy_receiver
            ref_rx = analysis_config.reference_receiver

            if canopy_rx not in self.receivers:
                raise ValueError(
                    f"VOD analysis '{analysis_name}' references "
                    f"unknown canopy receiver: {canopy_rx}"
                )
            # ref_rx can be either a raw receiver name or a store group name
            if ref_rx not in self.receivers and ref_rx not in valid_ref_groups:
                raise ValueError(
                    f"VOD analysis '{analysis_name}' references "
                    f"unknown reference receiver/group: {ref_rx}"
                )

            # Check canopy type
            canopy_type = self.receivers[canopy_rx]["type"]
            if canopy_type != "canopy":
                raise ValueError(
                    f"Receiver '{canopy_rx}' used as canopy but type is '{canopy_type}'"
                )
            # Check reference type (only if it's a raw receiver name)
            if ref_rx in self.receivers:
                ref_type = self.receivers[ref_rx]["type"]
                if ref_type != "reference":
                    raise ValueError(
                        f"Receiver '{ref_rx}' used as reference"
                        f" but type is '{ref_type}'"
                    )

        self._logger.debug("Site configuration validation passed")
        return True

    def get_receiver_groups(self) -> list[str]:
        """
        Get list of receiver groups that exist in the RINEX store.

        Returns
        -------
        list[str]
            Existing receiver group names.
        """
        return self.rinex_store.list_groups()

    def get_vod_analysis_groups(self) -> list[str]:
        """
        Get list of VOD analysis groups that exist in the VOD store.

        Returns
        -------
        list[str]
            Existing VOD analysis group names.
        """
        return self.vod_store.list_groups()

    def ingest_receiver_data(
        self, dataset: xr.Dataset, receiver_name: str, commit_message: str | None = None
    ) -> None:
        """
        Ingest RINEX data for a specific receiver.

        Parameters
        ----------
        dataset : xr.Dataset
            Processed RINEX dataset to store.
        receiver_name : str
            Name of the receiver (must be configured).
        commit_message : str, optional
            Commit message to store with the data.

        Raises
        ------
        ValueError
            If ``receiver_name`` is not configured.
        """
        if receiver_name not in self.receivers:
            available_receivers = list(self.receivers.keys())
            raise ValueError(
                f"Receiver '{receiver_name}' not configured. "
                f"Available: {available_receivers}"
            )

        # Merge receiver metadata into dataset attrs (never overwrite existing)
        receiver_meta = self.get_receiver_metadata(receiver_name)
        if receiver_meta:
            skipped = {k for k in receiver_meta if k in dataset.attrs}
            if skipped:
                self._logger.warning(
                    f"Receiver metadata keys {skipped} already exist in "
                    f"dataset attrs — skipping (existing attrs take precedence)"
                )
            new_attrs = {
                k: v for k, v in receiver_meta.items() if k not in dataset.attrs
            }
            dataset.attrs.update(new_attrs)

        self._logger.info(f"Ingesting RINEX data for receiver '{receiver_name}'")

        self.rinex_store.write_or_append_group(
            dataset=dataset, group_name=receiver_name, commit_message=commit_message
        )

        self._logger.info(f"Successfully ingested data for receiver '{receiver_name}'")

    def read_receiver_data(
        self, receiver_name: str, time_range: tuple[datetime, datetime] | None = None
    ) -> xr.Dataset:
        """
        Read data from a specific receiver.

        Parameters
        ----------
        receiver_name : str
            Name of the receiver.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the data.

        Returns
        -------
        xr.Dataset
            Dataset containing receiver observations.

        Raises
        ------
        ValueError
            If the receiver group does not exist.
        """
        if not self.rinex_store.group_exists(receiver_name):
            available_groups = self.get_receiver_groups()
            raise ValueError(
                f"No data found for receiver '{receiver_name}'. "
                f"Available: {available_groups}"
            )

        self._logger.info(f"Reading data for receiver '{receiver_name}'")

        if self.rinex_store._rinex_store_strategy == "append":
            ds = self.rinex_store.read_group_deduplicated(receiver_name, keep="last")
        else:
            ds = self.rinex_store.read_group(receiver_name)

        # Apply time filtering if specified
        if time_range is not None:
            start_time, end_time = time_range
            ds = ds.where(
                (ds.epoch >= np.datetime64(start_time, "ns"))
                & (ds.epoch <= np.datetime64(end_time, "ns")),
                drop=True,
            )

            self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

        return ds

    def store_vod_analysis(
        self,
        vod_dataset: xr.Dataset,
        analysis_name: str,
        commit_message: str | None = None,
    ) -> None:
        """
        Store VOD analysis results.

        Parameters
        ----------
        vod_dataset : xr.Dataset
            Dataset containing VOD analysis results.
        analysis_name : str
            Name of the analysis (must be configured).
        commit_message : str, optional
            Commit message to store with the results.

        Raises
        ------
        ValueError
            If ``analysis_name`` is not configured.
        """
        if analysis_name not in self.vod_analyses:
            available_analyses = list(self.vod_analyses.keys())
            raise ValueError(
                f"VOD analysis '{analysis_name}' not configured. "
                f"Available: {available_analyses}"
            )

        self._logger.info(f"Storing VOD analysis results: '{analysis_name}'")

        self.vod_store.write_or_append_group(
            dataset=vod_dataset, group_name=analysis_name, commit_message=commit_message
        )

        self._logger.info(f"Successfully stored VOD analysis: '{analysis_name}'")

    def read_vod_analysis(
        self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
    ) -> xr.Dataset:
        """
        Read VOD analysis results.

        Parameters
        ----------
        analysis_name : str
            Name of the analysis.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the results.

        Returns
        -------
        xr.Dataset
            Dataset containing VOD analysis results.

        Raises
        ------
        ValueError
            If the analysis group does not exist.
        """
        if not self.vod_store.group_exists(analysis_name):
            available_groups = self.get_vod_analysis_groups()
            raise ValueError(
                f"No VOD results found for analysis '{analysis_name}'. "
                f"Available: {available_groups}"
            )

        self._logger.info(f"Reading VOD analysis: '{analysis_name}'")

        ds = self.vod_store.read_group(analysis_name)

        # Apply time filtering if specified
        if time_range is not None:
            start_time, end_time = time_range
            ds = ds.sel(epoch=slice(start_time, end_time))
            self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

        return ds

    def prepare_vod_input_data(
        self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
    ) -> tuple[xr.Dataset, xr.Dataset]:
        """
        Prepare aligned input data for VOD analysis.

        Reads data from both receivers specified in the analysis configuration
        and returns them aligned for VOD processing.

        Parameters
        ----------
        analysis_name : str
            Name of the VOD analysis configuration.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the data.

        Returns
        -------
        tuple of (xr.Dataset, xr.Dataset)
            Tuple of (canopy_dataset, reference_dataset).

        Raises
        ------
        ValueError
            If the analysis is not configured or data is missing.
        """
        if analysis_name not in self.vod_analyses:
            available_analyses = list(self.vod_analyses.keys())
            raise ValueError(
                f"VOD analysis '{analysis_name}' not configured. "
                f"Available: {available_analyses}"
            )

        analysis_config = self.vod_analyses[analysis_name]
        canopy_receiver = analysis_config.canopy_receiver
        reference_receiver = analysis_config.reference_receiver

        self._logger.info(
            f"Preparing VOD input data: {canopy_receiver} vs {reference_receiver}"
        )

        # Read data from both receivers
        canopy_data = self.read_receiver_data(canopy_receiver, time_range)
        reference_data = self.read_receiver_data(reference_receiver, time_range)

        self._logger.info(
            f"Loaded data - Canopy: {dict(canopy_data.dims)}, "
            f"Reference: {dict(reference_data.dims)}"
        )

        return canopy_data, reference_data

    def calculate_vod(
        self,
        analysis_name: str,
        calculator_class: type[VODCalculator] | None = None,
        time_range: tuple[datetime, datetime] | None = None,
    ) -> xr.Dataset:
        """
        Calculate VOD for a configured analysis pair.

        Parameters
        ----------
        analysis_name : str
            Analysis name from config (e.g., 'canopy_01_vs_reference_01')
        calculator_class : type[VODCalculator], optional
            VOD calculator class to use. If None, uses TauOmegaZerothOrder.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the data

        Returns
        -------
        xr.Dataset
            VOD dataset

        Note
        ----
        Requires canvod-vod to be installed.
        """
        if calculator_class is None:
            try:
                from canvod.vod import TauOmegaZerothOrder

                calculator_class = TauOmegaZerothOrder
            except ImportError as e:
                raise ImportError(
                    "canvod-vod package required for VOD calculation. "
                    "Install with: pip install canvod-vod"
                ) from e

        canopy_ds, reference_ds = self.prepare_vod_input_data(analysis_name, time_range)

        # Align once so we can access both r arrays for radial_diff before
        # passing to the calculator (which would otherwise re-align internally).
        canopy_aligned, reference_aligned = xr.align(
            canopy_ds, reference_ds, join="inner"
        )

        # Use the calculator's class method for calculation (alignment already done)
        vod_ds = calculator_class.from_datasets(
            canopy_aligned, reference_aligned, align=False
        )

        # Apply config-gated derived quantities
        from canvod.utils.config import load_config as _load_config

        _params = _load_config().processing.processing

        if not _params.store_delta_snr:
            vod_ds = vod_ds.drop_vars("delta_snr", errors="ignore")

        if _params.store_radial_diff:
            if "r" in canopy_aligned and "r" in reference_aligned:
                radial_diff = canopy_aligned["r"] - reference_aligned["r"]
                radial_diff.attrs["units"] = "m"
                radial_diff.attrs["long_name"] = (
                    "radial distance difference (canopy − reference)"
                )
                vod_ds["radial_diff"] = radial_diff
            else:
                self._logger.warning(
                    "store_radial_diff=true but 'r' not present in receiver data; "
                    "set store_radial_distance=true at ingest time to enable this"
                )

        # Add metadata
        analysis_config = self.vod_analyses[analysis_name]
        vod_ds.attrs["analysis_name"] = analysis_name
        vod_ds.attrs["canopy_receiver"] = analysis_config.canopy_receiver
        vod_ds.attrs["reference_receiver"] = analysis_config.reference_receiver
        vod_ds.attrs["calculator"] = calculator_class.__name__
        vod_ds.attrs["canopy_hash"] = canopy_ds.attrs.get("File Hash", "unknown")
        vod_ds.attrs["reference_hash"] = reference_ds.attrs.get("File Hash", "unknown")

        self._logger.info(
            f"VOD calculated for {analysis_name} using {calculator_class.__name__}"
        )
        return vod_ds

    def store_vod(
        self,
        vod_ds: xr.Dataset,
        analysis_name: str,
    ) -> str:
        """
        Store VOD dataset in VOD store.

        Parameters
        ----------
        vod_ds : xr.Dataset
            VOD dataset to store
        analysis_name : str
            Analysis name (group name in store)

        Returns
        -------
        str
            Snapshot ID
        """
        import importlib.metadata

        from icechunk.xarray import to_icechunk

        canopy_hash = vod_ds.attrs.get("canopy_hash", "unknown")
        reference_hash = vod_ds.attrs.get("reference_hash", "unknown")
        combined_hash = f"{canopy_hash}_{reference_hash}"

        with self.vod_store.writable_session() as session:
            groups = self.vod_store.list_groups() or []

            if analysis_name not in groups:
                to_icechunk(vod_ds, session, group=analysis_name, mode="w")
                action = "write"
            else:
                to_icechunk(vod_ds, session, group=analysis_name, append_dim="epoch")
                action = "append"

            version = importlib.metadata.version("canvodpy")
            commit_msg = f"[v{version}] VOD for {analysis_name}"
            snapshot_id = session.commit(commit_msg)

        self.vod_store.append_metadata(
            group_name=analysis_name,
            rinex_hash=combined_hash,
            start=vod_ds["epoch"].values[0],
            end=vod_ds["epoch"].values[-1],
            snapshot_id=snapshot_id,
            action=action,
            commit_msg=commit_msg,
            dataset_attrs=dict(vod_ds.attrs),
        )

        self._logger.info(
            f"VOD stored for {analysis_name}, snapshot={snapshot_id[:8]}..."
        )
        return snapshot_id

    def get_site_summary(self) -> dict[str, Any]:
        """
        Get a comprehensive summary of the research site.

        Returns
        -------
        dict
            Dictionary with site statistics, data availability, and store paths.
        """
        rinex_groups = self.get_receiver_groups()
        vod_groups = self.get_vod_analysis_groups()

        summary: dict[str, Any] = {
            "site_name": self.site_name,
            "site_config": {
                "total_receivers": len(self.receivers),
                "active_receivers": len(self.active_receivers),
                "total_vod_analyses": len(self.vod_analyses),
                "active_vod_analyses": len(self.active_vod_analyses),
            },
            "data_status": {
                "rinex_groups_exist": len(rinex_groups),
                "rinex_groups": rinex_groups,
                "vod_groups_exist": len(vod_groups),
                "vod_groups": vod_groups,
            },
            "stores": {
                "rinex_store_path": str(self.rinex_store.store_path),
                "vod_store_path": str(self.vod_store.store_path),
            },
        }

        # Add receiver details
        summary["receivers"] = {}
        for receiver_name, receiver_config in self.active_receivers.items():
            has_data = receiver_name in rinex_groups
            summary["receivers"][receiver_name] = {
                "type": receiver_config["type"],
                "description": receiver_config["description"],
                "has_data": has_data,
            }

            if has_data:
                try:
                    info = self.rinex_store.get_group_info(receiver_name)
                    summary["receivers"][receiver_name]["data_info"] = {
                        "dimensions": info["dimensions"],
                        "variables": len(info["variables"]),
                        "temporal_info": info.get("temporal_info", {}),
                    }
                except Exception as e:
                    self._logger.warning(f"Failed to get info for {receiver_name}: {e}")

        # Add VOD analysis details
        summary["vod_analyses"] = {}
        for analysis_name, analysis_config in self.active_vod_analyses.items():
            has_results = analysis_name in vod_groups
            summary["vod_analyses"][analysis_name] = {
                "canopy_receiver": analysis_config.canopy_receiver,
                "reference_receiver": analysis_config.reference_receiver,
                "description": analysis_config.description,
                "has_results": has_results,
            }

            if has_results:
                try:
                    info = self.vod_store.get_group_info(analysis_name)
                    summary["vod_analyses"][analysis_name]["results_info"] = {
                        "dimensions": info["dimensions"],
                        "variables": len(info["variables"]),
                        "temporal_info": info.get("temporal_info", {}),
                    }
                except Exception as e:
                    self._logger.warning(
                        f"Failed to get VOD info for {analysis_name}: {e}"
                    )

        return summary

    def is_day_complete(
        self,
        yyyydoy: str,
        receiver_types: list[str] | None = None,
        completeness_threshold: float = 0.95,
    ) -> bool:
        """
        Check if a day has complete data coverage for all receiver types.

        Parameters
        ----------
        yyyydoy : str
            Date in YYYYDOY format (e.g., "2024256")
        receiver_types : List[str], optional
            Receiver types to check. Defaults to ['canopy', 'reference']
        completeness_threshold : float
            Fraction of expected epochs that must exist (default 0.95 = 95%)
            Allows for small gaps due to receiver issues

        Returns
        -------
        bool
            True if all receiver types have complete data for this day
        """
        if receiver_types is None:
            receiver_types = ["canopy", "reference"]

        from canvod.utils.tools import YYYYDOY

        yyyydoy_obj = YYYYDOY.from_str(yyyydoy)

        # Expected epochs for 24h at 30s sampling
        expected_epochs = int(24 * 3600 / 30)  # 2880 epochs
        required_epochs = int(expected_epochs * completeness_threshold)

        for receiver_type in receiver_types:
            # Get receiver name for this type
            receiver_name = None
            for name, config in self.active_receivers.items():
                if config.get("type") == receiver_type:
                    receiver_name = name
                    break

            if not receiver_name:
                self._logger.warning(f"No receiver configured for type {receiver_type}")
                return False

            try:
                # Try to read data for this day
                import datetime as _dt

                assert yyyydoy_obj.date is not None
                _day_start = datetime.combine(yyyydoy_obj.date, _dt.time.min)
                time_range = (_day_start, _day_start + _dt.timedelta(days=1))

                ds = self.read_receiver_data(
                    receiver_name=receiver_name, time_range=time_range
                )

                # Check epoch count
                n_epochs = ds.sizes.get("epoch", 0)

                if n_epochs < required_epochs:
                    self._logger.info(
                        f"{receiver_name} {yyyydoy}: Only "
                        f"{n_epochs}/{expected_epochs} epochs "
                        f"({n_epochs / expected_epochs * 100:.1f}%) - incomplete"
                    )
                    return False

                self._logger.debug(
                    f"{receiver_name} {yyyydoy}: "
                    f"{n_epochs}/{expected_epochs} epochs - complete"
                )

            except (ValueError, KeyError, Exception) as e:
                # No data exists or error reading
                self._logger.debug(f"{receiver_name} {yyyydoy}: No data found - {e}")
                return False

        # All receiver types have complete data
        return True

    def __repr__(self) -> str:
        """Return the developer-facing representation.

        Returns
        -------
        str
            Representation string.
        """
        return f"GnssResearchSite(site_name='{self.site_name}')"

    def __str__(self) -> str:
        """Return a human-readable summary.

        Returns
        -------
        str
            Summary string.
        """
        rinex_groups = len(self.get_receiver_groups())
        vod_groups = len(self.get_vod_analysis_groups())
        return (
            f"GNSS Research Site: {self.site_name}\n"
            f"  Receivers: {len(self.active_receivers)} configured, "
            f"{rinex_groups} with data\n"
            f"  VOD Analyses: {len(self.active_vod_analyses)} configured, "
            f"{vod_groups} with results"
        )

site_config property

Get the site configuration as a dictionary.

receivers property

Get all configured receivers for this site.

active_receivers property

Get only active receivers for this site.

vod_analyses property

Get all configured VOD analyses for this site.

Returns auto-derived analyses from scs_from if no explicit vod_analyses are configured.

active_vod_analyses property

Get only active VOD analyses for this site.

__init__(site_name)

Initialize the site manager.

Parameters

site_name : str Name of the research site.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def __init__(self, site_name: str) -> None:
    """Initialize the site manager.

    Parameters
    ----------
    site_name : str
        Name of the research site.
    """
    from canvod.utils.config import load_config

    config = load_config()
    sites = config.sites.sites

    if site_name not in sites:
        available_sites = list(sites.keys())
        raise KeyError(
            f"Site '{site_name}' not found in config. "
            f"Available sites: {available_sites}"
        )

    self.site_name = site_name
    self._site_config = sites[site_name]
    self._logger = get_logger(__name__).bind(site=site_name)

    rinex_store_path = config.processing.storage.get_rinex_store_path(site_name)
    vod_store_path = config.processing.storage.get_vod_store_path(site_name)

    # Initialize stores using paths from processing.yaml
    self.rinex_store = create_rinex_store(rinex_store_path)
    self.vod_store = create_vod_store(vod_store_path)

    self._logger.info(
        f"Initialized GNSS research site: {site_name}",
        rinex_store=str(rinex_store_path),
        vod_store=str(vod_store_path),
    )

get_receiver_metadata(receiver_name)

Get freeform metadata for a receiver.

Returns the metadata dict from ReceiverConfig in sites.yaml, or None if not configured.

Parameters

receiver_name : str Name of the receiver.

Returns

dict or None Receiver metadata dict, or None.

Source code in packages/canvod-store/src/canvod/store/manager.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def get_receiver_metadata(
    self, receiver_name: str
) -> dict[str, str | int | float | bool] | None:
    """Get freeform metadata for a receiver.

    Returns the ``metadata`` dict from ``ReceiverConfig`` in
    ``sites.yaml``, or ``None`` if not configured.

    Parameters
    ----------
    receiver_name : str
        Name of the receiver.

    Returns
    -------
    dict or None
        Receiver metadata dict, or None.
    """
    cfg = self._site_config.receivers.get(receiver_name)
    if cfg is None:
        return None
    return cfg.metadata

from_rinex_store_path(rinex_store_path) classmethod

Create a GnssResearchSite instance from a RINEX store path.

Parameters

rinex_store_path : Path Path to the RINEX Icechunk store.

Returns

GnssResearchSite Initialized research site manager.

Raises

ValueError If no matching site is found for the given path.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
@classmethod
def from_rinex_store_path(
    cls,
    rinex_store_path: Path,
) -> GnssResearchSite:
    """
    Create a GnssResearchSite instance from a RINEX store path.

    Parameters
    ----------
    rinex_store_path : Path
        Path to the RINEX Icechunk store.

    Returns
    -------
    GnssResearchSite
        Initialized research site manager.

    Raises
    ------
    ValueError
        If no matching site is found for the given path.
    """
    # Load config to get store paths
    from canvod.utils.config import load_config

    config = load_config()

    # Try to match against each site's expected rinex store path
    for site_name in config.sites.sites.keys():
        expected_path = config.processing.storage.get_rinex_store_path(site_name)
        if expected_path == rinex_store_path:
            return cls(site_name)

    raise ValueError(
        f"No research site found for RINEX store path: {rinex_store_path}"
    )

get_reference_canopy_pairs()

Expand scs_from into (reference_name, canopy_name) pairs.

Returns

list[tuple[str, str]] List of (reference_name, canopy_name) pairs.

Source code in packages/canvod-store/src/canvod/store/manager.py
199
200
201
202
203
204
205
206
207
def get_reference_canopy_pairs(self) -> list[tuple[str, str]]:
    """Expand scs_from into (reference_name, canopy_name) pairs.

    Returns
    -------
    list[tuple[str, str]]
        List of (reference_name, canopy_name) pairs.
    """
    return self._site_config.get_reference_canopy_pairs()

get_auto_vod_analyses()

Derive VOD analysis pairs from scs_from configuration.

Creates one VOD pair per (canopy, reference_for_that_canopy) combination.

Returns

dict[str, VodAnalysisConfig] Auto-derived VOD analyses keyed by analysis name.

Source code in packages/canvod-store/src/canvod/store/manager.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def get_auto_vod_analyses(self) -> dict[str, VodAnalysisConfig]:
    """Derive VOD analysis pairs from scs_from configuration.

    Creates one VOD pair per (canopy, reference_for_that_canopy) combination.

    Returns
    -------
    dict[str, VodAnalysisConfig]
        Auto-derived VOD analyses keyed by analysis name.
    """
    analyses: dict[str, VodAnalysisConfig] = {}
    for ref_name, canopy_name in self.get_reference_canopy_pairs():
        analysis_name = f"{canopy_name}_vs_{ref_name}"
        analyses[analysis_name] = VodAnalysisConfig(
            canopy_receiver=canopy_name,
            reference_receiver=f"{ref_name}_{canopy_name}",
            description=f"VOD analysis {canopy_name} vs {ref_name}",
        )
    return analyses

validate_site_config()

Validate that the site configuration is consistent.

Returns

bool True if configuration is valid.

Raises

ValueError If configuration is invalid.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def validate_site_config(self) -> bool:
    """
    Validate that the site configuration is consistent.

    Returns
    -------
    bool
        True if configuration is valid.

    Raises
    ------
    ValueError
        If configuration is invalid.
    """
    # Check that all VOD analyses reference valid receivers
    # Build set of valid reference store groups (e.g. reference_01_canopy_01)
    valid_ref_groups = {
        f"{ref}_{canopy}" for ref, canopy in self.get_reference_canopy_pairs()
    }

    for analysis_name, analysis_config in self.vod_analyses.items():
        canopy_rx = analysis_config.canopy_receiver
        ref_rx = analysis_config.reference_receiver

        if canopy_rx not in self.receivers:
            raise ValueError(
                f"VOD analysis '{analysis_name}' references "
                f"unknown canopy receiver: {canopy_rx}"
            )
        # ref_rx can be either a raw receiver name or a store group name
        if ref_rx not in self.receivers and ref_rx not in valid_ref_groups:
            raise ValueError(
                f"VOD analysis '{analysis_name}' references "
                f"unknown reference receiver/group: {ref_rx}"
            )

        # Check canopy type
        canopy_type = self.receivers[canopy_rx]["type"]
        if canopy_type != "canopy":
            raise ValueError(
                f"Receiver '{canopy_rx}' used as canopy but type is '{canopy_type}'"
            )
        # Check reference type (only if it's a raw receiver name)
        if ref_rx in self.receivers:
            ref_type = self.receivers[ref_rx]["type"]
            if ref_type != "reference":
                raise ValueError(
                    f"Receiver '{ref_rx}' used as reference"
                    f" but type is '{ref_type}'"
                )

    self._logger.debug("Site configuration validation passed")
    return True

get_receiver_groups()

Get list of receiver groups that exist in the RINEX store.

Returns

list[str] Existing receiver group names.

Source code in packages/canvod-store/src/canvod/store/manager.py
283
284
285
286
287
288
289
290
291
292
def get_receiver_groups(self) -> list[str]:
    """
    Get list of receiver groups that exist in the RINEX store.

    Returns
    -------
    list[str]
        Existing receiver group names.
    """
    return self.rinex_store.list_groups()

get_vod_analysis_groups()

Get list of VOD analysis groups that exist in the VOD store.

Returns

list[str] Existing VOD analysis group names.

Source code in packages/canvod-store/src/canvod/store/manager.py
294
295
296
297
298
299
300
301
302
303
def get_vod_analysis_groups(self) -> list[str]:
    """
    Get list of VOD analysis groups that exist in the VOD store.

    Returns
    -------
    list[str]
        Existing VOD analysis group names.
    """
    return self.vod_store.list_groups()

ingest_receiver_data(dataset, receiver_name, commit_message=None)

Ingest RINEX data for a specific receiver.

Parameters

dataset : xr.Dataset Processed RINEX dataset to store. receiver_name : str Name of the receiver (must be configured). commit_message : str, optional Commit message to store with the data.

Raises

ValueError If receiver_name is not configured.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def ingest_receiver_data(
    self, dataset: xr.Dataset, receiver_name: str, commit_message: str | None = None
) -> None:
    """
    Ingest RINEX data for a specific receiver.

    Parameters
    ----------
    dataset : xr.Dataset
        Processed RINEX dataset to store.
    receiver_name : str
        Name of the receiver (must be configured).
    commit_message : str, optional
        Commit message to store with the data.

    Raises
    ------
    ValueError
        If ``receiver_name`` is not configured.
    """
    if receiver_name not in self.receivers:
        available_receivers = list(self.receivers.keys())
        raise ValueError(
            f"Receiver '{receiver_name}' not configured. "
            f"Available: {available_receivers}"
        )

    # Merge receiver metadata into dataset attrs (never overwrite existing)
    receiver_meta = self.get_receiver_metadata(receiver_name)
    if receiver_meta:
        skipped = {k for k in receiver_meta if k in dataset.attrs}
        if skipped:
            self._logger.warning(
                f"Receiver metadata keys {skipped} already exist in "
                f"dataset attrs — skipping (existing attrs take precedence)"
            )
        new_attrs = {
            k: v for k, v in receiver_meta.items() if k not in dataset.attrs
        }
        dataset.attrs.update(new_attrs)

    self._logger.info(f"Ingesting RINEX data for receiver '{receiver_name}'")

    self.rinex_store.write_or_append_group(
        dataset=dataset, group_name=receiver_name, commit_message=commit_message
    )

    self._logger.info(f"Successfully ingested data for receiver '{receiver_name}'")

read_receiver_data(receiver_name, time_range=None)

Read data from a specific receiver.

Parameters

receiver_name : str Name of the receiver. time_range : tuple of datetime, optional (start_time, end_time) for filtering the data.

Returns

xr.Dataset Dataset containing receiver observations.

Raises

ValueError If the receiver group does not exist.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def read_receiver_data(
    self, receiver_name: str, time_range: tuple[datetime, datetime] | None = None
) -> xr.Dataset:
    """
    Read data from a specific receiver.

    Parameters
    ----------
    receiver_name : str
        Name of the receiver.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the data.

    Returns
    -------
    xr.Dataset
        Dataset containing receiver observations.

    Raises
    ------
    ValueError
        If the receiver group does not exist.
    """
    if not self.rinex_store.group_exists(receiver_name):
        available_groups = self.get_receiver_groups()
        raise ValueError(
            f"No data found for receiver '{receiver_name}'. "
            f"Available: {available_groups}"
        )

    self._logger.info(f"Reading data for receiver '{receiver_name}'")

    if self.rinex_store._rinex_store_strategy == "append":
        ds = self.rinex_store.read_group_deduplicated(receiver_name, keep="last")
    else:
        ds = self.rinex_store.read_group(receiver_name)

    # Apply time filtering if specified
    if time_range is not None:
        start_time, end_time = time_range
        ds = ds.where(
            (ds.epoch >= np.datetime64(start_time, "ns"))
            & (ds.epoch <= np.datetime64(end_time, "ns")),
            drop=True,
        )

        self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

    return ds

store_vod_analysis(vod_dataset, analysis_name, commit_message=None)

Store VOD analysis results.

Parameters

vod_dataset : xr.Dataset Dataset containing VOD analysis results. analysis_name : str Name of the analysis (must be configured). commit_message : str, optional Commit message to store with the results.

Raises

ValueError If analysis_name is not configured.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def store_vod_analysis(
    self,
    vod_dataset: xr.Dataset,
    analysis_name: str,
    commit_message: str | None = None,
) -> None:
    """
    Store VOD analysis results.

    Parameters
    ----------
    vod_dataset : xr.Dataset
        Dataset containing VOD analysis results.
    analysis_name : str
        Name of the analysis (must be configured).
    commit_message : str, optional
        Commit message to store with the results.

    Raises
    ------
    ValueError
        If ``analysis_name`` is not configured.
    """
    if analysis_name not in self.vod_analyses:
        available_analyses = list(self.vod_analyses.keys())
        raise ValueError(
            f"VOD analysis '{analysis_name}' not configured. "
            f"Available: {available_analyses}"
        )

    self._logger.info(f"Storing VOD analysis results: '{analysis_name}'")

    self.vod_store.write_or_append_group(
        dataset=vod_dataset, group_name=analysis_name, commit_message=commit_message
    )

    self._logger.info(f"Successfully stored VOD analysis: '{analysis_name}'")

read_vod_analysis(analysis_name, time_range=None)

Read VOD analysis results.

Parameters

analysis_name : str Name of the analysis. time_range : tuple of datetime, optional (start_time, end_time) for filtering the results.

Returns

xr.Dataset Dataset containing VOD analysis results.

Raises

ValueError If the analysis group does not exist.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def read_vod_analysis(
    self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
) -> xr.Dataset:
    """
    Read VOD analysis results.

    Parameters
    ----------
    analysis_name : str
        Name of the analysis.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the results.

    Returns
    -------
    xr.Dataset
        Dataset containing VOD analysis results.

    Raises
    ------
    ValueError
        If the analysis group does not exist.
    """
    if not self.vod_store.group_exists(analysis_name):
        available_groups = self.get_vod_analysis_groups()
        raise ValueError(
            f"No VOD results found for analysis '{analysis_name}'. "
            f"Available: {available_groups}"
        )

    self._logger.info(f"Reading VOD analysis: '{analysis_name}'")

    ds = self.vod_store.read_group(analysis_name)

    # Apply time filtering if specified
    if time_range is not None:
        start_time, end_time = time_range
        ds = ds.sel(epoch=slice(start_time, end_time))
        self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

    return ds

prepare_vod_input_data(analysis_name, time_range=None)

Prepare aligned input data for VOD analysis.

Reads data from both receivers specified in the analysis configuration and returns them aligned for VOD processing.

Parameters

analysis_name : str Name of the VOD analysis configuration. time_range : tuple of datetime, optional (start_time, end_time) for filtering the data.

Returns

tuple of (xr.Dataset, xr.Dataset) Tuple of (canopy_dataset, reference_dataset).

Raises

ValueError If the analysis is not configured or data is missing.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def prepare_vod_input_data(
    self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
) -> tuple[xr.Dataset, xr.Dataset]:
    """
    Prepare aligned input data for VOD analysis.

    Reads data from both receivers specified in the analysis configuration
    and returns them aligned for VOD processing.

    Parameters
    ----------
    analysis_name : str
        Name of the VOD analysis configuration.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the data.

    Returns
    -------
    tuple of (xr.Dataset, xr.Dataset)
        Tuple of (canopy_dataset, reference_dataset).

    Raises
    ------
    ValueError
        If the analysis is not configured or data is missing.
    """
    if analysis_name not in self.vod_analyses:
        available_analyses = list(self.vod_analyses.keys())
        raise ValueError(
            f"VOD analysis '{analysis_name}' not configured. "
            f"Available: {available_analyses}"
        )

    analysis_config = self.vod_analyses[analysis_name]
    canopy_receiver = analysis_config.canopy_receiver
    reference_receiver = analysis_config.reference_receiver

    self._logger.info(
        f"Preparing VOD input data: {canopy_receiver} vs {reference_receiver}"
    )

    # Read data from both receivers
    canopy_data = self.read_receiver_data(canopy_receiver, time_range)
    reference_data = self.read_receiver_data(reference_receiver, time_range)

    self._logger.info(
        f"Loaded data - Canopy: {dict(canopy_data.dims)}, "
        f"Reference: {dict(reference_data.dims)}"
    )

    return canopy_data, reference_data

calculate_vod(analysis_name, calculator_class=None, time_range=None)

Calculate VOD for a configured analysis pair.

Parameters

analysis_name : str Analysis name from config (e.g., 'canopy_01_vs_reference_01') calculator_class : type[VODCalculator], optional VOD calculator class to use. If None, uses TauOmegaZerothOrder. time_range : tuple of datetime, optional (start_time, end_time) for filtering the data

Returns

xr.Dataset VOD dataset

Note

Requires canvod-vod to be installed.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def calculate_vod(
    self,
    analysis_name: str,
    calculator_class: type[VODCalculator] | None = None,
    time_range: tuple[datetime, datetime] | None = None,
) -> xr.Dataset:
    """
    Calculate VOD for a configured analysis pair.

    Parameters
    ----------
    analysis_name : str
        Analysis name from config (e.g., 'canopy_01_vs_reference_01')
    calculator_class : type[VODCalculator], optional
        VOD calculator class to use. If None, uses TauOmegaZerothOrder.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the data

    Returns
    -------
    xr.Dataset
        VOD dataset

    Note
    ----
    Requires canvod-vod to be installed.
    """
    if calculator_class is None:
        try:
            from canvod.vod import TauOmegaZerothOrder

            calculator_class = TauOmegaZerothOrder
        except ImportError as e:
            raise ImportError(
                "canvod-vod package required for VOD calculation. "
                "Install with: pip install canvod-vod"
            ) from e

    canopy_ds, reference_ds = self.prepare_vod_input_data(analysis_name, time_range)

    # Align once so we can access both r arrays for radial_diff before
    # passing to the calculator (which would otherwise re-align internally).
    canopy_aligned, reference_aligned = xr.align(
        canopy_ds, reference_ds, join="inner"
    )

    # Use the calculator's class method for calculation (alignment already done)
    vod_ds = calculator_class.from_datasets(
        canopy_aligned, reference_aligned, align=False
    )

    # Apply config-gated derived quantities
    from canvod.utils.config import load_config as _load_config

    _params = _load_config().processing.processing

    if not _params.store_delta_snr:
        vod_ds = vod_ds.drop_vars("delta_snr", errors="ignore")

    if _params.store_radial_diff:
        if "r" in canopy_aligned and "r" in reference_aligned:
            radial_diff = canopy_aligned["r"] - reference_aligned["r"]
            radial_diff.attrs["units"] = "m"
            radial_diff.attrs["long_name"] = (
                "radial distance difference (canopy − reference)"
            )
            vod_ds["radial_diff"] = radial_diff
        else:
            self._logger.warning(
                "store_radial_diff=true but 'r' not present in receiver data; "
                "set store_radial_distance=true at ingest time to enable this"
            )

    # Add metadata
    analysis_config = self.vod_analyses[analysis_name]
    vod_ds.attrs["analysis_name"] = analysis_name
    vod_ds.attrs["canopy_receiver"] = analysis_config.canopy_receiver
    vod_ds.attrs["reference_receiver"] = analysis_config.reference_receiver
    vod_ds.attrs["calculator"] = calculator_class.__name__
    vod_ds.attrs["canopy_hash"] = canopy_ds.attrs.get("File Hash", "unknown")
    vod_ds.attrs["reference_hash"] = reference_ds.attrs.get("File Hash", "unknown")

    self._logger.info(
        f"VOD calculated for {analysis_name} using {calculator_class.__name__}"
    )
    return vod_ds

store_vod(vod_ds, analysis_name)

Store VOD dataset in VOD store.

Parameters

vod_ds : xr.Dataset VOD dataset to store analysis_name : str Analysis name (group name in store)

Returns

str Snapshot ID

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def store_vod(
    self,
    vod_ds: xr.Dataset,
    analysis_name: str,
) -> str:
    """
    Store VOD dataset in VOD store.

    Parameters
    ----------
    vod_ds : xr.Dataset
        VOD dataset to store
    analysis_name : str
        Analysis name (group name in store)

    Returns
    -------
    str
        Snapshot ID
    """
    import importlib.metadata

    from icechunk.xarray import to_icechunk

    canopy_hash = vod_ds.attrs.get("canopy_hash", "unknown")
    reference_hash = vod_ds.attrs.get("reference_hash", "unknown")
    combined_hash = f"{canopy_hash}_{reference_hash}"

    with self.vod_store.writable_session() as session:
        groups = self.vod_store.list_groups() or []

        if analysis_name not in groups:
            to_icechunk(vod_ds, session, group=analysis_name, mode="w")
            action = "write"
        else:
            to_icechunk(vod_ds, session, group=analysis_name, append_dim="epoch")
            action = "append"

        version = importlib.metadata.version("canvodpy")
        commit_msg = f"[v{version}] VOD for {analysis_name}"
        snapshot_id = session.commit(commit_msg)

    self.vod_store.append_metadata(
        group_name=analysis_name,
        rinex_hash=combined_hash,
        start=vod_ds["epoch"].values[0],
        end=vod_ds["epoch"].values[-1],
        snapshot_id=snapshot_id,
        action=action,
        commit_msg=commit_msg,
        dataset_attrs=dict(vod_ds.attrs),
    )

    self._logger.info(
        f"VOD stored for {analysis_name}, snapshot={snapshot_id[:8]}..."
    )
    return snapshot_id

get_site_summary()

Get a comprehensive summary of the research site.

Returns

dict Dictionary with site statistics, data availability, and store paths.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def get_site_summary(self) -> dict[str, Any]:
    """
    Get a comprehensive summary of the research site.

    Returns
    -------
    dict
        Dictionary with site statistics, data availability, and store paths.
    """
    rinex_groups = self.get_receiver_groups()
    vod_groups = self.get_vod_analysis_groups()

    summary: dict[str, Any] = {
        "site_name": self.site_name,
        "site_config": {
            "total_receivers": len(self.receivers),
            "active_receivers": len(self.active_receivers),
            "total_vod_analyses": len(self.vod_analyses),
            "active_vod_analyses": len(self.active_vod_analyses),
        },
        "data_status": {
            "rinex_groups_exist": len(rinex_groups),
            "rinex_groups": rinex_groups,
            "vod_groups_exist": len(vod_groups),
            "vod_groups": vod_groups,
        },
        "stores": {
            "rinex_store_path": str(self.rinex_store.store_path),
            "vod_store_path": str(self.vod_store.store_path),
        },
    }

    # Add receiver details
    summary["receivers"] = {}
    for receiver_name, receiver_config in self.active_receivers.items():
        has_data = receiver_name in rinex_groups
        summary["receivers"][receiver_name] = {
            "type": receiver_config["type"],
            "description": receiver_config["description"],
            "has_data": has_data,
        }

        if has_data:
            try:
                info = self.rinex_store.get_group_info(receiver_name)
                summary["receivers"][receiver_name]["data_info"] = {
                    "dimensions": info["dimensions"],
                    "variables": len(info["variables"]),
                    "temporal_info": info.get("temporal_info", {}),
                }
            except Exception as e:
                self._logger.warning(f"Failed to get info for {receiver_name}: {e}")

    # Add VOD analysis details
    summary["vod_analyses"] = {}
    for analysis_name, analysis_config in self.active_vod_analyses.items():
        has_results = analysis_name in vod_groups
        summary["vod_analyses"][analysis_name] = {
            "canopy_receiver": analysis_config.canopy_receiver,
            "reference_receiver": analysis_config.reference_receiver,
            "description": analysis_config.description,
            "has_results": has_results,
        }

        if has_results:
            try:
                info = self.vod_store.get_group_info(analysis_name)
                summary["vod_analyses"][analysis_name]["results_info"] = {
                    "dimensions": info["dimensions"],
                    "variables": len(info["variables"]),
                    "temporal_info": info.get("temporal_info", {}),
                }
            except Exception as e:
                self._logger.warning(
                    f"Failed to get VOD info for {analysis_name}: {e}"
                )

    return summary

is_day_complete(yyyydoy, receiver_types=None, completeness_threshold=0.95)

Check if a day has complete data coverage for all receiver types.

Parameters

yyyydoy : str Date in YYYYDOY format (e.g., "2024256") receiver_types : List[str], optional Receiver types to check. Defaults to ['canopy', 'reference'] completeness_threshold : float Fraction of expected epochs that must exist (default 0.95 = 95%) Allows for small gaps due to receiver issues

Returns

bool True if all receiver types have complete data for this day

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def is_day_complete(
    self,
    yyyydoy: str,
    receiver_types: list[str] | None = None,
    completeness_threshold: float = 0.95,
) -> bool:
    """
    Check if a day has complete data coverage for all receiver types.

    Parameters
    ----------
    yyyydoy : str
        Date in YYYYDOY format (e.g., "2024256")
    receiver_types : List[str], optional
        Receiver types to check. Defaults to ['canopy', 'reference']
    completeness_threshold : float
        Fraction of expected epochs that must exist (default 0.95 = 95%)
        Allows for small gaps due to receiver issues

    Returns
    -------
    bool
        True if all receiver types have complete data for this day
    """
    if receiver_types is None:
        receiver_types = ["canopy", "reference"]

    from canvod.utils.tools import YYYYDOY

    yyyydoy_obj = YYYYDOY.from_str(yyyydoy)

    # Expected epochs for 24h at 30s sampling
    expected_epochs = int(24 * 3600 / 30)  # 2880 epochs
    required_epochs = int(expected_epochs * completeness_threshold)

    for receiver_type in receiver_types:
        # Get receiver name for this type
        receiver_name = None
        for name, config in self.active_receivers.items():
            if config.get("type") == receiver_type:
                receiver_name = name
                break

        if not receiver_name:
            self._logger.warning(f"No receiver configured for type {receiver_type}")
            return False

        try:
            # Try to read data for this day
            import datetime as _dt

            assert yyyydoy_obj.date is not None
            _day_start = datetime.combine(yyyydoy_obj.date, _dt.time.min)
            time_range = (_day_start, _day_start + _dt.timedelta(days=1))

            ds = self.read_receiver_data(
                receiver_name=receiver_name, time_range=time_range
            )

            # Check epoch count
            n_epochs = ds.sizes.get("epoch", 0)

            if n_epochs < required_epochs:
                self._logger.info(
                    f"{receiver_name} {yyyydoy}: Only "
                    f"{n_epochs}/{expected_epochs} epochs "
                    f"({n_epochs / expected_epochs * 100:.1f}%) - incomplete"
                )
                return False

            self._logger.debug(
                f"{receiver_name} {yyyydoy}: "
                f"{n_epochs}/{expected_epochs} epochs - complete"
            )

        except (ValueError, KeyError, Exception) as e:
            # No data exists or error reading
            self._logger.debug(f"{receiver_name} {yyyydoy}: No data found - {e}")
            return False

    # All receiver types have complete data
    return True

__repr__()

Return the developer-facing representation.

Returns

str Representation string.

Source code in packages/canvod-store/src/canvod/store/manager.py
843
844
845
846
847
848
849
850
851
def __repr__(self) -> str:
    """Return the developer-facing representation.

    Returns
    -------
    str
        Representation string.
    """
    return f"GnssResearchSite(site_name='{self.site_name}')"

__str__()

Return a human-readable summary.

Returns

str Summary string.

Source code in packages/canvod-store/src/canvod/store/manager.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
def __str__(self) -> str:
    """Return a human-readable summary.

    Returns
    -------
    str
        Summary string.
    """
    rinex_groups = len(self.get_receiver_groups())
    vod_groups = len(self.get_vod_analysis_groups())
    return (
        f"GNSS Research Site: {self.site_name}\n"
        f"  Receivers: {len(self.active_receivers)} configured, "
        f"{rinex_groups} with data\n"
        f"  VOD Analyses: {len(self.active_vod_analyses)} configured, "
        f"{vod_groups} with results"
    )

IcechunkDataReader

Replacement for RinexFilesParser that reads from Icechunk stores.

This class provides a similar interface to the old parser but reads pre-processed data from Icechunk stores instead of processing RINEX files.

Parameters

matched_dirs : MatchedDirs Directory information for date/location matching site_name : str, optional Name of research site (defaults to DEFAULT_RESEARCH_SITE) n_max_workers : int, optional Maximum number of workers for parallel operations (defaults to N_MAX_THREADS) enable_gc : bool, optional Whether to enable garbage collection between operations (default True) gc_delay : float, optional Delay in seconds after garbage collection (default 1.0)

Source code in packages/canvod-store/src/canvod/store/reader.py
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
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
class IcechunkDataReader:
    """
    Replacement for RinexFilesParser that reads from Icechunk stores.

    This class provides a similar interface to the old parser but reads
    pre-processed data from Icechunk stores instead of processing RINEX files.

    Parameters
    ----------
    matched_dirs : MatchedDirs
        Directory information for date/location matching
    site_name : str, optional
        Name of research site (defaults to DEFAULT_RESEARCH_SITE)
    n_max_workers : int, optional
        Maximum number of workers for parallel operations (defaults to N_MAX_THREADS)
    enable_gc : bool, optional
        Whether to enable garbage collection between operations (default True)
    gc_delay : float, optional
        Delay in seconds after garbage collection (default 1.0)
    """

    def __init__(
        self,
        matched_dirs: MatchedDirs,
        site_name: str | None = None,
        n_max_workers: int | None = None,
        enable_gc: bool = True,
        gc_delay: float = 1.0,
    ) -> None:
        """Initialize the Icechunk data reader.

        Parameters
        ----------
        matched_dirs : MatchedDirs
            Directory information for date/location matching.
        site_name : str | None, optional
            Name of research site. If ``None``, uses the first site from config.
        n_max_workers : int | None, optional
            Maximum number of workers for parallel operations. Defaults to config.
        enable_gc : bool, optional
            Whether to enable garbage collection between operations.
        gc_delay : float, optional
            Delay in seconds after garbage collection.
        """
        config = load_config()
        if site_name is None:
            site_name = next(iter(config.sites.sites))
        if n_max_workers is None:
            resources = config.processing.processing.resolve_resources()
            n_max_workers = resources["n_workers"]

        self.matched_dirs = matched_dirs
        self.site_name = site_name
        self.n_max_workers = n_max_workers
        self.enable_gc = enable_gc
        self.gc_delay = gc_delay

        self._logger = get_logger(__name__).bind(
            site=site_name,
            date=matched_dirs.yyyydoy.to_str(),
        )
        self._site = GnssResearchSite(site_name)

        date_obj = self.matched_dirs.yyyydoy.date
        if date_obj is None:
            msg = (
                f"Matched date is missing for {self.matched_dirs.yyyydoy.to_str()} "
                f"at site {site_name}"
            )
            raise ValueError(msg)
        self._start_time = datetime.combine(date_obj, datetime.min.time())
        self._end_time = datetime.combine(date_obj, datetime.max.time())
        self._time_range = (self._start_time, self._end_time)

        # ✅ single persistent pool
        self._pool = ProcessPoolExecutor(
            max_workers=min(self.n_max_workers, 16),
        )

        self._logger.info(
            f"Initialized Icechunk data reader for {matched_dirs.yyyydoy.to_str()}"
        )

    def __del__(self) -> None:
        """Ensure the pool is shut down when the reader is deleted."""
        try:
            self._pool.shutdown(wait=True)
        except Exception:
            pass

    def _memory_cleanup(self) -> None:
        """Perform memory cleanup if enabled."""
        if self.enable_gc:
            gc.collect()
            if self.gc_delay > 0:
                time.sleep(self.gc_delay)

    def get_receiver_by_type(self, receiver_type: str) -> list[str]:
        """
        Get list of receiver names by type.

        Parameters
        ----------
        receiver_type : str
            Type of receiver ('canopy', 'reference')

        Returns
        -------
        list[str]
            List of receiver names of the specified type
        """
        return [
            name
            for name, config in self._site.active_receivers.items()
            if config["type"] == receiver_type
        ]

    def _get_receiver_name_for_type(self, receiver_type: str) -> str | None:
        """Get the first configured receiver name for a given type."""
        for name, config in self._site.active_receivers.items():
            if config["type"] == receiver_type:
                return name
        return None

    def _memory_cleanup(self) -> None:
        """Perform memory cleanup if enabled."""
        if self.enable_gc:
            gc.collect()
            if self.gc_delay > 0:
                time.sleep(self.gc_delay)

    def parsed_rinex_data_gen_v2(
        self,
        keep_vars: list[str] | None = None,
        receiver_types: list[str] | None = None,
    ) -> Generator[xr.Dataset]:
        """
        Generator that processes RINEX files, augments them (φ, θ, r),
        and appends to Icechunk stores on-the-fly.

        Yields enriched daily datasets (already augmented).
        """

        if receiver_types is None:
            receiver_types = ["canopy", "reference"]

        self._logger.info(
            f"Starting RINEX processing and ingestion for types: {receiver_types}"
        )

        # --- 1) Cache auxiliaries once per day ---
        from canvodpy.orchestrator import RinexDataProcessor

        processor_cls = cast(Any, RinexDataProcessor)
        processor: Any = processor_cls(
            matched_data_dirs=self.matched_dirs, icechunk_reader=self
        )

        ephem_ds = prep_aux_ds(processor.get_ephemeride_ds())
        clk_ds = prep_aux_ds(processor.get_clk_ds())

        aux_ds_dict = {"ephem": ephem_ds, "clk": clk_ds}
        approx_pos = None  # computed on first canopy dataset

        for receiver_type in receiver_types:
            # --- resolve dirs and names ---
            if receiver_type == "canopy":
                rinex_dir = self.matched_dirs.canopy_data_dir
                receiver_name = self._get_receiver_name_for_type("canopy")
                store_group = "canopy"
            elif receiver_type == "reference":
                rinex_dir = self.matched_dirs.reference_data_dir
                receiver_name = self._get_receiver_name_for_type("reference")
                store_group = "reference"
            else:
                self._logger.warning(f"Unknown receiver type: {receiver_type}")
                continue

            if not receiver_name:
                self._logger.warning(f"No configured receiver for type {receiver_type}")
                continue

            rinex_files = self._get_rinex_files(rinex_dir)
            if not rinex_files:
                self._logger.warning(f"No RINEX files found in {rinex_dir}")
                continue

            self._logger.info(
                f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
            )

            # --- parallel preprocessing ---
            futures = {
                self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
            }
            results: list[tuple[Path, xr.Dataset]] = []

            for fut in tqdm(
                as_completed(futures),
                total=len(futures),
                desc=f"Processing {receiver_type}",
            ):
                try:
                    fname, ds = fut.result()
                    results.append((fname, ds))
                except Exception as e:
                    self._logger.error(f"Failed preprocessing: {e}")

            results.sort(key=lambda x: x[0].name)  # chronological order

            # --- per-file commit ---
            for idx, (fname, ds) in enumerate(results):
                log = self._logger.bind(file=str(fname))
                try:
                    rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                    version = get_version_from_pyproject()

                    rinex_hash = ds.attrs.get("File Hash")
                    if not rinex_hash:
                        log.warning("Dataset missing hash → skipping")
                        continue

                    start_epoch = np.datetime64(ds.epoch.min().values)
                    end_epoch = np.datetime64(ds.epoch.max().values)

                    exists, matches = self._site.rinex_store.metadata_row_exists(
                        store_group, rinex_hash, start_epoch, end_epoch
                    )

                    ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                    # --- 2) Compute approx_pos once from first canopy file ---
                    if receiver_type == "canopy" and approx_pos is None:
                        approx_pos = processor.get_approx_position(ds)

                    # --- 3) Augment with φ, θ, r ---
                    matched = processor.match_datasets(ds, **aux_ds_dict)
                    ephem_matched = matched["ephem"]
                    if approx_pos is None:
                        msg = (
                            "Approximate receiver position is required before "
                            "azimuth/elevation augmentation."
                        )
                        raise RuntimeError(msg)
                    ds = processor.add_azi_ele(
                        rnx_obs_ds=ds,
                        ephem_ds=ephem_matched,
                        rx_x=approx_pos.x,
                        rx_y=approx_pos.y,
                        rx_z=approx_pos.z,
                    )

                    # --- 3b) Preprocessing pipeline ---
                    from canvod.ops import build_default_pipeline

                    preprocessing_config = load_config().processing.preprocessing
                    pipeline = build_default_pipeline(preprocessing_config)
                    ds, pipeline_result = pipeline(ds)
                    ds.attrs.update(pipeline_result.to_metadata_dict())

                    # --- 4) Store to Icechunk ---
                    existing_groups = self._site.rinex_store.list_groups()
                    if not exists and store_group not in existing_groups and idx == 0:
                        msg = (
                            f"[v{version}] Initial commit {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch})"
                        )
                        self._site.rinex_store.write_initial_group(
                            dataset=ds, group_name=store_group, commit_message=msg
                        )
                        log.info(msg)
                        continue

                    match (exists, self._site.rinex_store._rinex_store_strategy):
                        case (True, "skip"):
                            log.info(f"[v{version}] Skipped {rel_path}")
                            # just metadata row
                            self._site.rinex_store.append_metadata(
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                snapshot_id="none",
                                action="skip",
                                commit_msg="skip",
                                dataset_attrs=ds.attrs,
                            )

                        case (True, "overwrite"):
                            msg = f"[v{version}] Overwrote {rel_path}"
                            self._site.rinex_store.overwrite_file_in_group(
                                dataset=ds,
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                commit_message=msg,
                            )

                        case (True, "append"):
                            msg = f"[v{version}] Appended {rel_path}"
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="append",
                                commit_message=msg,
                            )

                        case (False, _):
                            msg = f"[v{version}] Wrote {rel_path}"
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="write",
                                commit_message=msg,
                            )
                except Exception as e:
                    log.exception("file_commit_failed", error=str(e))
                    raise

                self._memory_cleanup()

            # --- 5) Yield full daily dataset (already enriched) ---
            final_ds = self._site.read_receiver_data(store_group, self._time_range)
            self._logger.info(
                f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
            )
            yield final_ds
            self._memory_cleanup()

        self._logger.info("RINEX processing and ingestion completed")

    def parsed_rinex_data_gen(
        self,
        keep_vars: list[str] | None = None,
        receiver_types: list[str] | None = None,
    ) -> Generator[xr.Dataset]:
        """
        Generator that processes RINEX files and appends to Icechunk stores on-the-fly.

        Parameters
        ----------
        keep_vars : list[str], optional
            List of variables to keep in datasets
        receiver_types : list[str], optional
            List of receiver types to process ('canopy', 'reference').
            If None, defaults to ['canopy', 'reference']

        Yields
        ------
        xr.Dataset
            Processed and ingested datasets for each receiver type, in order
        """

        if receiver_types is None:
            receiver_types = ["canopy", "reference"]

        self._logger.info(
            f"Starting RINEX processing and ingestion for types: {receiver_types}"
        )

        for receiver_type in receiver_types:
            # --- resolve dirs and names ---
            if receiver_type == "canopy":
                rinex_dir = self.matched_dirs.canopy_data_dir
                receiver_name = self._get_receiver_name_for_type("canopy")
                store_group = "canopy"
            elif receiver_type == "reference":
                rinex_dir = self.matched_dirs.reference_data_dir
                receiver_name = self._get_receiver_name_for_type("reference")
                store_group = "reference"
            else:
                self._logger.warning(f"Unknown receiver type: {receiver_type}")
                continue

            if not receiver_name:
                self._logger.warning(f"No configured receiver for type {receiver_type}")
                continue

            rinex_files = self._get_rinex_files(rinex_dir)
            if not rinex_files:
                self._logger.warning(f"No RINEX files found in {rinex_dir}")
                continue

            self._logger.info(
                f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
            )

            groups = self._site.rinex_store.list_groups() or []

            # --- one pool per receiver type ---
            futures = {
                self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
            }
            results: list[tuple[Path, xr.Dataset]] = []

            # ✅ progressbar over all files, not per batch
            for fut in tqdm(
                as_completed(futures),
                total=len(futures),
                desc=f"Processing {receiver_type}",
            ):
                try:
                    fname, ds = fut.result()
                    results.append((fname, ds))
                except Exception as e:
                    self._logger.error(f"Failed preprocessing: {e}")

            # --- sort all results once (chronological order) ---
            results.sort(key=lambda x: x[0].name)

            # --- sequential append to Icechunk ---
            for idx, (fname, ds) in enumerate(results):
                log = self._logger.bind(file=str(fname))
                try:
                    rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                    version = get_version_from_pyproject()

                    rinex_hash = ds.attrs.get("File Hash")
                    if not rinex_hash:
                        log.warning(
                            f"No file hash found in dataset from {fname}. "
                            "Skipping duplicate detection for this file."
                        )
                        continue

                    start_epoch = np.datetime64(ds.epoch.min().values)
                    end_epoch = np.datetime64(ds.epoch.max().values)

                    exists, matches = self._site.rinex_store.metadata_row_exists(
                        store_group, rinex_hash, start_epoch, end_epoch
                    )

                    ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                    # --- Initial commit ---
                    if not exists and store_group not in groups and idx == 0:
                        msg = (
                            f"[v{version}] Initial commit with {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"to group '{store_group}'"
                        )
                        self._site.rinex_store.write_initial_group(
                            dataset=ds,
                            group_name=store_group,
                            commit_message=msg,
                        )
                        groups.append(store_group)
                        log.info(msg)
                        continue

                    # --- Handle strategies with match ---
                    match (exists, self._site.rinex_store._rinex_store_strategy):
                        case (True, "skip"):
                            msg = (
                                f"[v{version}] Skipped {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"in group '{store_group}'"
                            )
                            log.info(msg)
                            self._site.rinex_store.append_metadata(
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                snapshot_id="none",
                                action="skip",
                                commit_msg=msg,
                                dataset_attrs=ds.attrs,
                            )

                        case (True, "overwrite"):
                            msg = (
                                f"[v{version}] Overwrote {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"in group '{store_group}'"
                            )
                            log.info(msg)
                            self._site.rinex_store.overwrite_file_in_group(
                                dataset=ds,
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                commit_message=msg,
                            )

                        case (True, "append"):
                            msg = (
                                f"[v{version}] Appended {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"to group '{store_group}'"
                            )
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="append",
                                commit_message=msg,
                            )
                            log.info(msg)

                        case (False, _):
                            msg = (
                                f"[v{version}] Wrote {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"to group '{store_group}'"
                            )
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="write",
                                commit_message=msg,
                            )
                            log.info(msg)

                except Exception as e:
                    log.exception("file_commit_failed", error=str(e))
                    raise

                self._memory_cleanup()

            # --- read back final dataset ---
            final_ds = self._site.read_receiver_data(store_group, self._time_range)
            self._logger.info(
                f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
            )
            yield final_ds

            self._memory_cleanup()

        self._logger.info("RINEX processing and ingestion completed")

    def _get_receiver_name_for_type(self, receiver_type: str) -> str | None:
        """Get the first configured receiver name for a given type."""
        for name, config in self._site.active_receivers.items():
            if config["type"] == receiver_type:
                return name
        return None

    def _get_rinex_files(self, rinex_dir: Path) -> list[Path]:
        """Get sorted list of RINEX files from directory."""

        if not rinex_dir.exists():
            self._logger.warning(f"Directory does not exist: {rinex_dir}")
            return []

        # Look for common RINEX file patterns
        patterns = ["*.??o", "*.??O", "*.rnx", "*.RNX"]
        rinex_files = []

        for pattern in patterns:
            files = list(rinex_dir.glob(pattern))
            rinex_files.extend(files)

        return natsorted(rinex_files)

    def _append_to_icechunk_store(
        self,
        dataset: xr.Dataset,
        receiver_name: str,
        receiver_type: str,
    ) -> None:
        """Append dataset to the appropriate Icechunk store."""
        from gnssvodpy.utils.tools import (
            get_version_from_pyproject,  # type: ignore[unresolved-import]
        )

        try:
            version = get_version_from_pyproject()
            date_str = self.matched_dirs.yyyydoy.to_str()

            commit_message = (
                f"[v{version}] Processed and ingested {receiver_type} data "
                f"for {date_str}"
            )

            # Use site's ingestion method
            self._site.ingest_receiver_data(dataset, receiver_name, commit_message)

            self._logger.info(
                f"Successfully appended {receiver_type} data to store as "
                f"'{receiver_name}'"
            )

        except Exception as e:
            self._logger.exception(
                f"Failed to append {receiver_type} data to store", error=str(e)
            )
            raise

    def get_available_receivers(self) -> dict[str, list[str]]:
        """
        Get available receivers grouped by type.

        Returns
        -------
        dict[str, list[str]]
            Dictionary mapping receiver types to lists of receiver names.
        """
        available = {}
        for receiver_type in ["canopy", "reference"]:
            receivers = self.get_receiver_by_type(receiver_type)
            # Filter to only receivers that have data
            with_data = [r for r in receivers if self._site.rinex_store.group_exists(r)]
            available[receiver_type] = with_data

        return available

    def __str__(self) -> str:
        """Return a human-readable summary.

        Returns
        -------
        str
            Summary string.
        """
        available = self.get_available_receivers()
        return (
            f"IcechunkDataReader for {self.matched_dirs.yyyydoy.to_str()}\n"
            f"  Site: {self.site_name}\n"
            f"  Available receivers: {dict(available)}\n"
            f"  Workers: {self.n_max_workers}, GC enabled: {self.enable_gc}"
        )

__init__(matched_dirs, site_name=None, n_max_workers=None, enable_gc=True, gc_delay=1.0)

Initialize the Icechunk data reader.

Parameters

matched_dirs : MatchedDirs Directory information for date/location matching. site_name : str | None, optional Name of research site. If None, uses the first site from config. n_max_workers : int | None, optional Maximum number of workers for parallel operations. Defaults to config. enable_gc : bool, optional Whether to enable garbage collection between operations. gc_delay : float, optional Delay in seconds after garbage collection.

Source code in packages/canvod-store/src/canvod/store/reader.py
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
def __init__(
    self,
    matched_dirs: MatchedDirs,
    site_name: str | None = None,
    n_max_workers: int | None = None,
    enable_gc: bool = True,
    gc_delay: float = 1.0,
) -> None:
    """Initialize the Icechunk data reader.

    Parameters
    ----------
    matched_dirs : MatchedDirs
        Directory information for date/location matching.
    site_name : str | None, optional
        Name of research site. If ``None``, uses the first site from config.
    n_max_workers : int | None, optional
        Maximum number of workers for parallel operations. Defaults to config.
    enable_gc : bool, optional
        Whether to enable garbage collection between operations.
    gc_delay : float, optional
        Delay in seconds after garbage collection.
    """
    config = load_config()
    if site_name is None:
        site_name = next(iter(config.sites.sites))
    if n_max_workers is None:
        resources = config.processing.processing.resolve_resources()
        n_max_workers = resources["n_workers"]

    self.matched_dirs = matched_dirs
    self.site_name = site_name
    self.n_max_workers = n_max_workers
    self.enable_gc = enable_gc
    self.gc_delay = gc_delay

    self._logger = get_logger(__name__).bind(
        site=site_name,
        date=matched_dirs.yyyydoy.to_str(),
    )
    self._site = GnssResearchSite(site_name)

    date_obj = self.matched_dirs.yyyydoy.date
    if date_obj is None:
        msg = (
            f"Matched date is missing for {self.matched_dirs.yyyydoy.to_str()} "
            f"at site {site_name}"
        )
        raise ValueError(msg)
    self._start_time = datetime.combine(date_obj, datetime.min.time())
    self._end_time = datetime.combine(date_obj, datetime.max.time())
    self._time_range = (self._start_time, self._end_time)

    # ✅ single persistent pool
    self._pool = ProcessPoolExecutor(
        max_workers=min(self.n_max_workers, 16),
    )

    self._logger.info(
        f"Initialized Icechunk data reader for {matched_dirs.yyyydoy.to_str()}"
    )

__del__()

Ensure the pool is shut down when the reader is deleted.

Source code in packages/canvod-store/src/canvod/store/reader.py
200
201
202
203
204
205
def __del__(self) -> None:
    """Ensure the pool is shut down when the reader is deleted."""
    try:
        self._pool.shutdown(wait=True)
    except Exception:
        pass

get_receiver_by_type(receiver_type)

Get list of receiver names by type.

Parameters

receiver_type : str Type of receiver ('canopy', 'reference')

Returns

list[str] List of receiver names of the specified type

Source code in packages/canvod-store/src/canvod/store/reader.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def get_receiver_by_type(self, receiver_type: str) -> list[str]:
    """
    Get list of receiver names by type.

    Parameters
    ----------
    receiver_type : str
        Type of receiver ('canopy', 'reference')

    Returns
    -------
    list[str]
        List of receiver names of the specified type
    """
    return [
        name
        for name, config in self._site.active_receivers.items()
        if config["type"] == receiver_type
    ]

parsed_rinex_data_gen_v2(keep_vars=None, receiver_types=None)

Generator that processes RINEX files, augments them (φ, θ, r), and appends to Icechunk stores on-the-fly.

Yields enriched daily datasets (already augmented).

Source code in packages/canvod-store/src/canvod/store/reader.py
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
def parsed_rinex_data_gen_v2(
    self,
    keep_vars: list[str] | None = None,
    receiver_types: list[str] | None = None,
) -> Generator[xr.Dataset]:
    """
    Generator that processes RINEX files, augments them (φ, θ, r),
    and appends to Icechunk stores on-the-fly.

    Yields enriched daily datasets (already augmented).
    """

    if receiver_types is None:
        receiver_types = ["canopy", "reference"]

    self._logger.info(
        f"Starting RINEX processing and ingestion for types: {receiver_types}"
    )

    # --- 1) Cache auxiliaries once per day ---
    from canvodpy.orchestrator import RinexDataProcessor

    processor_cls = cast(Any, RinexDataProcessor)
    processor: Any = processor_cls(
        matched_data_dirs=self.matched_dirs, icechunk_reader=self
    )

    ephem_ds = prep_aux_ds(processor.get_ephemeride_ds())
    clk_ds = prep_aux_ds(processor.get_clk_ds())

    aux_ds_dict = {"ephem": ephem_ds, "clk": clk_ds}
    approx_pos = None  # computed on first canopy dataset

    for receiver_type in receiver_types:
        # --- resolve dirs and names ---
        if receiver_type == "canopy":
            rinex_dir = self.matched_dirs.canopy_data_dir
            receiver_name = self._get_receiver_name_for_type("canopy")
            store_group = "canopy"
        elif receiver_type == "reference":
            rinex_dir = self.matched_dirs.reference_data_dir
            receiver_name = self._get_receiver_name_for_type("reference")
            store_group = "reference"
        else:
            self._logger.warning(f"Unknown receiver type: {receiver_type}")
            continue

        if not receiver_name:
            self._logger.warning(f"No configured receiver for type {receiver_type}")
            continue

        rinex_files = self._get_rinex_files(rinex_dir)
        if not rinex_files:
            self._logger.warning(f"No RINEX files found in {rinex_dir}")
            continue

        self._logger.info(
            f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
        )

        # --- parallel preprocessing ---
        futures = {
            self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
        }
        results: list[tuple[Path, xr.Dataset]] = []

        for fut in tqdm(
            as_completed(futures),
            total=len(futures),
            desc=f"Processing {receiver_type}",
        ):
            try:
                fname, ds = fut.result()
                results.append((fname, ds))
            except Exception as e:
                self._logger.error(f"Failed preprocessing: {e}")

        results.sort(key=lambda x: x[0].name)  # chronological order

        # --- per-file commit ---
        for idx, (fname, ds) in enumerate(results):
            log = self._logger.bind(file=str(fname))
            try:
                rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                version = get_version_from_pyproject()

                rinex_hash = ds.attrs.get("File Hash")
                if not rinex_hash:
                    log.warning("Dataset missing hash → skipping")
                    continue

                start_epoch = np.datetime64(ds.epoch.min().values)
                end_epoch = np.datetime64(ds.epoch.max().values)

                exists, matches = self._site.rinex_store.metadata_row_exists(
                    store_group, rinex_hash, start_epoch, end_epoch
                )

                ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                # --- 2) Compute approx_pos once from first canopy file ---
                if receiver_type == "canopy" and approx_pos is None:
                    approx_pos = processor.get_approx_position(ds)

                # --- 3) Augment with φ, θ, r ---
                matched = processor.match_datasets(ds, **aux_ds_dict)
                ephem_matched = matched["ephem"]
                if approx_pos is None:
                    msg = (
                        "Approximate receiver position is required before "
                        "azimuth/elevation augmentation."
                    )
                    raise RuntimeError(msg)
                ds = processor.add_azi_ele(
                    rnx_obs_ds=ds,
                    ephem_ds=ephem_matched,
                    rx_x=approx_pos.x,
                    rx_y=approx_pos.y,
                    rx_z=approx_pos.z,
                )

                # --- 3b) Preprocessing pipeline ---
                from canvod.ops import build_default_pipeline

                preprocessing_config = load_config().processing.preprocessing
                pipeline = build_default_pipeline(preprocessing_config)
                ds, pipeline_result = pipeline(ds)
                ds.attrs.update(pipeline_result.to_metadata_dict())

                # --- 4) Store to Icechunk ---
                existing_groups = self._site.rinex_store.list_groups()
                if not exists and store_group not in existing_groups and idx == 0:
                    msg = (
                        f"[v{version}] Initial commit {rel_path} "
                        f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch})"
                    )
                    self._site.rinex_store.write_initial_group(
                        dataset=ds, group_name=store_group, commit_message=msg
                    )
                    log.info(msg)
                    continue

                match (exists, self._site.rinex_store._rinex_store_strategy):
                    case (True, "skip"):
                        log.info(f"[v{version}] Skipped {rel_path}")
                        # just metadata row
                        self._site.rinex_store.append_metadata(
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            snapshot_id="none",
                            action="skip",
                            commit_msg="skip",
                            dataset_attrs=ds.attrs,
                        )

                    case (True, "overwrite"):
                        msg = f"[v{version}] Overwrote {rel_path}"
                        self._site.rinex_store.overwrite_file_in_group(
                            dataset=ds,
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            commit_message=msg,
                        )

                    case (True, "append"):
                        msg = f"[v{version}] Appended {rel_path}"
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="append",
                            commit_message=msg,
                        )

                    case (False, _):
                        msg = f"[v{version}] Wrote {rel_path}"
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="write",
                            commit_message=msg,
                        )
            except Exception as e:
                log.exception("file_commit_failed", error=str(e))
                raise

            self._memory_cleanup()

        # --- 5) Yield full daily dataset (already enriched) ---
        final_ds = self._site.read_receiver_data(store_group, self._time_range)
        self._logger.info(
            f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
        )
        yield final_ds
        self._memory_cleanup()

    self._logger.info("RINEX processing and ingestion completed")

parsed_rinex_data_gen(keep_vars=None, receiver_types=None)

Generator that processes RINEX files and appends to Icechunk stores on-the-fly.

Parameters

keep_vars : list[str], optional List of variables to keep in datasets receiver_types : list[str], optional List of receiver types to process ('canopy', 'reference'). If None, defaults to ['canopy', 'reference']

Yields

xr.Dataset Processed and ingested datasets for each receiver type, in order

Source code in packages/canvod-store/src/canvod/store/reader.py
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
def parsed_rinex_data_gen(
    self,
    keep_vars: list[str] | None = None,
    receiver_types: list[str] | None = None,
) -> Generator[xr.Dataset]:
    """
    Generator that processes RINEX files and appends to Icechunk stores on-the-fly.

    Parameters
    ----------
    keep_vars : list[str], optional
        List of variables to keep in datasets
    receiver_types : list[str], optional
        List of receiver types to process ('canopy', 'reference').
        If None, defaults to ['canopy', 'reference']

    Yields
    ------
    xr.Dataset
        Processed and ingested datasets for each receiver type, in order
    """

    if receiver_types is None:
        receiver_types = ["canopy", "reference"]

    self._logger.info(
        f"Starting RINEX processing and ingestion for types: {receiver_types}"
    )

    for receiver_type in receiver_types:
        # --- resolve dirs and names ---
        if receiver_type == "canopy":
            rinex_dir = self.matched_dirs.canopy_data_dir
            receiver_name = self._get_receiver_name_for_type("canopy")
            store_group = "canopy"
        elif receiver_type == "reference":
            rinex_dir = self.matched_dirs.reference_data_dir
            receiver_name = self._get_receiver_name_for_type("reference")
            store_group = "reference"
        else:
            self._logger.warning(f"Unknown receiver type: {receiver_type}")
            continue

        if not receiver_name:
            self._logger.warning(f"No configured receiver for type {receiver_type}")
            continue

        rinex_files = self._get_rinex_files(rinex_dir)
        if not rinex_files:
            self._logger.warning(f"No RINEX files found in {rinex_dir}")
            continue

        self._logger.info(
            f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
        )

        groups = self._site.rinex_store.list_groups() or []

        # --- one pool per receiver type ---
        futures = {
            self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
        }
        results: list[tuple[Path, xr.Dataset]] = []

        # ✅ progressbar over all files, not per batch
        for fut in tqdm(
            as_completed(futures),
            total=len(futures),
            desc=f"Processing {receiver_type}",
        ):
            try:
                fname, ds = fut.result()
                results.append((fname, ds))
            except Exception as e:
                self._logger.error(f"Failed preprocessing: {e}")

        # --- sort all results once (chronological order) ---
        results.sort(key=lambda x: x[0].name)

        # --- sequential append to Icechunk ---
        for idx, (fname, ds) in enumerate(results):
            log = self._logger.bind(file=str(fname))
            try:
                rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                version = get_version_from_pyproject()

                rinex_hash = ds.attrs.get("File Hash")
                if not rinex_hash:
                    log.warning(
                        f"No file hash found in dataset from {fname}. "
                        "Skipping duplicate detection for this file."
                    )
                    continue

                start_epoch = np.datetime64(ds.epoch.min().values)
                end_epoch = np.datetime64(ds.epoch.max().values)

                exists, matches = self._site.rinex_store.metadata_row_exists(
                    store_group, rinex_hash, start_epoch, end_epoch
                )

                ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                # --- Initial commit ---
                if not exists and store_group not in groups and idx == 0:
                    msg = (
                        f"[v{version}] Initial commit with {rel_path} "
                        f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                        f"to group '{store_group}'"
                    )
                    self._site.rinex_store.write_initial_group(
                        dataset=ds,
                        group_name=store_group,
                        commit_message=msg,
                    )
                    groups.append(store_group)
                    log.info(msg)
                    continue

                # --- Handle strategies with match ---
                match (exists, self._site.rinex_store._rinex_store_strategy):
                    case (True, "skip"):
                        msg = (
                            f"[v{version}] Skipped {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"in group '{store_group}'"
                        )
                        log.info(msg)
                        self._site.rinex_store.append_metadata(
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            snapshot_id="none",
                            action="skip",
                            commit_msg=msg,
                            dataset_attrs=ds.attrs,
                        )

                    case (True, "overwrite"):
                        msg = (
                            f"[v{version}] Overwrote {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"in group '{store_group}'"
                        )
                        log.info(msg)
                        self._site.rinex_store.overwrite_file_in_group(
                            dataset=ds,
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            commit_message=msg,
                        )

                    case (True, "append"):
                        msg = (
                            f"[v{version}] Appended {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"to group '{store_group}'"
                        )
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="append",
                            commit_message=msg,
                        )
                        log.info(msg)

                    case (False, _):
                        msg = (
                            f"[v{version}] Wrote {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"to group '{store_group}'"
                        )
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="write",
                            commit_message=msg,
                        )
                        log.info(msg)

            except Exception as e:
                log.exception("file_commit_failed", error=str(e))
                raise

            self._memory_cleanup()

        # --- read back final dataset ---
        final_ds = self._site.read_receiver_data(store_group, self._time_range)
        self._logger.info(
            f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
        )
        yield final_ds

        self._memory_cleanup()

    self._logger.info("RINEX processing and ingestion completed")

get_available_receivers()

Get available receivers grouped by type.

Returns

dict[str, list[str]] Dictionary mapping receiver types to lists of receiver names.

Source code in packages/canvod-store/src/canvod/store/reader.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
def get_available_receivers(self) -> dict[str, list[str]]:
    """
    Get available receivers grouped by type.

    Returns
    -------
    dict[str, list[str]]
        Dictionary mapping receiver types to lists of receiver names.
    """
    available = {}
    for receiver_type in ["canopy", "reference"]:
        receivers = self.get_receiver_by_type(receiver_type)
        # Filter to only receivers that have data
        with_data = [r for r in receivers if self._site.rinex_store.group_exists(r)]
        available[receiver_type] = with_data

    return available

__str__()

Return a human-readable summary.

Returns

str Summary string.

Source code in packages/canvod-store/src/canvod/store/reader.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def __str__(self) -> str:
    """Return a human-readable summary.

    Returns
    -------
    str
        Summary string.
    """
    available = self.get_available_receivers()
    return (
        f"IcechunkDataReader for {self.matched_dirs.yyyydoy.to_str()}\n"
        f"  Site: {self.site_name}\n"
        f"  Available receivers: {dict(available)}\n"
        f"  Workers: {self.n_max_workers}, GC enabled: {self.enable_gc}"
    )

create_rinex_store(store_path)

Create a RINEX Icechunk store with appropriate configuration.

Parameters

store_path : Path Path to the store directory.

Returns

MyIcechunkStore Configured store for RINEX data.

Source code in packages/canvod-store/src/canvod/store/store.py
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
def create_rinex_store(store_path: Path) -> MyIcechunkStore:
    """
    Create a RINEX Icechunk store with appropriate configuration.

    Parameters
    ----------
    store_path : Path
        Path to the store directory.

    Returns
    -------
    MyIcechunkStore
        Configured store for RINEX data.
    """
    return MyIcechunkStore(store_path=store_path, store_type="rinex_store")

create_vod_store(store_path)

Create a VOD Icechunk store with appropriate configuration.

Parameters

store_path : Path Path to the store directory.

Returns

MyIcechunkStore Configured store for VOD analysis data.

Source code in packages/canvod-store/src/canvod/store/store.py
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
def create_vod_store(store_path: Path) -> MyIcechunkStore:
    """
    Create a VOD Icechunk store with appropriate configuration.

    Parameters
    ----------
    store_path : Path
        Path to the store directory.

    Returns
    -------
    MyIcechunkStore
        Configured store for VOD analysis data.
    """
    return MyIcechunkStore(store_path=store_path, store_type="vod_store")

Store Manager

Research site manager that coordinates RINEX and VOD Icechunk stores.

This module provides the GnssResearchSite class that manages both stores for a research site and provides high-level operations across them.

Module: src/gnssvodpy/icechunk_manager/manager.py

GnssResearchSite

High-level manager for a GNSS research site with dual Icechunk stores.

This class coordinates between RINEX data storage (Level 1) and VOD analysis storage (Level 2), providing a unified interface for site-wide operations.

Architecture: - RINEX Store: Raw/standardized observations per receiver - VOD Store: Analysis products comparing receiver pairs

Features: - Automatic store initialization from config - Receiver management and validation - Analysis workflow coordination - Unified logging and error handling

Parameters

site_name : str Name of the research site (must exist in config).

Raises

KeyError If site_name is not found in the RESEARCH_SITES config.

Source code in packages/canvod-store/src/canvod/store/manager.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
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
class GnssResearchSite:
    """
    High-level manager for a GNSS research site with dual Icechunk stores.

    This class coordinates between RINEX data storage (Level 1) and
    VOD analysis storage (Level 2), providing a unified interface
    for site-wide operations.

    Architecture:
    - RINEX Store: Raw/standardized observations per receiver
    - VOD Store: Analysis products comparing receiver pairs

    Features:
    - Automatic store initialization from config
    - Receiver management and validation
    - Analysis workflow coordination
    - Unified logging and error handling

    Parameters
    ----------
    site_name : str
        Name of the research site (must exist in config).

    Raises
    ------
    KeyError
        If ``site_name`` is not found in the RESEARCH_SITES config.
    """

    def __init__(self, site_name: str) -> None:
        """Initialize the site manager.

        Parameters
        ----------
        site_name : str
            Name of the research site.
        """
        from canvod.utils.config import load_config

        config = load_config()
        sites = config.sites.sites

        if site_name not in sites:
            available_sites = list(sites.keys())
            raise KeyError(
                f"Site '{site_name}' not found in config. "
                f"Available sites: {available_sites}"
            )

        self.site_name = site_name
        self._site_config = sites[site_name]
        self._logger = get_logger(__name__).bind(site=site_name)

        rinex_store_path = config.processing.storage.get_rinex_store_path(site_name)
        vod_store_path = config.processing.storage.get_vod_store_path(site_name)

        # Initialize stores using paths from processing.yaml
        self.rinex_store = create_rinex_store(rinex_store_path)
        self.vod_store = create_vod_store(vod_store_path)

        self._logger.info(
            f"Initialized GNSS research site: {site_name}",
            rinex_store=str(rinex_store_path),
            vod_store=str(vod_store_path),
        )

    @property
    def site_config(self) -> dict[str, Any]:
        """Get the site configuration as a dictionary."""
        return self._site_config.model_dump()

    @property
    def receivers(self) -> dict[str, dict[str, Any]]:
        """Get all configured receivers for this site."""
        return {
            name: cfg.model_dump() for name, cfg in self._site_config.receivers.items()
        }

    @property
    def active_receivers(self) -> dict[str, dict[str, Any]]:
        """Get only active receivers for this site."""
        return {
            name: config
            for name, config in self.receivers.items()
            if config.get("active", True)
        }

    @property
    def vod_analyses(self) -> dict[str, VodAnalysisConfig]:
        """Get all configured VOD analyses for this site.

        Returns auto-derived analyses from scs_from if no explicit
        vod_analyses are configured.
        """
        if self._site_config.vod_analyses is not None:
            return dict(self._site_config.vod_analyses)
        return self.get_auto_vod_analyses()

    @property
    def active_vod_analyses(self) -> dict[str, VodAnalysisConfig]:
        """Get only active VOD analyses for this site."""
        return {
            name: config
            for name, config in self.vod_analyses.items()
            if getattr(config, "active", True)
        }

    def get_receiver_metadata(
        self, receiver_name: str
    ) -> dict[str, str | int | float | bool] | None:
        """Get freeform metadata for a receiver.

        Returns the ``metadata`` dict from ``ReceiverConfig`` in
        ``sites.yaml``, or ``None`` if not configured.

        Parameters
        ----------
        receiver_name : str
            Name of the receiver.

        Returns
        -------
        dict or None
            Receiver metadata dict, or None.
        """
        cfg = self._site_config.receivers.get(receiver_name)
        if cfg is None:
            return None
        return cfg.metadata

    @classmethod
    def from_rinex_store_path(
        cls,
        rinex_store_path: Path,
    ) -> GnssResearchSite:
        """
        Create a GnssResearchSite instance from a RINEX store path.

        Parameters
        ----------
        rinex_store_path : Path
            Path to the RINEX Icechunk store.

        Returns
        -------
        GnssResearchSite
            Initialized research site manager.

        Raises
        ------
        ValueError
            If no matching site is found for the given path.
        """
        # Load config to get store paths
        from canvod.utils.config import load_config

        config = load_config()

        # Try to match against each site's expected rinex store path
        for site_name in config.sites.sites.keys():
            expected_path = config.processing.storage.get_rinex_store_path(site_name)
            if expected_path == rinex_store_path:
                return cls(site_name)

        raise ValueError(
            f"No research site found for RINEX store path: {rinex_store_path}"
        )

    def get_reference_canopy_pairs(self) -> list[tuple[str, str]]:
        """Expand scs_from into (reference_name, canopy_name) pairs.

        Returns
        -------
        list[tuple[str, str]]
            List of (reference_name, canopy_name) pairs.
        """
        return self._site_config.get_reference_canopy_pairs()

    def get_auto_vod_analyses(self) -> dict[str, VodAnalysisConfig]:
        """Derive VOD analysis pairs from scs_from configuration.

        Creates one VOD pair per (canopy, reference_for_that_canopy) combination.

        Returns
        -------
        dict[str, VodAnalysisConfig]
            Auto-derived VOD analyses keyed by analysis name.
        """
        analyses: dict[str, VodAnalysisConfig] = {}
        for ref_name, canopy_name in self.get_reference_canopy_pairs():
            analysis_name = f"{canopy_name}_vs_{ref_name}"
            analyses[analysis_name] = VodAnalysisConfig(
                canopy_receiver=canopy_name,
                reference_receiver=f"{ref_name}_{canopy_name}",
                description=f"VOD analysis {canopy_name} vs {ref_name}",
            )
        return analyses

    def validate_site_config(self) -> bool:
        """
        Validate that the site configuration is consistent.

        Returns
        -------
        bool
            True if configuration is valid.

        Raises
        ------
        ValueError
            If configuration is invalid.
        """
        # Check that all VOD analyses reference valid receivers
        # Build set of valid reference store groups (e.g. reference_01_canopy_01)
        valid_ref_groups = {
            f"{ref}_{canopy}" for ref, canopy in self.get_reference_canopy_pairs()
        }

        for analysis_name, analysis_config in self.vod_analyses.items():
            canopy_rx = analysis_config.canopy_receiver
            ref_rx = analysis_config.reference_receiver

            if canopy_rx not in self.receivers:
                raise ValueError(
                    f"VOD analysis '{analysis_name}' references "
                    f"unknown canopy receiver: {canopy_rx}"
                )
            # ref_rx can be either a raw receiver name or a store group name
            if ref_rx not in self.receivers and ref_rx not in valid_ref_groups:
                raise ValueError(
                    f"VOD analysis '{analysis_name}' references "
                    f"unknown reference receiver/group: {ref_rx}"
                )

            # Check canopy type
            canopy_type = self.receivers[canopy_rx]["type"]
            if canopy_type != "canopy":
                raise ValueError(
                    f"Receiver '{canopy_rx}' used as canopy but type is '{canopy_type}'"
                )
            # Check reference type (only if it's a raw receiver name)
            if ref_rx in self.receivers:
                ref_type = self.receivers[ref_rx]["type"]
                if ref_type != "reference":
                    raise ValueError(
                        f"Receiver '{ref_rx}' used as reference"
                        f" but type is '{ref_type}'"
                    )

        self._logger.debug("Site configuration validation passed")
        return True

    def get_receiver_groups(self) -> list[str]:
        """
        Get list of receiver groups that exist in the RINEX store.

        Returns
        -------
        list[str]
            Existing receiver group names.
        """
        return self.rinex_store.list_groups()

    def get_vod_analysis_groups(self) -> list[str]:
        """
        Get list of VOD analysis groups that exist in the VOD store.

        Returns
        -------
        list[str]
            Existing VOD analysis group names.
        """
        return self.vod_store.list_groups()

    def ingest_receiver_data(
        self, dataset: xr.Dataset, receiver_name: str, commit_message: str | None = None
    ) -> None:
        """
        Ingest RINEX data for a specific receiver.

        Parameters
        ----------
        dataset : xr.Dataset
            Processed RINEX dataset to store.
        receiver_name : str
            Name of the receiver (must be configured).
        commit_message : str, optional
            Commit message to store with the data.

        Raises
        ------
        ValueError
            If ``receiver_name`` is not configured.
        """
        if receiver_name not in self.receivers:
            available_receivers = list(self.receivers.keys())
            raise ValueError(
                f"Receiver '{receiver_name}' not configured. "
                f"Available: {available_receivers}"
            )

        # Merge receiver metadata into dataset attrs (never overwrite existing)
        receiver_meta = self.get_receiver_metadata(receiver_name)
        if receiver_meta:
            skipped = {k for k in receiver_meta if k in dataset.attrs}
            if skipped:
                self._logger.warning(
                    f"Receiver metadata keys {skipped} already exist in "
                    f"dataset attrs — skipping (existing attrs take precedence)"
                )
            new_attrs = {
                k: v for k, v in receiver_meta.items() if k not in dataset.attrs
            }
            dataset.attrs.update(new_attrs)

        self._logger.info(f"Ingesting RINEX data for receiver '{receiver_name}'")

        self.rinex_store.write_or_append_group(
            dataset=dataset, group_name=receiver_name, commit_message=commit_message
        )

        self._logger.info(f"Successfully ingested data for receiver '{receiver_name}'")

    def read_receiver_data(
        self, receiver_name: str, time_range: tuple[datetime, datetime] | None = None
    ) -> xr.Dataset:
        """
        Read data from a specific receiver.

        Parameters
        ----------
        receiver_name : str
            Name of the receiver.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the data.

        Returns
        -------
        xr.Dataset
            Dataset containing receiver observations.

        Raises
        ------
        ValueError
            If the receiver group does not exist.
        """
        if not self.rinex_store.group_exists(receiver_name):
            available_groups = self.get_receiver_groups()
            raise ValueError(
                f"No data found for receiver '{receiver_name}'. "
                f"Available: {available_groups}"
            )

        self._logger.info(f"Reading data for receiver '{receiver_name}'")

        if self.rinex_store._rinex_store_strategy == "append":
            ds = self.rinex_store.read_group_deduplicated(receiver_name, keep="last")
        else:
            ds = self.rinex_store.read_group(receiver_name)

        # Apply time filtering if specified
        if time_range is not None:
            start_time, end_time = time_range
            ds = ds.where(
                (ds.epoch >= np.datetime64(start_time, "ns"))
                & (ds.epoch <= np.datetime64(end_time, "ns")),
                drop=True,
            )

            self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

        return ds

    def store_vod_analysis(
        self,
        vod_dataset: xr.Dataset,
        analysis_name: str,
        commit_message: str | None = None,
    ) -> None:
        """
        Store VOD analysis results.

        Parameters
        ----------
        vod_dataset : xr.Dataset
            Dataset containing VOD analysis results.
        analysis_name : str
            Name of the analysis (must be configured).
        commit_message : str, optional
            Commit message to store with the results.

        Raises
        ------
        ValueError
            If ``analysis_name`` is not configured.
        """
        if analysis_name not in self.vod_analyses:
            available_analyses = list(self.vod_analyses.keys())
            raise ValueError(
                f"VOD analysis '{analysis_name}' not configured. "
                f"Available: {available_analyses}"
            )

        self._logger.info(f"Storing VOD analysis results: '{analysis_name}'")

        self.vod_store.write_or_append_group(
            dataset=vod_dataset, group_name=analysis_name, commit_message=commit_message
        )

        self._logger.info(f"Successfully stored VOD analysis: '{analysis_name}'")

    def read_vod_analysis(
        self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
    ) -> xr.Dataset:
        """
        Read VOD analysis results.

        Parameters
        ----------
        analysis_name : str
            Name of the analysis.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the results.

        Returns
        -------
        xr.Dataset
            Dataset containing VOD analysis results.

        Raises
        ------
        ValueError
            If the analysis group does not exist.
        """
        if not self.vod_store.group_exists(analysis_name):
            available_groups = self.get_vod_analysis_groups()
            raise ValueError(
                f"No VOD results found for analysis '{analysis_name}'. "
                f"Available: {available_groups}"
            )

        self._logger.info(f"Reading VOD analysis: '{analysis_name}'")

        ds = self.vod_store.read_group(analysis_name)

        # Apply time filtering if specified
        if time_range is not None:
            start_time, end_time = time_range
            ds = ds.sel(epoch=slice(start_time, end_time))
            self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

        return ds

    def prepare_vod_input_data(
        self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
    ) -> tuple[xr.Dataset, xr.Dataset]:
        """
        Prepare aligned input data for VOD analysis.

        Reads data from both receivers specified in the analysis configuration
        and returns them aligned for VOD processing.

        Parameters
        ----------
        analysis_name : str
            Name of the VOD analysis configuration.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the data.

        Returns
        -------
        tuple of (xr.Dataset, xr.Dataset)
            Tuple of (canopy_dataset, reference_dataset).

        Raises
        ------
        ValueError
            If the analysis is not configured or data is missing.
        """
        if analysis_name not in self.vod_analyses:
            available_analyses = list(self.vod_analyses.keys())
            raise ValueError(
                f"VOD analysis '{analysis_name}' not configured. "
                f"Available: {available_analyses}"
            )

        analysis_config = self.vod_analyses[analysis_name]
        canopy_receiver = analysis_config.canopy_receiver
        reference_receiver = analysis_config.reference_receiver

        self._logger.info(
            f"Preparing VOD input data: {canopy_receiver} vs {reference_receiver}"
        )

        # Read data from both receivers
        canopy_data = self.read_receiver_data(canopy_receiver, time_range)
        reference_data = self.read_receiver_data(reference_receiver, time_range)

        self._logger.info(
            f"Loaded data - Canopy: {dict(canopy_data.dims)}, "
            f"Reference: {dict(reference_data.dims)}"
        )

        return canopy_data, reference_data

    def calculate_vod(
        self,
        analysis_name: str,
        calculator_class: type[VODCalculator] | None = None,
        time_range: tuple[datetime, datetime] | None = None,
    ) -> xr.Dataset:
        """
        Calculate VOD for a configured analysis pair.

        Parameters
        ----------
        analysis_name : str
            Analysis name from config (e.g., 'canopy_01_vs_reference_01')
        calculator_class : type[VODCalculator], optional
            VOD calculator class to use. If None, uses TauOmegaZerothOrder.
        time_range : tuple of datetime, optional
            (start_time, end_time) for filtering the data

        Returns
        -------
        xr.Dataset
            VOD dataset

        Note
        ----
        Requires canvod-vod to be installed.
        """
        if calculator_class is None:
            try:
                from canvod.vod import TauOmegaZerothOrder

                calculator_class = TauOmegaZerothOrder
            except ImportError as e:
                raise ImportError(
                    "canvod-vod package required for VOD calculation. "
                    "Install with: pip install canvod-vod"
                ) from e

        canopy_ds, reference_ds = self.prepare_vod_input_data(analysis_name, time_range)

        # Align once so we can access both r arrays for radial_diff before
        # passing to the calculator (which would otherwise re-align internally).
        canopy_aligned, reference_aligned = xr.align(
            canopy_ds, reference_ds, join="inner"
        )

        # Use the calculator's class method for calculation (alignment already done)
        vod_ds = calculator_class.from_datasets(
            canopy_aligned, reference_aligned, align=False
        )

        # Apply config-gated derived quantities
        from canvod.utils.config import load_config as _load_config

        _params = _load_config().processing.processing

        if not _params.store_delta_snr:
            vod_ds = vod_ds.drop_vars("delta_snr", errors="ignore")

        if _params.store_radial_diff:
            if "r" in canopy_aligned and "r" in reference_aligned:
                radial_diff = canopy_aligned["r"] - reference_aligned["r"]
                radial_diff.attrs["units"] = "m"
                radial_diff.attrs["long_name"] = (
                    "radial distance difference (canopy − reference)"
                )
                vod_ds["radial_diff"] = radial_diff
            else:
                self._logger.warning(
                    "store_radial_diff=true but 'r' not present in receiver data; "
                    "set store_radial_distance=true at ingest time to enable this"
                )

        # Add metadata
        analysis_config = self.vod_analyses[analysis_name]
        vod_ds.attrs["analysis_name"] = analysis_name
        vod_ds.attrs["canopy_receiver"] = analysis_config.canopy_receiver
        vod_ds.attrs["reference_receiver"] = analysis_config.reference_receiver
        vod_ds.attrs["calculator"] = calculator_class.__name__
        vod_ds.attrs["canopy_hash"] = canopy_ds.attrs.get("File Hash", "unknown")
        vod_ds.attrs["reference_hash"] = reference_ds.attrs.get("File Hash", "unknown")

        self._logger.info(
            f"VOD calculated for {analysis_name} using {calculator_class.__name__}"
        )
        return vod_ds

    def store_vod(
        self,
        vod_ds: xr.Dataset,
        analysis_name: str,
    ) -> str:
        """
        Store VOD dataset in VOD store.

        Parameters
        ----------
        vod_ds : xr.Dataset
            VOD dataset to store
        analysis_name : str
            Analysis name (group name in store)

        Returns
        -------
        str
            Snapshot ID
        """
        import importlib.metadata

        from icechunk.xarray import to_icechunk

        canopy_hash = vod_ds.attrs.get("canopy_hash", "unknown")
        reference_hash = vod_ds.attrs.get("reference_hash", "unknown")
        combined_hash = f"{canopy_hash}_{reference_hash}"

        with self.vod_store.writable_session() as session:
            groups = self.vod_store.list_groups() or []

            if analysis_name not in groups:
                to_icechunk(vod_ds, session, group=analysis_name, mode="w")
                action = "write"
            else:
                to_icechunk(vod_ds, session, group=analysis_name, append_dim="epoch")
                action = "append"

            version = importlib.metadata.version("canvodpy")
            commit_msg = f"[v{version}] VOD for {analysis_name}"
            snapshot_id = session.commit(commit_msg)

        self.vod_store.append_metadata(
            group_name=analysis_name,
            rinex_hash=combined_hash,
            start=vod_ds["epoch"].values[0],
            end=vod_ds["epoch"].values[-1],
            snapshot_id=snapshot_id,
            action=action,
            commit_msg=commit_msg,
            dataset_attrs=dict(vod_ds.attrs),
        )

        self._logger.info(
            f"VOD stored for {analysis_name}, snapshot={snapshot_id[:8]}..."
        )
        return snapshot_id

    def get_site_summary(self) -> dict[str, Any]:
        """
        Get a comprehensive summary of the research site.

        Returns
        -------
        dict
            Dictionary with site statistics, data availability, and store paths.
        """
        rinex_groups = self.get_receiver_groups()
        vod_groups = self.get_vod_analysis_groups()

        summary: dict[str, Any] = {
            "site_name": self.site_name,
            "site_config": {
                "total_receivers": len(self.receivers),
                "active_receivers": len(self.active_receivers),
                "total_vod_analyses": len(self.vod_analyses),
                "active_vod_analyses": len(self.active_vod_analyses),
            },
            "data_status": {
                "rinex_groups_exist": len(rinex_groups),
                "rinex_groups": rinex_groups,
                "vod_groups_exist": len(vod_groups),
                "vod_groups": vod_groups,
            },
            "stores": {
                "rinex_store_path": str(self.rinex_store.store_path),
                "vod_store_path": str(self.vod_store.store_path),
            },
        }

        # Add receiver details
        summary["receivers"] = {}
        for receiver_name, receiver_config in self.active_receivers.items():
            has_data = receiver_name in rinex_groups
            summary["receivers"][receiver_name] = {
                "type": receiver_config["type"],
                "description": receiver_config["description"],
                "has_data": has_data,
            }

            if has_data:
                try:
                    info = self.rinex_store.get_group_info(receiver_name)
                    summary["receivers"][receiver_name]["data_info"] = {
                        "dimensions": info["dimensions"],
                        "variables": len(info["variables"]),
                        "temporal_info": info.get("temporal_info", {}),
                    }
                except Exception as e:
                    self._logger.warning(f"Failed to get info for {receiver_name}: {e}")

        # Add VOD analysis details
        summary["vod_analyses"] = {}
        for analysis_name, analysis_config in self.active_vod_analyses.items():
            has_results = analysis_name in vod_groups
            summary["vod_analyses"][analysis_name] = {
                "canopy_receiver": analysis_config.canopy_receiver,
                "reference_receiver": analysis_config.reference_receiver,
                "description": analysis_config.description,
                "has_results": has_results,
            }

            if has_results:
                try:
                    info = self.vod_store.get_group_info(analysis_name)
                    summary["vod_analyses"][analysis_name]["results_info"] = {
                        "dimensions": info["dimensions"],
                        "variables": len(info["variables"]),
                        "temporal_info": info.get("temporal_info", {}),
                    }
                except Exception as e:
                    self._logger.warning(
                        f"Failed to get VOD info for {analysis_name}: {e}"
                    )

        return summary

    def is_day_complete(
        self,
        yyyydoy: str,
        receiver_types: list[str] | None = None,
        completeness_threshold: float = 0.95,
    ) -> bool:
        """
        Check if a day has complete data coverage for all receiver types.

        Parameters
        ----------
        yyyydoy : str
            Date in YYYYDOY format (e.g., "2024256")
        receiver_types : List[str], optional
            Receiver types to check. Defaults to ['canopy', 'reference']
        completeness_threshold : float
            Fraction of expected epochs that must exist (default 0.95 = 95%)
            Allows for small gaps due to receiver issues

        Returns
        -------
        bool
            True if all receiver types have complete data for this day
        """
        if receiver_types is None:
            receiver_types = ["canopy", "reference"]

        from canvod.utils.tools import YYYYDOY

        yyyydoy_obj = YYYYDOY.from_str(yyyydoy)

        # Expected epochs for 24h at 30s sampling
        expected_epochs = int(24 * 3600 / 30)  # 2880 epochs
        required_epochs = int(expected_epochs * completeness_threshold)

        for receiver_type in receiver_types:
            # Get receiver name for this type
            receiver_name = None
            for name, config in self.active_receivers.items():
                if config.get("type") == receiver_type:
                    receiver_name = name
                    break

            if not receiver_name:
                self._logger.warning(f"No receiver configured for type {receiver_type}")
                return False

            try:
                # Try to read data for this day
                import datetime as _dt

                assert yyyydoy_obj.date is not None
                _day_start = datetime.combine(yyyydoy_obj.date, _dt.time.min)
                time_range = (_day_start, _day_start + _dt.timedelta(days=1))

                ds = self.read_receiver_data(
                    receiver_name=receiver_name, time_range=time_range
                )

                # Check epoch count
                n_epochs = ds.sizes.get("epoch", 0)

                if n_epochs < required_epochs:
                    self._logger.info(
                        f"{receiver_name} {yyyydoy}: Only "
                        f"{n_epochs}/{expected_epochs} epochs "
                        f"({n_epochs / expected_epochs * 100:.1f}%) - incomplete"
                    )
                    return False

                self._logger.debug(
                    f"{receiver_name} {yyyydoy}: "
                    f"{n_epochs}/{expected_epochs} epochs - complete"
                )

            except (ValueError, KeyError, Exception) as e:
                # No data exists or error reading
                self._logger.debug(f"{receiver_name} {yyyydoy}: No data found - {e}")
                return False

        # All receiver types have complete data
        return True

    def __repr__(self) -> str:
        """Return the developer-facing representation.

        Returns
        -------
        str
            Representation string.
        """
        return f"GnssResearchSite(site_name='{self.site_name}')"

    def __str__(self) -> str:
        """Return a human-readable summary.

        Returns
        -------
        str
            Summary string.
        """
        rinex_groups = len(self.get_receiver_groups())
        vod_groups = len(self.get_vod_analysis_groups())
        return (
            f"GNSS Research Site: {self.site_name}\n"
            f"  Receivers: {len(self.active_receivers)} configured, "
            f"{rinex_groups} with data\n"
            f"  VOD Analyses: {len(self.active_vod_analyses)} configured, "
            f"{vod_groups} with results"
        )

site_config property

Get the site configuration as a dictionary.

receivers property

Get all configured receivers for this site.

active_receivers property

Get only active receivers for this site.

vod_analyses property

Get all configured VOD analyses for this site.

Returns auto-derived analyses from scs_from if no explicit vod_analyses are configured.

active_vod_analyses property

Get only active VOD analyses for this site.

__init__(site_name)

Initialize the site manager.

Parameters

site_name : str Name of the research site.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def __init__(self, site_name: str) -> None:
    """Initialize the site manager.

    Parameters
    ----------
    site_name : str
        Name of the research site.
    """
    from canvod.utils.config import load_config

    config = load_config()
    sites = config.sites.sites

    if site_name not in sites:
        available_sites = list(sites.keys())
        raise KeyError(
            f"Site '{site_name}' not found in config. "
            f"Available sites: {available_sites}"
        )

    self.site_name = site_name
    self._site_config = sites[site_name]
    self._logger = get_logger(__name__).bind(site=site_name)

    rinex_store_path = config.processing.storage.get_rinex_store_path(site_name)
    vod_store_path = config.processing.storage.get_vod_store_path(site_name)

    # Initialize stores using paths from processing.yaml
    self.rinex_store = create_rinex_store(rinex_store_path)
    self.vod_store = create_vod_store(vod_store_path)

    self._logger.info(
        f"Initialized GNSS research site: {site_name}",
        rinex_store=str(rinex_store_path),
        vod_store=str(vod_store_path),
    )

get_receiver_metadata(receiver_name)

Get freeform metadata for a receiver.

Returns the metadata dict from ReceiverConfig in sites.yaml, or None if not configured.

Parameters

receiver_name : str Name of the receiver.

Returns

dict or None Receiver metadata dict, or None.

Source code in packages/canvod-store/src/canvod/store/manager.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def get_receiver_metadata(
    self, receiver_name: str
) -> dict[str, str | int | float | bool] | None:
    """Get freeform metadata for a receiver.

    Returns the ``metadata`` dict from ``ReceiverConfig`` in
    ``sites.yaml``, or ``None`` if not configured.

    Parameters
    ----------
    receiver_name : str
        Name of the receiver.

    Returns
    -------
    dict or None
        Receiver metadata dict, or None.
    """
    cfg = self._site_config.receivers.get(receiver_name)
    if cfg is None:
        return None
    return cfg.metadata

from_rinex_store_path(rinex_store_path) classmethod

Create a GnssResearchSite instance from a RINEX store path.

Parameters

rinex_store_path : Path Path to the RINEX Icechunk store.

Returns

GnssResearchSite Initialized research site manager.

Raises

ValueError If no matching site is found for the given path.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
@classmethod
def from_rinex_store_path(
    cls,
    rinex_store_path: Path,
) -> GnssResearchSite:
    """
    Create a GnssResearchSite instance from a RINEX store path.

    Parameters
    ----------
    rinex_store_path : Path
        Path to the RINEX Icechunk store.

    Returns
    -------
    GnssResearchSite
        Initialized research site manager.

    Raises
    ------
    ValueError
        If no matching site is found for the given path.
    """
    # Load config to get store paths
    from canvod.utils.config import load_config

    config = load_config()

    # Try to match against each site's expected rinex store path
    for site_name in config.sites.sites.keys():
        expected_path = config.processing.storage.get_rinex_store_path(site_name)
        if expected_path == rinex_store_path:
            return cls(site_name)

    raise ValueError(
        f"No research site found for RINEX store path: {rinex_store_path}"
    )

get_reference_canopy_pairs()

Expand scs_from into (reference_name, canopy_name) pairs.

Returns

list[tuple[str, str]] List of (reference_name, canopy_name) pairs.

Source code in packages/canvod-store/src/canvod/store/manager.py
199
200
201
202
203
204
205
206
207
def get_reference_canopy_pairs(self) -> list[tuple[str, str]]:
    """Expand scs_from into (reference_name, canopy_name) pairs.

    Returns
    -------
    list[tuple[str, str]]
        List of (reference_name, canopy_name) pairs.
    """
    return self._site_config.get_reference_canopy_pairs()

get_auto_vod_analyses()

Derive VOD analysis pairs from scs_from configuration.

Creates one VOD pair per (canopy, reference_for_that_canopy) combination.

Returns

dict[str, VodAnalysisConfig] Auto-derived VOD analyses keyed by analysis name.

Source code in packages/canvod-store/src/canvod/store/manager.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def get_auto_vod_analyses(self) -> dict[str, VodAnalysisConfig]:
    """Derive VOD analysis pairs from scs_from configuration.

    Creates one VOD pair per (canopy, reference_for_that_canopy) combination.

    Returns
    -------
    dict[str, VodAnalysisConfig]
        Auto-derived VOD analyses keyed by analysis name.
    """
    analyses: dict[str, VodAnalysisConfig] = {}
    for ref_name, canopy_name in self.get_reference_canopy_pairs():
        analysis_name = f"{canopy_name}_vs_{ref_name}"
        analyses[analysis_name] = VodAnalysisConfig(
            canopy_receiver=canopy_name,
            reference_receiver=f"{ref_name}_{canopy_name}",
            description=f"VOD analysis {canopy_name} vs {ref_name}",
        )
    return analyses

validate_site_config()

Validate that the site configuration is consistent.

Returns

bool True if configuration is valid.

Raises

ValueError If configuration is invalid.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def validate_site_config(self) -> bool:
    """
    Validate that the site configuration is consistent.

    Returns
    -------
    bool
        True if configuration is valid.

    Raises
    ------
    ValueError
        If configuration is invalid.
    """
    # Check that all VOD analyses reference valid receivers
    # Build set of valid reference store groups (e.g. reference_01_canopy_01)
    valid_ref_groups = {
        f"{ref}_{canopy}" for ref, canopy in self.get_reference_canopy_pairs()
    }

    for analysis_name, analysis_config in self.vod_analyses.items():
        canopy_rx = analysis_config.canopy_receiver
        ref_rx = analysis_config.reference_receiver

        if canopy_rx not in self.receivers:
            raise ValueError(
                f"VOD analysis '{analysis_name}' references "
                f"unknown canopy receiver: {canopy_rx}"
            )
        # ref_rx can be either a raw receiver name or a store group name
        if ref_rx not in self.receivers and ref_rx not in valid_ref_groups:
            raise ValueError(
                f"VOD analysis '{analysis_name}' references "
                f"unknown reference receiver/group: {ref_rx}"
            )

        # Check canopy type
        canopy_type = self.receivers[canopy_rx]["type"]
        if canopy_type != "canopy":
            raise ValueError(
                f"Receiver '{canopy_rx}' used as canopy but type is '{canopy_type}'"
            )
        # Check reference type (only if it's a raw receiver name)
        if ref_rx in self.receivers:
            ref_type = self.receivers[ref_rx]["type"]
            if ref_type != "reference":
                raise ValueError(
                    f"Receiver '{ref_rx}' used as reference"
                    f" but type is '{ref_type}'"
                )

    self._logger.debug("Site configuration validation passed")
    return True

get_receiver_groups()

Get list of receiver groups that exist in the RINEX store.

Returns

list[str] Existing receiver group names.

Source code in packages/canvod-store/src/canvod/store/manager.py
283
284
285
286
287
288
289
290
291
292
def get_receiver_groups(self) -> list[str]:
    """
    Get list of receiver groups that exist in the RINEX store.

    Returns
    -------
    list[str]
        Existing receiver group names.
    """
    return self.rinex_store.list_groups()

get_vod_analysis_groups()

Get list of VOD analysis groups that exist in the VOD store.

Returns

list[str] Existing VOD analysis group names.

Source code in packages/canvod-store/src/canvod/store/manager.py
294
295
296
297
298
299
300
301
302
303
def get_vod_analysis_groups(self) -> list[str]:
    """
    Get list of VOD analysis groups that exist in the VOD store.

    Returns
    -------
    list[str]
        Existing VOD analysis group names.
    """
    return self.vod_store.list_groups()

ingest_receiver_data(dataset, receiver_name, commit_message=None)

Ingest RINEX data for a specific receiver.

Parameters

dataset : xr.Dataset Processed RINEX dataset to store. receiver_name : str Name of the receiver (must be configured). commit_message : str, optional Commit message to store with the data.

Raises

ValueError If receiver_name is not configured.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def ingest_receiver_data(
    self, dataset: xr.Dataset, receiver_name: str, commit_message: str | None = None
) -> None:
    """
    Ingest RINEX data for a specific receiver.

    Parameters
    ----------
    dataset : xr.Dataset
        Processed RINEX dataset to store.
    receiver_name : str
        Name of the receiver (must be configured).
    commit_message : str, optional
        Commit message to store with the data.

    Raises
    ------
    ValueError
        If ``receiver_name`` is not configured.
    """
    if receiver_name not in self.receivers:
        available_receivers = list(self.receivers.keys())
        raise ValueError(
            f"Receiver '{receiver_name}' not configured. "
            f"Available: {available_receivers}"
        )

    # Merge receiver metadata into dataset attrs (never overwrite existing)
    receiver_meta = self.get_receiver_metadata(receiver_name)
    if receiver_meta:
        skipped = {k for k in receiver_meta if k in dataset.attrs}
        if skipped:
            self._logger.warning(
                f"Receiver metadata keys {skipped} already exist in "
                f"dataset attrs — skipping (existing attrs take precedence)"
            )
        new_attrs = {
            k: v for k, v in receiver_meta.items() if k not in dataset.attrs
        }
        dataset.attrs.update(new_attrs)

    self._logger.info(f"Ingesting RINEX data for receiver '{receiver_name}'")

    self.rinex_store.write_or_append_group(
        dataset=dataset, group_name=receiver_name, commit_message=commit_message
    )

    self._logger.info(f"Successfully ingested data for receiver '{receiver_name}'")

read_receiver_data(receiver_name, time_range=None)

Read data from a specific receiver.

Parameters

receiver_name : str Name of the receiver. time_range : tuple of datetime, optional (start_time, end_time) for filtering the data.

Returns

xr.Dataset Dataset containing receiver observations.

Raises

ValueError If the receiver group does not exist.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def read_receiver_data(
    self, receiver_name: str, time_range: tuple[datetime, datetime] | None = None
) -> xr.Dataset:
    """
    Read data from a specific receiver.

    Parameters
    ----------
    receiver_name : str
        Name of the receiver.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the data.

    Returns
    -------
    xr.Dataset
        Dataset containing receiver observations.

    Raises
    ------
    ValueError
        If the receiver group does not exist.
    """
    if not self.rinex_store.group_exists(receiver_name):
        available_groups = self.get_receiver_groups()
        raise ValueError(
            f"No data found for receiver '{receiver_name}'. "
            f"Available: {available_groups}"
        )

    self._logger.info(f"Reading data for receiver '{receiver_name}'")

    if self.rinex_store._rinex_store_strategy == "append":
        ds = self.rinex_store.read_group_deduplicated(receiver_name, keep="last")
    else:
        ds = self.rinex_store.read_group(receiver_name)

    # Apply time filtering if specified
    if time_range is not None:
        start_time, end_time = time_range
        ds = ds.where(
            (ds.epoch >= np.datetime64(start_time, "ns"))
            & (ds.epoch <= np.datetime64(end_time, "ns")),
            drop=True,
        )

        self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

    return ds

store_vod_analysis(vod_dataset, analysis_name, commit_message=None)

Store VOD analysis results.

Parameters

vod_dataset : xr.Dataset Dataset containing VOD analysis results. analysis_name : str Name of the analysis (must be configured). commit_message : str, optional Commit message to store with the results.

Raises

ValueError If analysis_name is not configured.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def store_vod_analysis(
    self,
    vod_dataset: xr.Dataset,
    analysis_name: str,
    commit_message: str | None = None,
) -> None:
    """
    Store VOD analysis results.

    Parameters
    ----------
    vod_dataset : xr.Dataset
        Dataset containing VOD analysis results.
    analysis_name : str
        Name of the analysis (must be configured).
    commit_message : str, optional
        Commit message to store with the results.

    Raises
    ------
    ValueError
        If ``analysis_name`` is not configured.
    """
    if analysis_name not in self.vod_analyses:
        available_analyses = list(self.vod_analyses.keys())
        raise ValueError(
            f"VOD analysis '{analysis_name}' not configured. "
            f"Available: {available_analyses}"
        )

    self._logger.info(f"Storing VOD analysis results: '{analysis_name}'")

    self.vod_store.write_or_append_group(
        dataset=vod_dataset, group_name=analysis_name, commit_message=commit_message
    )

    self._logger.info(f"Successfully stored VOD analysis: '{analysis_name}'")

read_vod_analysis(analysis_name, time_range=None)

Read VOD analysis results.

Parameters

analysis_name : str Name of the analysis. time_range : tuple of datetime, optional (start_time, end_time) for filtering the results.

Returns

xr.Dataset Dataset containing VOD analysis results.

Raises

ValueError If the analysis group does not exist.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def read_vod_analysis(
    self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
) -> xr.Dataset:
    """
    Read VOD analysis results.

    Parameters
    ----------
    analysis_name : str
        Name of the analysis.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the results.

    Returns
    -------
    xr.Dataset
        Dataset containing VOD analysis results.

    Raises
    ------
    ValueError
        If the analysis group does not exist.
    """
    if not self.vod_store.group_exists(analysis_name):
        available_groups = self.get_vod_analysis_groups()
        raise ValueError(
            f"No VOD results found for analysis '{analysis_name}'. "
            f"Available: {available_groups}"
        )

    self._logger.info(f"Reading VOD analysis: '{analysis_name}'")

    ds = self.vod_store.read_group(analysis_name)

    # Apply time filtering if specified
    if time_range is not None:
        start_time, end_time = time_range
        ds = ds.sel(epoch=slice(start_time, end_time))
        self._logger.debug(f"Applied time filter: {start_time} to {end_time}")

    return ds

prepare_vod_input_data(analysis_name, time_range=None)

Prepare aligned input data for VOD analysis.

Reads data from both receivers specified in the analysis configuration and returns them aligned for VOD processing.

Parameters

analysis_name : str Name of the VOD analysis configuration. time_range : tuple of datetime, optional (start_time, end_time) for filtering the data.

Returns

tuple of (xr.Dataset, xr.Dataset) Tuple of (canopy_dataset, reference_dataset).

Raises

ValueError If the analysis is not configured or data is missing.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def prepare_vod_input_data(
    self, analysis_name: str, time_range: tuple[datetime, datetime] | None = None
) -> tuple[xr.Dataset, xr.Dataset]:
    """
    Prepare aligned input data for VOD analysis.

    Reads data from both receivers specified in the analysis configuration
    and returns them aligned for VOD processing.

    Parameters
    ----------
    analysis_name : str
        Name of the VOD analysis configuration.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the data.

    Returns
    -------
    tuple of (xr.Dataset, xr.Dataset)
        Tuple of (canopy_dataset, reference_dataset).

    Raises
    ------
    ValueError
        If the analysis is not configured or data is missing.
    """
    if analysis_name not in self.vod_analyses:
        available_analyses = list(self.vod_analyses.keys())
        raise ValueError(
            f"VOD analysis '{analysis_name}' not configured. "
            f"Available: {available_analyses}"
        )

    analysis_config = self.vod_analyses[analysis_name]
    canopy_receiver = analysis_config.canopy_receiver
    reference_receiver = analysis_config.reference_receiver

    self._logger.info(
        f"Preparing VOD input data: {canopy_receiver} vs {reference_receiver}"
    )

    # Read data from both receivers
    canopy_data = self.read_receiver_data(canopy_receiver, time_range)
    reference_data = self.read_receiver_data(reference_receiver, time_range)

    self._logger.info(
        f"Loaded data - Canopy: {dict(canopy_data.dims)}, "
        f"Reference: {dict(reference_data.dims)}"
    )

    return canopy_data, reference_data

calculate_vod(analysis_name, calculator_class=None, time_range=None)

Calculate VOD for a configured analysis pair.

Parameters

analysis_name : str Analysis name from config (e.g., 'canopy_01_vs_reference_01') calculator_class : type[VODCalculator], optional VOD calculator class to use. If None, uses TauOmegaZerothOrder. time_range : tuple of datetime, optional (start_time, end_time) for filtering the data

Returns

xr.Dataset VOD dataset

Note

Requires canvod-vod to be installed.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def calculate_vod(
    self,
    analysis_name: str,
    calculator_class: type[VODCalculator] | None = None,
    time_range: tuple[datetime, datetime] | None = None,
) -> xr.Dataset:
    """
    Calculate VOD for a configured analysis pair.

    Parameters
    ----------
    analysis_name : str
        Analysis name from config (e.g., 'canopy_01_vs_reference_01')
    calculator_class : type[VODCalculator], optional
        VOD calculator class to use. If None, uses TauOmegaZerothOrder.
    time_range : tuple of datetime, optional
        (start_time, end_time) for filtering the data

    Returns
    -------
    xr.Dataset
        VOD dataset

    Note
    ----
    Requires canvod-vod to be installed.
    """
    if calculator_class is None:
        try:
            from canvod.vod import TauOmegaZerothOrder

            calculator_class = TauOmegaZerothOrder
        except ImportError as e:
            raise ImportError(
                "canvod-vod package required for VOD calculation. "
                "Install with: pip install canvod-vod"
            ) from e

    canopy_ds, reference_ds = self.prepare_vod_input_data(analysis_name, time_range)

    # Align once so we can access both r arrays for radial_diff before
    # passing to the calculator (which would otherwise re-align internally).
    canopy_aligned, reference_aligned = xr.align(
        canopy_ds, reference_ds, join="inner"
    )

    # Use the calculator's class method for calculation (alignment already done)
    vod_ds = calculator_class.from_datasets(
        canopy_aligned, reference_aligned, align=False
    )

    # Apply config-gated derived quantities
    from canvod.utils.config import load_config as _load_config

    _params = _load_config().processing.processing

    if not _params.store_delta_snr:
        vod_ds = vod_ds.drop_vars("delta_snr", errors="ignore")

    if _params.store_radial_diff:
        if "r" in canopy_aligned and "r" in reference_aligned:
            radial_diff = canopy_aligned["r"] - reference_aligned["r"]
            radial_diff.attrs["units"] = "m"
            radial_diff.attrs["long_name"] = (
                "radial distance difference (canopy − reference)"
            )
            vod_ds["radial_diff"] = radial_diff
        else:
            self._logger.warning(
                "store_radial_diff=true but 'r' not present in receiver data; "
                "set store_radial_distance=true at ingest time to enable this"
            )

    # Add metadata
    analysis_config = self.vod_analyses[analysis_name]
    vod_ds.attrs["analysis_name"] = analysis_name
    vod_ds.attrs["canopy_receiver"] = analysis_config.canopy_receiver
    vod_ds.attrs["reference_receiver"] = analysis_config.reference_receiver
    vod_ds.attrs["calculator"] = calculator_class.__name__
    vod_ds.attrs["canopy_hash"] = canopy_ds.attrs.get("File Hash", "unknown")
    vod_ds.attrs["reference_hash"] = reference_ds.attrs.get("File Hash", "unknown")

    self._logger.info(
        f"VOD calculated for {analysis_name} using {calculator_class.__name__}"
    )
    return vod_ds

store_vod(vod_ds, analysis_name)

Store VOD dataset in VOD store.

Parameters

vod_ds : xr.Dataset VOD dataset to store analysis_name : str Analysis name (group name in store)

Returns

str Snapshot ID

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def store_vod(
    self,
    vod_ds: xr.Dataset,
    analysis_name: str,
) -> str:
    """
    Store VOD dataset in VOD store.

    Parameters
    ----------
    vod_ds : xr.Dataset
        VOD dataset to store
    analysis_name : str
        Analysis name (group name in store)

    Returns
    -------
    str
        Snapshot ID
    """
    import importlib.metadata

    from icechunk.xarray import to_icechunk

    canopy_hash = vod_ds.attrs.get("canopy_hash", "unknown")
    reference_hash = vod_ds.attrs.get("reference_hash", "unknown")
    combined_hash = f"{canopy_hash}_{reference_hash}"

    with self.vod_store.writable_session() as session:
        groups = self.vod_store.list_groups() or []

        if analysis_name not in groups:
            to_icechunk(vod_ds, session, group=analysis_name, mode="w")
            action = "write"
        else:
            to_icechunk(vod_ds, session, group=analysis_name, append_dim="epoch")
            action = "append"

        version = importlib.metadata.version("canvodpy")
        commit_msg = f"[v{version}] VOD for {analysis_name}"
        snapshot_id = session.commit(commit_msg)

    self.vod_store.append_metadata(
        group_name=analysis_name,
        rinex_hash=combined_hash,
        start=vod_ds["epoch"].values[0],
        end=vod_ds["epoch"].values[-1],
        snapshot_id=snapshot_id,
        action=action,
        commit_msg=commit_msg,
        dataset_attrs=dict(vod_ds.attrs),
    )

    self._logger.info(
        f"VOD stored for {analysis_name}, snapshot={snapshot_id[:8]}..."
    )
    return snapshot_id

get_site_summary()

Get a comprehensive summary of the research site.

Returns

dict Dictionary with site statistics, data availability, and store paths.

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def get_site_summary(self) -> dict[str, Any]:
    """
    Get a comprehensive summary of the research site.

    Returns
    -------
    dict
        Dictionary with site statistics, data availability, and store paths.
    """
    rinex_groups = self.get_receiver_groups()
    vod_groups = self.get_vod_analysis_groups()

    summary: dict[str, Any] = {
        "site_name": self.site_name,
        "site_config": {
            "total_receivers": len(self.receivers),
            "active_receivers": len(self.active_receivers),
            "total_vod_analyses": len(self.vod_analyses),
            "active_vod_analyses": len(self.active_vod_analyses),
        },
        "data_status": {
            "rinex_groups_exist": len(rinex_groups),
            "rinex_groups": rinex_groups,
            "vod_groups_exist": len(vod_groups),
            "vod_groups": vod_groups,
        },
        "stores": {
            "rinex_store_path": str(self.rinex_store.store_path),
            "vod_store_path": str(self.vod_store.store_path),
        },
    }

    # Add receiver details
    summary["receivers"] = {}
    for receiver_name, receiver_config in self.active_receivers.items():
        has_data = receiver_name in rinex_groups
        summary["receivers"][receiver_name] = {
            "type": receiver_config["type"],
            "description": receiver_config["description"],
            "has_data": has_data,
        }

        if has_data:
            try:
                info = self.rinex_store.get_group_info(receiver_name)
                summary["receivers"][receiver_name]["data_info"] = {
                    "dimensions": info["dimensions"],
                    "variables": len(info["variables"]),
                    "temporal_info": info.get("temporal_info", {}),
                }
            except Exception as e:
                self._logger.warning(f"Failed to get info for {receiver_name}: {e}")

    # Add VOD analysis details
    summary["vod_analyses"] = {}
    for analysis_name, analysis_config in self.active_vod_analyses.items():
        has_results = analysis_name in vod_groups
        summary["vod_analyses"][analysis_name] = {
            "canopy_receiver": analysis_config.canopy_receiver,
            "reference_receiver": analysis_config.reference_receiver,
            "description": analysis_config.description,
            "has_results": has_results,
        }

        if has_results:
            try:
                info = self.vod_store.get_group_info(analysis_name)
                summary["vod_analyses"][analysis_name]["results_info"] = {
                    "dimensions": info["dimensions"],
                    "variables": len(info["variables"]),
                    "temporal_info": info.get("temporal_info", {}),
                }
            except Exception as e:
                self._logger.warning(
                    f"Failed to get VOD info for {analysis_name}: {e}"
                )

    return summary

is_day_complete(yyyydoy, receiver_types=None, completeness_threshold=0.95)

Check if a day has complete data coverage for all receiver types.

Parameters

yyyydoy : str Date in YYYYDOY format (e.g., "2024256") receiver_types : List[str], optional Receiver types to check. Defaults to ['canopy', 'reference'] completeness_threshold : float Fraction of expected epochs that must exist (default 0.95 = 95%) Allows for small gaps due to receiver issues

Returns

bool True if all receiver types have complete data for this day

Source code in packages/canvod-store/src/canvod/store/manager.py
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
def is_day_complete(
    self,
    yyyydoy: str,
    receiver_types: list[str] | None = None,
    completeness_threshold: float = 0.95,
) -> bool:
    """
    Check if a day has complete data coverage for all receiver types.

    Parameters
    ----------
    yyyydoy : str
        Date in YYYYDOY format (e.g., "2024256")
    receiver_types : List[str], optional
        Receiver types to check. Defaults to ['canopy', 'reference']
    completeness_threshold : float
        Fraction of expected epochs that must exist (default 0.95 = 95%)
        Allows for small gaps due to receiver issues

    Returns
    -------
    bool
        True if all receiver types have complete data for this day
    """
    if receiver_types is None:
        receiver_types = ["canopy", "reference"]

    from canvod.utils.tools import YYYYDOY

    yyyydoy_obj = YYYYDOY.from_str(yyyydoy)

    # Expected epochs for 24h at 30s sampling
    expected_epochs = int(24 * 3600 / 30)  # 2880 epochs
    required_epochs = int(expected_epochs * completeness_threshold)

    for receiver_type in receiver_types:
        # Get receiver name for this type
        receiver_name = None
        for name, config in self.active_receivers.items():
            if config.get("type") == receiver_type:
                receiver_name = name
                break

        if not receiver_name:
            self._logger.warning(f"No receiver configured for type {receiver_type}")
            return False

        try:
            # Try to read data for this day
            import datetime as _dt

            assert yyyydoy_obj.date is not None
            _day_start = datetime.combine(yyyydoy_obj.date, _dt.time.min)
            time_range = (_day_start, _day_start + _dt.timedelta(days=1))

            ds = self.read_receiver_data(
                receiver_name=receiver_name, time_range=time_range
            )

            # Check epoch count
            n_epochs = ds.sizes.get("epoch", 0)

            if n_epochs < required_epochs:
                self._logger.info(
                    f"{receiver_name} {yyyydoy}: Only "
                    f"{n_epochs}/{expected_epochs} epochs "
                    f"({n_epochs / expected_epochs * 100:.1f}%) - incomplete"
                )
                return False

            self._logger.debug(
                f"{receiver_name} {yyyydoy}: "
                f"{n_epochs}/{expected_epochs} epochs - complete"
            )

        except (ValueError, KeyError, Exception) as e:
            # No data exists or error reading
            self._logger.debug(f"{receiver_name} {yyyydoy}: No data found - {e}")
            return False

    # All receiver types have complete data
    return True

__repr__()

Return the developer-facing representation.

Returns

str Representation string.

Source code in packages/canvod-store/src/canvod/store/manager.py
843
844
845
846
847
848
849
850
851
def __repr__(self) -> str:
    """Return the developer-facing representation.

    Returns
    -------
    str
        Representation string.
    """
    return f"GnssResearchSite(site_name='{self.site_name}')"

__str__()

Return a human-readable summary.

Returns

str Summary string.

Source code in packages/canvod-store/src/canvod/store/manager.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
def __str__(self) -> str:
    """Return a human-readable summary.

    Returns
    -------
    str
        Summary string.
    """
    rinex_groups = len(self.get_receiver_groups())
    vod_groups = len(self.get_vod_analysis_groups())
    return (
        f"GNSS Research Site: {self.site_name}\n"
        f"  Receivers: {len(self.active_receivers)} configured, "
        f"{rinex_groups} with data\n"
        f"  VOD Analyses: {len(self.active_vod_analyses)} configured, "
        f"{vod_groups} with results"
    )

create_default_site()

Create a GnssResearchSite instance for the default site.

Returns

GnssResearchSite Instance for the DEFAULT_RESEARCH_SITE.

Source code in packages/canvod-store/src/canvod/store/manager.py
873
874
875
876
877
878
879
880
881
882
883
884
def create_default_site() -> GnssResearchSite:
    """
    Create a `GnssResearchSite` instance for the default site.

    Returns
    -------
    GnssResearchSite
        Instance for the ``DEFAULT_RESEARCH_SITE``.
    """
    from canvod.utils.config import load_config

    return GnssResearchSite(next(iter(load_config().sites.sites)))

Data Store

MyIcechunkStore

Core Icechunk store manager for GNSS data.

This class encapsulates all operations on a single Icechunk repository, providing a clean interface for GNSS data storage and retrieval with integrated logging and proper resource management.

Features: - Automatic repository creation/connection - Group management with validation - Session management with context managers - Integrated logging with file contexts - Configurable compression and chunking

Note on "metadata"

This class manages two distinct things both historically called "metadata":

  • File registry ({group}/metadata/table): per-file ingest ledger tracking hashes, temporal ranges, filenames, and paths. Managed by append_metadata(), load_metadata(), backup_metadata_table(), etc.

  • Store metadata (canvod.store_metadata package): store-level provenance (identity, creator, environment, compliance). Written to Zarr root attrs by the orchestrator. See canvod-store-metadata.

Parameters

store_path : Path Path to the Icechunk store directory. store_type : str, default "rinex_store" Type of store ("rinex_store" or "vod_store"). compression_level : int | None, optional Override default compression level. compression_algorithm : str | None, optional Override default compression algorithm.

Attributes

store_path : Path Path to the Icechunk store directory. store_type : str Type of store ("rinex_store" or "vod_store"). compression_level : int Compression level (1-9). compression_algorithm : icechunk.CompressionAlgorithm Compression algorithm enum. repo : icechunk.Repository The Icechunk repository instance.

Source code in packages/canvod-store/src/canvod/store/store.py
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 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
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
@add_rich_display_to_store
class MyIcechunkStore:
    """
    Core Icechunk store manager for GNSS data.

    This class encapsulates all operations on a single Icechunk repository,
    providing a clean interface for GNSS data storage and retrieval with
    integrated logging and proper resource management.

    Features:
    - Automatic repository creation/connection
    - Group management with validation
    - Session management with context managers
    - Integrated logging with file contexts
    - Configurable compression and chunking

    Note on "metadata"
    ------------------
    This class manages two distinct things both historically called "metadata":

    - **File registry** (``{group}/metadata/table``): per-file ingest ledger
      tracking hashes, temporal ranges, filenames, and paths. Managed by
      ``append_metadata()``, ``load_metadata()``, ``backup_metadata_table()``, etc.

    - **Store metadata** (``canvod.store_metadata`` package): store-level
      provenance (identity, creator, environment, compliance). Written to
      Zarr root attrs by the orchestrator. See ``canvod-store-metadata``.

    Parameters
    ----------
    store_path : Path
        Path to the Icechunk store directory.
    store_type : str, default "rinex_store"
        Type of store ("rinex_store" or "vod_store").
    compression_level : int | None, optional
        Override default compression level.
    compression_algorithm : str | None, optional
        Override default compression algorithm.

    Attributes
    ----------
    store_path : Path
        Path to the Icechunk store directory.
    store_type : str
        Type of store ("rinex_store" or "vod_store").
    compression_level : int
        Compression level (1-9).
    compression_algorithm : icechunk.CompressionAlgorithm
        Compression algorithm enum.
    repo : icechunk.Repository
        The Icechunk repository instance.
    """

    def __init__(
        self,
        store_path: Path,
        store_type: str = "rinex_store",
        compression_level: int | None = None,
        compression_algorithm: str | None = None,
    ) -> None:
        """Initialize the Icechunk store manager.

        Parameters
        ----------
        store_path : Path
            Path to the Icechunk store directory.
        store_type : str, default "rinex_store"
            Type of store ("rinex_store" or "vod_store").
        compression_level : int | None, optional
            Override default compression level.
        compression_algorithm : str | None, optional
            Override default compression algorithm.
        """
        from canvod.utils.config import load_config

        cfg = load_config()
        ic_cfg = cfg.processing.icechunk
        st_cfg = cfg.processing.storage

        self.store_path = Path(store_path)
        self.store_type = store_type
        # Site name is parent directory name
        self.site_name = self.store_path.parent.name

        # Compression
        self.compression_level = compression_level or ic_cfg.compression_level
        compression_alg = compression_algorithm or ic_cfg.compression_algorithm
        self.compression_algorithm = getattr(
            icechunk.CompressionAlgorithm, compression_alg.capitalize()
        )

        # Chunk strategy
        chunk_strategies = {
            k: {"epoch": v.epoch, "sid": v.sid}
            for k, v in ic_cfg.chunk_strategies.items()
        }
        self.chunk_strategy = chunk_strategies.get(store_type, {})

        # Storage config cached for metadata rows
        self._rinex_store_strategy = st_cfg.rinex_store_strategy
        self._rinex_store_expire_days = st_cfg.rinex_store_expire_days
        self._vod_store_strategy = st_cfg.vod_store_strategy

        # Configure repository
        self.config = icechunk.RepositoryConfig.default()
        self.config.compression = icechunk.CompressionConfig(
            level=self.compression_level, algorithm=self.compression_algorithm
        )
        self.config.inline_chunk_threshold_bytes = ic_cfg.inline_threshold
        self.config.get_partial_values_concurrency = ic_cfg.get_concurrency

        if ic_cfg.manifest_preload_enabled:
            self.config.manifest = icechunk.ManifestConfig(
                preload=icechunk.ManifestPreloadConfig(
                    max_total_refs=ic_cfg.manifest_preload_max_refs,
                    preload_if=icechunk.ManifestPreloadCondition.name_matches(
                        ic_cfg.manifest_preload_pattern
                    ),
                )
            )
            self._logger.info(
                f"Manifest preload enabled: {ic_cfg.manifest_preload_pattern}"
            )

        self._repo = None
        self._logger = get_logger(__name__)

        # Remove .DS_Store files that corrupt icechunk ref listing on macOS
        self._clean_ds_store()
        self._ensure_store_exists()

    def _clean_ds_store(self) -> None:
        """Remove .DS_Store files from the store directory tree.

        macOS creates these files automatically and they corrupt icechunk's
        ref listing, causing 'invalid ref type `.DS_Store`' errors.
        """
        if not self.store_path.exists():
            return
        for ds_store in self.store_path.rglob(".DS_Store"):
            ds_store.unlink()
            self._logger.debug(f"Removed {ds_store}")

    def _normalize_encodings(self, ds: xr.Dataset) -> xr.Dataset:
        """Normalize dataset encodings for Icechunk.

        Parameters
        ----------
        ds : xr.Dataset
            Dataset to normalize.

        Returns
        -------
        xr.Dataset
            Dataset with normalized encodings.
        """
        for v in ds.data_vars:
            if "dtype" in ds[v].encoding:
                ds[v].encoding["dtype"] = np.dtype(ds[v].dtype)
        return ds

    def _ensure_store_exists(self) -> None:
        """Ensure the store exists, creating if necessary."""
        storage = icechunk.local_filesystem_storage(str(self.store_path))

        if self.store_path.exists() and any(self.store_path.iterdir()):
            self._logger.info(f"Opening existing Icechunk store at {self.store_path}")
            self._repo = icechunk.Repository.open(storage=storage, config=self.config)
        else:
            self._logger.info(f"Creating new Icechunk store at {self.store_path}")
            self.store_path.mkdir(parents=True, exist_ok=True)
            self._repo = icechunk.Repository.create(storage=storage, config=self.config)

    @property
    def repo(self) -> icechunk.Repository:
        """Get the repository instance."""
        if self._repo is None:
            self._ensure_store_exists()
        return self._repo

    @contextlib.contextmanager
    def readonly_session(
        self,
        branch: str = "main",
    ) -> Generator[icechunk.ReadonlySession]:
        """Context manager for readonly sessions.

        Parameters
        ----------
        branch : str, default "main"
            Branch name.

        Returns
        -------
        Generator[icechunk.ReadonlySession, None, None]
            Readonly session context manager.
        """
        session = self.repo.readonly_session(branch)
        try:
            self._logger.debug(f"Opened readonly session for branch '{branch}'")
            yield session
        finally:
            self._logger.debug(f"Closed readonly session for branch '{branch}'")

    @contextlib.contextmanager
    def writable_session(
        self,
        branch: str = "main",
    ) -> Generator[icechunk.WritableSession]:
        """Context manager for writable sessions.

        Parameters
        ----------
        branch : str, default "main"
            Branch name.

        Returns
        -------
        Generator[icechunk.WritableSession, None, None]
            Writable session context manager.
        """
        session = self.repo.writable_session(branch)
        try:
            self._logger.debug(f"Opened writable session for branch '{branch}'")
            yield session
        finally:
            self._logger.debug(f"Closed writable session for branch '{branch}'")

    # ── Root-level store attributes ────────────────────────────────────────────

    def set_root_attrs(self, attrs: dict[str, Any], branch: str = "main") -> str:
        """Set root-level Zarr attributes on the store.

        Parameters
        ----------
        attrs : dict[str, Any]
            Key-value pairs to merge into root attrs.
        branch : str, default "main"
            Branch to write to.

        Returns
        -------
        str
            Snapshot ID from the commit.
        """
        with self.writable_session(branch) as session:
            try:
                root = zarr.open_group(session.store, mode="r+")
            except zarr.errors.GroupNotFoundError:
                root = zarr.open_group(session.store, mode="w")
            root.attrs.update(attrs)
            return session.commit(f"Set root attrs: {list(attrs.keys())}")

    def get_root_attrs(self, branch: str = "main") -> dict[str, Any]:
        """Read root-level Zarr attributes from the store.

        Returns
        -------
        dict[str, Any]
            Root attributes (empty dict if none set).
        """
        try:
            with self.readonly_session(branch) as session:
                root = zarr.open_group(session.store, mode="r")
                return dict(root.attrs)
        except Exception:
            return {}

    @property
    def source_format(self) -> str | None:
        """Return the ``source_format`` root attribute, or None."""
        return self.get_root_attrs().get("source_format")

    def get_branch_names(self) -> list[str]:
        """
        List all branches in the store.

        Returns
        -------
        list[str]
            List of branch names.
        """
        try:
            storage_config = icechunk.local_filesystem_storage(self.store_path)
            repo = icechunk.Repository.open(
                storage=storage_config,
            )

            return list(repo.list_branches())
        except Exception as e:
            self._logger.warning(f"Failed to list branches in {self!r}: {e}")
            warnings.warn(f"Failed to list branches in {self!r}: {e}", stacklevel=2)
            return []

    def get_group_names(self, branch: str | None = None) -> dict[str, list[str]]:
        """
        List all groups in the store.

        Parameters
        ----------
        branch: Optional[str]
            Repository branch to examine. Defaults to listing groups from all branches.

        Returns
        -------
        dict[str, list[str]]
            Dictionary mapping branch names to lists of group names.

        """
        try:
            if not branch:
                branches = self.get_branch_names()
            else:
                branches = [branch]

            storage_config = icechunk.local_filesystem_storage(self.store_path)
            repo = icechunk.Repository.open(
                storage=storage_config,
            )

            group_dict = {}
            for br in branches:
                with self.readonly_session(br) as session:
                    session = repo.readonly_session(br)
                    root = zarr.open(session.store, mode="r")
                    group_dict[br] = list(root.group_keys())

            return group_dict

        except Exception as e:
            self._logger.warning(f"Failed to list groups in {self!r}: {e}")
            return {}

    def list_groups(self, branch: str = "main") -> list[str]:
        """
        List all groups in a branch.

        Parameters
        ----------
        branch : str
            Branch name (default: "main")

        Returns
        -------
        list[str]
            List of group names in the branch
        """
        group_dict = self.get_group_names(branch=branch)
        if branch in group_dict:
            return group_dict[branch]
        return []

    @property
    def tree(self) -> None:
        """
        Display hierarchical tree of all branches, groups, and subgroups.
        """
        self.print_tree(max_depth=None)

    def print_tree(self, max_depth: int | None = None) -> None:
        """
        Display hierarchical tree of all branches, groups, and subgroups.

        Parameters
        ----------
        max_depth : int | None
            Maximum depth to display. None for unlimited depth.
            - 0: Only show branches
            - 1: Show branches and top-level groups
            - 2: Show branches, groups, and first level of subgroups/arrays
            - etc.
        """
        try:
            branches = self.get_branch_names()

            for i, branch in enumerate(branches):
                is_last_branch = i == len(branches) - 1
                branch_prefix = "└── " if is_last_branch else "├── "

                if max_depth is not None and max_depth < 1:
                    continue

                session = self.repo.readonly_session(branch)
                root = zarr.open(session.store, mode="r")

                if i == 0:
                    sys.stdout.write(f"{self.store_path}\n")

                sys.stdout.write(f"{branch_prefix}{branch}\n")
                # Build tree recursively
                branch_indent = "    " if is_last_branch else "│   "
                self._build_tree(root, branch_indent, max_depth, current_depth=1)

        except Exception as e:
            self._logger.warning(f"Failed to generate tree for {self!r}: {e}")
            sys.stdout.write(f"Error generating tree: {e}\n")

    def _build_tree(
        self,
        group: zarr.Group,
        prefix: str,
        max_depth: int | None,
        current_depth: int = 0,
    ) -> None:
        """Recursively build a tree structure.

        Parameters
        ----------
        group : zarr.Group
            Root group to traverse.
        prefix : str
            Prefix string for tree formatting.
        max_depth : int | None
            Maximum depth to display. None for unlimited.
        current_depth : int, default 0
            Current recursion depth.

        Returns
        -------
        None
        """
        if max_depth is not None and current_depth >= max_depth:
            return

        # Get all groups and arrays
        groups = list(group.group_keys())
        arrays = list(group.array_keys())
        items = groups + arrays

        for i, item_name in enumerate(items):
            is_last = i == len(items) - 1
            connector = "└── " if is_last else "├── "

            if item_name in groups:
                # It's a group
                sys.stdout.write(f"{prefix}{connector}{item_name}\n")

                # Recurse into subgroup
                subgroup = group[item_name]
                new_prefix = prefix + ("    " if is_last else "│   ")
                self._build_tree(subgroup, new_prefix, max_depth, current_depth + 1)
            else:
                # It's an array
                arr = group[item_name]
                shape_str = str(arr.shape)
                dtype_str = str(arr.dtype)
                sys.stdout.write(
                    f"{prefix}{connector}{item_name} {shape_str} {dtype_str}\n"
                )

    def group_exists(self, group_name: str, branch: str = "main") -> bool:
        """
        Check if a group exists.

        Parameters
        ----------
        group_name : str
            Name of the group to check.
        branch : str, default "main"
            Repository branch to examine.

        Returns
        -------
        bool
            True if the group exists, False otherwise.
        """
        group_dict = self.get_group_names(branch)

        # get_group_names returns dict like {'main': ['canopy_01', ...]}
        if branch in group_dict:
            exists = group_name in group_dict[branch]
        else:
            exists = False

        self._logger.debug(
            f"Group '{group_name}' exists on branch '{branch}': {exists}"
        )
        return exists

    def read_group(
        self,
        group_name: str,
        branch: str = "main",
        time_slice: slice | None = None,
        date: str | None = None,
        chunks: dict[str, Any] | None = None,
    ) -> xr.Dataset:
        """
        Read data from a group.

        Parameters
        ----------
        group_name : str
            Name of the group to read.
        branch : str, default "main"
            Repository branch.
        time_slice : slice | None, optional
            Optional label-based time slice for filtering (passed to ``ds.sel``).
        date : str | None, optional
            YYYYDOY string (e.g. ``"2025001"``) selecting a single calendar day.
            Converted to a ``time_slice``; mutually exclusive with ``time_slice``.
        chunks : dict[str, Any] | None, optional
            Chunking specification (uses config defaults if None).

        Returns
        -------
        xr.Dataset
            Dataset from the group.
        """
        self._logger.info(f"Reading group '{group_name}' from branch '{branch}'")

        if date is not None:
            from canvod.utils.tools.date_utils import YYYYDOY

            _d = YYYYDOY.from_str(date).date
            time_slice = slice(str(_d), str(_d + timedelta(days=1)))

        with self.readonly_session(branch) as session:
            # Use default chunking strategy if none provided
            if chunks is None:
                chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

            ds = xr.open_zarr(
                session.store,
                group=group_name,
                chunks=chunks,
                consolidated=False,
            )

            if time_slice is not None:
                ds = ds.sel(epoch=time_slice)
                self._logger.debug(f"Applied time slice: {time_slice}")

            self._logger.info(
                f"Successfully read group '{group_name}' - shape: {dict(ds.sizes)}"
            )
            return ds

    def read_group_deduplicated(
        self,
        group_name: str,
        branch: str = "main",
        keep: str = "last",
        time_slice: slice | None = None,
        chunks: dict[str, Any] | None = None,
    ) -> xr.Dataset:
        """
        Read data from a group with automatic deduplication.

        This method calls read_group() then removes duplicates using metadata table
        intelligence when available, falling back to simple epoch deduplication.

        Parameters
        ----------
        group_name : str
            Name of the group to read.
        branch : str, default "main"
            Repository branch.
        keep : str, default "last"
            Deduplication strategy for duplicate epochs.
        time_slice : slice | None, optional
            Optional time slice for filtering.
        chunks : dict[str, Any] | None, optional
            Chunking specification (uses config defaults if None).

        Returns
        -------
        xr.Dataset
            Dataset with duplicates removed (latest data only).
        """

        if keep not in ["last"]:
            raise ValueError("Currently only 'last' is supported for keep parameter.")

        self._logger.info(f"Reading group '{group_name}' with deduplication")

        # First, read the raw data
        ds = self.read_group(
            group_name, branch=branch, time_slice=time_slice, chunks=chunks
        )

        # Then deduplicate using metadata table intelligence
        with self.readonly_session(branch) as session:
            try:
                zmeta = zarr.open_group(session.store, mode="r")[
                    f"{group_name}/metadata/table"
                ]

                # Load metadata and get latest entries for each time range
                data = {col: zmeta[col][:] for col in zmeta.array_keys()}
                df = pl.DataFrame(data)

                # Ensure datetime dtypes
                df = df.with_columns(
                    [
                        pl.col("start").cast(pl.Datetime("ns")),
                        pl.col("end").cast(pl.Datetime("ns")),
                    ]
                )

                # Get latest entry for each unique (start, end) combination
                latest_entries = df.sort("written_at").unique(
                    subset=["start", "end"], keep=keep
                )

                if latest_entries.height > 0:
                    # Create time masks for latest data only
                    time_masks = []
                    for row in latest_entries.iter_rows(named=True):
                        start_time = np.datetime64(row["start"], "ns")
                        end_time = np.datetime64(row["end"], "ns")
                        mask = (ds.epoch >= start_time) & (ds.epoch <= end_time)
                        time_masks.append(mask)

                    # Combine all masks with OR logic
                    if time_masks:
                        combined_mask = time_masks[0]
                        for mask in time_masks[1:]:
                            combined_mask = combined_mask | mask
                        ds = ds.isel(epoch=combined_mask)

                        self._logger.info(
                            "Deduplicated using metadata table: kept "
                            f"{len(latest_entries)} time ranges"
                        )

            except Exception as e:
                # Fall back to simple deduplication
                self._logger.warning(
                    f"Metadata-based deduplication failed, using simple approach: {e}"
                )
                ds = ds.drop_duplicates("epoch", keep="last")
                self._logger.info("Applied simple epoch deduplication (keep='last')")

        return ds

    def _cleanse_dataset_attrs(self, dataset: xr.Dataset) -> xr.Dataset:
        """Remove any attributes that might interfere with Icechunk storage."""

        attrs_to_remove = [
            "Created",
            "File Path",
            "File Type",
            "Date",
            "institution",
            "Time of First Observation",
            "GLONASS COD",
            "GLONASS PHS",
            "GLONASS BIS",
            "Leap Seconds",
        ]
        for attr in attrs_to_remove:
            if attr in dataset.attrs:
                del dataset.attrs[attr]
        return dataset

    def write_dataset(
        self,
        dataset: xr.Dataset,
        group_name: str,
        session: Any,
        mode: str = "a",
        chunks: dict[str, int] | None = None,
    ) -> None:
        """
        Write a dataset to Icechunk with proper chunking.

        Parameters
        ----------
        dataset : xr.Dataset
            Dataset to write
        group_name : str
            Group path in store
        session : Any
            Active writable session or store handle.
        mode : str
            Write mode: 'w' (overwrite) or 'a' (append)
        chunks : dict[str, int] | None
            Chunking spec. If None, uses store's chunk_strategy.
            Example: {'epoch': 34560, 'sid': -1}
        """
        # Use explicit chunks, or fall back to store's chunk strategy
        if chunks is None:
            chunks = self.chunk_strategy

        # Apply chunking if strategy defined
        if chunks:
            dataset = dataset.chunk(chunks)
            self._logger.info(f"Rechunked to {dict(dataset.chunks)} before write")

        # Normalize encodings
        dataset = self._normalize_encodings(dataset)

        # Calculate dataset metrics for tracing
        dataset_size_mb = dataset.nbytes / 1024 / 1024
        num_variables = len(dataset.data_vars)

        # Write to Icechunk with OpenTelemetry tracing
        try:
            from canvodpy.utils.telemetry import trace_icechunk_write

            with trace_icechunk_write(
                group_name=group_name,
                dataset_size_mb=dataset_size_mb,
                num_variables=num_variables,
            ):
                to_icechunk(dataset, session, group=group_name, mode=mode)
        except ImportError:
            # Fallback if telemetry not available
            to_icechunk(dataset, session, group=group_name, mode=mode)

        self._logger.info(f"Wrote dataset to group '{group_name}' (mode={mode})")

    def write_initial_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        branch: str = "main",
        commit_message: str | None = None,
    ) -> None:
        """Write initial data to a new group."""
        if self.group_exists(group_name, branch):
            raise ValueError(
                f"Group '{group_name}' already exists. Use append_to_group() instead."
            )

        with self.writable_session(branch) as session:
            dataset = self._normalize_encodings(dataset)

            rinex_hash = dataset.attrs.get("File Hash")
            if rinex_hash is None:
                raise ValueError("Dataset missing 'File Hash' attribute")
            start = dataset.epoch.min().values
            end = dataset.epoch.max().values

            to_icechunk(dataset, session, group=group_name, mode="w")

            if commit_message is None:
                version = get_version_from_pyproject()
                commit_message = f"[v{version}] Initial commit to group '{group_name}'"

            snapshot_id = session.commit(commit_message)

            self.append_metadata(
                group_name=group_name,
                rinex_hash=rinex_hash,
                start=start,
                end=end,
                snapshot_id=snapshot_id,
                action="write",  # Correct action for initial data
                commit_msg=commit_message,
                dataset_attrs=dataset.attrs,
            )

        self._logger.info(
            f"Created group '{group_name}' with {len(dataset.epoch)} epochs, "
            f"hash={rinex_hash}"
        )

    def backup_metadata_table(
        self,
        group_name: str,
        session: Any,
    ) -> pl.DataFrame | None:
        """Backup the metadata table to a Polars DataFrame.

        Parameters
        ----------
        group_name : str
            Group name.
        session : Any
            Active session for reading.

        Returns
        -------
        pl.DataFrame | None
            DataFrame with metadata rows, or None if missing.
        """
        try:
            zroot = zarr.open_group(session.store, mode="r")
            meta_group_path = f"{group_name}/metadata/table"

            if (
                "metadata" not in zroot[group_name]
                or "table" not in zroot[group_name]["metadata"]
            ):
                self._logger.info(
                    "No metadata table found for group "
                    f"'{group_name}' - nothing to backup"
                )
                return None

            zmeta = zroot[meta_group_path]

            # Load all columns into a dictionary
            data = {}
            for col_name in zmeta.array_keys():
                data[col_name] = zmeta[col_name][:]

            # Convert to Polars DataFrame
            df = pl.DataFrame(data)

            self._logger.info(
                "Backed up metadata table with "
                f"{df.height} rows for group '{group_name}'"
            )
            return df

        except Exception as e:
            self._logger.warning(
                f"Failed to backup metadata table for group '{group_name}': {e}"
            )
            return None

    def restore_metadata_table(
        self,
        group_name: str,
        df: pl.DataFrame,
        session: Any,
    ) -> None:
        """Restore the metadata table from a Polars DataFrame.

        This recreates the full Zarr structure for the metadata table.

        Parameters
        ----------
        group_name : str
            Group name.
        df : pl.DataFrame
            Metadata table to restore.
        session : Any
            Active session for writing.

        Returns
        -------
        None
        """
        if df is None or df.height == 0:
            self._logger.info(f"No metadata to restore for group '{group_name}'")
            return

        try:
            zroot = zarr.open_group(session.store, mode="a")
            meta_group_path = f"{group_name}/metadata/table"

            # Create the metadata subgroup
            zmeta = zroot.require_group(meta_group_path)

            # Create all arrays from the DataFrame
            for col_name in df.columns:
                col_data = df[col_name]

                if col_name == "index":
                    # Index column as int64
                    arr = col_data.to_numpy().astype("i8")
                    dtype = "i8"
                elif col_name in ("start", "end"):
                    # Datetime columns
                    arr = col_data.to_numpy().astype("datetime64[ns]")
                    dtype = "M8[ns]"
                else:
                    # String columns - use VariableLengthUTF8
                    arr = col_data.to_list()  # Convert to list for VariableLengthUTF8
                    dtype = VariableLengthUTF8()

                # Create the array
                zmeta.create_array(
                    name=col_name,
                    shape=(len(arr),),
                    dtype=dtype,
                    chunks=(1024,),
                    overwrite=True,
                )

                # Write the data
                zmeta[col_name][:] = arr

            self._logger.info(
                "Restored metadata table with "
                f"{df.height} rows for group '{group_name}'"
            )

        except Exception as e:
            self._logger.error(
                f"Failed to restore metadata table for group '{group_name}': {e}"
            )
            raise RuntimeError(
                f"Critical error: could not restore metadata table: {e}"
            ) from e

    def overwrite_file_in_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        rinex_hash: str,
        start: np.datetime64,
        end: np.datetime64,
        branch: str = "main",
        commit_message: str | None = None,
    ) -> None:
        """Overwrite a file's contribution to the group (same hash, new epoch range)."""

        dataset = self._normalize_encodings(dataset)

        # --- Step 3: rewrite store ---
        with self.writable_session(branch) as session:
            ds_from_store = xr.open_zarr(
                session.store, group=group_name, consolidated=False
            ).compute(
                scheduler="synchronous"
            )  # synchronous avoids Dask serialization error

            # Backup the existing metadata table
            metadata_backup = self.backup_metadata_table(group_name, session)

            mask = (ds_from_store.epoch.values < start) | (
                ds_from_store.epoch.values > end
            )
            ds_from_store_cleansed = ds_from_store.isel(epoch=mask)
            ds_from_store_cleansed = self._normalize_encodings(ds_from_store_cleansed)

            # Check if any epochs remain after cleansing, then write leftovers.
            if ds_from_store_cleansed.sizes.get("epoch", 0) > 0:
                to_icechunk(ds_from_store_cleansed, session, group=group_name, mode="w")
            # no epochs left, reset group to empty
            else:
                to_icechunk(dataset.isel(epoch=[]), session, group=group_name, mode="w")

            # write back the backed up metadata table
            self.restore_metadata_table(group_name, metadata_backup, session)

            # Append the new dataset
            to_icechunk(dataset, session, group=group_name, append_dim="epoch")

            if commit_message is None:
                version = get_version_from_pyproject()
                commit_message = (
                    f"[v{version}] Overwrote file {rinex_hash} in group '{group_name}'"
                )

            snapshot_id = session.commit(commit_message)

            self.append_metadata(
                group_name=group_name,
                rinex_hash=rinex_hash,
                start=start,
                end=end,
                snapshot_id=snapshot_id,
                action="overwrite",
                commit_msg=commit_message,
                dataset_attrs=dataset.attrs,
            )

    def get_group_info(self, group_name: str, branch: str = "main") -> dict[str, Any]:
        """
        Get metadata about a group.

        Parameters
        ----------
        group_name : str
            Name of the group.
        branch : str, default "main"
            Repository branch to examine.

        Returns
        -------
        dict[str, Any]
            Group metadata.

        Raises
        ------
        ValueError
            If the group does not exist.
        """
        if not self.group_exists(group_name, branch):
            raise ValueError(f"Group '{group_name}' does not exist")

        ds = self.read_group(group_name, branch)

        info = {
            "group_name": group_name,
            "store_type": self.store_type,
            "dimensions": dict(ds.sizes),
            "variables": list(ds.data_vars.keys()),
            "coordinates": list(ds.coords.keys()),
            "attributes": dict(ds.attrs),
        }

        # Add temporal information if epoch dimension exists
        if "epoch" in ds.sizes:
            info["temporal_info"] = {
                "start": str(ds.epoch.min().values),
                "end": str(ds.epoch.max().values),
                "count": ds.sizes["epoch"],
                "resolution": str(ds.epoch.diff("epoch").median().values),
            }

        return info

    # ── Generic metadata datasets ─────────────────────────────────────────────

    def metadata_dataset_exists(
        self, group_name: str, name: str, branch: str = "main"
    ) -> bool:
        """Return True if a metadata dataset *name* exists for *group_name*."""
        path = f"{group_name}/metadata/{name}"
        try:
            with self.readonly_session(branch) as session:
                zarr.open_group(session.store, mode="r", path=path)
                return True
        except Exception:
            return False

    def write_metadata_dataset(
        self,
        meta_ds: xr.Dataset,
        group_name: str,
        name: str,
        branch: str = "main",
    ) -> str:
        """Write a pre-concatenated metadata dataset to *{group_name}/metadata/{name}*.

        Always writes with ``mode="w"`` (full overwrite for the day).

        Parameters
        ----------
        meta_ds : xr.Dataset
            Pre-concatenated ``(epoch, sid)`` metadata dataset.
        group_name : str
            Target group (receiver name).
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch to write to.

        Returns
        -------
        str
            Icechunk snapshot ID.
        """
        version = get_version_from_pyproject()
        path = f"{group_name}/metadata/{name}"
        ds = self._normalize_encodings(meta_ds)
        ds = self._cleanse_dataset_attrs(ds)
        with self.writable_session(branch) as session:
            to_icechunk(ds, session, group=path, mode="w")
            return session.commit(f"[v{version}] metadata/{name} for {group_name}")

    def append_metadata_datasets(
        self,
        parts: list[xr.Dataset],
        group_name: str,
        name: str,
        branch: str = "main",
    ) -> str:
        """Write metadata datasets incrementally — no in-memory concat.

        The first dataset initialises the group (``mode="w"``), subsequent
        datasets are appended along ``epoch``.  All writes happen inside a
        single session/commit so the operation is atomic.

        Parameters
        ----------
        parts : list[xr.Dataset]
            Individual per-file metadata datasets with an ``epoch`` dim.
        group_name : str
            Target group (receiver name).
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch to write to.

        Returns
        -------
        str
            Icechunk snapshot ID.
        """
        if not parts:
            msg = "parts list is empty"
            raise ValueError(msg)

        version = get_version_from_pyproject()
        path = f"{group_name}/metadata/{name}"
        total_epochs = 0

        with self.writable_session(branch) as session:
            for i, part in enumerate(parts):
                ds = self._normalize_encodings(part)
                ds = self._cleanse_dataset_attrs(ds)
                if i == 0:
                    to_icechunk(ds, session, group=path, mode="w")
                else:
                    to_icechunk(ds, session, group=path, append_dim="epoch")
                total_epochs += ds.sizes.get("epoch", 0)

            return session.commit(
                f"[v{version}] metadata/{name} for {group_name} ({total_epochs} epochs)"
            )

    def read_metadata_dataset(
        self,
        group_name: str,
        name: str,
        branch: str = "main",
        chunks: dict | None = None,
    ) -> xr.Dataset:
        """Read a metadata dataset *name* for *group_name*.

        Parameters
        ----------
        group_name : str
            Group (receiver) name.
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch.
        chunks : dict | None, optional
            Dask chunk specification.  Defaults to
            ``{"epoch": 34560, "sid": -1}``.

        Returns
        -------
        xr.Dataset
            Lazy ``(epoch, sid)`` metadata dataset.
        """
        path = f"{group_name}/metadata/{name}"
        with self.readonly_session(branch) as session:
            return xr.open_zarr(
                session.store,
                group=path,
                chunks=chunks or self.chunk_strategy or {"epoch": 34560, "sid": -1},
                consolidated=False,
            )

    def get_metadata_dataset_info(
        self,
        group_name: str,
        name: str,
        branch: str = "main",
    ) -> dict[str, Any]:
        """Get info about metadata dataset *name* for *group_name*.

        Parameters
        ----------
        group_name : str
            Group (receiver) name.
        name : str
            Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
        branch : str, default "main"
            Repository branch.

        Returns
        -------
        dict[str, Any]
            Info dict with the same structure as ``get_group_info()``.

        Raises
        ------
        ValueError
            If the metadata dataset does not exist.
        """
        if not self.metadata_dataset_exists(group_name, name, branch):
            raise ValueError(f"No metadata dataset '{name}' for group '{group_name}'")
        ds = self.read_metadata_dataset(group_name, name, branch, chunks={})
        info: dict[str, Any] = {
            "group_name": group_name,
            "store_path": f"{group_name}/metadata/{name}",
            "store_type": f"metadata/{name}",
            "dimensions": dict(ds.sizes),
            "variables": list(ds.data_vars.keys()),
            "coordinates": list(ds.coords.keys()),
            "attributes": dict(ds.attrs),
        }
        if "epoch" in ds.sizes:
            info["temporal_info"] = {
                "start": str(ds.epoch.min().values),
                "end": str(ds.epoch.max().values),
                "count": ds.sizes["epoch"],
                "resolution": str(ds.epoch.diff("epoch").median().values),
            }
        return info

    # Convenience aliases (SBF)
    def sbf_metadata_exists(self, group_name: str, branch: str = "main") -> bool:
        """Return True if an SBF metadata dataset exists for *group_name*."""
        return self.metadata_dataset_exists(group_name, "sbf_obs", branch)

    def write_sbf_metadata(
        self, meta_ds: xr.Dataset, group_name: str, branch: str = "main"
    ) -> str:
        """Write SBF metadata dataset."""
        return self.write_metadata_dataset(meta_ds, group_name, "sbf_obs", branch)

    def read_sbf_metadata(
        self, group_name: str, branch: str = "main", chunks: dict | None = None
    ) -> xr.Dataset:
        """Read SBF metadata dataset."""
        return self.read_metadata_dataset(group_name, "sbf_obs", branch, chunks)

    def get_sbf_metadata_info(
        self, group_name: str, branch: str = "main"
    ) -> dict[str, Any]:
        """Get SBF metadata info."""
        return self.get_metadata_dataset_info(group_name, "sbf_obs", branch)

    def rel_path_for_commit(self, file_path: Path) -> str:
        """
        Generate relative path for commit messages.

        Parameters
        ----------
        file_path : Path
            Full file path.

        Returns
        -------
        str
            Relative path string with log_path_depth parts.
        """
        depth = load_config().processing.logging.log_path_depth
        return str(Path(*file_path.parts[-depth:]))

    def get_store_stats(self) -> dict[str, Any]:
        """
        Get statistics about the store.

        Returns
        -------
        dict[str, Any]
            Store statistics.
        """
        groups = self.get_group_names()
        stats = {
            "store_path": str(self.store_path),
            "store_type": self.store_type,
            "compression_level": self.compression_level,
            "compression_algorithm": self.compression_algorithm.name,
            "total_groups": len(groups),
            "groups": groups,
        }

        # Add group-specific stats
        for group_name in groups:
            try:
                info = self.get_group_info(group_name)
                stats[f"group_{group_name}"] = {
                    "dimensions": info["dimensions"],
                    "variables_count": len(info["variables"]),
                    "has_temporal_data": "temporal_info" in info,
                }
            except Exception as e:
                self._logger.warning(
                    f"Failed to get stats for group '{group_name}': {e}"
                )

        return stats

    def append_to_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        append_dim: str = "epoch",
        branch: str = "main",
        action: str = "write",
        commit_message: str | None = None,
    ) -> None:
        """Append data to an existing group."""
        if not self.group_exists(group_name, branch):
            raise ValueError(
                f"Group '{group_name}' does not exist. Use write_initial_group() first."
            )

        dataset = self._normalize_encodings(dataset)

        rinex_hash = dataset.attrs.get("File Hash")
        if rinex_hash is None:
            raise ValueError("Dataset missing 'File Hash' attribute")
        start = dataset.epoch.min().values
        end = dataset.epoch.max().values

        # Guard: check hash + temporal overlap before appending
        exists, matches = self.metadata_row_exists(
            group_name, rinex_hash, start, end, branch
        )
        if exists and action != "overwrite":
            self._logger.warning(
                "append_blocked_by_guardrail",
                group=group_name,
                hash=rinex_hash[:16],
                range=f"{start}{end}",
                reason="hash_or_temporal_overlap",
                matching_files=matches.height if not matches.is_empty() else 0,
            )
            return

        with self.writable_session(branch) as session:
            to_icechunk(dataset, session, group=group_name, append_dim=append_dim)

            if commit_message is None and action == "write":
                version = get_version_from_pyproject()
                commit_message = f"[v{version}] Wrote to group '{group_name}'"
            elif commit_message is None and action != "append":
                version = get_version_from_pyproject()
                commit_message = f"[v{version}] Appended to group '{group_name}'"

            snapshot_id = session.commit(commit_message)

            self.append_metadata(
                group_name=group_name,
                rinex_hash=rinex_hash,
                start=start,
                end=end,
                snapshot_id=snapshot_id,
                action=action,
                commit_msg=commit_message,
                dataset_attrs=dataset.attrs,
            )

        if action == "append":
            self._logger.info(
                f"Appended {len(dataset.epoch)} epochs to group '{group_name}', "
                f"hash={rinex_hash}"
            )
        elif action == "write":
            self._logger.info(
                f"Wrote {len(dataset.epoch)} epochs to group '{group_name}', "
                f"hash={rinex_hash}"
            )
        else:
            self._logger.info(
                f"Action '{action}' completed for group '{group_name}', "
                f"hash={rinex_hash}"
            )

    def write_or_append_group(
        self,
        dataset: xr.Dataset,
        group_name: str,
        append_dim: str = "epoch",
        branch: str = "main",
        commit_message: str | None = None,
        dedup: bool = False,
    ) -> bool:
        """Write or append a dataset to a group.

        By default (``dedup=False``) no guardrails are applied — suitable for
        VOD stores and other derived-data stores where rinex-style dedup does
        not apply.

        When ``dedup=True`` the method runs a full hash-match + temporal-overlap
        check (via :meth:`should_skip_file`) **before** opening a write session.
        This makes the store the authoritative final gate for RINEX/SBF ingest
        paths, backstopping any pre-checks in the caller.

        If the group does not exist, creates it (``mode='w'``).
        If it exists, appends along ``append_dim``.

        Parameters
        ----------
        dataset : xr.Dataset
            Dataset to write or append.
        group_name : str
            Target Icechunk group.
        append_dim : str, default "epoch"
            Dimension along which to append when the group already exists.
        branch : str, default "main"
            Icechunk branch to write to.
        commit_message : str or None
            Commit message.  Auto-generated if ``None``.
        dedup : bool, default False
            When ``True``, check for duplicate hash or temporal overlap before
            writing.  If the dataset would be a duplicate, the write is skipped,
            a warning is logged, and ``False`` is returned.  Set to ``True`` for
            RINEX/SBF ingest; leave ``False`` for VOD and derived-data stores.

        Returns
        -------
        bool
            ``True`` if the dataset was written, ``False`` if skipped
            (only possible when ``dedup=True``).
        """
        if dedup:
            file_hash = dataset.attrs.get("File Hash")
            time_start = dataset.epoch.min().values
            time_end = dataset.epoch.max().values
            skip, reason = self.should_skip_file(
                group_name=group_name,
                file_hash=file_hash,
                time_start=time_start,
                time_end=time_end,
                branch=branch,
            )
            if skip:
                self._logger.warning(
                    "write_or_append_group skipped duplicate",
                    group=group_name,
                    reason=reason,
                    file_hash=file_hash,
                )
                return False

        dataset = self._normalize_encodings(dataset)

        if self.group_exists(group_name, branch):
            with self.writable_session(branch) as session:
                to_icechunk(dataset, session, group=group_name, append_dim=append_dim)
                if commit_message is None:
                    commit_message = f"Appended to group '{group_name}'"
                session.commit(commit_message)
            self._logger.info(
                f"Appended {len(dataset.epoch)} epochs to group '{group_name}'"
            )
        else:
            with self.writable_session(branch) as session:
                to_icechunk(dataset, session, group=group_name, mode="w")
                if commit_message is None:
                    commit_message = f"Created group '{group_name}'"
                session.commit(commit_message)
            self._logger.info(
                f"Created group '{group_name}' with {len(dataset.epoch)} epochs"
            )
        return True

    def append_metadata(
        self,
        group_name: str,
        rinex_hash: str,
        start: np.datetime64,
        end: np.datetime64,
        snapshot_id: str,
        action: str,
        commit_msg: str,
        dataset_attrs: dict,
        branch: str = "main",
        canonical_name: str | None = None,
        physical_path: str | None = None,
    ) -> None:
        """
        Append a metadata row into the group_name/metadata/table.

        Schema:
            index           int64 (continuous row id)
            rinex_hash      str   (UTF-8, VariableLengthUTF8)
            start           datetime64[ns]
            end             datetime64[ns]
            snapshot_id     str   (UTF-8)
            action          str   (UTF-8, e.g. "insert"|"append"|"overwrite"|"skip")
            commit_msg      str   (UTF-8)
            written_at      str   (UTF-8, ISO8601 with timezone)
            write_strategy  str   (UTF-8, RINEX_STORE_STRATEGY or VOD_STORE_STRATEGY)
            attrs           str   (UTF-8, JSON dump of dataset attrs)
        """
        written_at = datetime.now().astimezone().isoformat()

        row = {
            "rinex_hash": str(rinex_hash),
            "start": np.datetime64(start, "ns"),
            "end": np.datetime64(end, "ns"),
            "snapshot_id": str(snapshot_id),
            "action": str(action),
            "commit_msg": str(commit_msg),
            "written_at": written_at,
            "write_strategy": str(self._rinex_store_strategy)
            if self.store_type == "rinex_store"
            else str(self._vod_store_strategy),
            "attrs": json.dumps(dataset_attrs, default=str),
            "canonical_name": str(canonical_name) if canonical_name else "",
            "physical_path": str(physical_path) if physical_path else "",
        }
        df_row = pl.DataFrame([row])

        with self.writable_session(branch) as session:
            zroot = zarr.open_group(session.store, mode="a")
            meta_group_path = f"{group_name}/metadata/table"

            if (
                "metadata" not in zroot[group_name]
                or "table" not in zroot[group_name]["metadata"]
            ):
                # --- First time: create arrays with correct dtypes ---
                zmeta = zroot.require_group(meta_group_path)

                # index counter
                zmeta.create_array(
                    name="index", shape=(0,), dtype="i8", chunks=(1024,), overwrite=True
                )
                zmeta["index"].append([0])

                for col in df_row.columns:
                    if col in ("start", "end"):
                        dtype = "M8[ns]"
                        arr = np.array(df_row[col].to_numpy(), dtype=dtype)
                    else:
                        dtype = VariableLengthUTF8()
                        arr = df_row[col].to_list()

                    zmeta.create_array(
                        name=col,
                        shape=(0,),
                        dtype=dtype,
                        chunks=(1024,),
                        overwrite=True,
                    )
                    zmeta[col].append(arr)

            else:
                # --- Append to existing ---
                zmeta = zroot[meta_group_path]

                # index increment
                current_len = zmeta["index"].shape[0]
                next_idx = current_len
                zmeta["index"].append([next_idx])

                for col in df_row.columns:
                    if col in ("start", "end"):
                        arr = np.array(df_row[col].to_numpy(), dtype="M8[ns]")
                    else:
                        arr = df_row[col].to_list()
                    zmeta[col].append(arr)

            session.commit(f"Appended metadata row for {group_name}, hash={rinex_hash}")

        self._logger.info(
            f"Metadata appended for group '{group_name}': "
            f"hash={rinex_hash}, snapshot={snapshot_id}, action={action}"
        )

    def append_metadata_bulk(
        self,
        group_name: str,
        rows: list[dict[str, Any]],
        session: icechunk.WritableSession | None = None,
    ) -> None:
        """
        Append multiple metadata rows in one commit.

        Parameters
        ----------
        group_name : str
            Group name (e.g. "canopy", "reference")
        rows : list[dict[str, Any]]
            List of metadata records matching the schema used in
            append_metadata().
        session : icechunk.WritableSession, optional
            If provided, rows are written into this session (caller commits later).
            If None, this method opens its own writable session and commits once.
        """
        if not rows:
            self._logger.info(f"No metadata rows to append for group '{group_name}'")
            return

        # Ensure datetime conversions for consistency
        for row in rows:
            if isinstance(row.get("start"), str):
                row["start"] = np.datetime64(row["start"])
            if isinstance(row.get("end"), str):
                row["end"] = np.datetime64(row["end"])
            if "written_at" not in row:
                row["written_at"] = datetime.now(UTC).isoformat()

        # Prepare the Polars DataFrame
        df = pl.DataFrame(rows)

        def _do_append(session_obj: icechunk.WritableSession) -> None:
            """Append metadata rows to a writable session.

            Parameters
            ----------
            session_obj : icechunk.WritableSession
                Writable session to update.

            Returns
            -------
            None
            """
            zroot = zarr.open_group(session_obj.store, mode="a")
            meta_group_path = f"{group_name}/metadata/table"
            zmeta = zroot.require_group(meta_group_path)

            start_index = 0
            if "index" in zmeta:
                existing_len = zmeta["index"].shape[0]
                start_index = (
                    int(zmeta["index"][-1].item()) + 1 if existing_len > 0 else 0
                )

            # Assign sequential indices
            df_with_index = df.with_columns(
                (pl.arange(start_index, start_index + df.height)).alias("index")
            )

            # Write each column
            for col_name in df_with_index.columns:
                col_data = df_with_index[col_name]

                if col_name == "index":
                    dtype = "i8"
                    arr = col_data.to_numpy().astype(dtype)
                elif col_name in ("start", "end"):
                    dtype = "M8[ns]"
                    arr = col_data.to_numpy().astype(dtype)
                else:
                    # strings / jsons / ids
                    dtype = VariableLengthUTF8()
                    arr = col_data.to_list()

                if col_name not in zmeta:
                    # Create array if it doesn't exist
                    zmeta.create_array(
                        name=col_name,
                        shape=(0,),
                        dtype=dtype,
                        chunks=(1024,),
                        overwrite=True,
                    )

                # Resize and append
                old_len = zmeta[col_name].shape[0]
                new_len = old_len + len(arr)
                zmeta[col_name].resize(new_len)
                zmeta[col_name][old_len:new_len] = arr

            self._logger.info(
                f"Appended {df_with_index.height} metadata rows to group '{group_name}'"
            )

        if session is not None:
            _do_append(session)
        else:
            with self.writable_session() as sess:
                _do_append(sess)
                sess.commit(f"Bulk metadata append for {group_name}")

    def load_metadata(self, store: Any, group_name: str) -> pl.DataFrame:
        """Load metadata directly from Zarr into a Polars DataFrame.

        Parameters
        ----------
        store : Any
            Zarr store or session store handle.
        group_name : str
            Group name.

        Returns
        -------
        pl.DataFrame
            Metadata table.
        """
        zroot = zarr.open_group(store, mode="r")
        zmeta = zroot[f"{group_name}/metadata/table"]

        # Read all columns into a dict of numpy arrays
        data = {col: zmeta[col][...] for col in zmeta.array_keys()}

        # Build Polars DataFrame
        df = pl.DataFrame(data)

        # Convert numeric datetime64 columns back to proper Polars datetimes
        if df["start"].dtype in (pl.Int64, pl.Float64):
            df = df.with_columns(pl.col("start").cast(pl.Datetime("ns")))
        if df["end"].dtype in (pl.Int64, pl.Float64):
            df = df.with_columns(pl.col("end").cast(pl.Datetime("ns")))
        if df["written_at"].dtype == pl.Utf8:
            df = df.with_columns(pl.col("written_at").str.to_datetime("%+"))
        return df

    def read_metadata_table(self, session: Any, group_name: str) -> pl.DataFrame:
        """Read the metadata table from a session.

        Parameters
        ----------
        session : Any
            Active session for reading.
        group_name : str
            Group name.

        Returns
        -------
        pl.DataFrame
            Metadata table.
        """
        zmeta = zarr.open_group(
            session.store,
            mode="r",
        )[f"{group_name}/metadata/table"]

        data = {col: zmeta[col][:] for col in zmeta.array_keys()}
        df = pl.DataFrame(data)

        # Ensure start/end are proper datetime
        df = df.with_columns(
            [
                pl.col("start").cast(pl.Datetime("ns")),
                pl.col("end").cast(pl.Datetime("ns")),
            ]
        )
        return df

    def metadata_row_exists(
        self,
        group_name: str,
        rinex_hash: str,
        start: np.datetime64,
        end: np.datetime64,
        branch: str = "main",
    ) -> tuple[bool, pl.DataFrame]:
        """
        Check whether a file already exists or temporally overlaps existing data.

        Performs two checks in order:

        1. **Hash match** — if ``rinex_hash`` already appears in the metadata
           table, the file was previously ingested (exact duplicate).
        2. **Temporal overlap** — if the incoming ``[start, end]`` interval
           overlaps any existing metadata interval, the file covers a time
           range that is already (partially) present in the store.  This
           catches cases like a daily concatenation file coexisting with the
           sub-daily files it was built from.

        Parameters
        ----------
        group_name : str
            Icechunk group name.
        rinex_hash : str
            Hash of the current GNSS dataset.
        start : np.datetime64
            Start epoch of the incoming file.
        end : np.datetime64
            End epoch of the incoming file.
        branch : str, default "main"
            Branch name in the Icechunk repository.

        Returns
        -------
        tuple[bool, pl.DataFrame]
            ``(True, overlapping_rows)`` when the file should be skipped,
            ``(False, empty_df)`` when it is safe to ingest.
        """
        with self.readonly_session(branch) as session:
            try:
                zmeta = zarr.open_group(session.store, mode="r")[
                    f"{group_name}/metadata/table"
                ]
            except Exception:
                return False, pl.DataFrame()

            data = {col: zmeta[col][:] for col in zmeta.array_keys()}
            df = pl.DataFrame(data)

            df = df.with_columns(
                [
                    pl.col("start").cast(pl.Datetime("ns")),
                    pl.col("end").cast(pl.Datetime("ns")),
                ]
            )

            # --- Check 1: exact hash match (file already ingested) ---
            hash_matches = df.filter(pl.col("rinex_hash") == rinex_hash)
            if not hash_matches.is_empty():
                return True, hash_matches

            # --- Check 2: temporal overlap ---
            # Two intervals [A.start, A.end] and [B.start, B.end] overlap
            # iff A.start <= B.end AND A.end >= B.start
            start_ns = np.datetime64(start, "ns")
            end_ns = np.datetime64(end, "ns")

            overlaps = df.filter(
                (pl.col("start") <= end_ns) & (pl.col("end") >= start_ns)
            )

            if not overlaps.is_empty():
                n = overlaps.height
                existing_range = f"{overlaps['start'].min()}{overlaps['end'].max()}"
                self._logger.warning(
                    "temporal_overlap_detected",
                    group=group_name,
                    incoming_hash=rinex_hash,
                    incoming_range=f"{start}{end}",
                    existing_range=existing_range,
                    overlapping_files=n,
                )
                return True, overlaps

            return False, pl.DataFrame()

    def should_skip_file(
        self,
        group_name: str,
        file_hash: str | None,
        time_start: np.datetime64,
        time_end: np.datetime64,
        branch: str = "main",
    ) -> tuple[bool, str]:
        """Check whether a file should be skipped before processing and writing.

        Thin public wrapper around :meth:`metadata_row_exists` that returns a
        simple ``(skip, reason)`` pair instead of a DataFrame, suitable for use
        in Airflow task functions as an early-exit optimisation.

        This method is an early-exit optimisation: it avoids opening a write
        session for files that are already present.  Pass ``dedup=True`` to
        :meth:`write_or_append_group` to make the store the authoritative
        final gate (runs the same check again before writing).

        Checks performed (in order):

        1. **Hash match** — file was previously ingested (exact duplicate).
        2. **Temporal overlap** — incoming time range overlaps existing epochs.

        Layer 3 (intra-batch overlap) is not applicable here because task
        functions process files one at a time.

        Parameters
        ----------
        group_name : str
            Icechunk group name.
        file_hash : str or None
            Hash from ``dataset.attrs["File Hash"]``.  When ``None`` the check
            is skipped and ``(False, "")`` is returned.
        time_start : np.datetime64
            First epoch of the incoming dataset.
        time_end : np.datetime64
            Last epoch of the incoming dataset.
        branch : str, default "main"
            Branch name in the Icechunk repository.

        Returns
        -------
        tuple[bool, str]
            ``(True, "hash_match")`` — exact duplicate, skip.
            ``(True, "temporal_overlap")`` — overlapping time range, skip.
            ``(False, "")`` — safe to ingest.
        """
        if file_hash is None:
            return False, ""

        exists, matches = self.metadata_row_exists(
            group_name, file_hash, time_start, time_end, branch
        )
        if not exists:
            return False, ""

        if not matches.is_empty() and (matches["rinex_hash"] == file_hash).any():
            return True, "hash_match"
        return True, "temporal_overlap"

    def batch_check_existing(self, group_name: str, file_hashes: list[str]) -> set[str]:
        """Check which file hashes already exist in metadata."""

        try:
            with self.readonly_session("main") as session:
                df = self.load_metadata(session.store, group_name)

                # Filter to matching hashes
                existing = df.filter(pl.col("rinex_hash").is_in(file_hashes))
                return set(existing["rinex_hash"].to_list())

        except KeyError, zarr.errors.GroupNotFoundError, Exception:
            # Branch/group/metadata doesn't exist yet (fresh store)
            return set()

    def check_temporal_overlaps(
        self,
        group_name: str,
        file_intervals: list[tuple[str, np.datetime64, np.datetime64]],
        branch: str = "main",
    ) -> set[str]:
        """Check which files temporally overlap existing metadata intervals.

        Parameters
        ----------
        group_name : str
            Icechunk group name.
        file_intervals : list[tuple[str, np.datetime64, np.datetime64]]
            List of ``(rinex_hash, start, end)`` tuples for incoming files.
        branch : str, default "main"
            Branch name in the Icechunk repository.

        Returns
        -------
        set[str]
            Hashes of files whose ``[start, end]`` overlaps any existing
            metadata interval.  Files whose hash already exists in the store
            are NOT included (use ``batch_check_existing`` for those).
        """
        if not file_intervals:
            return set()

        try:
            with self.readonly_session(branch) as session:
                df = self.load_metadata(session.store, group_name)
        except KeyError, zarr.errors.GroupNotFoundError, Exception:
            return set()

        if df.is_empty():
            return set()

        df = df.with_columns(
            [
                pl.col("start").cast(pl.Datetime("ns")),
                pl.col("end").cast(pl.Datetime("ns")),
            ]
        )

        overlapping: set[str] = set()
        for rinex_hash, start, end in file_intervals:
            start_ns = np.datetime64(start, "ns")
            end_ns = np.datetime64(end, "ns")

            hits = df.filter((pl.col("start") <= end_ns) & (pl.col("end") >= start_ns))
            if not hits.is_empty():
                self._logger.warning(
                    "temporal_overlap_detected",
                    group=group_name,
                    incoming_hash=rinex_hash[:16],
                    incoming_range=f"{start}{end}",
                    existing_files=hits.height,
                )
                overlapping.add(rinex_hash)

        return overlapping

    def append_metadata_bulk_store(
        self,
        group_name: str,
        rows: list[dict[str, Any]],
        store: Any,
    ) -> None:
        """
        Append metadata rows into an open transaction store.

        Parameters
        ----------
        group_name : str
            Group name (e.g. "canopy", "reference").
        rows : list[dict[str, Any]]
            Metadata rows to append.
        store : Any
            Open Icechunk transaction store.
        """
        if not rows:
            return

        zroot = zarr.open_group(store, mode="a")
        zmeta = zroot.require_group(f"{group_name}/metadata/table")

        # Find next index
        start_index = 0
        if "index" in zmeta:
            start_index = (
                int(zmeta["index"][-1]) + 1 if zmeta["index"].shape[0] > 0 else 0
            )

        for i, row in enumerate(rows, start=start_index):
            row["index"] = i

        import polars as pl

        df = pl.DataFrame(rows)

        for col in df.columns:
            list_only_cols = {
                "attrs",
                "commit_msg",
                "action",
                "write_strategy",
                "rinex_hash",
                "snapshot_id",
            }
            if col in list_only_cols:
                values = df[col].to_list()
            else:
                values = df[col].to_numpy()

            if col == "index":
                dtype = "i8"
            elif col in ("start", "end"):
                dtype = "M8[ns]"
            else:
                dtype = VariableLengthUTF8()

            if col not in zmeta:
                zmeta.create_array(
                    name=col, shape=(0,), dtype=dtype, chunks=(1024,), overwrite=True
                )

            arr = zmeta[col]
            old_len = arr.shape[0]
            new_len = old_len + len(values)
            arr.resize(new_len)
            arr[old_len:new_len] = values

        self._logger.info(f"Appended {df.height} metadata rows to group '{group_name}'")

    def expire_old_snapshots(
        self,
        days: int | None = None,
        branch: str = "main",
        delete_expired_branches: bool = True,
        delete_expired_tags: bool = True,
    ) -> set[str]:
        """
        Expire and garbage-collect snapshots older than the given retention period.

        Parameters
        ----------
        days : int | None, optional
            Number of days to retain snapshots. Defaults to config value.
        branch : str, default "main"
            Branch to apply expiration on.
        delete_expired_branches : bool, default True
            Whether to delete branches pointing to expired snapshots.
        delete_expired_tags : bool, default True
            Whether to delete tags pointing to expired snapshots.

        Returns
        -------
        set[str]
            Expired snapshot IDs.
        """
        if days is None:
            days = self._rinex_store_expire_days
        cutoff = datetime.now(UTC) - timedelta(days=days)

        # cutoff = datetime(2025, 10, 3, 16, 44, 1, tzinfo=timezone.utc)
        self._logger.info(
            f"Running expiration on store '{self.store_type}' "
            f"(branch '{branch}') with cutoff {cutoff.isoformat()}"
        )

        # Expire snapshots older than cutoff
        expired_ids = self.repo.expire_snapshots(
            older_than=cutoff,
            delete_expired_branches=delete_expired_branches,
            delete_expired_tags=delete_expired_tags,
        )

        if expired_ids:
            self._logger.info(
                f"Expired {len(expired_ids)} snapshots: {sorted(expired_ids)}"
            )
        else:
            self._logger.info("No snapshots to expire.")

        # Garbage-collect expired objects to reclaim storage
        summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
        self._logger.info(
            f"Garbage collection summary: "
            f"deleted_bytes={summary.bytes_deleted}, "
            f"deleted_chunks={summary.chunks_deleted}, "
            f"deleted_manifests={summary.manifests_deleted}, "
            f"deleted_snapshots={summary.snapshots_deleted}, "
            f"deleted_attributes={summary.attributes_deleted}, "
            f"deleted_transaction_logs={summary.transaction_logs_deleted}"
        )

        return expired_ids

    def get_history(self, branch: str = "main", limit: int | None = None) -> list[dict]:
        """
        Return commit ancestry (history) for a branch.

        Parameters
        ----------
        branch : str, default "main"
            Branch name.
        limit : int | None, optional
            Maximum number of commits to return.

        Returns
        -------
        list[dict]
            Commit info dictionaries (id, message, written_at, parent_ids).
        """
        self._logger.info(f"Fetching ancestry for branch '{branch}'")

        history = []
        for i, ancestor in enumerate(self.repo.ancestry(branch=branch)):
            history.append(
                {
                    "snapshot_id": ancestor.id,
                    "commit_msg": ancestor.message,
                    "written_at": ancestor.written_at,
                    "parent_ids": ancestor.parent_id,
                }
            )
            if limit is not None and i + 1 >= limit:
                break

        return history

    def print_history(self, branch: str = "main", limit: int | None = 100) -> None:
        """
        Pretty-print the ancestry for quick inspection.
        """
        for entry in self.get_history(branch=branch, limit=limit):
            ts = entry["written_at"].strftime("%Y-%m-%d %H:%M:%S")
            print(f"{ts} {entry['snapshot_id'][:8]} {entry['commit_msg']}")

    def __repr__(self) -> str:
        """Return the developer-facing representation.

        Returns
        -------
        str
            Representation string.
        """
        display_names = {"rinex_store": "GNSS Store", "vod_store": "VOD Store"}
        display = display_names.get(self.store_type, self.store_type)
        return f"MyIcechunkStore(store_path={self.store_path}, store_type={display})"

    def __str__(self) -> str:
        """Return a human-readable summary.

        Returns
        -------
        str
            Summary string.
        """

        # Capture tree output
        old_stdout = sys.stdout
        sys.stdout = buffer = io.StringIO()

        try:
            self.print_tree()
            tree_output = buffer.getvalue()
        finally:
            sys.stdout = old_stdout

        branches = self.get_branch_names()
        group_dict = self.get_group_names()
        total_groups = sum(len(groups) for groups in group_dict.values())

        return (
            f"MyIcechunkStore: {self.store_path}\n"
            f"Branches: {len(branches)} | Total Groups: {total_groups}\n\n"
            f"{tree_output}"
        )

    def rechunk_group(
        self,
        group_name: str,
        chunks: dict[str, int],
        source_branch: str = "main",
        temp_branch: str | None = None,
        promote_to_main: bool = True,
        delete_temp_branch: bool = True,
    ) -> str:
        """
        Rechunk a group with optimal chunk sizes.

        Parameters
        ----------
        group_name : str
            Name of the group to rechunk
        chunks : dict[str, int]
            Chunking specification, e.g. {'epoch': 34560, 'sid': -1}
        source_branch : str
            Branch to read original data from (default: "main")
        temp_branch : str | None
            Temporary branch name for rechunked data. If None, uses
            "{group_name}_rechunked".
        promote_to_main : bool
            If True, reset main branch to rechunked snapshot after writing
        delete_temp_branch : bool
            If True, delete temporary branch after promotion (only if
            promote_to_main=True).

        Returns
        -------
        str
            Snapshot ID of the rechunked data
        """
        if temp_branch is None:
            temp_branch = f"{group_name}_rechunked_temp"

        self._logger.info(
            f"Starting rechunk of group '{group_name}' with chunks={chunks}"
        )

        # Get CURRENT snapshot from source branch to preserve all other groups
        current_snapshot = next(self.repo.ancestry(branch=source_branch)).id

        # Create temp branch from current snapshot (preserves all existing groups)
        try:
            self.repo.create_branch(temp_branch, current_snapshot)
            self._logger.info(
                f"Created temporary branch '{temp_branch}' from current {source_branch}"
            )
        except Exception as e:
            self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

        # Read original data
        ds_original = self.read_group(group_name, branch=source_branch)
        self._logger.info(f"Original chunks: {ds_original.chunks}")

        # Rechunk
        ds_rechunked = ds_original.chunk(chunks)
        self._logger.info(f"New chunks: {ds_rechunked.chunks}")

        # Clear encoding to avoid conflicts
        for var in ds_rechunked.data_vars:
            ds_rechunked[var].encoding = {}

        # Write rechunked data (overwrites only this group)
        with self.writable_session(temp_branch) as session:
            to_icechunk(ds_rechunked, session, group=group_name, mode="w")
            snapshot_id = session.commit(f"Rechunked {group_name} with chunks={chunks}")

        self._logger.info(
            f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
        )

        # Promote to main if requested
        if promote_to_main:
            rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
            self.repo.reset_branch(source_branch, rechunked_snapshot)
            self._logger.info(
                f"Reset branch '{source_branch}' to rechunked snapshot "
                f"{rechunked_snapshot}"
            )

            # Delete temp branch if requested
            if delete_temp_branch:
                self.repo.delete_branch(temp_branch)
                self._logger.info(f"Deleted temporary branch '{temp_branch}'")

        return snapshot_id

    def rechunk_group_verbose(
        self,
        group_name: str,
        chunks: dict[str, int] | None = None,
        source_branch: str = "main",
        temp_branch: str | None = None,
        promote_to_main: bool = True,
        delete_temp_branch: bool = True,
    ) -> str:
        """
        Rechunk a group with optimal chunk sizes.

        Parameters
        ----------
        group_name : str
            Name of the group to rechunk
        chunks : dict[str, int] | None
            Chunking specification, e.g. {'epoch': 34560, 'sid': -1}. Defaults
            to `gnnsvodpy.globals.ICECHUNK_CHUNK_STRATEGIES`.
        source_branch : str
            Branch to read original data from (default: "main")
        temp_branch : str | None
            Temporary branch name for rechunked data. If None, uses
            "{group_name}_rechunked".
        promote_to_main : bool
            If True, reset main branch to rechunked snapshot after writing
        delete_temp_branch : bool
            If True, delete temporary branch after promotion (only if
            promote_to_main=True).

        Returns
        -------
        str
            Snapshot ID of the rechunked data
        """
        if temp_branch is None:
            temp_branch = f"{group_name}_rechunked_temp"

        if chunks is None:
            chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

        print(f"\n{'=' * 60}")
        print(f"Starting rechunk of group '{group_name}'")
        print(f"Target chunks: {chunks}")
        print(f"{'=' * 60}\n")

        self._logger.info(
            f"Starting rechunk of group '{group_name}' with chunks={chunks}"
        )

        # Get CURRENT snapshot from source branch to preserve all other groups
        print(f"[1/7] Getting current snapshot from branch '{source_branch}'...")
        current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
        print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

        # Create temp branch from current snapshot (preserves all existing groups)
        print(f"\n[2/7] Creating temporary branch '{temp_branch}'...")
        try:
            self.repo.create_branch(temp_branch, current_snapshot)
            print(f"      ✓ Branch '{temp_branch}' created")
            self._logger.info(
                f"Created temporary branch '{temp_branch}' from current {source_branch}"
            )
        except Exception as e:
            print(
                f"      ⚠ Branch '{temp_branch}' already exists, using existing branch"
            )
            self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

        # Read original data
        print(f"\n[3/7] Reading original data from '{group_name}'...")
        ds_original = self.read_group(group_name, branch=source_branch)

        # Unify chunks if inconsistent
        try:
            ds_original = ds_original.unify_chunks()
            print("      ✓ Unified inconsistent chunks")
        except TypeError, ValueError:
            pass  # Chunks are already consistent

        print(f"      ✓ Data shape: {dict(ds_original.sizes)}")
        print(f"      ✓ Original chunks: {ds_original.chunks}")
        self._logger.info(f"Original chunks: {ds_original.chunks}")

        # Rechunk
        print("\n[4/7] Rechunking data...")
        ds_rechunked = ds_original.chunk(chunks)
        ds_rechunked = ds_rechunked.unify_chunks()
        print(f"      ✓ New chunks: {ds_rechunked.chunks}")
        self._logger.info(f"New chunks: {ds_rechunked.chunks}")

        # Clear encoding to avoid conflicts
        for var in ds_rechunked.data_vars:
            ds_rechunked[var].encoding = {}
        for coord in ds_rechunked.coords:
            if "chunks" in ds_rechunked[coord].encoding:
                del ds_rechunked[coord].encoding["chunks"]

        # Write rechunked data first (overwrites entire group)
        print(f"\n[5/7] Writing rechunked data to branch '{temp_branch}'...")
        print("      This may take several minutes for large datasets...")
        with self.writable_session(temp_branch) as session:
            to_icechunk(ds_rechunked, session, group=group_name, mode="w")
            session.commit(f"Wrote rechunked data for {group_name}")
        print("      ✓ Data written successfully")

        # Copy subgroups after writing rechunked data
        print(f"\n[6/7] Copying subgroups from '{group_name}'...")
        with self.writable_session(temp_branch) as session:
            with self.readonly_session(source_branch) as icsession:
                source_group = zarr.open_group(icsession.store, mode="r")[group_name]
            target_group = zarr.open_group(session.store, mode="a")[group_name]

            subgroup_count = 0
            for subgroup_name in source_group.group_keys():
                print(f"      ✓ Copying subgroup '{subgroup_name}'...")
                source_subgroup = source_group[subgroup_name]
                target_subgroup = target_group.create_group(
                    subgroup_name, overwrite=True
                )

                # Copy arrays from subgroup
                for array_name in source_subgroup.array_keys():
                    source_array = source_subgroup[array_name]
                    target_array = target_subgroup.create_array(
                        array_name,
                        shape=source_array.shape,
                        dtype=source_array.dtype,
                        chunks=source_array.chunks,
                        overwrite=True,
                    )
                    target_array[:] = source_array[:]

                # Copy subgroup attributes
                target_subgroup.attrs.update(source_subgroup.attrs)
                subgroup_count += 1

            if subgroup_count > 0:
                snapshot_id = session.commit(
                    f"Rechunked {group_name} with chunks={chunks}"
                )
                print(f"      ✓ {subgroup_count} subgroups copied")
            else:
                snapshot_id = next(self.repo.ancestry(branch=temp_branch)).id
                print("      ✓ No subgroups to copy")

        print(f"      ✓ Snapshot ID: {snapshot_id[:12]}")
        self._logger.info(
            f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
        )

        # Promote to main if requested
        if promote_to_main:
            print(f"\n[7/7] Promoting to '{source_branch}' branch...")
            rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
            self.repo.reset_branch(source_branch, rechunked_snapshot)
            print(
                f"      ✓ Branch '{source_branch}' reset to {rechunked_snapshot[:12]}"
            )
            self._logger.info(
                f"Reset branch '{source_branch}' to rechunked snapshot "
                f"{rechunked_snapshot}"
            )

            # Delete temp branch if requested
            if delete_temp_branch:
                print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
                self.delete_branch(temp_branch)
                print("      ✓ Temporary branch deleted")
                self._logger.info(f"Deleted temporary branch '{temp_branch}'")
        else:
            print("\n[7/7] Skipping promotion (promote_to_main=False)")
            print(f"      Rechunked data available on branch '{temp_branch}'")

        print(f"\n{'=' * 60}")
        print(f"✓ Rechunking complete for '{group_name}'")
        print(f"{'=' * 60}\n")

        return snapshot_id

    def create_release_tag(self, tag_name: str, snapshot_id: str | None = None) -> None:
        """
        Create an immutable tag for an important version.

        Parameters
        ----------
        tag_name : str
            Name for the tag (e.g., "v2024_complete", "before_reprocess")
        snapshot_id : str | None
            Snapshot to tag. If None, uses current tip of main branch.
        """
        if snapshot_id is None:
            # Tag current main branch tip
            snapshot_id = next(self.repo.ancestry(branch="main")).id

        self.repo.create_tag(tag_name, snapshot_id)
        self._logger.info(f"Created tag '{tag_name}' at snapshot {snapshot_id[:8]}")

    def list_tags(self) -> list[str]:
        """List all tags in the repository."""
        return list(self.repo.list_tags())

    def delete_tag(self, tag_name: str) -> None:
        """Delete a tag (use with caution - tags are meant to be permanent)."""
        self.repo.delete_tag(tag_name)
        self._logger.warning(f"Deleted tag '{tag_name}'")

    def plot_commit_graph(self, max_commits: int = 100) -> Figure:
        """
        Visualize commit history as an interactive git-like graph.

        Creates an interactive visualization showing:
        - Branches with different colors
        - Chronological commit ordering
        - Branch divergence points
        - Commit messages on hover
        - Click to see commit details

        Parameters
        ----------
        max_commits : int
            Maximum number of commits to display (default: 100).

        Returns
        -------
        Figure
            Interactive plotly figure (works in marimo and Jupyter).
        """
        from collections import defaultdict
        from datetime import datetime

        import plotly.graph_objects as go

        # Collect all commits with full metadata
        commit_map = {}  # id -> commit data
        branch_tips = {}  # branch -> latest commit id

        for branch in self.repo.list_branches():
            ancestors = list(self.repo.ancestry(branch=branch))
            if ancestors:
                branch_tips[branch] = ancestors[0].id

            for ancestor in ancestors:
                if ancestor.id not in commit_map:
                    commit_map[ancestor.id] = {
                        "id": ancestor.id,
                        "parent_id": ancestor.parent_id,
                        "message": ancestor.message,
                        "written_at": ancestor.written_at,
                        "branches": [branch],
                    }
                else:
                    # Multiple branches point to same commit
                    commit_map[ancestor.id]["branches"].append(branch)

                if len(commit_map) >= max_commits:
                    break
            if len(commit_map) >= max_commits:
                break

        # Build parent-child relationships
        commits_list = list(commit_map.values())
        commits_list.sort(key=lambda c: c["written_at"])  # Oldest first

        # Assign horizontal positions (chronological)
        commit_x_positions = {}
        for idx, commit in enumerate(commits_list):
            commit["x"] = idx
            commit_x_positions[commit["id"]] = idx

        # Assign vertical positions: commits shared by branches stay on same Y
        # Only diverge when branches have different commits
        branch_names = sorted(
            self.repo.list_branches(), key=lambda b: (b != "main", b)
        )  # main first

        # Build a set of all commit IDs for each branch
        branch_commits = {}
        for branch in branch_names:
            history = list(self.repo.ancestry(branch=branch))
            branch_commits[branch] = {h.id for h in history if h.id in commit_map}

        # Find where branches diverge
        def branches_share_commit(
            commit_id: str,
            branches: list[str],
        ) -> list[str]:
            """Return branches that contain a commit.

            Parameters
            ----------
            commit_id : str
                Commit identifier to check.
            branches : list[str]
                Branch names to search.

            Returns
            -------
            list[str]
                Branches that contain the commit.
            """
            return [b for b in branches if commit_id in branch_commits[b]]

        # Assign Y position: all commits on a single horizontal line initially
        # We'll use vertical offset for parallel branch indicators
        for commit in commits_list:
            commit["y"] = 0  # All on same timeline
            commit["branch_set"] = frozenset(commit["branches"])

        # Color palette for branches
        colors = [
            "#4a9a4a",  # green (main)
            "#5580c8",  # blue
            "#d97643",  # orange
            "#9b59b6",  # purple
            "#e74c3c",  # red
            "#1abc9c",  # turquoise
            "#f39c12",  # yellow
            "#34495e",  # dark gray
        ]
        branch_colors = {b: colors[i % len(colors)] for i, b in enumerate(branch_names)}

        # Build edges: draw parallel lines for shared commits (metro-style)
        edges_by_branch = defaultdict(list)  # branch -> list of edge dicts

        for commit in commits_list:
            if commit["parent_id"] and commit["parent_id"] in commit_map:
                parent = commit_map[commit["parent_id"]]

                # Find which branches share both this commit and its parent
                shared_branches = [
                    b for b in commit["branches"] if b in parent["branches"]
                ]

                for branch in shared_branches:
                    edges_by_branch[branch].append(
                        {
                            "x0": parent["x"],
                            "y0": parent["y"],
                            "x1": commit["x"],
                            "y1": commit["y"],
                        }
                    )

        # Create plotly figure
        fig = go.Figure()

        # Draw edges grouped by branch (parallel lines for shared paths)
        for branch_idx, branch in enumerate(branch_names):
            if branch not in edges_by_branch:
                continue

            color = branch_colors[branch]

            # Draw each edge as a separate line
            for edge in edges_by_branch[branch]:
                # Vertical offset for parallel lines (metro-style)
                offset = (branch_idx - (len(branch_names) - 1) / 2) * 0.15

                fig.add_trace(
                    go.Scatter(
                        x=[edge["x0"], edge["x1"]],
                        y=[edge["y0"] + offset, edge["y1"] + offset],
                        mode="lines",
                        line=dict(color=color, width=3),
                        hoverinfo="skip",
                        showlegend=False,
                        opacity=0.7,
                    )
                )

        # Draw commits (nodes) - one trace per unique commit
        # Color by which branches include it
        x_vals = [c["x"] for c in commits_list]
        y_vals = [c["y"] for c in commits_list]

        # Format hover text
        hover_texts = []
        marker_colors = []
        marker_symbols = []

        for c in commits_list:
            # Handle both string and datetime objects
            if isinstance(c["written_at"], str):
                time_str = datetime.fromisoformat(c["written_at"]).strftime(
                    "%Y-%m-%d %H:%M"
                )
            else:
                time_str = c["written_at"].strftime("%Y-%m-%d %H:%M")

            branches_str = ", ".join(c["branches"])
            hover_texts.append(
                f"<b>{c['message'] or 'No message'}</b><br>"
                f"Commit: {c['id'][:12]}<br>"
                f"Branches: {branches_str}<br>"
                f"Time: {time_str}"
            )

            # Color by first branch (priority: main)
            if "main" in c["branches"]:
                marker_colors.append(branch_colors["main"])
            else:
                marker_colors.append(branch_colors[c["branches"][0]])

            # Star for branch tips
            if c["id"] in branch_tips.values():
                marker_symbols.append("star")
            else:
                marker_symbols.append("circle")

        fig.add_trace(
            go.Scatter(
                x=x_vals,
                y=y_vals,
                mode="markers",
                name="Commits",
                marker=dict(
                    size=14,
                    color=marker_colors,
                    symbol=marker_symbols,
                    line=dict(color="white", width=2),
                ),
                hovertext=hover_texts,
                hoverinfo="text",
                showlegend=False,
            )
        )

        # Add legend traces (invisible points just for legend)
        for branch_idx, branch in enumerate(branch_names):
            fig.add_trace(
                go.Scatter(
                    x=[None],
                    y=[None],
                    mode="markers",
                    name=branch,
                    marker=dict(
                        size=10,
                        color=branch_colors[branch],
                        line=dict(color="white", width=2),
                    ),
                    showlegend=True,
                )
            )

        # Layout styling
        title_text = (
            f"Commit Graph: {self.site_name} ({len(commits_list)} commits, "
            f"{len(branch_names)} branches)"
        )
        fig.update_layout(
            title=dict(
                text=title_text,
                font=dict(size=16, color="#e5e5e5"),
            ),
            xaxis=dict(
                title="Time (oldest ← → newest)",
                showticklabels=False,
                showgrid=True,
                gridcolor="rgba(255,255,255,0.1)",
                zeroline=False,
            ),
            yaxis=dict(
                title="",
                showticklabels=False,
                showgrid=False,
                zeroline=False,
                range=[-1, 1],  # Fixed range for single timeline
            ),
            plot_bgcolor="#1a1a1a",
            paper_bgcolor="#1a1a1a",
            font=dict(color="#e5e5e5"),
            hovermode="closest",
            height=400,
            width=max(800, len(commits_list) * 50),
            legend=dict(
                title="Branches",
                orientation="h",
                x=0,
                y=-0.15,
                bgcolor="rgba(30,30,30,0.8)",
                bordercolor="rgba(255,255,255,0.2)",
                borderwidth=1,
            ),
        )

        return fig

    def cleanup_stale_branches(
        self, keep_patterns: list[str] | None = None
    ) -> list[str]:
        """
        Delete stale temporary branches (e.g., from failed rechunking).

        Parameters
        ----------
        keep_patterns : list[str] | None
            Patterns to preserve. Default: ["main", "dev"]

        Returns
        -------
        list[str]
            Names of deleted branches
        """
        if keep_patterns is None:
            keep_patterns = ["main", "dev"]

        deleted = []

        for branch in self.repo.list_branches():
            # Keep if matches any pattern
            should_keep = any(pattern in branch for pattern in keep_patterns)

            if not should_keep:
                # Check if it's a temp branch from rechunking
                if "_rechunked_temp" in branch or "_temp" in branch:
                    try:
                        self.repo.delete_branch(branch)
                        deleted.append(branch)
                        self._logger.info(f"Deleted stale branch: {branch}")
                    except Exception as e:
                        self._logger.warning(f"Failed to delete branch {branch}: {e}")

        return deleted

    def delete_branch(self, branch_name: str) -> None:
        """Delete a branch."""
        if branch_name == "main":
            raise ValueError("Cannot delete 'main' branch")

        self.repo.delete_branch(branch_name)
        self._logger.info(f"Deleted branch '{branch_name}'")

    def get_snapshot_info(self, snapshot_id: str) -> dict:
        """
        Get detailed information about a specific snapshot.

        Parameters
        ----------
        snapshot_id : str
            Snapshot ID to inspect

        Returns
        -------
        dict
            Snapshot metadata and statistics
        """
        # Find the snapshot in ancestry
        for ancestor in self.repo.ancestry(branch="main"):
            if ancestor.id == snapshot_id or ancestor.id.startswith(snapshot_id):
                info = {
                    "snapshot_id": ancestor.id,
                    "message": ancestor.message,
                    "written_at": ancestor.written_at,
                    "parent_id": ancestor.parent_id,
                }

                # Try to get groups at this snapshot
                try:
                    session = self.repo.readonly_session(snapshot_id=ancestor.id)
                    root = zarr.open(session.store, mode="r")
                    info["groups"] = list(root.group_keys())
                    info["arrays"] = list(root.array_keys())
                except Exception as e:
                    self._logger.warning(f"Could not inspect snapshot contents: {e}")

                return info

        raise ValueError(f"Snapshot {snapshot_id} not found in history")

    def compare_snapshots(self, snapshot_id_1: str, snapshot_id_2: str) -> dict:
        """
        Compare two snapshots to see what changed.

        Parameters
        ----------
        snapshot_id_1 : str
            First snapshot (older)
        snapshot_id_2 : str
            Second snapshot (newer)

        Returns
        -------
        dict
            Comparison results showing added/removed/modified groups
        """
        info_1 = self.get_snapshot_info(snapshot_id_1)
        info_2 = self.get_snapshot_info(snapshot_id_2)

        groups_1 = set(info_1.get("groups", []))
        groups_2 = set(info_2.get("groups", []))

        return {
            "snapshot_1": snapshot_id_1[:8],
            "snapshot_2": snapshot_id_2[:8],
            "added_groups": list(groups_2 - groups_1),
            "removed_groups": list(groups_1 - groups_2),
            "common_groups": list(groups_1 & groups_2),
            "time_diff": (info_2["written_at"] - info_1["written_at"]).total_seconds(),
        }

    def maintenance(
        self, expire_days: int = 7, cleanup_branches: bool = True, run_gc: bool = True
    ) -> dict:
        """
        Run full maintenance on the store.

        Parameters
        ----------
        expire_days : int
            Days of snapshot history to keep
        cleanup_branches : bool
            Remove stale temporary branches
        run_gc : bool
            Run garbage collection after expiration

        Returns
        -------
        dict
            Summary of maintenance actions
        """
        self._logger.info(f"Starting maintenance on {self.store_type}")

        results = {"expired_snapshots": 0, "deleted_branches": [], "gc_summary": None}

        # Expire old snapshots
        expired_ids = self.expire_old_snapshots(days=expire_days)
        results["expired_snapshots"] = len(expired_ids)

        # Cleanup stale branches
        if cleanup_branches:
            deleted_branches = self.cleanup_stale_branches()
            results["deleted_branches"] = deleted_branches

        # Garbage collection
        if run_gc:
            from datetime import datetime, timedelta

            cutoff = datetime.now(UTC) - timedelta(days=expire_days)
            gc_summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
            results["gc_summary"] = {
                "bytes_deleted": gc_summary.bytes_deleted,
                "chunks_deleted": gc_summary.chunks_deleted,
                "manifests_deleted": gc_summary.manifests_deleted,
            }

        self._logger.info(f"Maintenance complete: {results}")
        return results

    def sanitize_store(
        self,
        source_branch: str = "main",
        temp_branch: str = "sanitize_temp",
        promote_to_main: bool = True,
        delete_temp_branch: bool = True,
    ) -> str:
        """
        Sanitize all groups by removing NaN-only SIDs and cleaning coordinates.

        Creates a temporary branch, applies sanitization to all groups, then
        optionally promotes to main and cleans up.

        Parameters
        ----------
        source_branch : str, default "main"
            Branch to read original data from.
        temp_branch : str, default "sanitize_temp"
            Temporary branch name for sanitized data.
        promote_to_main : bool, default True
            If True, reset main branch to sanitized snapshot after writing.
        delete_temp_branch : bool, default True
            If True, delete temporary branch after promotion.

        Returns
        -------
        str
            Snapshot ID of the sanitized data.
        """
        import time

        from icechunk.xarray import to_icechunk

        print(f"\n{'=' * 60}")
        print("Starting store sanitization")
        print(f"{'=' * 60}\n")

        # Step 1: Get current snapshot
        print(f"[1/6] Getting current snapshot from '{source_branch}'...")
        current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
        print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

        # Step 2: Create temp branch
        print(f"\n[2/6] Creating temporary branch '{temp_branch}'...")
        try:
            self.repo.create_branch(temp_branch, current_snapshot)
            print(f"      ✓ Branch '{temp_branch}' created")
        except Exception:
            print("      ⚠ Branch exists, deleting and recreating...")
            self.delete_branch(temp_branch)
            self.repo.create_branch(temp_branch, current_snapshot)
            print(f"      ✓ Branch '{temp_branch}' created")

        # Step 3: Get all groups
        print("\n[3/6] Discovering groups...")
        groups = self.list_groups()
        print(f"      ✓ Found {len(groups)} groups: {groups}")

        # Step 4: Sanitize each group
        print("\n[4/6] Sanitizing groups...")
        sanitized_count = 0

        for group_name in groups:
            print(f"\n      Processing '{group_name}'...")
            t_start = time.time()

            try:
                # Read original data
                ds_original = self.read_group(group_name, branch=source_branch)
                original_sids = len(ds_original.sid)
                print(f"        • Original: {original_sids} SIDs")

                # Sanitize: remove SIDs with all-NaN data
                ds_sanitized = self._sanitize_dataset(ds_original)
                sanitized_sids = len(ds_sanitized.sid)
                removed_sids = original_sids - sanitized_sids

                print(
                    f"        • Sanitized: {sanitized_sids} SIDs "
                    f"(removed {removed_sids})"
                )

                # Write sanitized data
                with self.writable_session(temp_branch) as session:
                    to_icechunk(ds_sanitized, session, group=group_name, mode="w")

                    # Copy metadata subgroups if they exist
                    try:
                        with self.readonly_session(source_branch) as read_session:
                            source_group = zarr.open_group(
                                read_session.store, mode="r"
                            )[group_name]
                            if "metadata" in source_group.group_keys():
                                # Copy entire metadata subgroup
                                dest_group = zarr.open_group(session.store)[group_name]
                                zarr.copy(
                                    source_group["metadata"],
                                    dest_group,
                                    name="metadata",
                                )
                                print("        • Copied metadata subgroup")
                    except Exception as e:
                        print(f"        ⚠ Could not copy metadata: {e}")

                    session.commit(
                        f"Sanitized {group_name}: removed {removed_sids} empty SIDs"
                    )

                t_elapsed = time.time() - t_start
                print(f"        ✓ Completed in {t_elapsed:.2f}s")
                sanitized_count += 1

            except Exception as e:
                print(f"        ✗ Failed: {e}")
                continue

        print(f"\n      ✓ Sanitized {sanitized_count}/{len(groups)} groups")

        # Step 5: Get final snapshot
        print("\n[5/6] Getting sanitized snapshot...")
        sanitized_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
        print(f"      ✓ Snapshot: {sanitized_snapshot[:12]}")

        # Step 6: Promote to main
        if promote_to_main:
            print(f"\n[6/6] Promoting to '{source_branch}' branch...")
            self.repo.reset_branch(source_branch, sanitized_snapshot)
            print(
                f"      ✓ Branch '{source_branch}' reset to {sanitized_snapshot[:12]}"
            )

            if delete_temp_branch:
                print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
                self.delete_branch(temp_branch)
                print("      ✓ Temporary branch deleted")
        else:
            print("\n[6/6] Skipping promotion (promote_to_main=False)")
            print(f"      Sanitized data available on branch '{temp_branch}'")

        print(f"\n{'=' * 60}")
        print("✓ Sanitization complete")
        print(f"{'=' * 60}\n")

        return sanitized_snapshot

    def _sanitize_dataset(self, ds: xr.Dataset) -> xr.Dataset:
        """
        Remove SIDs that have all-NaN data and clean coordinate metadata.

        Parameters
        ----------
        ds : xr.Dataset
            Dataset to sanitize

        Returns
        -------
        xr.Dataset
            Sanitized dataset with NaN-only SIDs removed
        """
        # Find SIDs that have at least some non-NaN data across all variables
        has_data = ds.to_array().notnull().any(dim=["variable", "epoch"])

        # Keep only SIDs with data
        sids_with_data = ds.sid.values[has_data.values]
        ds_clean = ds.sel(sid=sids_with_data)

        # Clean coordinate metadata - remove NaN values from string coordinates
        for coord in ["band", "system", "code", "sv"]:
            if coord in ds_clean.coords:
                coord_values = ds_clean[coord].values
                # Convert object arrays, handling NaN
                if coord_values.dtype == object:
                    clean_values = []
                    for val in coord_values:
                        if isinstance(val, float) and np.isnan(val):
                            clean_values.append("")
                        elif val is None or (isinstance(val, str) and val == "nan"):
                            clean_values.append("")
                        else:
                            clean_values.append(str(val))
                    ds_clean = ds_clean.assign_coords({coord: ("sid", clean_values)})

        # Numeric coordinates can keep NaN if needed
        for coord in ["freq_center", "freq_min", "freq_max"]:
            if coord in ds_clean.coords:
                # These are fine as-is since they're numeric
                pass

        return ds_clean

    def safe_temporal_aggregate(
        self,
        group: str,
        freq: str = "1D",
        vars_to_aggregate: Sequence[str] = ("VOD",),
        geometry_vars: Sequence[str] = ("phi", "theta"),
        drop_empty: bool = True,
        branch: str = "main",
    ) -> xr.Dataset:
        """Aggregate temporally irregular VOD data per SID.

        Each satellite (SID) is aggregated independently within each
        time bin.  Mixing observations across satellites is physically
        meaningless because each observes a different part of the canopy
        from a different sky position.

        .. note::

           For production use, prefer ``canvod.ops.TemporalAggregate``
           which uses Polars groupby and handles all coordinate types
           explicitly.  This method is a convenience wrapper for quick
           interactive exploration.

        Parameters
        ----------
        group : str
            Group name to aggregate.
        freq : str, default "1D"
            Resample frequency string.
        vars_to_aggregate : Sequence[str], optional
            Variables to aggregate using mean.
        geometry_vars : Sequence[str], optional
            Geometry variables to aggregate using mean (centroid of
            contributing sky positions).
        drop_empty : bool, default True
            Drop empty epochs after aggregation.
        branch : str, default "main"
            Branch name to read from.

        Returns
        -------
        xr.Dataset
            Aggregated dataset with independent per-SID aggregation.
        """
        log = get_logger(__name__)

        with self.readonly_session(branch=branch) as session:
            ds = xr.open_zarr(session.store, group=group, consolidated=False)

            log.info(
                "Aggregating group",
                group=group,
                branch=branch,
                freq=freq,
            )

            # Aggregate data and geometry vars with mean (per SID
            # independently — resample preserves the sid dimension).
            all_vars = list(vars_to_aggregate) + list(geometry_vars)
            merged_vars = []
            for var in all_vars:
                if var in ds:
                    merged_vars.append(ds[var].resample(epoch=freq).mean())
                else:
                    log.warning("Skipping missing variable", var=var)
            ds_agg = xr.merge(merged_vars)

            # Preserve sid-only coordinates (sv, band, code, etc.)
            for coord in ds.coords:
                if coord in ds_agg.coords or coord == "epoch":
                    continue
                coord_dims = ds.coords[coord].dims
                # Only copy coords whose dims all survive in ds_agg
                if all(d in ds_agg.dims for d in coord_dims):
                    ds_agg[coord] = ds[coord]

            # Drop all-NaN epochs if requested
            if drop_empty and "VOD" in ds_agg:
                valid_mask = ds_agg["VOD"].notnull().any(dim="sid").compute()
                ds_agg = ds_agg.isel(epoch=valid_mask)

            log.info("Aggregation done", sizes=dict(ds_agg.sizes))
            return ds_agg

    def safe_temporal_aggregate_to_branch(
        self,
        source_group: str,
        target_group: str,
        target_branch: str,
        freq: str = "1D",
        overwrite: bool = False,
        **kwargs: Any,
    ) -> xr.Dataset:
        """Aggregate a group and save to a new Icechunk branch/group.

        Parameters
        ----------
        source_group : str
            Source group name.
        target_group : str
            Target group name.
        target_branch : str
            Target branch name.
        freq : str, default "1D"
            Resample frequency string.
        overwrite : bool, default False
            Whether to overwrite an existing branch.
        **kwargs : Any
            Additional keyword args passed to safe_temporal_aggregate().

        Returns
        -------
        xr.Dataset
            Aggregated dataset written to the target branch.
        """

        print(
            f"🚀 Creating new aggregated branch '{target_branch}' at '{target_group}'"
        )

        # Compute safe aggregation
        ds_agg = self.safe_temporal_aggregate(
            group=source_group,
            freq=freq,
            **kwargs,
        )

        # Write to new branch
        current_snapshot = next(self.repo.ancestry(branch="main")).id
        self.delete_branch(target_branch)
        self.repo.create_branch(target_branch, current_snapshot)
        with self.writable_session(target_branch) as session:
            to_icechunk(
                obj=ds_agg,
                session=session,
                group=target_group,
                mode="w",
            )
            session.commit(f"Saved aggregated data to {target_group} at freq={freq}")

        print(
            f"✅ Saved aggregated dataset to branch '{target_branch}' "
            f"(group '{target_group}')"
        )
        return ds_agg

repo property

Get the repository instance.

source_format property

Return the source_format root attribute, or None.

tree property

Display hierarchical tree of all branches, groups, and subgroups.

__init__(store_path, store_type='rinex_store', compression_level=None, compression_algorithm=None)

Initialize the Icechunk store manager.

Parameters

store_path : Path Path to the Icechunk store directory. store_type : str, default "rinex_store" Type of store ("rinex_store" or "vod_store"). compression_level : int | None, optional Override default compression level. compression_algorithm : str | None, optional Override default compression algorithm.

Source code in packages/canvod-store/src/canvod/store/store.py
 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
def __init__(
    self,
    store_path: Path,
    store_type: str = "rinex_store",
    compression_level: int | None = None,
    compression_algorithm: str | None = None,
) -> None:
    """Initialize the Icechunk store manager.

    Parameters
    ----------
    store_path : Path
        Path to the Icechunk store directory.
    store_type : str, default "rinex_store"
        Type of store ("rinex_store" or "vod_store").
    compression_level : int | None, optional
        Override default compression level.
    compression_algorithm : str | None, optional
        Override default compression algorithm.
    """
    from canvod.utils.config import load_config

    cfg = load_config()
    ic_cfg = cfg.processing.icechunk
    st_cfg = cfg.processing.storage

    self.store_path = Path(store_path)
    self.store_type = store_type
    # Site name is parent directory name
    self.site_name = self.store_path.parent.name

    # Compression
    self.compression_level = compression_level or ic_cfg.compression_level
    compression_alg = compression_algorithm or ic_cfg.compression_algorithm
    self.compression_algorithm = getattr(
        icechunk.CompressionAlgorithm, compression_alg.capitalize()
    )

    # Chunk strategy
    chunk_strategies = {
        k: {"epoch": v.epoch, "sid": v.sid}
        for k, v in ic_cfg.chunk_strategies.items()
    }
    self.chunk_strategy = chunk_strategies.get(store_type, {})

    # Storage config cached for metadata rows
    self._rinex_store_strategy = st_cfg.rinex_store_strategy
    self._rinex_store_expire_days = st_cfg.rinex_store_expire_days
    self._vod_store_strategy = st_cfg.vod_store_strategy

    # Configure repository
    self.config = icechunk.RepositoryConfig.default()
    self.config.compression = icechunk.CompressionConfig(
        level=self.compression_level, algorithm=self.compression_algorithm
    )
    self.config.inline_chunk_threshold_bytes = ic_cfg.inline_threshold
    self.config.get_partial_values_concurrency = ic_cfg.get_concurrency

    if ic_cfg.manifest_preload_enabled:
        self.config.manifest = icechunk.ManifestConfig(
            preload=icechunk.ManifestPreloadConfig(
                max_total_refs=ic_cfg.manifest_preload_max_refs,
                preload_if=icechunk.ManifestPreloadCondition.name_matches(
                    ic_cfg.manifest_preload_pattern
                ),
            )
        )
        self._logger.info(
            f"Manifest preload enabled: {ic_cfg.manifest_preload_pattern}"
        )

    self._repo = None
    self._logger = get_logger(__name__)

    # Remove .DS_Store files that corrupt icechunk ref listing on macOS
    self._clean_ds_store()
    self._ensure_store_exists()

readonly_session(branch='main')

Context manager for readonly sessions.

Parameters

branch : str, default "main" Branch name.

Returns

Generator[icechunk.ReadonlySession, None, None] Readonly session context manager.

Source code in packages/canvod-store/src/canvod/store/store.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@contextlib.contextmanager
def readonly_session(
    self,
    branch: str = "main",
) -> Generator[icechunk.ReadonlySession]:
    """Context manager for readonly sessions.

    Parameters
    ----------
    branch : str, default "main"
        Branch name.

    Returns
    -------
    Generator[icechunk.ReadonlySession, None, None]
        Readonly session context manager.
    """
    session = self.repo.readonly_session(branch)
    try:
        self._logger.debug(f"Opened readonly session for branch '{branch}'")
        yield session
    finally:
        self._logger.debug(f"Closed readonly session for branch '{branch}'")

writable_session(branch='main')

Context manager for writable sessions.

Parameters

branch : str, default "main" Branch name.

Returns

Generator[icechunk.WritableSession, None, None] Writable session context manager.

Source code in packages/canvod-store/src/canvod/store/store.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
@contextlib.contextmanager
def writable_session(
    self,
    branch: str = "main",
) -> Generator[icechunk.WritableSession]:
    """Context manager for writable sessions.

    Parameters
    ----------
    branch : str, default "main"
        Branch name.

    Returns
    -------
    Generator[icechunk.WritableSession, None, None]
        Writable session context manager.
    """
    session = self.repo.writable_session(branch)
    try:
        self._logger.debug(f"Opened writable session for branch '{branch}'")
        yield session
    finally:
        self._logger.debug(f"Closed writable session for branch '{branch}'")

set_root_attrs(attrs, branch='main')

Set root-level Zarr attributes on the store.

Parameters

attrs : dict[str, Any] Key-value pairs to merge into root attrs. branch : str, default "main" Branch to write to.

Returns

str Snapshot ID from the commit.

Source code in packages/canvod-store/src/canvod/store/store.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def set_root_attrs(self, attrs: dict[str, Any], branch: str = "main") -> str:
    """Set root-level Zarr attributes on the store.

    Parameters
    ----------
    attrs : dict[str, Any]
        Key-value pairs to merge into root attrs.
    branch : str, default "main"
        Branch to write to.

    Returns
    -------
    str
        Snapshot ID from the commit.
    """
    with self.writable_session(branch) as session:
        try:
            root = zarr.open_group(session.store, mode="r+")
        except zarr.errors.GroupNotFoundError:
            root = zarr.open_group(session.store, mode="w")
        root.attrs.update(attrs)
        return session.commit(f"Set root attrs: {list(attrs.keys())}")

get_root_attrs(branch='main')

Read root-level Zarr attributes from the store.

Returns

dict[str, Any] Root attributes (empty dict if none set).

Source code in packages/canvod-store/src/canvod/store/store.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def get_root_attrs(self, branch: str = "main") -> dict[str, Any]:
    """Read root-level Zarr attributes from the store.

    Returns
    -------
    dict[str, Any]
        Root attributes (empty dict if none set).
    """
    try:
        with self.readonly_session(branch) as session:
            root = zarr.open_group(session.store, mode="r")
            return dict(root.attrs)
    except Exception:
        return {}

get_branch_names()

List all branches in the store.

Returns

list[str] List of branch names.

Source code in packages/canvod-store/src/canvod/store/store.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def get_branch_names(self) -> list[str]:
    """
    List all branches in the store.

    Returns
    -------
    list[str]
        List of branch names.
    """
    try:
        storage_config = icechunk.local_filesystem_storage(self.store_path)
        repo = icechunk.Repository.open(
            storage=storage_config,
        )

        return list(repo.list_branches())
    except Exception as e:
        self._logger.warning(f"Failed to list branches in {self!r}: {e}")
        warnings.warn(f"Failed to list branches in {self!r}: {e}", stacklevel=2)
        return []

get_group_names(branch=None)

List all groups in the store.

Parameters

branch: Optional[str] Repository branch to examine. Defaults to listing groups from all branches.

Returns

dict[str, list[str]] Dictionary mapping branch names to lists of group names.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_group_names(self, branch: str | None = None) -> dict[str, list[str]]:
    """
    List all groups in the store.

    Parameters
    ----------
    branch: Optional[str]
        Repository branch to examine. Defaults to listing groups from all branches.

    Returns
    -------
    dict[str, list[str]]
        Dictionary mapping branch names to lists of group names.

    """
    try:
        if not branch:
            branches = self.get_branch_names()
        else:
            branches = [branch]

        storage_config = icechunk.local_filesystem_storage(self.store_path)
        repo = icechunk.Repository.open(
            storage=storage_config,
        )

        group_dict = {}
        for br in branches:
            with self.readonly_session(br) as session:
                session = repo.readonly_session(br)
                root = zarr.open(session.store, mode="r")
                group_dict[br] = list(root.group_keys())

        return group_dict

    except Exception as e:
        self._logger.warning(f"Failed to list groups in {self!r}: {e}")
        return {}

list_groups(branch='main')

List all groups in a branch.

Parameters

branch : str Branch name (default: "main")

Returns

list[str] List of group names in the branch

Source code in packages/canvod-store/src/canvod/store/store.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def list_groups(self, branch: str = "main") -> list[str]:
    """
    List all groups in a branch.

    Parameters
    ----------
    branch : str
        Branch name (default: "main")

    Returns
    -------
    list[str]
        List of group names in the branch
    """
    group_dict = self.get_group_names(branch=branch)
    if branch in group_dict:
        return group_dict[branch]
    return []

print_tree(max_depth=None)

Display hierarchical tree of all branches, groups, and subgroups.

Parameters

max_depth : int | None Maximum depth to display. None for unlimited depth. - 0: Only show branches - 1: Show branches and top-level groups - 2: Show branches, groups, and first level of subgroups/arrays - etc.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def print_tree(self, max_depth: int | None = None) -> None:
    """
    Display hierarchical tree of all branches, groups, and subgroups.

    Parameters
    ----------
    max_depth : int | None
        Maximum depth to display. None for unlimited depth.
        - 0: Only show branches
        - 1: Show branches and top-level groups
        - 2: Show branches, groups, and first level of subgroups/arrays
        - etc.
    """
    try:
        branches = self.get_branch_names()

        for i, branch in enumerate(branches):
            is_last_branch = i == len(branches) - 1
            branch_prefix = "└── " if is_last_branch else "├── "

            if max_depth is not None and max_depth < 1:
                continue

            session = self.repo.readonly_session(branch)
            root = zarr.open(session.store, mode="r")

            if i == 0:
                sys.stdout.write(f"{self.store_path}\n")

            sys.stdout.write(f"{branch_prefix}{branch}\n")
            # Build tree recursively
            branch_indent = "    " if is_last_branch else "│   "
            self._build_tree(root, branch_indent, max_depth, current_depth=1)

    except Exception as e:
        self._logger.warning(f"Failed to generate tree for {self!r}: {e}")
        sys.stdout.write(f"Error generating tree: {e}\n")

group_exists(group_name, branch='main')

Check if a group exists.

Parameters

group_name : str Name of the group to check. branch : str, default "main" Repository branch to examine.

Returns

bool True if the group exists, False otherwise.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def group_exists(self, group_name: str, branch: str = "main") -> bool:
    """
    Check if a group exists.

    Parameters
    ----------
    group_name : str
        Name of the group to check.
    branch : str, default "main"
        Repository branch to examine.

    Returns
    -------
    bool
        True if the group exists, False otherwise.
    """
    group_dict = self.get_group_names(branch)

    # get_group_names returns dict like {'main': ['canopy_01', ...]}
    if branch in group_dict:
        exists = group_name in group_dict[branch]
    else:
        exists = False

    self._logger.debug(
        f"Group '{group_name}' exists on branch '{branch}': {exists}"
    )
    return exists

read_group(group_name, branch='main', time_slice=None, date=None, chunks=None)

Read data from a group.

Parameters

group_name : str Name of the group to read. branch : str, default "main" Repository branch. time_slice : slice | None, optional Optional label-based time slice for filtering (passed to ds.sel). date : str | None, optional YYYYDOY string (e.g. "2025001") selecting a single calendar day. Converted to a time_slice; mutually exclusive with time_slice. chunks : dict[str, Any] | None, optional Chunking specification (uses config defaults if None).

Returns

xr.Dataset Dataset from the group.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_group(
    self,
    group_name: str,
    branch: str = "main",
    time_slice: slice | None = None,
    date: str | None = None,
    chunks: dict[str, Any] | None = None,
) -> xr.Dataset:
    """
    Read data from a group.

    Parameters
    ----------
    group_name : str
        Name of the group to read.
    branch : str, default "main"
        Repository branch.
    time_slice : slice | None, optional
        Optional label-based time slice for filtering (passed to ``ds.sel``).
    date : str | None, optional
        YYYYDOY string (e.g. ``"2025001"``) selecting a single calendar day.
        Converted to a ``time_slice``; mutually exclusive with ``time_slice``.
    chunks : dict[str, Any] | None, optional
        Chunking specification (uses config defaults if None).

    Returns
    -------
    xr.Dataset
        Dataset from the group.
    """
    self._logger.info(f"Reading group '{group_name}' from branch '{branch}'")

    if date is not None:
        from canvod.utils.tools.date_utils import YYYYDOY

        _d = YYYYDOY.from_str(date).date
        time_slice = slice(str(_d), str(_d + timedelta(days=1)))

    with self.readonly_session(branch) as session:
        # Use default chunking strategy if none provided
        if chunks is None:
            chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

        ds = xr.open_zarr(
            session.store,
            group=group_name,
            chunks=chunks,
            consolidated=False,
        )

        if time_slice is not None:
            ds = ds.sel(epoch=time_slice)
            self._logger.debug(f"Applied time slice: {time_slice}")

        self._logger.info(
            f"Successfully read group '{group_name}' - shape: {dict(ds.sizes)}"
        )
        return ds

read_group_deduplicated(group_name, branch='main', keep='last', time_slice=None, chunks=None)

Read data from a group with automatic deduplication.

This method calls read_group() then removes duplicates using metadata table intelligence when available, falling back to simple epoch deduplication.

Parameters

group_name : str Name of the group to read. branch : str, default "main" Repository branch. keep : str, default "last" Deduplication strategy for duplicate epochs. time_slice : slice | None, optional Optional time slice for filtering. chunks : dict[str, Any] | None, optional Chunking specification (uses config defaults if None).

Returns

xr.Dataset Dataset with duplicates removed (latest data only).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_group_deduplicated(
    self,
    group_name: str,
    branch: str = "main",
    keep: str = "last",
    time_slice: slice | None = None,
    chunks: dict[str, Any] | None = None,
) -> xr.Dataset:
    """
    Read data from a group with automatic deduplication.

    This method calls read_group() then removes duplicates using metadata table
    intelligence when available, falling back to simple epoch deduplication.

    Parameters
    ----------
    group_name : str
        Name of the group to read.
    branch : str, default "main"
        Repository branch.
    keep : str, default "last"
        Deduplication strategy for duplicate epochs.
    time_slice : slice | None, optional
        Optional time slice for filtering.
    chunks : dict[str, Any] | None, optional
        Chunking specification (uses config defaults if None).

    Returns
    -------
    xr.Dataset
        Dataset with duplicates removed (latest data only).
    """

    if keep not in ["last"]:
        raise ValueError("Currently only 'last' is supported for keep parameter.")

    self._logger.info(f"Reading group '{group_name}' with deduplication")

    # First, read the raw data
    ds = self.read_group(
        group_name, branch=branch, time_slice=time_slice, chunks=chunks
    )

    # Then deduplicate using metadata table intelligence
    with self.readonly_session(branch) as session:
        try:
            zmeta = zarr.open_group(session.store, mode="r")[
                f"{group_name}/metadata/table"
            ]

            # Load metadata and get latest entries for each time range
            data = {col: zmeta[col][:] for col in zmeta.array_keys()}
            df = pl.DataFrame(data)

            # Ensure datetime dtypes
            df = df.with_columns(
                [
                    pl.col("start").cast(pl.Datetime("ns")),
                    pl.col("end").cast(pl.Datetime("ns")),
                ]
            )

            # Get latest entry for each unique (start, end) combination
            latest_entries = df.sort("written_at").unique(
                subset=["start", "end"], keep=keep
            )

            if latest_entries.height > 0:
                # Create time masks for latest data only
                time_masks = []
                for row in latest_entries.iter_rows(named=True):
                    start_time = np.datetime64(row["start"], "ns")
                    end_time = np.datetime64(row["end"], "ns")
                    mask = (ds.epoch >= start_time) & (ds.epoch <= end_time)
                    time_masks.append(mask)

                # Combine all masks with OR logic
                if time_masks:
                    combined_mask = time_masks[0]
                    for mask in time_masks[1:]:
                        combined_mask = combined_mask | mask
                    ds = ds.isel(epoch=combined_mask)

                    self._logger.info(
                        "Deduplicated using metadata table: kept "
                        f"{len(latest_entries)} time ranges"
                    )

        except Exception as e:
            # Fall back to simple deduplication
            self._logger.warning(
                f"Metadata-based deduplication failed, using simple approach: {e}"
            )
            ds = ds.drop_duplicates("epoch", keep="last")
            self._logger.info("Applied simple epoch deduplication (keep='last')")

    return ds

write_dataset(dataset, group_name, session, mode='a', chunks=None)

Write a dataset to Icechunk with proper chunking.

Parameters

dataset : xr.Dataset Dataset to write group_name : str Group path in store session : Any Active writable session or store handle. mode : str Write mode: 'w' (overwrite) or 'a' (append) chunks : dict[str, int] | None Chunking spec. If None, uses store's chunk_strategy. Example: {'epoch': 34560, 'sid': -1}

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_dataset(
    self,
    dataset: xr.Dataset,
    group_name: str,
    session: Any,
    mode: str = "a",
    chunks: dict[str, int] | None = None,
) -> None:
    """
    Write a dataset to Icechunk with proper chunking.

    Parameters
    ----------
    dataset : xr.Dataset
        Dataset to write
    group_name : str
        Group path in store
    session : Any
        Active writable session or store handle.
    mode : str
        Write mode: 'w' (overwrite) or 'a' (append)
    chunks : dict[str, int] | None
        Chunking spec. If None, uses store's chunk_strategy.
        Example: {'epoch': 34560, 'sid': -1}
    """
    # Use explicit chunks, or fall back to store's chunk strategy
    if chunks is None:
        chunks = self.chunk_strategy

    # Apply chunking if strategy defined
    if chunks:
        dataset = dataset.chunk(chunks)
        self._logger.info(f"Rechunked to {dict(dataset.chunks)} before write")

    # Normalize encodings
    dataset = self._normalize_encodings(dataset)

    # Calculate dataset metrics for tracing
    dataset_size_mb = dataset.nbytes / 1024 / 1024
    num_variables = len(dataset.data_vars)

    # Write to Icechunk with OpenTelemetry tracing
    try:
        from canvodpy.utils.telemetry import trace_icechunk_write

        with trace_icechunk_write(
            group_name=group_name,
            dataset_size_mb=dataset_size_mb,
            num_variables=num_variables,
        ):
            to_icechunk(dataset, session, group=group_name, mode=mode)
    except ImportError:
        # Fallback if telemetry not available
        to_icechunk(dataset, session, group=group_name, mode=mode)

    self._logger.info(f"Wrote dataset to group '{group_name}' (mode={mode})")

write_initial_group(dataset, group_name, branch='main', commit_message=None)

Write initial data to a new group.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_initial_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    branch: str = "main",
    commit_message: str | None = None,
) -> None:
    """Write initial data to a new group."""
    if self.group_exists(group_name, branch):
        raise ValueError(
            f"Group '{group_name}' already exists. Use append_to_group() instead."
        )

    with self.writable_session(branch) as session:
        dataset = self._normalize_encodings(dataset)

        rinex_hash = dataset.attrs.get("File Hash")
        if rinex_hash is None:
            raise ValueError("Dataset missing 'File Hash' attribute")
        start = dataset.epoch.min().values
        end = dataset.epoch.max().values

        to_icechunk(dataset, session, group=group_name, mode="w")

        if commit_message is None:
            version = get_version_from_pyproject()
            commit_message = f"[v{version}] Initial commit to group '{group_name}'"

        snapshot_id = session.commit(commit_message)

        self.append_metadata(
            group_name=group_name,
            rinex_hash=rinex_hash,
            start=start,
            end=end,
            snapshot_id=snapshot_id,
            action="write",  # Correct action for initial data
            commit_msg=commit_message,
            dataset_attrs=dataset.attrs,
        )

    self._logger.info(
        f"Created group '{group_name}' with {len(dataset.epoch)} epochs, "
        f"hash={rinex_hash}"
    )

backup_metadata_table(group_name, session)

Backup the metadata table to a Polars DataFrame.

Parameters

group_name : str Group name. session : Any Active session for reading.

Returns

pl.DataFrame | None DataFrame with metadata rows, or None if missing.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def backup_metadata_table(
    self,
    group_name: str,
    session: Any,
) -> pl.DataFrame | None:
    """Backup the metadata table to a Polars DataFrame.

    Parameters
    ----------
    group_name : str
        Group name.
    session : Any
        Active session for reading.

    Returns
    -------
    pl.DataFrame | None
        DataFrame with metadata rows, or None if missing.
    """
    try:
        zroot = zarr.open_group(session.store, mode="r")
        meta_group_path = f"{group_name}/metadata/table"

        if (
            "metadata" not in zroot[group_name]
            or "table" not in zroot[group_name]["metadata"]
        ):
            self._logger.info(
                "No metadata table found for group "
                f"'{group_name}' - nothing to backup"
            )
            return None

        zmeta = zroot[meta_group_path]

        # Load all columns into a dictionary
        data = {}
        for col_name in zmeta.array_keys():
            data[col_name] = zmeta[col_name][:]

        # Convert to Polars DataFrame
        df = pl.DataFrame(data)

        self._logger.info(
            "Backed up metadata table with "
            f"{df.height} rows for group '{group_name}'"
        )
        return df

    except Exception as e:
        self._logger.warning(
            f"Failed to backup metadata table for group '{group_name}': {e}"
        )
        return None

restore_metadata_table(group_name, df, session)

Restore the metadata table from a Polars DataFrame.

This recreates the full Zarr structure for the metadata table.

Parameters

group_name : str Group name. df : pl.DataFrame Metadata table to restore. session : Any Active session for writing.

Returns

None

Source code in packages/canvod-store/src/canvod/store/store.py
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
def restore_metadata_table(
    self,
    group_name: str,
    df: pl.DataFrame,
    session: Any,
) -> None:
    """Restore the metadata table from a Polars DataFrame.

    This recreates the full Zarr structure for the metadata table.

    Parameters
    ----------
    group_name : str
        Group name.
    df : pl.DataFrame
        Metadata table to restore.
    session : Any
        Active session for writing.

    Returns
    -------
    None
    """
    if df is None or df.height == 0:
        self._logger.info(f"No metadata to restore for group '{group_name}'")
        return

    try:
        zroot = zarr.open_group(session.store, mode="a")
        meta_group_path = f"{group_name}/metadata/table"

        # Create the metadata subgroup
        zmeta = zroot.require_group(meta_group_path)

        # Create all arrays from the DataFrame
        for col_name in df.columns:
            col_data = df[col_name]

            if col_name == "index":
                # Index column as int64
                arr = col_data.to_numpy().astype("i8")
                dtype = "i8"
            elif col_name in ("start", "end"):
                # Datetime columns
                arr = col_data.to_numpy().astype("datetime64[ns]")
                dtype = "M8[ns]"
            else:
                # String columns - use VariableLengthUTF8
                arr = col_data.to_list()  # Convert to list for VariableLengthUTF8
                dtype = VariableLengthUTF8()

            # Create the array
            zmeta.create_array(
                name=col_name,
                shape=(len(arr),),
                dtype=dtype,
                chunks=(1024,),
                overwrite=True,
            )

            # Write the data
            zmeta[col_name][:] = arr

        self._logger.info(
            "Restored metadata table with "
            f"{df.height} rows for group '{group_name}'"
        )

    except Exception as e:
        self._logger.error(
            f"Failed to restore metadata table for group '{group_name}': {e}"
        )
        raise RuntimeError(
            f"Critical error: could not restore metadata table: {e}"
        ) from e

overwrite_file_in_group(dataset, group_name, rinex_hash, start, end, branch='main', commit_message=None)

Overwrite a file's contribution to the group (same hash, new epoch range).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def overwrite_file_in_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    rinex_hash: str,
    start: np.datetime64,
    end: np.datetime64,
    branch: str = "main",
    commit_message: str | None = None,
) -> None:
    """Overwrite a file's contribution to the group (same hash, new epoch range)."""

    dataset = self._normalize_encodings(dataset)

    # --- Step 3: rewrite store ---
    with self.writable_session(branch) as session:
        ds_from_store = xr.open_zarr(
            session.store, group=group_name, consolidated=False
        ).compute(
            scheduler="synchronous"
        )  # synchronous avoids Dask serialization error

        # Backup the existing metadata table
        metadata_backup = self.backup_metadata_table(group_name, session)

        mask = (ds_from_store.epoch.values < start) | (
            ds_from_store.epoch.values > end
        )
        ds_from_store_cleansed = ds_from_store.isel(epoch=mask)
        ds_from_store_cleansed = self._normalize_encodings(ds_from_store_cleansed)

        # Check if any epochs remain after cleansing, then write leftovers.
        if ds_from_store_cleansed.sizes.get("epoch", 0) > 0:
            to_icechunk(ds_from_store_cleansed, session, group=group_name, mode="w")
        # no epochs left, reset group to empty
        else:
            to_icechunk(dataset.isel(epoch=[]), session, group=group_name, mode="w")

        # write back the backed up metadata table
        self.restore_metadata_table(group_name, metadata_backup, session)

        # Append the new dataset
        to_icechunk(dataset, session, group=group_name, append_dim="epoch")

        if commit_message is None:
            version = get_version_from_pyproject()
            commit_message = (
                f"[v{version}] Overwrote file {rinex_hash} in group '{group_name}'"
            )

        snapshot_id = session.commit(commit_message)

        self.append_metadata(
            group_name=group_name,
            rinex_hash=rinex_hash,
            start=start,
            end=end,
            snapshot_id=snapshot_id,
            action="overwrite",
            commit_msg=commit_message,
            dataset_attrs=dataset.attrs,
        )

get_group_info(group_name, branch='main')

Get metadata about a group.

Parameters

group_name : str Name of the group. branch : str, default "main" Repository branch to examine.

Returns

dict[str, Any] Group metadata.

Raises

ValueError If the group does not exist.

Source code in packages/canvod-store/src/canvod/store/store.py
 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
def get_group_info(self, group_name: str, branch: str = "main") -> dict[str, Any]:
    """
    Get metadata about a group.

    Parameters
    ----------
    group_name : str
        Name of the group.
    branch : str, default "main"
        Repository branch to examine.

    Returns
    -------
    dict[str, Any]
        Group metadata.

    Raises
    ------
    ValueError
        If the group does not exist.
    """
    if not self.group_exists(group_name, branch):
        raise ValueError(f"Group '{group_name}' does not exist")

    ds = self.read_group(group_name, branch)

    info = {
        "group_name": group_name,
        "store_type": self.store_type,
        "dimensions": dict(ds.sizes),
        "variables": list(ds.data_vars.keys()),
        "coordinates": list(ds.coords.keys()),
        "attributes": dict(ds.attrs),
    }

    # Add temporal information if epoch dimension exists
    if "epoch" in ds.sizes:
        info["temporal_info"] = {
            "start": str(ds.epoch.min().values),
            "end": str(ds.epoch.max().values),
            "count": ds.sizes["epoch"],
            "resolution": str(ds.epoch.diff("epoch").median().values),
        }

    return info

metadata_dataset_exists(group_name, name, branch='main')

Return True if a metadata dataset name exists for group_name.

Source code in packages/canvod-store/src/canvod/store/store.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
def metadata_dataset_exists(
    self, group_name: str, name: str, branch: str = "main"
) -> bool:
    """Return True if a metadata dataset *name* exists for *group_name*."""
    path = f"{group_name}/metadata/{name}"
    try:
        with self.readonly_session(branch) as session:
            zarr.open_group(session.store, mode="r", path=path)
            return True
    except Exception:
        return False

write_metadata_dataset(meta_ds, group_name, name, branch='main')

Write a pre-concatenated metadata dataset to {group_name}/metadata/{name}.

Always writes with mode="w" (full overwrite for the day).

Parameters

meta_ds : xr.Dataset Pre-concatenated (epoch, sid) metadata dataset. group_name : str Target group (receiver name). name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch to write to.

Returns

str Icechunk snapshot ID.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_metadata_dataset(
    self,
    meta_ds: xr.Dataset,
    group_name: str,
    name: str,
    branch: str = "main",
) -> str:
    """Write a pre-concatenated metadata dataset to *{group_name}/metadata/{name}*.

    Always writes with ``mode="w"`` (full overwrite for the day).

    Parameters
    ----------
    meta_ds : xr.Dataset
        Pre-concatenated ``(epoch, sid)`` metadata dataset.
    group_name : str
        Target group (receiver name).
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch to write to.

    Returns
    -------
    str
        Icechunk snapshot ID.
    """
    version = get_version_from_pyproject()
    path = f"{group_name}/metadata/{name}"
    ds = self._normalize_encodings(meta_ds)
    ds = self._cleanse_dataset_attrs(ds)
    with self.writable_session(branch) as session:
        to_icechunk(ds, session, group=path, mode="w")
        return session.commit(f"[v{version}] metadata/{name} for {group_name}")

append_metadata_datasets(parts, group_name, name, branch='main')

Write metadata datasets incrementally — no in-memory concat.

The first dataset initialises the group (mode="w"), subsequent datasets are appended along epoch. All writes happen inside a single session/commit so the operation is atomic.

Parameters

parts : list[xr.Dataset] Individual per-file metadata datasets with an epoch dim. group_name : str Target group (receiver name). name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch to write to.

Returns

str Icechunk snapshot ID.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata_datasets(
    self,
    parts: list[xr.Dataset],
    group_name: str,
    name: str,
    branch: str = "main",
) -> str:
    """Write metadata datasets incrementally — no in-memory concat.

    The first dataset initialises the group (``mode="w"``), subsequent
    datasets are appended along ``epoch``.  All writes happen inside a
    single session/commit so the operation is atomic.

    Parameters
    ----------
    parts : list[xr.Dataset]
        Individual per-file metadata datasets with an ``epoch`` dim.
    group_name : str
        Target group (receiver name).
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch to write to.

    Returns
    -------
    str
        Icechunk snapshot ID.
    """
    if not parts:
        msg = "parts list is empty"
        raise ValueError(msg)

    version = get_version_from_pyproject()
    path = f"{group_name}/metadata/{name}"
    total_epochs = 0

    with self.writable_session(branch) as session:
        for i, part in enumerate(parts):
            ds = self._normalize_encodings(part)
            ds = self._cleanse_dataset_attrs(ds)
            if i == 0:
                to_icechunk(ds, session, group=path, mode="w")
            else:
                to_icechunk(ds, session, group=path, append_dim="epoch")
            total_epochs += ds.sizes.get("epoch", 0)

        return session.commit(
            f"[v{version}] metadata/{name} for {group_name} ({total_epochs} epochs)"
        )

read_metadata_dataset(group_name, name, branch='main', chunks=None)

Read a metadata dataset name for group_name.

Parameters

group_name : str Group (receiver) name. name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch. chunks : dict | None, optional Dask chunk specification. Defaults to {"epoch": 34560, "sid": -1}.

Returns

xr.Dataset Lazy (epoch, sid) metadata dataset.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_metadata_dataset(
    self,
    group_name: str,
    name: str,
    branch: str = "main",
    chunks: dict | None = None,
) -> xr.Dataset:
    """Read a metadata dataset *name* for *group_name*.

    Parameters
    ----------
    group_name : str
        Group (receiver) name.
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch.
    chunks : dict | None, optional
        Dask chunk specification.  Defaults to
        ``{"epoch": 34560, "sid": -1}``.

    Returns
    -------
    xr.Dataset
        Lazy ``(epoch, sid)`` metadata dataset.
    """
    path = f"{group_name}/metadata/{name}"
    with self.readonly_session(branch) as session:
        return xr.open_zarr(
            session.store,
            group=path,
            chunks=chunks or self.chunk_strategy or {"epoch": 34560, "sid": -1},
            consolidated=False,
        )

get_metadata_dataset_info(group_name, name, branch='main')

Get info about metadata dataset name for group_name.

Parameters

group_name : str Group (receiver) name. name : str Dataset name under metadata/ (e.g. "sbf_obs"). branch : str, default "main" Repository branch.

Returns

dict[str, Any] Info dict with the same structure as get_group_info().

Raises

ValueError If the metadata dataset does not exist.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_metadata_dataset_info(
    self,
    group_name: str,
    name: str,
    branch: str = "main",
) -> dict[str, Any]:
    """Get info about metadata dataset *name* for *group_name*.

    Parameters
    ----------
    group_name : str
        Group (receiver) name.
    name : str
        Dataset name under ``metadata/`` (e.g. ``"sbf_obs"``).
    branch : str, default "main"
        Repository branch.

    Returns
    -------
    dict[str, Any]
        Info dict with the same structure as ``get_group_info()``.

    Raises
    ------
    ValueError
        If the metadata dataset does not exist.
    """
    if not self.metadata_dataset_exists(group_name, name, branch):
        raise ValueError(f"No metadata dataset '{name}' for group '{group_name}'")
    ds = self.read_metadata_dataset(group_name, name, branch, chunks={})
    info: dict[str, Any] = {
        "group_name": group_name,
        "store_path": f"{group_name}/metadata/{name}",
        "store_type": f"metadata/{name}",
        "dimensions": dict(ds.sizes),
        "variables": list(ds.data_vars.keys()),
        "coordinates": list(ds.coords.keys()),
        "attributes": dict(ds.attrs),
    }
    if "epoch" in ds.sizes:
        info["temporal_info"] = {
            "start": str(ds.epoch.min().values),
            "end": str(ds.epoch.max().values),
            "count": ds.sizes["epoch"],
            "resolution": str(ds.epoch.diff("epoch").median().values),
        }
    return info

sbf_metadata_exists(group_name, branch='main')

Return True if an SBF metadata dataset exists for group_name.

Source code in packages/canvod-store/src/canvod/store/store.py
1211
1212
1213
def sbf_metadata_exists(self, group_name: str, branch: str = "main") -> bool:
    """Return True if an SBF metadata dataset exists for *group_name*."""
    return self.metadata_dataset_exists(group_name, "sbf_obs", branch)

write_sbf_metadata(meta_ds, group_name, branch='main')

Write SBF metadata dataset.

Source code in packages/canvod-store/src/canvod/store/store.py
1215
1216
1217
1218
1219
def write_sbf_metadata(
    self, meta_ds: xr.Dataset, group_name: str, branch: str = "main"
) -> str:
    """Write SBF metadata dataset."""
    return self.write_metadata_dataset(meta_ds, group_name, "sbf_obs", branch)

read_sbf_metadata(group_name, branch='main', chunks=None)

Read SBF metadata dataset.

Source code in packages/canvod-store/src/canvod/store/store.py
1221
1222
1223
1224
1225
def read_sbf_metadata(
    self, group_name: str, branch: str = "main", chunks: dict | None = None
) -> xr.Dataset:
    """Read SBF metadata dataset."""
    return self.read_metadata_dataset(group_name, "sbf_obs", branch, chunks)

get_sbf_metadata_info(group_name, branch='main')

Get SBF metadata info.

Source code in packages/canvod-store/src/canvod/store/store.py
1227
1228
1229
1230
1231
def get_sbf_metadata_info(
    self, group_name: str, branch: str = "main"
) -> dict[str, Any]:
    """Get SBF metadata info."""
    return self.get_metadata_dataset_info(group_name, "sbf_obs", branch)

rel_path_for_commit(file_path)

Generate relative path for commit messages.

Parameters

file_path : Path Full file path.

Returns

str Relative path string with log_path_depth parts.

Source code in packages/canvod-store/src/canvod/store/store.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
def rel_path_for_commit(self, file_path: Path) -> str:
    """
    Generate relative path for commit messages.

    Parameters
    ----------
    file_path : Path
        Full file path.

    Returns
    -------
    str
        Relative path string with log_path_depth parts.
    """
    depth = load_config().processing.logging.log_path_depth
    return str(Path(*file_path.parts[-depth:]))

get_store_stats()

Get statistics about the store.

Returns

dict[str, Any] Store statistics.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_store_stats(self) -> dict[str, Any]:
    """
    Get statistics about the store.

    Returns
    -------
    dict[str, Any]
        Store statistics.
    """
    groups = self.get_group_names()
    stats = {
        "store_path": str(self.store_path),
        "store_type": self.store_type,
        "compression_level": self.compression_level,
        "compression_algorithm": self.compression_algorithm.name,
        "total_groups": len(groups),
        "groups": groups,
    }

    # Add group-specific stats
    for group_name in groups:
        try:
            info = self.get_group_info(group_name)
            stats[f"group_{group_name}"] = {
                "dimensions": info["dimensions"],
                "variables_count": len(info["variables"]),
                "has_temporal_data": "temporal_info" in info,
            }
        except Exception as e:
            self._logger.warning(
                f"Failed to get stats for group '{group_name}': {e}"
            )

    return stats

append_to_group(dataset, group_name, append_dim='epoch', branch='main', action='write', commit_message=None)

Append data to an existing group.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_to_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    append_dim: str = "epoch",
    branch: str = "main",
    action: str = "write",
    commit_message: str | None = None,
) -> None:
    """Append data to an existing group."""
    if not self.group_exists(group_name, branch):
        raise ValueError(
            f"Group '{group_name}' does not exist. Use write_initial_group() first."
        )

    dataset = self._normalize_encodings(dataset)

    rinex_hash = dataset.attrs.get("File Hash")
    if rinex_hash is None:
        raise ValueError("Dataset missing 'File Hash' attribute")
    start = dataset.epoch.min().values
    end = dataset.epoch.max().values

    # Guard: check hash + temporal overlap before appending
    exists, matches = self.metadata_row_exists(
        group_name, rinex_hash, start, end, branch
    )
    if exists and action != "overwrite":
        self._logger.warning(
            "append_blocked_by_guardrail",
            group=group_name,
            hash=rinex_hash[:16],
            range=f"{start}{end}",
            reason="hash_or_temporal_overlap",
            matching_files=matches.height if not matches.is_empty() else 0,
        )
        return

    with self.writable_session(branch) as session:
        to_icechunk(dataset, session, group=group_name, append_dim=append_dim)

        if commit_message is None and action == "write":
            version = get_version_from_pyproject()
            commit_message = f"[v{version}] Wrote to group '{group_name}'"
        elif commit_message is None and action != "append":
            version = get_version_from_pyproject()
            commit_message = f"[v{version}] Appended to group '{group_name}'"

        snapshot_id = session.commit(commit_message)

        self.append_metadata(
            group_name=group_name,
            rinex_hash=rinex_hash,
            start=start,
            end=end,
            snapshot_id=snapshot_id,
            action=action,
            commit_msg=commit_message,
            dataset_attrs=dataset.attrs,
        )

    if action == "append":
        self._logger.info(
            f"Appended {len(dataset.epoch)} epochs to group '{group_name}', "
            f"hash={rinex_hash}"
        )
    elif action == "write":
        self._logger.info(
            f"Wrote {len(dataset.epoch)} epochs to group '{group_name}', "
            f"hash={rinex_hash}"
        )
    else:
        self._logger.info(
            f"Action '{action}' completed for group '{group_name}', "
            f"hash={rinex_hash}"
        )

write_or_append_group(dataset, group_name, append_dim='epoch', branch='main', commit_message=None, dedup=False)

Write or append a dataset to a group.

By default (dedup=False) no guardrails are applied — suitable for VOD stores and other derived-data stores where rinex-style dedup does not apply.

When dedup=True the method runs a full hash-match + temporal-overlap check (via :meth:should_skip_file) before opening a write session. This makes the store the authoritative final gate for RINEX/SBF ingest paths, backstopping any pre-checks in the caller.

If the group does not exist, creates it (mode='w'). If it exists, appends along append_dim.

Parameters

dataset : xr.Dataset Dataset to write or append. group_name : str Target Icechunk group. append_dim : str, default "epoch" Dimension along which to append when the group already exists. branch : str, default "main" Icechunk branch to write to. commit_message : str or None Commit message. Auto-generated if None. dedup : bool, default False When True, check for duplicate hash or temporal overlap before writing. If the dataset would be a duplicate, the write is skipped, a warning is logged, and False is returned. Set to True for RINEX/SBF ingest; leave False for VOD and derived-data stores.

Returns

bool True if the dataset was written, False if skipped (only possible when dedup=True).

Source code in packages/canvod-store/src/canvod/store/store.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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
def write_or_append_group(
    self,
    dataset: xr.Dataset,
    group_name: str,
    append_dim: str = "epoch",
    branch: str = "main",
    commit_message: str | None = None,
    dedup: bool = False,
) -> bool:
    """Write or append a dataset to a group.

    By default (``dedup=False``) no guardrails are applied — suitable for
    VOD stores and other derived-data stores where rinex-style dedup does
    not apply.

    When ``dedup=True`` the method runs a full hash-match + temporal-overlap
    check (via :meth:`should_skip_file`) **before** opening a write session.
    This makes the store the authoritative final gate for RINEX/SBF ingest
    paths, backstopping any pre-checks in the caller.

    If the group does not exist, creates it (``mode='w'``).
    If it exists, appends along ``append_dim``.

    Parameters
    ----------
    dataset : xr.Dataset
        Dataset to write or append.
    group_name : str
        Target Icechunk group.
    append_dim : str, default "epoch"
        Dimension along which to append when the group already exists.
    branch : str, default "main"
        Icechunk branch to write to.
    commit_message : str or None
        Commit message.  Auto-generated if ``None``.
    dedup : bool, default False
        When ``True``, check for duplicate hash or temporal overlap before
        writing.  If the dataset would be a duplicate, the write is skipped,
        a warning is logged, and ``False`` is returned.  Set to ``True`` for
        RINEX/SBF ingest; leave ``False`` for VOD and derived-data stores.

    Returns
    -------
    bool
        ``True`` if the dataset was written, ``False`` if skipped
        (only possible when ``dedup=True``).
    """
    if dedup:
        file_hash = dataset.attrs.get("File Hash")
        time_start = dataset.epoch.min().values
        time_end = dataset.epoch.max().values
        skip, reason = self.should_skip_file(
            group_name=group_name,
            file_hash=file_hash,
            time_start=time_start,
            time_end=time_end,
            branch=branch,
        )
        if skip:
            self._logger.warning(
                "write_or_append_group skipped duplicate",
                group=group_name,
                reason=reason,
                file_hash=file_hash,
            )
            return False

    dataset = self._normalize_encodings(dataset)

    if self.group_exists(group_name, branch):
        with self.writable_session(branch) as session:
            to_icechunk(dataset, session, group=group_name, append_dim=append_dim)
            if commit_message is None:
                commit_message = f"Appended to group '{group_name}'"
            session.commit(commit_message)
        self._logger.info(
            f"Appended {len(dataset.epoch)} epochs to group '{group_name}'"
        )
    else:
        with self.writable_session(branch) as session:
            to_icechunk(dataset, session, group=group_name, mode="w")
            if commit_message is None:
                commit_message = f"Created group '{group_name}'"
            session.commit(commit_message)
        self._logger.info(
            f"Created group '{group_name}' with {len(dataset.epoch)} epochs"
        )
    return True

append_metadata(group_name, rinex_hash, start, end, snapshot_id, action, commit_msg, dataset_attrs, branch='main', canonical_name=None, physical_path=None)

Append a metadata row into the group_name/metadata/table.

Schema

index int64 (continuous row id) rinex_hash str (UTF-8, VariableLengthUTF8) start datetime64[ns] end datetime64[ns] snapshot_id str (UTF-8) action str (UTF-8, e.g. "insert"|"append"|"overwrite"|"skip") commit_msg str (UTF-8) written_at str (UTF-8, ISO8601 with timezone) write_strategy str (UTF-8, RINEX_STORE_STRATEGY or VOD_STORE_STRATEGY) attrs str (UTF-8, JSON dump of dataset attrs)

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata(
    self,
    group_name: str,
    rinex_hash: str,
    start: np.datetime64,
    end: np.datetime64,
    snapshot_id: str,
    action: str,
    commit_msg: str,
    dataset_attrs: dict,
    branch: str = "main",
    canonical_name: str | None = None,
    physical_path: str | None = None,
) -> None:
    """
    Append a metadata row into the group_name/metadata/table.

    Schema:
        index           int64 (continuous row id)
        rinex_hash      str   (UTF-8, VariableLengthUTF8)
        start           datetime64[ns]
        end             datetime64[ns]
        snapshot_id     str   (UTF-8)
        action          str   (UTF-8, e.g. "insert"|"append"|"overwrite"|"skip")
        commit_msg      str   (UTF-8)
        written_at      str   (UTF-8, ISO8601 with timezone)
        write_strategy  str   (UTF-8, RINEX_STORE_STRATEGY or VOD_STORE_STRATEGY)
        attrs           str   (UTF-8, JSON dump of dataset attrs)
    """
    written_at = datetime.now().astimezone().isoformat()

    row = {
        "rinex_hash": str(rinex_hash),
        "start": np.datetime64(start, "ns"),
        "end": np.datetime64(end, "ns"),
        "snapshot_id": str(snapshot_id),
        "action": str(action),
        "commit_msg": str(commit_msg),
        "written_at": written_at,
        "write_strategy": str(self._rinex_store_strategy)
        if self.store_type == "rinex_store"
        else str(self._vod_store_strategy),
        "attrs": json.dumps(dataset_attrs, default=str),
        "canonical_name": str(canonical_name) if canonical_name else "",
        "physical_path": str(physical_path) if physical_path else "",
    }
    df_row = pl.DataFrame([row])

    with self.writable_session(branch) as session:
        zroot = zarr.open_group(session.store, mode="a")
        meta_group_path = f"{group_name}/metadata/table"

        if (
            "metadata" not in zroot[group_name]
            or "table" not in zroot[group_name]["metadata"]
        ):
            # --- First time: create arrays with correct dtypes ---
            zmeta = zroot.require_group(meta_group_path)

            # index counter
            zmeta.create_array(
                name="index", shape=(0,), dtype="i8", chunks=(1024,), overwrite=True
            )
            zmeta["index"].append([0])

            for col in df_row.columns:
                if col in ("start", "end"):
                    dtype = "M8[ns]"
                    arr = np.array(df_row[col].to_numpy(), dtype=dtype)
                else:
                    dtype = VariableLengthUTF8()
                    arr = df_row[col].to_list()

                zmeta.create_array(
                    name=col,
                    shape=(0,),
                    dtype=dtype,
                    chunks=(1024,),
                    overwrite=True,
                )
                zmeta[col].append(arr)

        else:
            # --- Append to existing ---
            zmeta = zroot[meta_group_path]

            # index increment
            current_len = zmeta["index"].shape[0]
            next_idx = current_len
            zmeta["index"].append([next_idx])

            for col in df_row.columns:
                if col in ("start", "end"):
                    arr = np.array(df_row[col].to_numpy(), dtype="M8[ns]")
                else:
                    arr = df_row[col].to_list()
                zmeta[col].append(arr)

        session.commit(f"Appended metadata row for {group_name}, hash={rinex_hash}")

    self._logger.info(
        f"Metadata appended for group '{group_name}': "
        f"hash={rinex_hash}, snapshot={snapshot_id}, action={action}"
    )

append_metadata_bulk(group_name, rows, session=None)

Append multiple metadata rows in one commit.

Parameters

group_name : str Group name (e.g. "canopy", "reference") rows : list[dict[str, Any]] List of metadata records matching the schema used in append_metadata(). session : icechunk.WritableSession, optional If provided, rows are written into this session (caller commits later). If None, this method opens its own writable session and commits once.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata_bulk(
    self,
    group_name: str,
    rows: list[dict[str, Any]],
    session: icechunk.WritableSession | None = None,
) -> None:
    """
    Append multiple metadata rows in one commit.

    Parameters
    ----------
    group_name : str
        Group name (e.g. "canopy", "reference")
    rows : list[dict[str, Any]]
        List of metadata records matching the schema used in
        append_metadata().
    session : icechunk.WritableSession, optional
        If provided, rows are written into this session (caller commits later).
        If None, this method opens its own writable session and commits once.
    """
    if not rows:
        self._logger.info(f"No metadata rows to append for group '{group_name}'")
        return

    # Ensure datetime conversions for consistency
    for row in rows:
        if isinstance(row.get("start"), str):
            row["start"] = np.datetime64(row["start"])
        if isinstance(row.get("end"), str):
            row["end"] = np.datetime64(row["end"])
        if "written_at" not in row:
            row["written_at"] = datetime.now(UTC).isoformat()

    # Prepare the Polars DataFrame
    df = pl.DataFrame(rows)

    def _do_append(session_obj: icechunk.WritableSession) -> None:
        """Append metadata rows to a writable session.

        Parameters
        ----------
        session_obj : icechunk.WritableSession
            Writable session to update.

        Returns
        -------
        None
        """
        zroot = zarr.open_group(session_obj.store, mode="a")
        meta_group_path = f"{group_name}/metadata/table"
        zmeta = zroot.require_group(meta_group_path)

        start_index = 0
        if "index" in zmeta:
            existing_len = zmeta["index"].shape[0]
            start_index = (
                int(zmeta["index"][-1].item()) + 1 if existing_len > 0 else 0
            )

        # Assign sequential indices
        df_with_index = df.with_columns(
            (pl.arange(start_index, start_index + df.height)).alias("index")
        )

        # Write each column
        for col_name in df_with_index.columns:
            col_data = df_with_index[col_name]

            if col_name == "index":
                dtype = "i8"
                arr = col_data.to_numpy().astype(dtype)
            elif col_name in ("start", "end"):
                dtype = "M8[ns]"
                arr = col_data.to_numpy().astype(dtype)
            else:
                # strings / jsons / ids
                dtype = VariableLengthUTF8()
                arr = col_data.to_list()

            if col_name not in zmeta:
                # Create array if it doesn't exist
                zmeta.create_array(
                    name=col_name,
                    shape=(0,),
                    dtype=dtype,
                    chunks=(1024,),
                    overwrite=True,
                )

            # Resize and append
            old_len = zmeta[col_name].shape[0]
            new_len = old_len + len(arr)
            zmeta[col_name].resize(new_len)
            zmeta[col_name][old_len:new_len] = arr

        self._logger.info(
            f"Appended {df_with_index.height} metadata rows to group '{group_name}'"
        )

    if session is not None:
        _do_append(session)
    else:
        with self.writable_session() as sess:
            _do_append(sess)
            sess.commit(f"Bulk metadata append for {group_name}")

load_metadata(store, group_name)

Load metadata directly from Zarr into a Polars DataFrame.

Parameters

store : Any Zarr store or session store handle. group_name : str Group name.

Returns

pl.DataFrame Metadata table.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def load_metadata(self, store: Any, group_name: str) -> pl.DataFrame:
    """Load metadata directly from Zarr into a Polars DataFrame.

    Parameters
    ----------
    store : Any
        Zarr store or session store handle.
    group_name : str
        Group name.

    Returns
    -------
    pl.DataFrame
        Metadata table.
    """
    zroot = zarr.open_group(store, mode="r")
    zmeta = zroot[f"{group_name}/metadata/table"]

    # Read all columns into a dict of numpy arrays
    data = {col: zmeta[col][...] for col in zmeta.array_keys()}

    # Build Polars DataFrame
    df = pl.DataFrame(data)

    # Convert numeric datetime64 columns back to proper Polars datetimes
    if df["start"].dtype in (pl.Int64, pl.Float64):
        df = df.with_columns(pl.col("start").cast(pl.Datetime("ns")))
    if df["end"].dtype in (pl.Int64, pl.Float64):
        df = df.with_columns(pl.col("end").cast(pl.Datetime("ns")))
    if df["written_at"].dtype == pl.Utf8:
        df = df.with_columns(pl.col("written_at").str.to_datetime("%+"))
    return df

read_metadata_table(session, group_name)

Read the metadata table from a session.

Parameters

session : Any Active session for reading. group_name : str Group name.

Returns

pl.DataFrame Metadata table.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def read_metadata_table(self, session: Any, group_name: str) -> pl.DataFrame:
    """Read the metadata table from a session.

    Parameters
    ----------
    session : Any
        Active session for reading.
    group_name : str
        Group name.

    Returns
    -------
    pl.DataFrame
        Metadata table.
    """
    zmeta = zarr.open_group(
        session.store,
        mode="r",
    )[f"{group_name}/metadata/table"]

    data = {col: zmeta[col][:] for col in zmeta.array_keys()}
    df = pl.DataFrame(data)

    # Ensure start/end are proper datetime
    df = df.with_columns(
        [
            pl.col("start").cast(pl.Datetime("ns")),
            pl.col("end").cast(pl.Datetime("ns")),
        ]
    )
    return df

metadata_row_exists(group_name, rinex_hash, start, end, branch='main')

Check whether a file already exists or temporally overlaps existing data.

Performs two checks in order:

  1. Hash match — if rinex_hash already appears in the metadata table, the file was previously ingested (exact duplicate).
  2. Temporal overlap — if the incoming [start, end] interval overlaps any existing metadata interval, the file covers a time range that is already (partially) present in the store. This catches cases like a daily concatenation file coexisting with the sub-daily files it was built from.
Parameters

group_name : str Icechunk group name. rinex_hash : str Hash of the current GNSS dataset. start : np.datetime64 Start epoch of the incoming file. end : np.datetime64 End epoch of the incoming file. branch : str, default "main" Branch name in the Icechunk repository.

Returns

tuple[bool, pl.DataFrame] (True, overlapping_rows) when the file should be skipped, (False, empty_df) when it is safe to ingest.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def metadata_row_exists(
    self,
    group_name: str,
    rinex_hash: str,
    start: np.datetime64,
    end: np.datetime64,
    branch: str = "main",
) -> tuple[bool, pl.DataFrame]:
    """
    Check whether a file already exists or temporally overlaps existing data.

    Performs two checks in order:

    1. **Hash match** — if ``rinex_hash`` already appears in the metadata
       table, the file was previously ingested (exact duplicate).
    2. **Temporal overlap** — if the incoming ``[start, end]`` interval
       overlaps any existing metadata interval, the file covers a time
       range that is already (partially) present in the store.  This
       catches cases like a daily concatenation file coexisting with the
       sub-daily files it was built from.

    Parameters
    ----------
    group_name : str
        Icechunk group name.
    rinex_hash : str
        Hash of the current GNSS dataset.
    start : np.datetime64
        Start epoch of the incoming file.
    end : np.datetime64
        End epoch of the incoming file.
    branch : str, default "main"
        Branch name in the Icechunk repository.

    Returns
    -------
    tuple[bool, pl.DataFrame]
        ``(True, overlapping_rows)`` when the file should be skipped,
        ``(False, empty_df)`` when it is safe to ingest.
    """
    with self.readonly_session(branch) as session:
        try:
            zmeta = zarr.open_group(session.store, mode="r")[
                f"{group_name}/metadata/table"
            ]
        except Exception:
            return False, pl.DataFrame()

        data = {col: zmeta[col][:] for col in zmeta.array_keys()}
        df = pl.DataFrame(data)

        df = df.with_columns(
            [
                pl.col("start").cast(pl.Datetime("ns")),
                pl.col("end").cast(pl.Datetime("ns")),
            ]
        )

        # --- Check 1: exact hash match (file already ingested) ---
        hash_matches = df.filter(pl.col("rinex_hash") == rinex_hash)
        if not hash_matches.is_empty():
            return True, hash_matches

        # --- Check 2: temporal overlap ---
        # Two intervals [A.start, A.end] and [B.start, B.end] overlap
        # iff A.start <= B.end AND A.end >= B.start
        start_ns = np.datetime64(start, "ns")
        end_ns = np.datetime64(end, "ns")

        overlaps = df.filter(
            (pl.col("start") <= end_ns) & (pl.col("end") >= start_ns)
        )

        if not overlaps.is_empty():
            n = overlaps.height
            existing_range = f"{overlaps['start'].min()}{overlaps['end'].max()}"
            self._logger.warning(
                "temporal_overlap_detected",
                group=group_name,
                incoming_hash=rinex_hash,
                incoming_range=f"{start}{end}",
                existing_range=existing_range,
                overlapping_files=n,
            )
            return True, overlaps

        return False, pl.DataFrame()

should_skip_file(group_name, file_hash, time_start, time_end, branch='main')

Check whether a file should be skipped before processing and writing.

Thin public wrapper around :meth:metadata_row_exists that returns a simple (skip, reason) pair instead of a DataFrame, suitable for use in Airflow task functions as an early-exit optimisation.

This method is an early-exit optimisation: it avoids opening a write session for files that are already present. Pass dedup=True to :meth:write_or_append_group to make the store the authoritative final gate (runs the same check again before writing).

Checks performed (in order):

  1. Hash match — file was previously ingested (exact duplicate).
  2. Temporal overlap — incoming time range overlaps existing epochs.

Layer 3 (intra-batch overlap) is not applicable here because task functions process files one at a time.

Parameters

group_name : str Icechunk group name. file_hash : str or None Hash from dataset.attrs["File Hash"]. When None the check is skipped and (False, "") is returned. time_start : np.datetime64 First epoch of the incoming dataset. time_end : np.datetime64 Last epoch of the incoming dataset. branch : str, default "main" Branch name in the Icechunk repository.

Returns

tuple[bool, str] (True, "hash_match") — exact duplicate, skip. (True, "temporal_overlap") — overlapping time range, skip. (False, "") — safe to ingest.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def should_skip_file(
    self,
    group_name: str,
    file_hash: str | None,
    time_start: np.datetime64,
    time_end: np.datetime64,
    branch: str = "main",
) -> tuple[bool, str]:
    """Check whether a file should be skipped before processing and writing.

    Thin public wrapper around :meth:`metadata_row_exists` that returns a
    simple ``(skip, reason)`` pair instead of a DataFrame, suitable for use
    in Airflow task functions as an early-exit optimisation.

    This method is an early-exit optimisation: it avoids opening a write
    session for files that are already present.  Pass ``dedup=True`` to
    :meth:`write_or_append_group` to make the store the authoritative
    final gate (runs the same check again before writing).

    Checks performed (in order):

    1. **Hash match** — file was previously ingested (exact duplicate).
    2. **Temporal overlap** — incoming time range overlaps existing epochs.

    Layer 3 (intra-batch overlap) is not applicable here because task
    functions process files one at a time.

    Parameters
    ----------
    group_name : str
        Icechunk group name.
    file_hash : str or None
        Hash from ``dataset.attrs["File Hash"]``.  When ``None`` the check
        is skipped and ``(False, "")`` is returned.
    time_start : np.datetime64
        First epoch of the incoming dataset.
    time_end : np.datetime64
        Last epoch of the incoming dataset.
    branch : str, default "main"
        Branch name in the Icechunk repository.

    Returns
    -------
    tuple[bool, str]
        ``(True, "hash_match")`` — exact duplicate, skip.
        ``(True, "temporal_overlap")`` — overlapping time range, skip.
        ``(False, "")`` — safe to ingest.
    """
    if file_hash is None:
        return False, ""

    exists, matches = self.metadata_row_exists(
        group_name, file_hash, time_start, time_end, branch
    )
    if not exists:
        return False, ""

    if not matches.is_empty() and (matches["rinex_hash"] == file_hash).any():
        return True, "hash_match"
    return True, "temporal_overlap"

batch_check_existing(group_name, file_hashes)

Check which file hashes already exist in metadata.

Source code in packages/canvod-store/src/canvod/store/store.py
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def batch_check_existing(self, group_name: str, file_hashes: list[str]) -> set[str]:
    """Check which file hashes already exist in metadata."""

    try:
        with self.readonly_session("main") as session:
            df = self.load_metadata(session.store, group_name)

            # Filter to matching hashes
            existing = df.filter(pl.col("rinex_hash").is_in(file_hashes))
            return set(existing["rinex_hash"].to_list())

    except KeyError, zarr.errors.GroupNotFoundError, Exception:
        # Branch/group/metadata doesn't exist yet (fresh store)
        return set()

check_temporal_overlaps(group_name, file_intervals, branch='main')

Check which files temporally overlap existing metadata intervals.

Parameters

group_name : str Icechunk group name. file_intervals : list[tuple[str, np.datetime64, np.datetime64]] List of (rinex_hash, start, end) tuples for incoming files. branch : str, default "main" Branch name in the Icechunk repository.

Returns

set[str] Hashes of files whose [start, end] overlaps any existing metadata interval. Files whose hash already exists in the store are NOT included (use batch_check_existing for those).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def check_temporal_overlaps(
    self,
    group_name: str,
    file_intervals: list[tuple[str, np.datetime64, np.datetime64]],
    branch: str = "main",
) -> set[str]:
    """Check which files temporally overlap existing metadata intervals.

    Parameters
    ----------
    group_name : str
        Icechunk group name.
    file_intervals : list[tuple[str, np.datetime64, np.datetime64]]
        List of ``(rinex_hash, start, end)`` tuples for incoming files.
    branch : str, default "main"
        Branch name in the Icechunk repository.

    Returns
    -------
    set[str]
        Hashes of files whose ``[start, end]`` overlaps any existing
        metadata interval.  Files whose hash already exists in the store
        are NOT included (use ``batch_check_existing`` for those).
    """
    if not file_intervals:
        return set()

    try:
        with self.readonly_session(branch) as session:
            df = self.load_metadata(session.store, group_name)
    except KeyError, zarr.errors.GroupNotFoundError, Exception:
        return set()

    if df.is_empty():
        return set()

    df = df.with_columns(
        [
            pl.col("start").cast(pl.Datetime("ns")),
            pl.col("end").cast(pl.Datetime("ns")),
        ]
    )

    overlapping: set[str] = set()
    for rinex_hash, start, end in file_intervals:
        start_ns = np.datetime64(start, "ns")
        end_ns = np.datetime64(end, "ns")

        hits = df.filter((pl.col("start") <= end_ns) & (pl.col("end") >= start_ns))
        if not hits.is_empty():
            self._logger.warning(
                "temporal_overlap_detected",
                group=group_name,
                incoming_hash=rinex_hash[:16],
                incoming_range=f"{start}{end}",
                existing_files=hits.height,
            )
            overlapping.add(rinex_hash)

    return overlapping

append_metadata_bulk_store(group_name, rows, store)

Append metadata rows into an open transaction store.

Parameters

group_name : str Group name (e.g. "canopy", "reference"). rows : list[dict[str, Any]] Metadata rows to append. store : Any Open Icechunk transaction store.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def append_metadata_bulk_store(
    self,
    group_name: str,
    rows: list[dict[str, Any]],
    store: Any,
) -> None:
    """
    Append metadata rows into an open transaction store.

    Parameters
    ----------
    group_name : str
        Group name (e.g. "canopy", "reference").
    rows : list[dict[str, Any]]
        Metadata rows to append.
    store : Any
        Open Icechunk transaction store.
    """
    if not rows:
        return

    zroot = zarr.open_group(store, mode="a")
    zmeta = zroot.require_group(f"{group_name}/metadata/table")

    # Find next index
    start_index = 0
    if "index" in zmeta:
        start_index = (
            int(zmeta["index"][-1]) + 1 if zmeta["index"].shape[0] > 0 else 0
        )

    for i, row in enumerate(rows, start=start_index):
        row["index"] = i

    import polars as pl

    df = pl.DataFrame(rows)

    for col in df.columns:
        list_only_cols = {
            "attrs",
            "commit_msg",
            "action",
            "write_strategy",
            "rinex_hash",
            "snapshot_id",
        }
        if col in list_only_cols:
            values = df[col].to_list()
        else:
            values = df[col].to_numpy()

        if col == "index":
            dtype = "i8"
        elif col in ("start", "end"):
            dtype = "M8[ns]"
        else:
            dtype = VariableLengthUTF8()

        if col not in zmeta:
            zmeta.create_array(
                name=col, shape=(0,), dtype=dtype, chunks=(1024,), overwrite=True
            )

        arr = zmeta[col]
        old_len = arr.shape[0]
        new_len = old_len + len(values)
        arr.resize(new_len)
        arr[old_len:new_len] = values

    self._logger.info(f"Appended {df.height} metadata rows to group '{group_name}'")

expire_old_snapshots(days=None, branch='main', delete_expired_branches=True, delete_expired_tags=True)

Expire and garbage-collect snapshots older than the given retention period.

Parameters

days : int | None, optional Number of days to retain snapshots. Defaults to config value. branch : str, default "main" Branch to apply expiration on. delete_expired_branches : bool, default True Whether to delete branches pointing to expired snapshots. delete_expired_tags : bool, default True Whether to delete tags pointing to expired snapshots.

Returns

set[str] Expired snapshot IDs.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def expire_old_snapshots(
    self,
    days: int | None = None,
    branch: str = "main",
    delete_expired_branches: bool = True,
    delete_expired_tags: bool = True,
) -> set[str]:
    """
    Expire and garbage-collect snapshots older than the given retention period.

    Parameters
    ----------
    days : int | None, optional
        Number of days to retain snapshots. Defaults to config value.
    branch : str, default "main"
        Branch to apply expiration on.
    delete_expired_branches : bool, default True
        Whether to delete branches pointing to expired snapshots.
    delete_expired_tags : bool, default True
        Whether to delete tags pointing to expired snapshots.

    Returns
    -------
    set[str]
        Expired snapshot IDs.
    """
    if days is None:
        days = self._rinex_store_expire_days
    cutoff = datetime.now(UTC) - timedelta(days=days)

    # cutoff = datetime(2025, 10, 3, 16, 44, 1, tzinfo=timezone.utc)
    self._logger.info(
        f"Running expiration on store '{self.store_type}' "
        f"(branch '{branch}') with cutoff {cutoff.isoformat()}"
    )

    # Expire snapshots older than cutoff
    expired_ids = self.repo.expire_snapshots(
        older_than=cutoff,
        delete_expired_branches=delete_expired_branches,
        delete_expired_tags=delete_expired_tags,
    )

    if expired_ids:
        self._logger.info(
            f"Expired {len(expired_ids)} snapshots: {sorted(expired_ids)}"
        )
    else:
        self._logger.info("No snapshots to expire.")

    # Garbage-collect expired objects to reclaim storage
    summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
    self._logger.info(
        f"Garbage collection summary: "
        f"deleted_bytes={summary.bytes_deleted}, "
        f"deleted_chunks={summary.chunks_deleted}, "
        f"deleted_manifests={summary.manifests_deleted}, "
        f"deleted_snapshots={summary.snapshots_deleted}, "
        f"deleted_attributes={summary.attributes_deleted}, "
        f"deleted_transaction_logs={summary.transaction_logs_deleted}"
    )

    return expired_ids

get_history(branch='main', limit=None)

Return commit ancestry (history) for a branch.

Parameters

branch : str, default "main" Branch name. limit : int | None, optional Maximum number of commits to return.

Returns

list[dict] Commit info dictionaries (id, message, written_at, parent_ids).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_history(self, branch: str = "main", limit: int | None = None) -> list[dict]:
    """
    Return commit ancestry (history) for a branch.

    Parameters
    ----------
    branch : str, default "main"
        Branch name.
    limit : int | None, optional
        Maximum number of commits to return.

    Returns
    -------
    list[dict]
        Commit info dictionaries (id, message, written_at, parent_ids).
    """
    self._logger.info(f"Fetching ancestry for branch '{branch}'")

    history = []
    for i, ancestor in enumerate(self.repo.ancestry(branch=branch)):
        history.append(
            {
                "snapshot_id": ancestor.id,
                "commit_msg": ancestor.message,
                "written_at": ancestor.written_at,
                "parent_ids": ancestor.parent_id,
            }
        )
        if limit is not None and i + 1 >= limit:
            break

    return history

print_history(branch='main', limit=100)

Pretty-print the ancestry for quick inspection.

Source code in packages/canvod-store/src/canvod/store/store.py
2121
2122
2123
2124
2125
2126
2127
def print_history(self, branch: str = "main", limit: int | None = 100) -> None:
    """
    Pretty-print the ancestry for quick inspection.
    """
    for entry in self.get_history(branch=branch, limit=limit):
        ts = entry["written_at"].strftime("%Y-%m-%d %H:%M:%S")
        print(f"{ts} {entry['snapshot_id'][:8]} {entry['commit_msg']}")

__repr__()

Return the developer-facing representation.

Returns

str Representation string.

Source code in packages/canvod-store/src/canvod/store/store.py
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
def __repr__(self) -> str:
    """Return the developer-facing representation.

    Returns
    -------
    str
        Representation string.
    """
    display_names = {"rinex_store": "GNSS Store", "vod_store": "VOD Store"}
    display = display_names.get(self.store_type, self.store_type)
    return f"MyIcechunkStore(store_path={self.store_path}, store_type={display})"

__str__()

Return a human-readable summary.

Returns

str Summary string.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def __str__(self) -> str:
    """Return a human-readable summary.

    Returns
    -------
    str
        Summary string.
    """

    # Capture tree output
    old_stdout = sys.stdout
    sys.stdout = buffer = io.StringIO()

    try:
        self.print_tree()
        tree_output = buffer.getvalue()
    finally:
        sys.stdout = old_stdout

    branches = self.get_branch_names()
    group_dict = self.get_group_names()
    total_groups = sum(len(groups) for groups in group_dict.values())

    return (
        f"MyIcechunkStore: {self.store_path}\n"
        f"Branches: {len(branches)} | Total Groups: {total_groups}\n\n"
        f"{tree_output}"
    )

rechunk_group(group_name, chunks, source_branch='main', temp_branch=None, promote_to_main=True, delete_temp_branch=True)

Rechunk a group with optimal chunk sizes.

Parameters

group_name : str Name of the group to rechunk chunks : dict[str, int] Chunking specification, e.g. {'epoch': 34560, 'sid': -1} source_branch : str Branch to read original data from (default: "main") temp_branch : str | None Temporary branch name for rechunked data. If None, uses "{group_name}_rechunked". promote_to_main : bool If True, reset main branch to rechunked snapshot after writing delete_temp_branch : bool If True, delete temporary branch after promotion (only if promote_to_main=True).

Returns

str Snapshot ID of the rechunked data

Source code in packages/canvod-store/src/canvod/store/store.py
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
def rechunk_group(
    self,
    group_name: str,
    chunks: dict[str, int],
    source_branch: str = "main",
    temp_branch: str | None = None,
    promote_to_main: bool = True,
    delete_temp_branch: bool = True,
) -> str:
    """
    Rechunk a group with optimal chunk sizes.

    Parameters
    ----------
    group_name : str
        Name of the group to rechunk
    chunks : dict[str, int]
        Chunking specification, e.g. {'epoch': 34560, 'sid': -1}
    source_branch : str
        Branch to read original data from (default: "main")
    temp_branch : str | None
        Temporary branch name for rechunked data. If None, uses
        "{group_name}_rechunked".
    promote_to_main : bool
        If True, reset main branch to rechunked snapshot after writing
    delete_temp_branch : bool
        If True, delete temporary branch after promotion (only if
        promote_to_main=True).

    Returns
    -------
    str
        Snapshot ID of the rechunked data
    """
    if temp_branch is None:
        temp_branch = f"{group_name}_rechunked_temp"

    self._logger.info(
        f"Starting rechunk of group '{group_name}' with chunks={chunks}"
    )

    # Get CURRENT snapshot from source branch to preserve all other groups
    current_snapshot = next(self.repo.ancestry(branch=source_branch)).id

    # Create temp branch from current snapshot (preserves all existing groups)
    try:
        self.repo.create_branch(temp_branch, current_snapshot)
        self._logger.info(
            f"Created temporary branch '{temp_branch}' from current {source_branch}"
        )
    except Exception as e:
        self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

    # Read original data
    ds_original = self.read_group(group_name, branch=source_branch)
    self._logger.info(f"Original chunks: {ds_original.chunks}")

    # Rechunk
    ds_rechunked = ds_original.chunk(chunks)
    self._logger.info(f"New chunks: {ds_rechunked.chunks}")

    # Clear encoding to avoid conflicts
    for var in ds_rechunked.data_vars:
        ds_rechunked[var].encoding = {}

    # Write rechunked data (overwrites only this group)
    with self.writable_session(temp_branch) as session:
        to_icechunk(ds_rechunked, session, group=group_name, mode="w")
        snapshot_id = session.commit(f"Rechunked {group_name} with chunks={chunks}")

    self._logger.info(
        f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
    )

    # Promote to main if requested
    if promote_to_main:
        rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
        self.repo.reset_branch(source_branch, rechunked_snapshot)
        self._logger.info(
            f"Reset branch '{source_branch}' to rechunked snapshot "
            f"{rechunked_snapshot}"
        )

        # Delete temp branch if requested
        if delete_temp_branch:
            self.repo.delete_branch(temp_branch)
            self._logger.info(f"Deleted temporary branch '{temp_branch}'")

    return snapshot_id

rechunk_group_verbose(group_name, chunks=None, source_branch='main', temp_branch=None, promote_to_main=True, delete_temp_branch=True)

Rechunk a group with optimal chunk sizes.

Parameters

group_name : str Name of the group to rechunk chunks : dict[str, int] | None Chunking specification, e.g. {'epoch': 34560, 'sid': -1}. Defaults to gnnsvodpy.globals.ICECHUNK_CHUNK_STRATEGIES. source_branch : str Branch to read original data from (default: "main") temp_branch : str | None Temporary branch name for rechunked data. If None, uses "{group_name}_rechunked". promote_to_main : bool If True, reset main branch to rechunked snapshot after writing delete_temp_branch : bool If True, delete temporary branch after promotion (only if promote_to_main=True).

Returns

str Snapshot ID of the rechunked data

Source code in packages/canvod-store/src/canvod/store/store.py
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
def rechunk_group_verbose(
    self,
    group_name: str,
    chunks: dict[str, int] | None = None,
    source_branch: str = "main",
    temp_branch: str | None = None,
    promote_to_main: bool = True,
    delete_temp_branch: bool = True,
) -> str:
    """
    Rechunk a group with optimal chunk sizes.

    Parameters
    ----------
    group_name : str
        Name of the group to rechunk
    chunks : dict[str, int] | None
        Chunking specification, e.g. {'epoch': 34560, 'sid': -1}. Defaults
        to `gnnsvodpy.globals.ICECHUNK_CHUNK_STRATEGIES`.
    source_branch : str
        Branch to read original data from (default: "main")
    temp_branch : str | None
        Temporary branch name for rechunked data. If None, uses
        "{group_name}_rechunked".
    promote_to_main : bool
        If True, reset main branch to rechunked snapshot after writing
    delete_temp_branch : bool
        If True, delete temporary branch after promotion (only if
        promote_to_main=True).

    Returns
    -------
    str
        Snapshot ID of the rechunked data
    """
    if temp_branch is None:
        temp_branch = f"{group_name}_rechunked_temp"

    if chunks is None:
        chunks = self.chunk_strategy or {"epoch": 34560, "sid": -1}

    print(f"\n{'=' * 60}")
    print(f"Starting rechunk of group '{group_name}'")
    print(f"Target chunks: {chunks}")
    print(f"{'=' * 60}\n")

    self._logger.info(
        f"Starting rechunk of group '{group_name}' with chunks={chunks}"
    )

    # Get CURRENT snapshot from source branch to preserve all other groups
    print(f"[1/7] Getting current snapshot from branch '{source_branch}'...")
    current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
    print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

    # Create temp branch from current snapshot (preserves all existing groups)
    print(f"\n[2/7] Creating temporary branch '{temp_branch}'...")
    try:
        self.repo.create_branch(temp_branch, current_snapshot)
        print(f"      ✓ Branch '{temp_branch}' created")
        self._logger.info(
            f"Created temporary branch '{temp_branch}' from current {source_branch}"
        )
    except Exception as e:
        print(
            f"      ⚠ Branch '{temp_branch}' already exists, using existing branch"
        )
        self._logger.warning(f"Branch '{temp_branch}' may already exist: {e}")

    # Read original data
    print(f"\n[3/7] Reading original data from '{group_name}'...")
    ds_original = self.read_group(group_name, branch=source_branch)

    # Unify chunks if inconsistent
    try:
        ds_original = ds_original.unify_chunks()
        print("      ✓ Unified inconsistent chunks")
    except TypeError, ValueError:
        pass  # Chunks are already consistent

    print(f"      ✓ Data shape: {dict(ds_original.sizes)}")
    print(f"      ✓ Original chunks: {ds_original.chunks}")
    self._logger.info(f"Original chunks: {ds_original.chunks}")

    # Rechunk
    print("\n[4/7] Rechunking data...")
    ds_rechunked = ds_original.chunk(chunks)
    ds_rechunked = ds_rechunked.unify_chunks()
    print(f"      ✓ New chunks: {ds_rechunked.chunks}")
    self._logger.info(f"New chunks: {ds_rechunked.chunks}")

    # Clear encoding to avoid conflicts
    for var in ds_rechunked.data_vars:
        ds_rechunked[var].encoding = {}
    for coord in ds_rechunked.coords:
        if "chunks" in ds_rechunked[coord].encoding:
            del ds_rechunked[coord].encoding["chunks"]

    # Write rechunked data first (overwrites entire group)
    print(f"\n[5/7] Writing rechunked data to branch '{temp_branch}'...")
    print("      This may take several minutes for large datasets...")
    with self.writable_session(temp_branch) as session:
        to_icechunk(ds_rechunked, session, group=group_name, mode="w")
        session.commit(f"Wrote rechunked data for {group_name}")
    print("      ✓ Data written successfully")

    # Copy subgroups after writing rechunked data
    print(f"\n[6/7] Copying subgroups from '{group_name}'...")
    with self.writable_session(temp_branch) as session:
        with self.readonly_session(source_branch) as icsession:
            source_group = zarr.open_group(icsession.store, mode="r")[group_name]
        target_group = zarr.open_group(session.store, mode="a")[group_name]

        subgroup_count = 0
        for subgroup_name in source_group.group_keys():
            print(f"      ✓ Copying subgroup '{subgroup_name}'...")
            source_subgroup = source_group[subgroup_name]
            target_subgroup = target_group.create_group(
                subgroup_name, overwrite=True
            )

            # Copy arrays from subgroup
            for array_name in source_subgroup.array_keys():
                source_array = source_subgroup[array_name]
                target_array = target_subgroup.create_array(
                    array_name,
                    shape=source_array.shape,
                    dtype=source_array.dtype,
                    chunks=source_array.chunks,
                    overwrite=True,
                )
                target_array[:] = source_array[:]

            # Copy subgroup attributes
            target_subgroup.attrs.update(source_subgroup.attrs)
            subgroup_count += 1

        if subgroup_count > 0:
            snapshot_id = session.commit(
                f"Rechunked {group_name} with chunks={chunks}"
            )
            print(f"      ✓ {subgroup_count} subgroups copied")
        else:
            snapshot_id = next(self.repo.ancestry(branch=temp_branch)).id
            print("      ✓ No subgroups to copy")

    print(f"      ✓ Snapshot ID: {snapshot_id[:12]}")
    self._logger.info(
        f"Rechunked data written to branch '{temp_branch}', snapshot={snapshot_id}"
    )

    # Promote to main if requested
    if promote_to_main:
        print(f"\n[7/7] Promoting to '{source_branch}' branch...")
        rechunked_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
        self.repo.reset_branch(source_branch, rechunked_snapshot)
        print(
            f"      ✓ Branch '{source_branch}' reset to {rechunked_snapshot[:12]}"
        )
        self._logger.info(
            f"Reset branch '{source_branch}' to rechunked snapshot "
            f"{rechunked_snapshot}"
        )

        # Delete temp branch if requested
        if delete_temp_branch:
            print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
            self.delete_branch(temp_branch)
            print("      ✓ Temporary branch deleted")
            self._logger.info(f"Deleted temporary branch '{temp_branch}'")
    else:
        print("\n[7/7] Skipping promotion (promote_to_main=False)")
        print(f"      Rechunked data available on branch '{temp_branch}'")

    print(f"\n{'=' * 60}")
    print(f"✓ Rechunking complete for '{group_name}'")
    print(f"{'=' * 60}\n")

    return snapshot_id

create_release_tag(tag_name, snapshot_id=None)

Create an immutable tag for an important version.

Parameters

tag_name : str Name for the tag (e.g., "v2024_complete", "before_reprocess") snapshot_id : str | None Snapshot to tag. If None, uses current tip of main branch.

Source code in packages/canvod-store/src/canvod/store/store.py
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
def create_release_tag(self, tag_name: str, snapshot_id: str | None = None) -> None:
    """
    Create an immutable tag for an important version.

    Parameters
    ----------
    tag_name : str
        Name for the tag (e.g., "v2024_complete", "before_reprocess")
    snapshot_id : str | None
        Snapshot to tag. If None, uses current tip of main branch.
    """
    if snapshot_id is None:
        # Tag current main branch tip
        snapshot_id = next(self.repo.ancestry(branch="main")).id

    self.repo.create_tag(tag_name, snapshot_id)
    self._logger.info(f"Created tag '{tag_name}' at snapshot {snapshot_id[:8]}")

list_tags()

List all tags in the repository.

Source code in packages/canvod-store/src/canvod/store/store.py
2458
2459
2460
def list_tags(self) -> list[str]:
    """List all tags in the repository."""
    return list(self.repo.list_tags())

delete_tag(tag_name)

Delete a tag (use with caution - tags are meant to be permanent).

Source code in packages/canvod-store/src/canvod/store/store.py
2462
2463
2464
2465
def delete_tag(self, tag_name: str) -> None:
    """Delete a tag (use with caution - tags are meant to be permanent)."""
    self.repo.delete_tag(tag_name)
    self._logger.warning(f"Deleted tag '{tag_name}'")

plot_commit_graph(max_commits=100)

Visualize commit history as an interactive git-like graph.

Creates an interactive visualization showing: - Branches with different colors - Chronological commit ordering - Branch divergence points - Commit messages on hover - Click to see commit details

Parameters

max_commits : int Maximum number of commits to display (default: 100).

Returns

Figure Interactive plotly figure (works in marimo and Jupyter).

Source code in packages/canvod-store/src/canvod/store/store.py
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
def plot_commit_graph(self, max_commits: int = 100) -> Figure:
    """
    Visualize commit history as an interactive git-like graph.

    Creates an interactive visualization showing:
    - Branches with different colors
    - Chronological commit ordering
    - Branch divergence points
    - Commit messages on hover
    - Click to see commit details

    Parameters
    ----------
    max_commits : int
        Maximum number of commits to display (default: 100).

    Returns
    -------
    Figure
        Interactive plotly figure (works in marimo and Jupyter).
    """
    from collections import defaultdict
    from datetime import datetime

    import plotly.graph_objects as go

    # Collect all commits with full metadata
    commit_map = {}  # id -> commit data
    branch_tips = {}  # branch -> latest commit id

    for branch in self.repo.list_branches():
        ancestors = list(self.repo.ancestry(branch=branch))
        if ancestors:
            branch_tips[branch] = ancestors[0].id

        for ancestor in ancestors:
            if ancestor.id not in commit_map:
                commit_map[ancestor.id] = {
                    "id": ancestor.id,
                    "parent_id": ancestor.parent_id,
                    "message": ancestor.message,
                    "written_at": ancestor.written_at,
                    "branches": [branch],
                }
            else:
                # Multiple branches point to same commit
                commit_map[ancestor.id]["branches"].append(branch)

            if len(commit_map) >= max_commits:
                break
        if len(commit_map) >= max_commits:
            break

    # Build parent-child relationships
    commits_list = list(commit_map.values())
    commits_list.sort(key=lambda c: c["written_at"])  # Oldest first

    # Assign horizontal positions (chronological)
    commit_x_positions = {}
    for idx, commit in enumerate(commits_list):
        commit["x"] = idx
        commit_x_positions[commit["id"]] = idx

    # Assign vertical positions: commits shared by branches stay on same Y
    # Only diverge when branches have different commits
    branch_names = sorted(
        self.repo.list_branches(), key=lambda b: (b != "main", b)
    )  # main first

    # Build a set of all commit IDs for each branch
    branch_commits = {}
    for branch in branch_names:
        history = list(self.repo.ancestry(branch=branch))
        branch_commits[branch] = {h.id for h in history if h.id in commit_map}

    # Find where branches diverge
    def branches_share_commit(
        commit_id: str,
        branches: list[str],
    ) -> list[str]:
        """Return branches that contain a commit.

        Parameters
        ----------
        commit_id : str
            Commit identifier to check.
        branches : list[str]
            Branch names to search.

        Returns
        -------
        list[str]
            Branches that contain the commit.
        """
        return [b for b in branches if commit_id in branch_commits[b]]

    # Assign Y position: all commits on a single horizontal line initially
    # We'll use vertical offset for parallel branch indicators
    for commit in commits_list:
        commit["y"] = 0  # All on same timeline
        commit["branch_set"] = frozenset(commit["branches"])

    # Color palette for branches
    colors = [
        "#4a9a4a",  # green (main)
        "#5580c8",  # blue
        "#d97643",  # orange
        "#9b59b6",  # purple
        "#e74c3c",  # red
        "#1abc9c",  # turquoise
        "#f39c12",  # yellow
        "#34495e",  # dark gray
    ]
    branch_colors = {b: colors[i % len(colors)] for i, b in enumerate(branch_names)}

    # Build edges: draw parallel lines for shared commits (metro-style)
    edges_by_branch = defaultdict(list)  # branch -> list of edge dicts

    for commit in commits_list:
        if commit["parent_id"] and commit["parent_id"] in commit_map:
            parent = commit_map[commit["parent_id"]]

            # Find which branches share both this commit and its parent
            shared_branches = [
                b for b in commit["branches"] if b in parent["branches"]
            ]

            for branch in shared_branches:
                edges_by_branch[branch].append(
                    {
                        "x0": parent["x"],
                        "y0": parent["y"],
                        "x1": commit["x"],
                        "y1": commit["y"],
                    }
                )

    # Create plotly figure
    fig = go.Figure()

    # Draw edges grouped by branch (parallel lines for shared paths)
    for branch_idx, branch in enumerate(branch_names):
        if branch not in edges_by_branch:
            continue

        color = branch_colors[branch]

        # Draw each edge as a separate line
        for edge in edges_by_branch[branch]:
            # Vertical offset for parallel lines (metro-style)
            offset = (branch_idx - (len(branch_names) - 1) / 2) * 0.15

            fig.add_trace(
                go.Scatter(
                    x=[edge["x0"], edge["x1"]],
                    y=[edge["y0"] + offset, edge["y1"] + offset],
                    mode="lines",
                    line=dict(color=color, width=3),
                    hoverinfo="skip",
                    showlegend=False,
                    opacity=0.7,
                )
            )

    # Draw commits (nodes) - one trace per unique commit
    # Color by which branches include it
    x_vals = [c["x"] for c in commits_list]
    y_vals = [c["y"] for c in commits_list]

    # Format hover text
    hover_texts = []
    marker_colors = []
    marker_symbols = []

    for c in commits_list:
        # Handle both string and datetime objects
        if isinstance(c["written_at"], str):
            time_str = datetime.fromisoformat(c["written_at"]).strftime(
                "%Y-%m-%d %H:%M"
            )
        else:
            time_str = c["written_at"].strftime("%Y-%m-%d %H:%M")

        branches_str = ", ".join(c["branches"])
        hover_texts.append(
            f"<b>{c['message'] or 'No message'}</b><br>"
            f"Commit: {c['id'][:12]}<br>"
            f"Branches: {branches_str}<br>"
            f"Time: {time_str}"
        )

        # Color by first branch (priority: main)
        if "main" in c["branches"]:
            marker_colors.append(branch_colors["main"])
        else:
            marker_colors.append(branch_colors[c["branches"][0]])

        # Star for branch tips
        if c["id"] in branch_tips.values():
            marker_symbols.append("star")
        else:
            marker_symbols.append("circle")

    fig.add_trace(
        go.Scatter(
            x=x_vals,
            y=y_vals,
            mode="markers",
            name="Commits",
            marker=dict(
                size=14,
                color=marker_colors,
                symbol=marker_symbols,
                line=dict(color="white", width=2),
            ),
            hovertext=hover_texts,
            hoverinfo="text",
            showlegend=False,
        )
    )

    # Add legend traces (invisible points just for legend)
    for branch_idx, branch in enumerate(branch_names):
        fig.add_trace(
            go.Scatter(
                x=[None],
                y=[None],
                mode="markers",
                name=branch,
                marker=dict(
                    size=10,
                    color=branch_colors[branch],
                    line=dict(color="white", width=2),
                ),
                showlegend=True,
            )
        )

    # Layout styling
    title_text = (
        f"Commit Graph: {self.site_name} ({len(commits_list)} commits, "
        f"{len(branch_names)} branches)"
    )
    fig.update_layout(
        title=dict(
            text=title_text,
            font=dict(size=16, color="#e5e5e5"),
        ),
        xaxis=dict(
            title="Time (oldest ← → newest)",
            showticklabels=False,
            showgrid=True,
            gridcolor="rgba(255,255,255,0.1)",
            zeroline=False,
        ),
        yaxis=dict(
            title="",
            showticklabels=False,
            showgrid=False,
            zeroline=False,
            range=[-1, 1],  # Fixed range for single timeline
        ),
        plot_bgcolor="#1a1a1a",
        paper_bgcolor="#1a1a1a",
        font=dict(color="#e5e5e5"),
        hovermode="closest",
        height=400,
        width=max(800, len(commits_list) * 50),
        legend=dict(
            title="Branches",
            orientation="h",
            x=0,
            y=-0.15,
            bgcolor="rgba(30,30,30,0.8)",
            bordercolor="rgba(255,255,255,0.2)",
            borderwidth=1,
        ),
    )

    return fig

cleanup_stale_branches(keep_patterns=None)

Delete stale temporary branches (e.g., from failed rechunking).

Parameters

keep_patterns : list[str] | None Patterns to preserve. Default: ["main", "dev"]

Returns

list[str] Names of deleted branches

Source code in packages/canvod-store/src/canvod/store/store.py
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
def cleanup_stale_branches(
    self, keep_patterns: list[str] | None = None
) -> list[str]:
    """
    Delete stale temporary branches (e.g., from failed rechunking).

    Parameters
    ----------
    keep_patterns : list[str] | None
        Patterns to preserve. Default: ["main", "dev"]

    Returns
    -------
    list[str]
        Names of deleted branches
    """
    if keep_patterns is None:
        keep_patterns = ["main", "dev"]

    deleted = []

    for branch in self.repo.list_branches():
        # Keep if matches any pattern
        should_keep = any(pattern in branch for pattern in keep_patterns)

        if not should_keep:
            # Check if it's a temp branch from rechunking
            if "_rechunked_temp" in branch or "_temp" in branch:
                try:
                    self.repo.delete_branch(branch)
                    deleted.append(branch)
                    self._logger.info(f"Deleted stale branch: {branch}")
                except Exception as e:
                    self._logger.warning(f"Failed to delete branch {branch}: {e}")

    return deleted

delete_branch(branch_name)

Delete a branch.

Source code in packages/canvod-store/src/canvod/store/store.py
2785
2786
2787
2788
2789
2790
2791
def delete_branch(self, branch_name: str) -> None:
    """Delete a branch."""
    if branch_name == "main":
        raise ValueError("Cannot delete 'main' branch")

    self.repo.delete_branch(branch_name)
    self._logger.info(f"Deleted branch '{branch_name}'")

get_snapshot_info(snapshot_id)

Get detailed information about a specific snapshot.

Parameters

snapshot_id : str Snapshot ID to inspect

Returns

dict Snapshot metadata and statistics

Source code in packages/canvod-store/src/canvod/store/store.py
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
def get_snapshot_info(self, snapshot_id: str) -> dict:
    """
    Get detailed information about a specific snapshot.

    Parameters
    ----------
    snapshot_id : str
        Snapshot ID to inspect

    Returns
    -------
    dict
        Snapshot metadata and statistics
    """
    # Find the snapshot in ancestry
    for ancestor in self.repo.ancestry(branch="main"):
        if ancestor.id == snapshot_id or ancestor.id.startswith(snapshot_id):
            info = {
                "snapshot_id": ancestor.id,
                "message": ancestor.message,
                "written_at": ancestor.written_at,
                "parent_id": ancestor.parent_id,
            }

            # Try to get groups at this snapshot
            try:
                session = self.repo.readonly_session(snapshot_id=ancestor.id)
                root = zarr.open(session.store, mode="r")
                info["groups"] = list(root.group_keys())
                info["arrays"] = list(root.array_keys())
            except Exception as e:
                self._logger.warning(f"Could not inspect snapshot contents: {e}")

            return info

    raise ValueError(f"Snapshot {snapshot_id} not found in history")

compare_snapshots(snapshot_id_1, snapshot_id_2)

Compare two snapshots to see what changed.

Parameters

snapshot_id_1 : str First snapshot (older) snapshot_id_2 : str Second snapshot (newer)

Returns

dict Comparison results showing added/removed/modified groups

Source code in packages/canvod-store/src/canvod/store/store.py
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
def compare_snapshots(self, snapshot_id_1: str, snapshot_id_2: str) -> dict:
    """
    Compare two snapshots to see what changed.

    Parameters
    ----------
    snapshot_id_1 : str
        First snapshot (older)
    snapshot_id_2 : str
        Second snapshot (newer)

    Returns
    -------
    dict
        Comparison results showing added/removed/modified groups
    """
    info_1 = self.get_snapshot_info(snapshot_id_1)
    info_2 = self.get_snapshot_info(snapshot_id_2)

    groups_1 = set(info_1.get("groups", []))
    groups_2 = set(info_2.get("groups", []))

    return {
        "snapshot_1": snapshot_id_1[:8],
        "snapshot_2": snapshot_id_2[:8],
        "added_groups": list(groups_2 - groups_1),
        "removed_groups": list(groups_1 - groups_2),
        "common_groups": list(groups_1 & groups_2),
        "time_diff": (info_2["written_at"] - info_1["written_at"]).total_seconds(),
    }

maintenance(expire_days=7, cleanup_branches=True, run_gc=True)

Run full maintenance on the store.

Parameters

expire_days : int Days of snapshot history to keep cleanup_branches : bool Remove stale temporary branches run_gc : bool Run garbage collection after expiration

Returns

dict Summary of maintenance actions

Source code in packages/canvod-store/src/canvod/store/store.py
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
def maintenance(
    self, expire_days: int = 7, cleanup_branches: bool = True, run_gc: bool = True
) -> dict:
    """
    Run full maintenance on the store.

    Parameters
    ----------
    expire_days : int
        Days of snapshot history to keep
    cleanup_branches : bool
        Remove stale temporary branches
    run_gc : bool
        Run garbage collection after expiration

    Returns
    -------
    dict
        Summary of maintenance actions
    """
    self._logger.info(f"Starting maintenance on {self.store_type}")

    results = {"expired_snapshots": 0, "deleted_branches": [], "gc_summary": None}

    # Expire old snapshots
    expired_ids = self.expire_old_snapshots(days=expire_days)
    results["expired_snapshots"] = len(expired_ids)

    # Cleanup stale branches
    if cleanup_branches:
        deleted_branches = self.cleanup_stale_branches()
        results["deleted_branches"] = deleted_branches

    # Garbage collection
    if run_gc:
        from datetime import datetime, timedelta

        cutoff = datetime.now(UTC) - timedelta(days=expire_days)
        gc_summary = self.repo.garbage_collect(delete_object_older_than=cutoff)
        results["gc_summary"] = {
            "bytes_deleted": gc_summary.bytes_deleted,
            "chunks_deleted": gc_summary.chunks_deleted,
            "manifests_deleted": gc_summary.manifests_deleted,
        }

    self._logger.info(f"Maintenance complete: {results}")
    return results

sanitize_store(source_branch='main', temp_branch='sanitize_temp', promote_to_main=True, delete_temp_branch=True)

Sanitize all groups by removing NaN-only SIDs and cleaning coordinates.

Creates a temporary branch, applies sanitization to all groups, then optionally promotes to main and cleans up.

Parameters

source_branch : str, default "main" Branch to read original data from. temp_branch : str, default "sanitize_temp" Temporary branch name for sanitized data. promote_to_main : bool, default True If True, reset main branch to sanitized snapshot after writing. delete_temp_branch : bool, default True If True, delete temporary branch after promotion.

Returns

str Snapshot ID of the sanitized data.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def sanitize_store(
    self,
    source_branch: str = "main",
    temp_branch: str = "sanitize_temp",
    promote_to_main: bool = True,
    delete_temp_branch: bool = True,
) -> str:
    """
    Sanitize all groups by removing NaN-only SIDs and cleaning coordinates.

    Creates a temporary branch, applies sanitization to all groups, then
    optionally promotes to main and cleans up.

    Parameters
    ----------
    source_branch : str, default "main"
        Branch to read original data from.
    temp_branch : str, default "sanitize_temp"
        Temporary branch name for sanitized data.
    promote_to_main : bool, default True
        If True, reset main branch to sanitized snapshot after writing.
    delete_temp_branch : bool, default True
        If True, delete temporary branch after promotion.

    Returns
    -------
    str
        Snapshot ID of the sanitized data.
    """
    import time

    from icechunk.xarray import to_icechunk

    print(f"\n{'=' * 60}")
    print("Starting store sanitization")
    print(f"{'=' * 60}\n")

    # Step 1: Get current snapshot
    print(f"[1/6] Getting current snapshot from '{source_branch}'...")
    current_snapshot = next(self.repo.ancestry(branch=source_branch)).id
    print(f"      ✓ Current snapshot: {current_snapshot[:12]}")

    # Step 2: Create temp branch
    print(f"\n[2/6] Creating temporary branch '{temp_branch}'...")
    try:
        self.repo.create_branch(temp_branch, current_snapshot)
        print(f"      ✓ Branch '{temp_branch}' created")
    except Exception:
        print("      ⚠ Branch exists, deleting and recreating...")
        self.delete_branch(temp_branch)
        self.repo.create_branch(temp_branch, current_snapshot)
        print(f"      ✓ Branch '{temp_branch}' created")

    # Step 3: Get all groups
    print("\n[3/6] Discovering groups...")
    groups = self.list_groups()
    print(f"      ✓ Found {len(groups)} groups: {groups}")

    # Step 4: Sanitize each group
    print("\n[4/6] Sanitizing groups...")
    sanitized_count = 0

    for group_name in groups:
        print(f"\n      Processing '{group_name}'...")
        t_start = time.time()

        try:
            # Read original data
            ds_original = self.read_group(group_name, branch=source_branch)
            original_sids = len(ds_original.sid)
            print(f"        • Original: {original_sids} SIDs")

            # Sanitize: remove SIDs with all-NaN data
            ds_sanitized = self._sanitize_dataset(ds_original)
            sanitized_sids = len(ds_sanitized.sid)
            removed_sids = original_sids - sanitized_sids

            print(
                f"        • Sanitized: {sanitized_sids} SIDs "
                f"(removed {removed_sids})"
            )

            # Write sanitized data
            with self.writable_session(temp_branch) as session:
                to_icechunk(ds_sanitized, session, group=group_name, mode="w")

                # Copy metadata subgroups if they exist
                try:
                    with self.readonly_session(source_branch) as read_session:
                        source_group = zarr.open_group(
                            read_session.store, mode="r"
                        )[group_name]
                        if "metadata" in source_group.group_keys():
                            # Copy entire metadata subgroup
                            dest_group = zarr.open_group(session.store)[group_name]
                            zarr.copy(
                                source_group["metadata"],
                                dest_group,
                                name="metadata",
                            )
                            print("        • Copied metadata subgroup")
                except Exception as e:
                    print(f"        ⚠ Could not copy metadata: {e}")

                session.commit(
                    f"Sanitized {group_name}: removed {removed_sids} empty SIDs"
                )

            t_elapsed = time.time() - t_start
            print(f"        ✓ Completed in {t_elapsed:.2f}s")
            sanitized_count += 1

        except Exception as e:
            print(f"        ✗ Failed: {e}")
            continue

    print(f"\n      ✓ Sanitized {sanitized_count}/{len(groups)} groups")

    # Step 5: Get final snapshot
    print("\n[5/6] Getting sanitized snapshot...")
    sanitized_snapshot = next(self.repo.ancestry(branch=temp_branch)).id
    print(f"      ✓ Snapshot: {sanitized_snapshot[:12]}")

    # Step 6: Promote to main
    if promote_to_main:
        print(f"\n[6/6] Promoting to '{source_branch}' branch...")
        self.repo.reset_branch(source_branch, sanitized_snapshot)
        print(
            f"      ✓ Branch '{source_branch}' reset to {sanitized_snapshot[:12]}"
        )

        if delete_temp_branch:
            print(f"      ✓ Deleting temporary branch '{temp_branch}'...")
            self.delete_branch(temp_branch)
            print("      ✓ Temporary branch deleted")
    else:
        print("\n[6/6] Skipping promotion (promote_to_main=False)")
        print(f"      Sanitized data available on branch '{temp_branch}'")

    print(f"\n{'=' * 60}")
    print("✓ Sanitization complete")
    print(f"{'=' * 60}\n")

    return sanitized_snapshot

safe_temporal_aggregate(group, freq='1D', vars_to_aggregate=('VOD',), geometry_vars=('phi', 'theta'), drop_empty=True, branch='main')

Aggregate temporally irregular VOD data per SID.

Each satellite (SID) is aggregated independently within each time bin. Mixing observations across satellites is physically meaningless because each observes a different part of the canopy from a different sky position.

.. note::

For production use, prefer canvod.ops.TemporalAggregate which uses Polars groupby and handles all coordinate types explicitly. This method is a convenience wrapper for quick interactive exploration.

Parameters

group : str Group name to aggregate. freq : str, default "1D" Resample frequency string. vars_to_aggregate : Sequence[str], optional Variables to aggregate using mean. geometry_vars : Sequence[str], optional Geometry variables to aggregate using mean (centroid of contributing sky positions). drop_empty : bool, default True Drop empty epochs after aggregation. branch : str, default "main" Branch name to read from.

Returns

xr.Dataset Aggregated dataset with independent per-SID aggregation.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def safe_temporal_aggregate(
    self,
    group: str,
    freq: str = "1D",
    vars_to_aggregate: Sequence[str] = ("VOD",),
    geometry_vars: Sequence[str] = ("phi", "theta"),
    drop_empty: bool = True,
    branch: str = "main",
) -> xr.Dataset:
    """Aggregate temporally irregular VOD data per SID.

    Each satellite (SID) is aggregated independently within each
    time bin.  Mixing observations across satellites is physically
    meaningless because each observes a different part of the canopy
    from a different sky position.

    .. note::

       For production use, prefer ``canvod.ops.TemporalAggregate``
       which uses Polars groupby and handles all coordinate types
       explicitly.  This method is a convenience wrapper for quick
       interactive exploration.

    Parameters
    ----------
    group : str
        Group name to aggregate.
    freq : str, default "1D"
        Resample frequency string.
    vars_to_aggregate : Sequence[str], optional
        Variables to aggregate using mean.
    geometry_vars : Sequence[str], optional
        Geometry variables to aggregate using mean (centroid of
        contributing sky positions).
    drop_empty : bool, default True
        Drop empty epochs after aggregation.
    branch : str, default "main"
        Branch name to read from.

    Returns
    -------
    xr.Dataset
        Aggregated dataset with independent per-SID aggregation.
    """
    log = get_logger(__name__)

    with self.readonly_session(branch=branch) as session:
        ds = xr.open_zarr(session.store, group=group, consolidated=False)

        log.info(
            "Aggregating group",
            group=group,
            branch=branch,
            freq=freq,
        )

        # Aggregate data and geometry vars with mean (per SID
        # independently — resample preserves the sid dimension).
        all_vars = list(vars_to_aggregate) + list(geometry_vars)
        merged_vars = []
        for var in all_vars:
            if var in ds:
                merged_vars.append(ds[var].resample(epoch=freq).mean())
            else:
                log.warning("Skipping missing variable", var=var)
        ds_agg = xr.merge(merged_vars)

        # Preserve sid-only coordinates (sv, band, code, etc.)
        for coord in ds.coords:
            if coord in ds_agg.coords or coord == "epoch":
                continue
            coord_dims = ds.coords[coord].dims
            # Only copy coords whose dims all survive in ds_agg
            if all(d in ds_agg.dims for d in coord_dims):
                ds_agg[coord] = ds[coord]

        # Drop all-NaN epochs if requested
        if drop_empty and "VOD" in ds_agg:
            valid_mask = ds_agg["VOD"].notnull().any(dim="sid").compute()
            ds_agg = ds_agg.isel(epoch=valid_mask)

        log.info("Aggregation done", sizes=dict(ds_agg.sizes))
        return ds_agg

safe_temporal_aggregate_to_branch(source_group, target_group, target_branch, freq='1D', overwrite=False, **kwargs)

Aggregate a group and save to a new Icechunk branch/group.

Parameters

source_group : str Source group name. target_group : str Target group name. target_branch : str Target branch name. freq : str, default "1D" Resample frequency string. overwrite : bool, default False Whether to overwrite an existing branch. **kwargs : Any Additional keyword args passed to safe_temporal_aggregate().

Returns

xr.Dataset Aggregated dataset written to the target branch.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def safe_temporal_aggregate_to_branch(
    self,
    source_group: str,
    target_group: str,
    target_branch: str,
    freq: str = "1D",
    overwrite: bool = False,
    **kwargs: Any,
) -> xr.Dataset:
    """Aggregate a group and save to a new Icechunk branch/group.

    Parameters
    ----------
    source_group : str
        Source group name.
    target_group : str
        Target group name.
    target_branch : str
        Target branch name.
    freq : str, default "1D"
        Resample frequency string.
    overwrite : bool, default False
        Whether to overwrite an existing branch.
    **kwargs : Any
        Additional keyword args passed to safe_temporal_aggregate().

    Returns
    -------
    xr.Dataset
        Aggregated dataset written to the target branch.
    """

    print(
        f"🚀 Creating new aggregated branch '{target_branch}' at '{target_group}'"
    )

    # Compute safe aggregation
    ds_agg = self.safe_temporal_aggregate(
        group=source_group,
        freq=freq,
        **kwargs,
    )

    # Write to new branch
    current_snapshot = next(self.repo.ancestry(branch="main")).id
    self.delete_branch(target_branch)
    self.repo.create_branch(target_branch, current_snapshot)
    with self.writable_session(target_branch) as session:
        to_icechunk(
            obj=ds_agg,
            session=session,
            group=target_group,
            mode="w",
        )
        session.commit(f"Saved aggregated data to {target_group} at freq={freq}")

    print(
        f"✅ Saved aggregated dataset to branch '{target_branch}' "
        f"(group '{target_group}')"
    )
    return ds_agg

create_rinex_store(store_path)

Create a RINEX Icechunk store with appropriate configuration.

Parameters

store_path : Path Path to the store directory.

Returns

MyIcechunkStore Configured store for RINEX data.

Source code in packages/canvod-store/src/canvod/store/store.py
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
def create_rinex_store(store_path: Path) -> MyIcechunkStore:
    """
    Create a RINEX Icechunk store with appropriate configuration.

    Parameters
    ----------
    store_path : Path
        Path to the store directory.

    Returns
    -------
    MyIcechunkStore
        Configured store for RINEX data.
    """
    return MyIcechunkStore(store_path=store_path, store_type="rinex_store")

create_vod_store(store_path)

Create a VOD Icechunk store with appropriate configuration.

Parameters

store_path : Path Path to the store directory.

Returns

MyIcechunkStore Configured store for VOD analysis data.

Source code in packages/canvod-store/src/canvod/store/store.py
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
def create_vod_store(store_path: Path) -> MyIcechunkStore:
    """
    Create a VOD Icechunk store with appropriate configuration.

    Parameters
    ----------
    store_path : Path
        Path to the store directory.

    Returns
    -------
    MyIcechunkStore
        Configured store for VOD analysis data.
    """
    return MyIcechunkStore(store_path=store_path, store_type="vod_store")

write_vod_to_store(vod_store, group_name, vod_ds, canopy_hash, sky_hash, commit_msg='VOD calculation')

Write VOD data to store with metadata tracking.

Source code in packages/canvod-store/src/canvod/store/store.py
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
def write_vod_to_store(
    vod_store: MyIcechunkStore,
    group_name: str,
    vod_ds: xr.Dataset,
    canopy_hash: str,
    sky_hash: str,
    commit_msg: str = "VOD calculation",
) -> str:
    """Write VOD data to store with metadata tracking."""

    with vod_store.writable_session() as session:
        vod_store.write_dataset(dataset=vod_ds, group_name=group_name, session=session)

        start = vod_ds["epoch"].values[0]
        end = vod_ds["epoch"].values[-1]

        vod_store.append_metadata(
            group_name=group_name,
            rinex_hash=f"{canopy_hash}_{sky_hash}",
            start=start,
            end=end,
            snapshot_id=session.snapshot_id,
            action="insert",
            commit_msg=commit_msg,
            dataset_attrs=dict(vod_ds.attrs),
        )

        snapshot_id = session.commit(commit_msg)

    return snapshot_id

Data Reader

Icechunk-backed readers for RINEX datasets.

IcechunkDataReader

Replacement for RinexFilesParser that reads from Icechunk stores.

This class provides a similar interface to the old parser but reads pre-processed data from Icechunk stores instead of processing RINEX files.

Parameters

matched_dirs : MatchedDirs Directory information for date/location matching site_name : str, optional Name of research site (defaults to DEFAULT_RESEARCH_SITE) n_max_workers : int, optional Maximum number of workers for parallel operations (defaults to N_MAX_THREADS) enable_gc : bool, optional Whether to enable garbage collection between operations (default True) gc_delay : float, optional Delay in seconds after garbage collection (default 1.0)

Source code in packages/canvod-store/src/canvod/store/reader.py
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
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
class IcechunkDataReader:
    """
    Replacement for RinexFilesParser that reads from Icechunk stores.

    This class provides a similar interface to the old parser but reads
    pre-processed data from Icechunk stores instead of processing RINEX files.

    Parameters
    ----------
    matched_dirs : MatchedDirs
        Directory information for date/location matching
    site_name : str, optional
        Name of research site (defaults to DEFAULT_RESEARCH_SITE)
    n_max_workers : int, optional
        Maximum number of workers for parallel operations (defaults to N_MAX_THREADS)
    enable_gc : bool, optional
        Whether to enable garbage collection between operations (default True)
    gc_delay : float, optional
        Delay in seconds after garbage collection (default 1.0)
    """

    def __init__(
        self,
        matched_dirs: MatchedDirs,
        site_name: str | None = None,
        n_max_workers: int | None = None,
        enable_gc: bool = True,
        gc_delay: float = 1.0,
    ) -> None:
        """Initialize the Icechunk data reader.

        Parameters
        ----------
        matched_dirs : MatchedDirs
            Directory information for date/location matching.
        site_name : str | None, optional
            Name of research site. If ``None``, uses the first site from config.
        n_max_workers : int | None, optional
            Maximum number of workers for parallel operations. Defaults to config.
        enable_gc : bool, optional
            Whether to enable garbage collection between operations.
        gc_delay : float, optional
            Delay in seconds after garbage collection.
        """
        config = load_config()
        if site_name is None:
            site_name = next(iter(config.sites.sites))
        if n_max_workers is None:
            resources = config.processing.processing.resolve_resources()
            n_max_workers = resources["n_workers"]

        self.matched_dirs = matched_dirs
        self.site_name = site_name
        self.n_max_workers = n_max_workers
        self.enable_gc = enable_gc
        self.gc_delay = gc_delay

        self._logger = get_logger(__name__).bind(
            site=site_name,
            date=matched_dirs.yyyydoy.to_str(),
        )
        self._site = GnssResearchSite(site_name)

        date_obj = self.matched_dirs.yyyydoy.date
        if date_obj is None:
            msg = (
                f"Matched date is missing for {self.matched_dirs.yyyydoy.to_str()} "
                f"at site {site_name}"
            )
            raise ValueError(msg)
        self._start_time = datetime.combine(date_obj, datetime.min.time())
        self._end_time = datetime.combine(date_obj, datetime.max.time())
        self._time_range = (self._start_time, self._end_time)

        # ✅ single persistent pool
        self._pool = ProcessPoolExecutor(
            max_workers=min(self.n_max_workers, 16),
        )

        self._logger.info(
            f"Initialized Icechunk data reader for {matched_dirs.yyyydoy.to_str()}"
        )

    def __del__(self) -> None:
        """Ensure the pool is shut down when the reader is deleted."""
        try:
            self._pool.shutdown(wait=True)
        except Exception:
            pass

    def _memory_cleanup(self) -> None:
        """Perform memory cleanup if enabled."""
        if self.enable_gc:
            gc.collect()
            if self.gc_delay > 0:
                time.sleep(self.gc_delay)

    def get_receiver_by_type(self, receiver_type: str) -> list[str]:
        """
        Get list of receiver names by type.

        Parameters
        ----------
        receiver_type : str
            Type of receiver ('canopy', 'reference')

        Returns
        -------
        list[str]
            List of receiver names of the specified type
        """
        return [
            name
            for name, config in self._site.active_receivers.items()
            if config["type"] == receiver_type
        ]

    def _get_receiver_name_for_type(self, receiver_type: str) -> str | None:
        """Get the first configured receiver name for a given type."""
        for name, config in self._site.active_receivers.items():
            if config["type"] == receiver_type:
                return name
        return None

    def _memory_cleanup(self) -> None:
        """Perform memory cleanup if enabled."""
        if self.enable_gc:
            gc.collect()
            if self.gc_delay > 0:
                time.sleep(self.gc_delay)

    def parsed_rinex_data_gen_v2(
        self,
        keep_vars: list[str] | None = None,
        receiver_types: list[str] | None = None,
    ) -> Generator[xr.Dataset]:
        """
        Generator that processes RINEX files, augments them (φ, θ, r),
        and appends to Icechunk stores on-the-fly.

        Yields enriched daily datasets (already augmented).
        """

        if receiver_types is None:
            receiver_types = ["canopy", "reference"]

        self._logger.info(
            f"Starting RINEX processing and ingestion for types: {receiver_types}"
        )

        # --- 1) Cache auxiliaries once per day ---
        from canvodpy.orchestrator import RinexDataProcessor

        processor_cls = cast(Any, RinexDataProcessor)
        processor: Any = processor_cls(
            matched_data_dirs=self.matched_dirs, icechunk_reader=self
        )

        ephem_ds = prep_aux_ds(processor.get_ephemeride_ds())
        clk_ds = prep_aux_ds(processor.get_clk_ds())

        aux_ds_dict = {"ephem": ephem_ds, "clk": clk_ds}
        approx_pos = None  # computed on first canopy dataset

        for receiver_type in receiver_types:
            # --- resolve dirs and names ---
            if receiver_type == "canopy":
                rinex_dir = self.matched_dirs.canopy_data_dir
                receiver_name = self._get_receiver_name_for_type("canopy")
                store_group = "canopy"
            elif receiver_type == "reference":
                rinex_dir = self.matched_dirs.reference_data_dir
                receiver_name = self._get_receiver_name_for_type("reference")
                store_group = "reference"
            else:
                self._logger.warning(f"Unknown receiver type: {receiver_type}")
                continue

            if not receiver_name:
                self._logger.warning(f"No configured receiver for type {receiver_type}")
                continue

            rinex_files = self._get_rinex_files(rinex_dir)
            if not rinex_files:
                self._logger.warning(f"No RINEX files found in {rinex_dir}")
                continue

            self._logger.info(
                f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
            )

            # --- parallel preprocessing ---
            futures = {
                self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
            }
            results: list[tuple[Path, xr.Dataset]] = []

            for fut in tqdm(
                as_completed(futures),
                total=len(futures),
                desc=f"Processing {receiver_type}",
            ):
                try:
                    fname, ds = fut.result()
                    results.append((fname, ds))
                except Exception as e:
                    self._logger.error(f"Failed preprocessing: {e}")

            results.sort(key=lambda x: x[0].name)  # chronological order

            # --- per-file commit ---
            for idx, (fname, ds) in enumerate(results):
                log = self._logger.bind(file=str(fname))
                try:
                    rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                    version = get_version_from_pyproject()

                    rinex_hash = ds.attrs.get("File Hash")
                    if not rinex_hash:
                        log.warning("Dataset missing hash → skipping")
                        continue

                    start_epoch = np.datetime64(ds.epoch.min().values)
                    end_epoch = np.datetime64(ds.epoch.max().values)

                    exists, matches = self._site.rinex_store.metadata_row_exists(
                        store_group, rinex_hash, start_epoch, end_epoch
                    )

                    ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                    # --- 2) Compute approx_pos once from first canopy file ---
                    if receiver_type == "canopy" and approx_pos is None:
                        approx_pos = processor.get_approx_position(ds)

                    # --- 3) Augment with φ, θ, r ---
                    matched = processor.match_datasets(ds, **aux_ds_dict)
                    ephem_matched = matched["ephem"]
                    if approx_pos is None:
                        msg = (
                            "Approximate receiver position is required before "
                            "azimuth/elevation augmentation."
                        )
                        raise RuntimeError(msg)
                    ds = processor.add_azi_ele(
                        rnx_obs_ds=ds,
                        ephem_ds=ephem_matched,
                        rx_x=approx_pos.x,
                        rx_y=approx_pos.y,
                        rx_z=approx_pos.z,
                    )

                    # --- 3b) Preprocessing pipeline ---
                    from canvod.ops import build_default_pipeline

                    preprocessing_config = load_config().processing.preprocessing
                    pipeline = build_default_pipeline(preprocessing_config)
                    ds, pipeline_result = pipeline(ds)
                    ds.attrs.update(pipeline_result.to_metadata_dict())

                    # --- 4) Store to Icechunk ---
                    existing_groups = self._site.rinex_store.list_groups()
                    if not exists and store_group not in existing_groups and idx == 0:
                        msg = (
                            f"[v{version}] Initial commit {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch})"
                        )
                        self._site.rinex_store.write_initial_group(
                            dataset=ds, group_name=store_group, commit_message=msg
                        )
                        log.info(msg)
                        continue

                    match (exists, self._site.rinex_store._rinex_store_strategy):
                        case (True, "skip"):
                            log.info(f"[v{version}] Skipped {rel_path}")
                            # just metadata row
                            self._site.rinex_store.append_metadata(
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                snapshot_id="none",
                                action="skip",
                                commit_msg="skip",
                                dataset_attrs=ds.attrs,
                            )

                        case (True, "overwrite"):
                            msg = f"[v{version}] Overwrote {rel_path}"
                            self._site.rinex_store.overwrite_file_in_group(
                                dataset=ds,
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                commit_message=msg,
                            )

                        case (True, "append"):
                            msg = f"[v{version}] Appended {rel_path}"
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="append",
                                commit_message=msg,
                            )

                        case (False, _):
                            msg = f"[v{version}] Wrote {rel_path}"
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="write",
                                commit_message=msg,
                            )
                except Exception as e:
                    log.exception("file_commit_failed", error=str(e))
                    raise

                self._memory_cleanup()

            # --- 5) Yield full daily dataset (already enriched) ---
            final_ds = self._site.read_receiver_data(store_group, self._time_range)
            self._logger.info(
                f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
            )
            yield final_ds
            self._memory_cleanup()

        self._logger.info("RINEX processing and ingestion completed")

    def parsed_rinex_data_gen(
        self,
        keep_vars: list[str] | None = None,
        receiver_types: list[str] | None = None,
    ) -> Generator[xr.Dataset]:
        """
        Generator that processes RINEX files and appends to Icechunk stores on-the-fly.

        Parameters
        ----------
        keep_vars : list[str], optional
            List of variables to keep in datasets
        receiver_types : list[str], optional
            List of receiver types to process ('canopy', 'reference').
            If None, defaults to ['canopy', 'reference']

        Yields
        ------
        xr.Dataset
            Processed and ingested datasets for each receiver type, in order
        """

        if receiver_types is None:
            receiver_types = ["canopy", "reference"]

        self._logger.info(
            f"Starting RINEX processing and ingestion for types: {receiver_types}"
        )

        for receiver_type in receiver_types:
            # --- resolve dirs and names ---
            if receiver_type == "canopy":
                rinex_dir = self.matched_dirs.canopy_data_dir
                receiver_name = self._get_receiver_name_for_type("canopy")
                store_group = "canopy"
            elif receiver_type == "reference":
                rinex_dir = self.matched_dirs.reference_data_dir
                receiver_name = self._get_receiver_name_for_type("reference")
                store_group = "reference"
            else:
                self._logger.warning(f"Unknown receiver type: {receiver_type}")
                continue

            if not receiver_name:
                self._logger.warning(f"No configured receiver for type {receiver_type}")
                continue

            rinex_files = self._get_rinex_files(rinex_dir)
            if not rinex_files:
                self._logger.warning(f"No RINEX files found in {rinex_dir}")
                continue

            self._logger.info(
                f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
            )

            groups = self._site.rinex_store.list_groups() or []

            # --- one pool per receiver type ---
            futures = {
                self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
            }
            results: list[tuple[Path, xr.Dataset]] = []

            # ✅ progressbar over all files, not per batch
            for fut in tqdm(
                as_completed(futures),
                total=len(futures),
                desc=f"Processing {receiver_type}",
            ):
                try:
                    fname, ds = fut.result()
                    results.append((fname, ds))
                except Exception as e:
                    self._logger.error(f"Failed preprocessing: {e}")

            # --- sort all results once (chronological order) ---
            results.sort(key=lambda x: x[0].name)

            # --- sequential append to Icechunk ---
            for idx, (fname, ds) in enumerate(results):
                log = self._logger.bind(file=str(fname))
                try:
                    rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                    version = get_version_from_pyproject()

                    rinex_hash = ds.attrs.get("File Hash")
                    if not rinex_hash:
                        log.warning(
                            f"No file hash found in dataset from {fname}. "
                            "Skipping duplicate detection for this file."
                        )
                        continue

                    start_epoch = np.datetime64(ds.epoch.min().values)
                    end_epoch = np.datetime64(ds.epoch.max().values)

                    exists, matches = self._site.rinex_store.metadata_row_exists(
                        store_group, rinex_hash, start_epoch, end_epoch
                    )

                    ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                    # --- Initial commit ---
                    if not exists and store_group not in groups and idx == 0:
                        msg = (
                            f"[v{version}] Initial commit with {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"to group '{store_group}'"
                        )
                        self._site.rinex_store.write_initial_group(
                            dataset=ds,
                            group_name=store_group,
                            commit_message=msg,
                        )
                        groups.append(store_group)
                        log.info(msg)
                        continue

                    # --- Handle strategies with match ---
                    match (exists, self._site.rinex_store._rinex_store_strategy):
                        case (True, "skip"):
                            msg = (
                                f"[v{version}] Skipped {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"in group '{store_group}'"
                            )
                            log.info(msg)
                            self._site.rinex_store.append_metadata(
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                snapshot_id="none",
                                action="skip",
                                commit_msg=msg,
                                dataset_attrs=ds.attrs,
                            )

                        case (True, "overwrite"):
                            msg = (
                                f"[v{version}] Overwrote {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"in group '{store_group}'"
                            )
                            log.info(msg)
                            self._site.rinex_store.overwrite_file_in_group(
                                dataset=ds,
                                group_name=store_group,
                                rinex_hash=rinex_hash,
                                start=start_epoch,
                                end=end_epoch,
                                commit_message=msg,
                            )

                        case (True, "append"):
                            msg = (
                                f"[v{version}] Appended {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"to group '{store_group}'"
                            )
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="append",
                                commit_message=msg,
                            )
                            log.info(msg)

                        case (False, _):
                            msg = (
                                f"[v{version}] Wrote {rel_path} "
                                f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                                f"to group '{store_group}'"
                            )
                            self._site.rinex_store.append_to_group(
                                dataset=ds,
                                group_name=store_group,
                                append_dim="epoch",
                                action="write",
                                commit_message=msg,
                            )
                            log.info(msg)

                except Exception as e:
                    log.exception("file_commit_failed", error=str(e))
                    raise

                self._memory_cleanup()

            # --- read back final dataset ---
            final_ds = self._site.read_receiver_data(store_group, self._time_range)
            self._logger.info(
                f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
            )
            yield final_ds

            self._memory_cleanup()

        self._logger.info("RINEX processing and ingestion completed")

    def _get_receiver_name_for_type(self, receiver_type: str) -> str | None:
        """Get the first configured receiver name for a given type."""
        for name, config in self._site.active_receivers.items():
            if config["type"] == receiver_type:
                return name
        return None

    def _get_rinex_files(self, rinex_dir: Path) -> list[Path]:
        """Get sorted list of RINEX files from directory."""

        if not rinex_dir.exists():
            self._logger.warning(f"Directory does not exist: {rinex_dir}")
            return []

        # Look for common RINEX file patterns
        patterns = ["*.??o", "*.??O", "*.rnx", "*.RNX"]
        rinex_files = []

        for pattern in patterns:
            files = list(rinex_dir.glob(pattern))
            rinex_files.extend(files)

        return natsorted(rinex_files)

    def _append_to_icechunk_store(
        self,
        dataset: xr.Dataset,
        receiver_name: str,
        receiver_type: str,
    ) -> None:
        """Append dataset to the appropriate Icechunk store."""
        from gnssvodpy.utils.tools import (
            get_version_from_pyproject,  # type: ignore[unresolved-import]
        )

        try:
            version = get_version_from_pyproject()
            date_str = self.matched_dirs.yyyydoy.to_str()

            commit_message = (
                f"[v{version}] Processed and ingested {receiver_type} data "
                f"for {date_str}"
            )

            # Use site's ingestion method
            self._site.ingest_receiver_data(dataset, receiver_name, commit_message)

            self._logger.info(
                f"Successfully appended {receiver_type} data to store as "
                f"'{receiver_name}'"
            )

        except Exception as e:
            self._logger.exception(
                f"Failed to append {receiver_type} data to store", error=str(e)
            )
            raise

    def get_available_receivers(self) -> dict[str, list[str]]:
        """
        Get available receivers grouped by type.

        Returns
        -------
        dict[str, list[str]]
            Dictionary mapping receiver types to lists of receiver names.
        """
        available = {}
        for receiver_type in ["canopy", "reference"]:
            receivers = self.get_receiver_by_type(receiver_type)
            # Filter to only receivers that have data
            with_data = [r for r in receivers if self._site.rinex_store.group_exists(r)]
            available[receiver_type] = with_data

        return available

    def __str__(self) -> str:
        """Return a human-readable summary.

        Returns
        -------
        str
            Summary string.
        """
        available = self.get_available_receivers()
        return (
            f"IcechunkDataReader for {self.matched_dirs.yyyydoy.to_str()}\n"
            f"  Site: {self.site_name}\n"
            f"  Available receivers: {dict(available)}\n"
            f"  Workers: {self.n_max_workers}, GC enabled: {self.enable_gc}"
        )

__init__(matched_dirs, site_name=None, n_max_workers=None, enable_gc=True, gc_delay=1.0)

Initialize the Icechunk data reader.

Parameters

matched_dirs : MatchedDirs Directory information for date/location matching. site_name : str | None, optional Name of research site. If None, uses the first site from config. n_max_workers : int | None, optional Maximum number of workers for parallel operations. Defaults to config. enable_gc : bool, optional Whether to enable garbage collection between operations. gc_delay : float, optional Delay in seconds after garbage collection.

Source code in packages/canvod-store/src/canvod/store/reader.py
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
def __init__(
    self,
    matched_dirs: MatchedDirs,
    site_name: str | None = None,
    n_max_workers: int | None = None,
    enable_gc: bool = True,
    gc_delay: float = 1.0,
) -> None:
    """Initialize the Icechunk data reader.

    Parameters
    ----------
    matched_dirs : MatchedDirs
        Directory information for date/location matching.
    site_name : str | None, optional
        Name of research site. If ``None``, uses the first site from config.
    n_max_workers : int | None, optional
        Maximum number of workers for parallel operations. Defaults to config.
    enable_gc : bool, optional
        Whether to enable garbage collection between operations.
    gc_delay : float, optional
        Delay in seconds after garbage collection.
    """
    config = load_config()
    if site_name is None:
        site_name = next(iter(config.sites.sites))
    if n_max_workers is None:
        resources = config.processing.processing.resolve_resources()
        n_max_workers = resources["n_workers"]

    self.matched_dirs = matched_dirs
    self.site_name = site_name
    self.n_max_workers = n_max_workers
    self.enable_gc = enable_gc
    self.gc_delay = gc_delay

    self._logger = get_logger(__name__).bind(
        site=site_name,
        date=matched_dirs.yyyydoy.to_str(),
    )
    self._site = GnssResearchSite(site_name)

    date_obj = self.matched_dirs.yyyydoy.date
    if date_obj is None:
        msg = (
            f"Matched date is missing for {self.matched_dirs.yyyydoy.to_str()} "
            f"at site {site_name}"
        )
        raise ValueError(msg)
    self._start_time = datetime.combine(date_obj, datetime.min.time())
    self._end_time = datetime.combine(date_obj, datetime.max.time())
    self._time_range = (self._start_time, self._end_time)

    # ✅ single persistent pool
    self._pool = ProcessPoolExecutor(
        max_workers=min(self.n_max_workers, 16),
    )

    self._logger.info(
        f"Initialized Icechunk data reader for {matched_dirs.yyyydoy.to_str()}"
    )

__del__()

Ensure the pool is shut down when the reader is deleted.

Source code in packages/canvod-store/src/canvod/store/reader.py
200
201
202
203
204
205
def __del__(self) -> None:
    """Ensure the pool is shut down when the reader is deleted."""
    try:
        self._pool.shutdown(wait=True)
    except Exception:
        pass

get_receiver_by_type(receiver_type)

Get list of receiver names by type.

Parameters

receiver_type : str Type of receiver ('canopy', 'reference')

Returns

list[str] List of receiver names of the specified type

Source code in packages/canvod-store/src/canvod/store/reader.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def get_receiver_by_type(self, receiver_type: str) -> list[str]:
    """
    Get list of receiver names by type.

    Parameters
    ----------
    receiver_type : str
        Type of receiver ('canopy', 'reference')

    Returns
    -------
    list[str]
        List of receiver names of the specified type
    """
    return [
        name
        for name, config in self._site.active_receivers.items()
        if config["type"] == receiver_type
    ]

parsed_rinex_data_gen_v2(keep_vars=None, receiver_types=None)

Generator that processes RINEX files, augments them (φ, θ, r), and appends to Icechunk stores on-the-fly.

Yields enriched daily datasets (already augmented).

Source code in packages/canvod-store/src/canvod/store/reader.py
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
def parsed_rinex_data_gen_v2(
    self,
    keep_vars: list[str] | None = None,
    receiver_types: list[str] | None = None,
) -> Generator[xr.Dataset]:
    """
    Generator that processes RINEX files, augments them (φ, θ, r),
    and appends to Icechunk stores on-the-fly.

    Yields enriched daily datasets (already augmented).
    """

    if receiver_types is None:
        receiver_types = ["canopy", "reference"]

    self._logger.info(
        f"Starting RINEX processing and ingestion for types: {receiver_types}"
    )

    # --- 1) Cache auxiliaries once per day ---
    from canvodpy.orchestrator import RinexDataProcessor

    processor_cls = cast(Any, RinexDataProcessor)
    processor: Any = processor_cls(
        matched_data_dirs=self.matched_dirs, icechunk_reader=self
    )

    ephem_ds = prep_aux_ds(processor.get_ephemeride_ds())
    clk_ds = prep_aux_ds(processor.get_clk_ds())

    aux_ds_dict = {"ephem": ephem_ds, "clk": clk_ds}
    approx_pos = None  # computed on first canopy dataset

    for receiver_type in receiver_types:
        # --- resolve dirs and names ---
        if receiver_type == "canopy":
            rinex_dir = self.matched_dirs.canopy_data_dir
            receiver_name = self._get_receiver_name_for_type("canopy")
            store_group = "canopy"
        elif receiver_type == "reference":
            rinex_dir = self.matched_dirs.reference_data_dir
            receiver_name = self._get_receiver_name_for_type("reference")
            store_group = "reference"
        else:
            self._logger.warning(f"Unknown receiver type: {receiver_type}")
            continue

        if not receiver_name:
            self._logger.warning(f"No configured receiver for type {receiver_type}")
            continue

        rinex_files = self._get_rinex_files(rinex_dir)
        if not rinex_files:
            self._logger.warning(f"No RINEX files found in {rinex_dir}")
            continue

        self._logger.info(
            f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
        )

        # --- parallel preprocessing ---
        futures = {
            self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
        }
        results: list[tuple[Path, xr.Dataset]] = []

        for fut in tqdm(
            as_completed(futures),
            total=len(futures),
            desc=f"Processing {receiver_type}",
        ):
            try:
                fname, ds = fut.result()
                results.append((fname, ds))
            except Exception as e:
                self._logger.error(f"Failed preprocessing: {e}")

        results.sort(key=lambda x: x[0].name)  # chronological order

        # --- per-file commit ---
        for idx, (fname, ds) in enumerate(results):
            log = self._logger.bind(file=str(fname))
            try:
                rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                version = get_version_from_pyproject()

                rinex_hash = ds.attrs.get("File Hash")
                if not rinex_hash:
                    log.warning("Dataset missing hash → skipping")
                    continue

                start_epoch = np.datetime64(ds.epoch.min().values)
                end_epoch = np.datetime64(ds.epoch.max().values)

                exists, matches = self._site.rinex_store.metadata_row_exists(
                    store_group, rinex_hash, start_epoch, end_epoch
                )

                ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                # --- 2) Compute approx_pos once from first canopy file ---
                if receiver_type == "canopy" and approx_pos is None:
                    approx_pos = processor.get_approx_position(ds)

                # --- 3) Augment with φ, θ, r ---
                matched = processor.match_datasets(ds, **aux_ds_dict)
                ephem_matched = matched["ephem"]
                if approx_pos is None:
                    msg = (
                        "Approximate receiver position is required before "
                        "azimuth/elevation augmentation."
                    )
                    raise RuntimeError(msg)
                ds = processor.add_azi_ele(
                    rnx_obs_ds=ds,
                    ephem_ds=ephem_matched,
                    rx_x=approx_pos.x,
                    rx_y=approx_pos.y,
                    rx_z=approx_pos.z,
                )

                # --- 3b) Preprocessing pipeline ---
                from canvod.ops import build_default_pipeline

                preprocessing_config = load_config().processing.preprocessing
                pipeline = build_default_pipeline(preprocessing_config)
                ds, pipeline_result = pipeline(ds)
                ds.attrs.update(pipeline_result.to_metadata_dict())

                # --- 4) Store to Icechunk ---
                existing_groups = self._site.rinex_store.list_groups()
                if not exists and store_group not in existing_groups and idx == 0:
                    msg = (
                        f"[v{version}] Initial commit {rel_path} "
                        f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch})"
                    )
                    self._site.rinex_store.write_initial_group(
                        dataset=ds, group_name=store_group, commit_message=msg
                    )
                    log.info(msg)
                    continue

                match (exists, self._site.rinex_store._rinex_store_strategy):
                    case (True, "skip"):
                        log.info(f"[v{version}] Skipped {rel_path}")
                        # just metadata row
                        self._site.rinex_store.append_metadata(
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            snapshot_id="none",
                            action="skip",
                            commit_msg="skip",
                            dataset_attrs=ds.attrs,
                        )

                    case (True, "overwrite"):
                        msg = f"[v{version}] Overwrote {rel_path}"
                        self._site.rinex_store.overwrite_file_in_group(
                            dataset=ds,
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            commit_message=msg,
                        )

                    case (True, "append"):
                        msg = f"[v{version}] Appended {rel_path}"
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="append",
                            commit_message=msg,
                        )

                    case (False, _):
                        msg = f"[v{version}] Wrote {rel_path}"
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="write",
                            commit_message=msg,
                        )
            except Exception as e:
                log.exception("file_commit_failed", error=str(e))
                raise

            self._memory_cleanup()

        # --- 5) Yield full daily dataset (already enriched) ---
        final_ds = self._site.read_receiver_data(store_group, self._time_range)
        self._logger.info(
            f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
        )
        yield final_ds
        self._memory_cleanup()

    self._logger.info("RINEX processing and ingestion completed")

parsed_rinex_data_gen(keep_vars=None, receiver_types=None)

Generator that processes RINEX files and appends to Icechunk stores on-the-fly.

Parameters

keep_vars : list[str], optional List of variables to keep in datasets receiver_types : list[str], optional List of receiver types to process ('canopy', 'reference'). If None, defaults to ['canopy', 'reference']

Yields

xr.Dataset Processed and ingested datasets for each receiver type, in order

Source code in packages/canvod-store/src/canvod/store/reader.py
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
def parsed_rinex_data_gen(
    self,
    keep_vars: list[str] | None = None,
    receiver_types: list[str] | None = None,
) -> Generator[xr.Dataset]:
    """
    Generator that processes RINEX files and appends to Icechunk stores on-the-fly.

    Parameters
    ----------
    keep_vars : list[str], optional
        List of variables to keep in datasets
    receiver_types : list[str], optional
        List of receiver types to process ('canopy', 'reference').
        If None, defaults to ['canopy', 'reference']

    Yields
    ------
    xr.Dataset
        Processed and ingested datasets for each receiver type, in order
    """

    if receiver_types is None:
        receiver_types = ["canopy", "reference"]

    self._logger.info(
        f"Starting RINEX processing and ingestion for types: {receiver_types}"
    )

    for receiver_type in receiver_types:
        # --- resolve dirs and names ---
        if receiver_type == "canopy":
            rinex_dir = self.matched_dirs.canopy_data_dir
            receiver_name = self._get_receiver_name_for_type("canopy")
            store_group = "canopy"
        elif receiver_type == "reference":
            rinex_dir = self.matched_dirs.reference_data_dir
            receiver_name = self._get_receiver_name_for_type("reference")
            store_group = "reference"
        else:
            self._logger.warning(f"Unknown receiver type: {receiver_type}")
            continue

        if not receiver_name:
            self._logger.warning(f"No configured receiver for type {receiver_type}")
            continue

        rinex_files = self._get_rinex_files(rinex_dir)
        if not rinex_files:
            self._logger.warning(f"No RINEX files found in {rinex_dir}")
            continue

        self._logger.info(
            f"Processing {len(rinex_files)} RINEX files for {receiver_type}"
        )

        groups = self._site.rinex_store.list_groups() or []

        # --- one pool per receiver type ---
        futures = {
            self._pool.submit(preprocess_rnx, f, keep_vars): f for f in rinex_files
        }
        results: list[tuple[Path, xr.Dataset]] = []

        # ✅ progressbar over all files, not per batch
        for fut in tqdm(
            as_completed(futures),
            total=len(futures),
            desc=f"Processing {receiver_type}",
        ):
            try:
                fname, ds = fut.result()
                results.append((fname, ds))
            except Exception as e:
                self._logger.error(f"Failed preprocessing: {e}")

        # --- sort all results once (chronological order) ---
        results.sort(key=lambda x: x[0].name)

        # --- sequential append to Icechunk ---
        for idx, (fname, ds) in enumerate(results):
            log = self._logger.bind(file=str(fname))
            try:
                rel_path = self._site.rinex_store.rel_path_for_commit(fname)
                version = get_version_from_pyproject()

                rinex_hash = ds.attrs.get("File Hash")
                if not rinex_hash:
                    log.warning(
                        f"No file hash found in dataset from {fname}. "
                        "Skipping duplicate detection for this file."
                    )
                    continue

                start_epoch = np.datetime64(ds.epoch.min().values)
                end_epoch = np.datetime64(ds.epoch.max().values)

                exists, matches = self._site.rinex_store.metadata_row_exists(
                    store_group, rinex_hash, start_epoch, end_epoch
                )

                ds = self._site.rinex_store._cleanse_dataset_attrs(ds)

                # --- Initial commit ---
                if not exists and store_group not in groups and idx == 0:
                    msg = (
                        f"[v{version}] Initial commit with {rel_path} "
                        f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                        f"to group '{store_group}'"
                    )
                    self._site.rinex_store.write_initial_group(
                        dataset=ds,
                        group_name=store_group,
                        commit_message=msg,
                    )
                    groups.append(store_group)
                    log.info(msg)
                    continue

                # --- Handle strategies with match ---
                match (exists, self._site.rinex_store._rinex_store_strategy):
                    case (True, "skip"):
                        msg = (
                            f"[v{version}] Skipped {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"in group '{store_group}'"
                        )
                        log.info(msg)
                        self._site.rinex_store.append_metadata(
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            snapshot_id="none",
                            action="skip",
                            commit_msg=msg,
                            dataset_attrs=ds.attrs,
                        )

                    case (True, "overwrite"):
                        msg = (
                            f"[v{version}] Overwrote {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"in group '{store_group}'"
                        )
                        log.info(msg)
                        self._site.rinex_store.overwrite_file_in_group(
                            dataset=ds,
                            group_name=store_group,
                            rinex_hash=rinex_hash,
                            start=start_epoch,
                            end=end_epoch,
                            commit_message=msg,
                        )

                    case (True, "append"):
                        msg = (
                            f"[v{version}] Appended {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"to group '{store_group}'"
                        )
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="append",
                            commit_message=msg,
                        )
                        log.info(msg)

                    case (False, _):
                        msg = (
                            f"[v{version}] Wrote {rel_path} "
                            f"(hash={rinex_hash}, epoch={start_epoch}{end_epoch}) "
                            f"to group '{store_group}'"
                        )
                        self._site.rinex_store.append_to_group(
                            dataset=ds,
                            group_name=store_group,
                            append_dim="epoch",
                            action="write",
                            commit_message=msg,
                        )
                        log.info(msg)

            except Exception as e:
                log.exception("file_commit_failed", error=str(e))
                raise

            self._memory_cleanup()

        # --- read back final dataset ---
        final_ds = self._site.read_receiver_data(store_group, self._time_range)
        self._logger.info(
            f"Yielding {receiver_type} dataset: {dict(final_ds.sizes)}"
        )
        yield final_ds

        self._memory_cleanup()

    self._logger.info("RINEX processing and ingestion completed")

get_available_receivers()

Get available receivers grouped by type.

Returns

dict[str, list[str]] Dictionary mapping receiver types to lists of receiver names.

Source code in packages/canvod-store/src/canvod/store/reader.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
def get_available_receivers(self) -> dict[str, list[str]]:
    """
    Get available receivers grouped by type.

    Returns
    -------
    dict[str, list[str]]
        Dictionary mapping receiver types to lists of receiver names.
    """
    available = {}
    for receiver_type in ["canopy", "reference"]:
        receivers = self.get_receiver_by_type(receiver_type)
        # Filter to only receivers that have data
        with_data = [r for r in receivers if self._site.rinex_store.group_exists(r)]
        available[receiver_type] = with_data

    return available

__str__()

Return a human-readable summary.

Returns

str Summary string.

Source code in packages/canvod-store/src/canvod/store/reader.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def __str__(self) -> str:
    """Return a human-readable summary.

    Returns
    -------
    str
        Summary string.
    """
    available = self.get_available_receivers()
    return (
        f"IcechunkDataReader for {self.matched_dirs.yyyydoy.to_str()}\n"
        f"  Site: {self.site_name}\n"
        f"  Available receivers: {dict(available)}\n"
        f"  Workers: {self.n_max_workers}, GC enabled: {self.enable_gc}"
    )

preprocess_rnx(rnx_file, keep_vars=None)

Preprocess a single RINEX file and attach file hash metadata.

Parameters

rnx_file : Path RINEX file to preprocess. keep_vars : list[str] | None, optional Variables to retain in the dataset.

Returns

tuple[Path, xr.Dataset] The input file path and the processed dataset.

Source code in packages/canvod-store/src/canvod/store/reader.py
 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
def preprocess_rnx(
    rnx_file: Path,
    keep_vars: list[str] | None = None,
) -> tuple[Path, xr.Dataset]:
    """
    Preprocess a single RINEX file and attach file hash metadata.

    Parameters
    ----------
    rnx_file : Path
        RINEX file to preprocess.
    keep_vars : list[str] | None, optional
        Variables to retain in the dataset.

    Returns
    -------
    tuple[Path, xr.Dataset]
        The input file path and the processed dataset.
    """
    log = get_logger(__name__).bind(file=str(rnx_file))
    log.info("preprocessing_started")

    try:
        rnx = Rnxv3Obs(fpath=rnx_file)
        ds = rnx.to_ds(write_global_attrs=True)

        # Attach cached file hash
        ds.attrs["File Hash"] = rnx.file_hash

        # Filter variables if specified
        if keep_vars:
            available_vars = [var for var in keep_vars if var in ds.data_vars]
            if available_vars:
                ds_subset = ds[available_vars]
                if isinstance(ds_subset, xr.DataArray):
                    ds = ds_subset.to_dataset(name=ds_subset.name or "value")
                else:
                    ds = ds_subset

        log.info("preprocessing_complete")
        return rnx_file, ds
    except Exception as e:
        log.exception("preprocessing_failed", error=str(e))
        raise

Preprocessing

Preprocessing wrapper for Icechunk storage.

This module provides the IcechunkPreprocessor class which wraps preprocessing functions from canvod.auxiliary.preprocessing. It maintains backward compatibility with gnssvodpy code while delegating to the new modular implementation.

IcechunkPreprocessor

Handles preprocessing of RINEX-converted datasets before writing to Icechunk.

This class wraps functions from canvod.auxiliary.preprocessing to provide backward compatibility with existing gnssvodpy code.

Note

All methods now delegate to canvod.auxiliary.preprocessing functions. The aggregate_glonass_fdma parameter should be passed from configuration.

Source code in packages/canvod-store/src/canvod/store/preprocessing.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
class IcechunkPreprocessor:
    """
    Handles preprocessing of RINEX-converted datasets before writing to Icechunk.

    This class wraps functions from canvod.auxiliary.preprocessing to provide
    backward compatibility with existing gnssvodpy code.

    Note:
        All methods now delegate to canvod.auxiliary.preprocessing functions.
        The aggregate_glonass_fdma parameter should be passed from configuration.
    """

    @staticmethod
    def map_aux_sv_to_sid(
        aux_ds: xr.Dataset,
        fill_value: float | None = None,
        aggregate_glonass_fdma: bool = True,
    ) -> xr.Dataset:
        """
        Transform auxiliary dataset from sv → sid dimension.

        Delegates to canvod.auxiliary.preprocessing.map_aux_sv_to_sid()

        Parameters
        ----------
        aux_ds : xr.Dataset
            Dataset with 'sv' dimension
        fill_value : float, optional
            Fill value for missing entries (default: np.nan)
        aggregate_glonass_fdma : bool, default True
            Whether to aggregate GLONASS FDMA bands

        Returns
        -------
        xr.Dataset
            Dataset with 'sid' dimension replacing 'sv'
        """
        import numpy as np

        if fill_value is None:
            fill_value = np.nan
        return map_aux_sv_to_sid(aux_ds, fill_value, aggregate_glonass_fdma)

    @staticmethod
    def pad_to_global_sid(
        ds: xr.Dataset,
        keep_sids: list[str] | None = None,
        aggregate_glonass_fdma: bool = True,
    ) -> xr.Dataset:
        """
        Pad dataset so it has all possible SIDs across all constellations.

        Delegates to canvod.auxiliary.preprocessing.pad_to_global_sid()

        Parameters
        ----------
        ds : xr.Dataset
            Dataset with 'sid' dimension
        keep_sids : list[str] | None
            Optional list of specific SIDs to keep
        aggregate_glonass_fdma : bool, default True
            Whether to aggregate GLONASS FDMA bands

        Returns
        -------
        xr.Dataset
            Dataset padded with NaN for missing SIDs
        """
        return pad_to_global_sid(ds, keep_sids, aggregate_glonass_fdma)

    @staticmethod
    def normalize_sid_dtype(ds: xr.Dataset) -> xr.Dataset:
        """
        Ensure sid coordinate uses object dtype.

        Delegates to canvod.auxiliary.preprocessing.normalize_sid_dtype()

        Parameters
        ----------
        ds : xr.Dataset
            Dataset with 'sid' coordinate

        Returns
        -------
        xr.Dataset
            Dataset with sid as object dtype
        """
        return normalize_sid_dtype(ds)

    @staticmethod
    def strip_fillvalue(ds: xr.Dataset) -> xr.Dataset:
        """
        Remove _FillValue attrs/encodings.

        Delegates to canvod.auxiliary.preprocessing.strip_fillvalue()

        Parameters
        ----------
        ds : xr.Dataset
            Dataset to clean

        Returns
        -------
        xr.Dataset
            Dataset with _FillValue attributes removed
        """
        return strip_fillvalue(ds)

    @staticmethod
    def add_future_datavars(
        ds: xr.Dataset,
        var_config: dict[str, dict[str, Any]],
    ) -> xr.Dataset:
        """
        Add placeholder data variables from configuration.

        Delegates to canvod.auxiliary.preprocessing.add_future_datavars()

        Parameters
        ----------
        ds : xr.Dataset
            Dataset to add variables to
        var_config : dict[str, dict[str, Any]]
            Variable configuration dictionary

        Returns
        -------
        xr.Dataset
            Dataset with new variables added
        """
        return add_future_datavars(ds, var_config)

    @staticmethod
    def prep_aux_ds(
        aux_ds: xr.Dataset,
        fill_value: float | None = None,
        aggregate_glonass_fdma: bool = True,
        keep_sids: list[str] | None = None,
    ) -> xr.Dataset:
        """
        Preprocess auxiliary dataset before writing to Icechunk.

        Delegates to canvod.auxiliary.preprocessing.prep_aux_ds()

        Performs complete 4-step preprocessing:
        1. Convert sv → sid dimension
        2. Pad to global sid list or filter to keep_sids
        3. Normalize sid dtype to object
        4. Strip _FillValue attributes

        Parameters
        ----------
        aux_ds : xr.Dataset
            Dataset with 'sv' dimension
        fill_value : float, optional
            Fill value for missing entries (default: np.nan)
        aggregate_glonass_fdma : bool, default True
            Whether to aggregate GLONASS FDMA bands
        keep_sids : list[str] | None, default None
            List of specific SIDs to keep. If None, keeps all possible SIDs.

        Returns
        -------
        xr.Dataset
            Fully preprocessed dataset ready for Icechunk
        """
        import numpy as np

        if fill_value is None:
            fill_value = np.nan
        return prep_aux_ds(aux_ds, fill_value, aggregate_glonass_fdma, keep_sids)

map_aux_sv_to_sid(aux_ds, fill_value=None, aggregate_glonass_fdma=True) staticmethod

Transform auxiliary dataset from sv → sid dimension.

Delegates to canvod.auxiliary.preprocessing.map_aux_sv_to_sid()

Parameters

aux_ds : xr.Dataset Dataset with 'sv' dimension fill_value : float, optional Fill value for missing entries (default: np.nan) aggregate_glonass_fdma : bool, default True Whether to aggregate GLONASS FDMA bands

Returns

xr.Dataset Dataset with 'sid' dimension replacing 'sv'

Source code in packages/canvod-store/src/canvod/store/preprocessing.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
@staticmethod
def map_aux_sv_to_sid(
    aux_ds: xr.Dataset,
    fill_value: float | None = None,
    aggregate_glonass_fdma: bool = True,
) -> xr.Dataset:
    """
    Transform auxiliary dataset from sv → sid dimension.

    Delegates to canvod.auxiliary.preprocessing.map_aux_sv_to_sid()

    Parameters
    ----------
    aux_ds : xr.Dataset
        Dataset with 'sv' dimension
    fill_value : float, optional
        Fill value for missing entries (default: np.nan)
    aggregate_glonass_fdma : bool, default True
        Whether to aggregate GLONASS FDMA bands

    Returns
    -------
    xr.Dataset
        Dataset with 'sid' dimension replacing 'sv'
    """
    import numpy as np

    if fill_value is None:
        fill_value = np.nan
    return map_aux_sv_to_sid(aux_ds, fill_value, aggregate_glonass_fdma)

pad_to_global_sid(ds, keep_sids=None, aggregate_glonass_fdma=True) staticmethod

Pad dataset so it has all possible SIDs across all constellations.

Delegates to canvod.auxiliary.preprocessing.pad_to_global_sid()

Parameters

ds : xr.Dataset Dataset with 'sid' dimension keep_sids : list[str] | None Optional list of specific SIDs to keep aggregate_glonass_fdma : bool, default True Whether to aggregate GLONASS FDMA bands

Returns

xr.Dataset Dataset padded with NaN for missing SIDs

Source code in packages/canvod-store/src/canvod/store/preprocessing.py
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
@staticmethod
def pad_to_global_sid(
    ds: xr.Dataset,
    keep_sids: list[str] | None = None,
    aggregate_glonass_fdma: bool = True,
) -> xr.Dataset:
    """
    Pad dataset so it has all possible SIDs across all constellations.

    Delegates to canvod.auxiliary.preprocessing.pad_to_global_sid()

    Parameters
    ----------
    ds : xr.Dataset
        Dataset with 'sid' dimension
    keep_sids : list[str] | None
        Optional list of specific SIDs to keep
    aggregate_glonass_fdma : bool, default True
        Whether to aggregate GLONASS FDMA bands

    Returns
    -------
    xr.Dataset
        Dataset padded with NaN for missing SIDs
    """
    return pad_to_global_sid(ds, keep_sids, aggregate_glonass_fdma)

normalize_sid_dtype(ds) staticmethod

Ensure sid coordinate uses object dtype.

Delegates to canvod.auxiliary.preprocessing.normalize_sid_dtype()

Parameters

ds : xr.Dataset Dataset with 'sid' coordinate

Returns

xr.Dataset Dataset with sid as object dtype

Source code in packages/canvod-store/src/canvod/store/preprocessing.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@staticmethod
def normalize_sid_dtype(ds: xr.Dataset) -> xr.Dataset:
    """
    Ensure sid coordinate uses object dtype.

    Delegates to canvod.auxiliary.preprocessing.normalize_sid_dtype()

    Parameters
    ----------
    ds : xr.Dataset
        Dataset with 'sid' coordinate

    Returns
    -------
    xr.Dataset
        Dataset with sid as object dtype
    """
    return normalize_sid_dtype(ds)

strip_fillvalue(ds) staticmethod

Remove _FillValue attrs/encodings.

Delegates to canvod.auxiliary.preprocessing.strip_fillvalue()

Parameters

ds : xr.Dataset Dataset to clean

Returns

xr.Dataset Dataset with _FillValue attributes removed

Source code in packages/canvod-store/src/canvod/store/preprocessing.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@staticmethod
def strip_fillvalue(ds: xr.Dataset) -> xr.Dataset:
    """
    Remove _FillValue attrs/encodings.

    Delegates to canvod.auxiliary.preprocessing.strip_fillvalue()

    Parameters
    ----------
    ds : xr.Dataset
        Dataset to clean

    Returns
    -------
    xr.Dataset
        Dataset with _FillValue attributes removed
    """
    return strip_fillvalue(ds)

add_future_datavars(ds, var_config) staticmethod

Add placeholder data variables from configuration.

Delegates to canvod.auxiliary.preprocessing.add_future_datavars()

Parameters

ds : xr.Dataset Dataset to add variables to var_config : dict[str, dict[str, Any]] Variable configuration dictionary

Returns

xr.Dataset Dataset with new variables added

Source code in packages/canvod-store/src/canvod/store/preprocessing.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@staticmethod
def add_future_datavars(
    ds: xr.Dataset,
    var_config: dict[str, dict[str, Any]],
) -> xr.Dataset:
    """
    Add placeholder data variables from configuration.

    Delegates to canvod.auxiliary.preprocessing.add_future_datavars()

    Parameters
    ----------
    ds : xr.Dataset
        Dataset to add variables to
    var_config : dict[str, dict[str, Any]]
        Variable configuration dictionary

    Returns
    -------
    xr.Dataset
        Dataset with new variables added
    """
    return add_future_datavars(ds, var_config)

prep_aux_ds(aux_ds, fill_value=None, aggregate_glonass_fdma=True, keep_sids=None) staticmethod

Preprocess auxiliary dataset before writing to Icechunk.

Delegates to canvod.auxiliary.preprocessing.prep_aux_ds()

Performs complete 4-step preprocessing: 1. Convert sv → sid dimension 2. Pad to global sid list or filter to keep_sids 3. Normalize sid dtype to object 4. Strip _FillValue attributes

Parameters

aux_ds : xr.Dataset Dataset with 'sv' dimension fill_value : float, optional Fill value for missing entries (default: np.nan) aggregate_glonass_fdma : bool, default True Whether to aggregate GLONASS FDMA bands keep_sids : list[str] | None, default None List of specific SIDs to keep. If None, keeps all possible SIDs.

Returns

xr.Dataset Fully preprocessed dataset ready for Icechunk

Source code in packages/canvod-store/src/canvod/store/preprocessing.py
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
@staticmethod
def prep_aux_ds(
    aux_ds: xr.Dataset,
    fill_value: float | None = None,
    aggregate_glonass_fdma: bool = True,
    keep_sids: list[str] | None = None,
) -> xr.Dataset:
    """
    Preprocess auxiliary dataset before writing to Icechunk.

    Delegates to canvod.auxiliary.preprocessing.prep_aux_ds()

    Performs complete 4-step preprocessing:
    1. Convert sv → sid dimension
    2. Pad to global sid list or filter to keep_sids
    3. Normalize sid dtype to object
    4. Strip _FillValue attributes

    Parameters
    ----------
    aux_ds : xr.Dataset
        Dataset with 'sv' dimension
    fill_value : float, optional
        Fill value for missing entries (default: np.nan)
    aggregate_glonass_fdma : bool, default True
        Whether to aggregate GLONASS FDMA bands
    keep_sids : list[str] | None, default None
        List of specific SIDs to keep. If None, keeps all possible SIDs.

    Returns
    -------
    xr.Dataset
        Fully preprocessed dataset ready for Icechunk
    """
    import numpy as np

    if fill_value is None:
        fill_value = np.nan
    return prep_aux_ds(aux_ds, fill_value, aggregate_glonass_fdma, keep_sids)

Grid Adapters

Grid adapters for hemisphere grid storage in Icechunk.