scientific-workflow 0.8.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
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
//! Recording persistence and reconstruction for scientific state samples.
//!
//! This module is the complete public storage boundary. Simulations configure
//! named output streams with coordinate-aware sampling intervals through
//! [`SystemStateWriterBuilder`], then offer a borrowed live [`SystemState`] to
//! [`SystemStateWriter::observe_state`] after each evolution step. The writer
//! checks time before accessing any payload and encodes only streams whose
//! sampling interval includes the current iteration. One bounded queue
//! and worker serve every configured stream. Each stream accumulates an
//! independent byte-targeted chunk entirely in reusable userspace memory and
//! performs filesystem IO only when publishing that chunk. The recording owns exactly one
//! authoritative `metadata.json` lifecycle.
//!
//! # Ownership and backpressure
//!
//! Sampling never clones, removes, or retains a scientific payload. The
//! selected values are borrowed only while Serde creates one owned JSONL
//! record. That record is then moved into the recording writer. If the configured
//! queue-byte budget is full, [`SystemStateWriter::observe_state`] blocks until the writer
//! commits enough queued bytes or reports a terminal error. Records are never
//! split between chunks.
//!
//! # Lifecycle
//!
//! [`SystemStateWriterBuilder::create_new_recording`] refuses an existing output root, validates every
//! stream against one shared state specification, publishes initial `running`
//! metadata, and then starts the recording writer. A complete buffered chunk is
//! written once, synchronized, described in metadata, and atomically sealed.
//! [`SystemStateWriter::complete_recording`] drains the writer, atomically commits
//! completion timing and terminal metadata, and returns [`CompletedRecording`];
//! [`SystemStateWriter::mark_recording_failed`] records an explicit failed
//! lifecycle instead. Dropping an active recording drains its writer thread for
//! memory and file safety but deliberately leaves metadata as `running`.
//!
//! [`SystemStateWriterBuilder::continue_existing_recording`] explicitly validates and appends an
//! existing running run. [`SystemStateWriterBuilder::continue_recording_from_latest_checkpoint`]
//! additionally reconstructs a complete owned checkpoint state through
//! caller-supplied payload decoders. Recovery discards an unpublished temporary
//! chunk, while completing the rename of a descriptor-prepared chunk.
//! [`SystemStateWriterBuilder::open_or_resume_from_latest_checkpoint`] is the
//! concise create-or-continue entry point: it infers the newest complete-state
//! checkpoint and removes every stream record later than that checkpoint
//! before writing resumes.
//! Checkpoint-aware continuation verifies the
//! selected latest sealed checkpoint chunk's exact byte count and SHA-256
//! checksum before decoding it or returning an append-capable writer.
//!
//! # Reading
//!
//! [`StoredStateSeriesReader`] accepts a completed output directory and a [`JsonPayloadDecoderRegistry`]
//! registry. The reader validates metadata, chunks, checksums, record order,
//! and decoder coverage before reconstructing typed
//! [`StateSeries`](crate::time_series::StateSeries) values. Decoder
//! implementations remain per payload type and registrations remain per exact
//! state key. Latest-state reads verify and decode only the newest chunk.
//!
//! # Boundary
//!
//! Storage owns durable mechanics: run directories, stream chunking, queue
//! flushing, metadata transitions, and reconstruction integrity checks. Callers
//! own simulation evolution, stream schemas, payload codecs, and scheduling.
//! Storage does not define modeling APIs, RNG behavior, or artifact semantics.

use std::collections::{HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};

use fs2::FileExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::clock::{duration_nanoseconds, utc_now_rfc3339};
use crate::configuration::ResolvedConfiguration;
use crate::system_state::{StateSchemaSource, SystemState, SystemStateSchema};

mod error;
mod json_payload_decoder;
mod json_state_record_encoder;
mod jsonl_format;
mod queued_state_writer;
mod resume;
mod stored_state_series_reader;

pub use error::StorageError;
pub use json_payload_decoder::{
    JsonPayloadDecoder, JsonPayloadDecoderRegistry, JsonStringDecoder, JsonVecF64Decoder,
};
pub use stored_state_series_reader::StoredStateSeriesReader;

use json_state_record_encoder::JsonStateRecordEncoder;
use jsonl_format::{
    RecordingMetadata, RecordingStatus, StateFieldMetadata, StateStreamMetadata,
    TimeAxisMetadata as StoredTimeAxis,
};
use queued_state_writer::{RecoveredStateStream, StateStreamStorageConfig, StateWriterWorker};

/// Stable name of the sole structural metadata file in one output root.
const METADATA_FILE: &str = "metadata.json";

/// Temporary sibling used for atomic metadata replacement.
const METADATA_TEMP_FILE: &str = ".metadata.json.tmp";

/// Public description of the temporal coordinates used by a run.
///
/// Every record always has an integer iteration. Physical time remains
/// optional, and its unit is legal only when a physical-coordinate name is
/// configured. Labels are documentation persisted once in `metadata.json`;
/// they do not change [`crate::system_state::SimulationTime`] representation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TimeAxisMetadata {
    iteration_name: String,
    iteration_unit: Option<String>,
    physical_time_name: Option<String>,
    physical_time_unit: Option<String>,
}

impl TimeAxisMetadata {
    /// Creates a time-axis declaration with a mandatory iteration label.
    ///
    /// Whitespace is retained in the builder and rejected by
    /// [`SystemStateWriterBuilder::create_new_recording`], keeping fluent configuration infallible
    /// while ensuring persisted labels are never silently normalized.
    pub fn new(iteration_name: impl Into<String>) -> Self {
        Self {
            iteration_name: iteration_name.into(),
            iteration_unit: None,
            physical_time_name: None,
            physical_time_unit: None,
        }
    }

    /// Sets the optional unit of the iteration coordinate.
    #[must_use]
    pub fn with_iteration_unit(mut self, unit: impl Into<String>) -> Self {
        self.iteration_unit = Some(unit.into());
        self
    }

    /// Declares the optional floating-point physical coordinate.
    #[must_use]
    pub fn with_physical_time_name(mut self, name: impl Into<String>) -> Self {
        self.physical_time_name = Some(name.into());
        self
    }

    /// Sets the physical-coordinate unit.
    ///
    /// A matching [`TimeAxisMetadata::with_physical_time_name`] is required; construction fails
    /// at [`SystemStateWriterBuilder::create_new_recording`] if the unit is configured alone.
    #[must_use]
    pub fn with_physical_time_unit(mut self, unit: impl Into<String>) -> Self {
        self.physical_time_unit = Some(unit.into());
        self
    }

    /// Declares the physical-time name and unit together.
    #[must_use]
    pub fn with_physical_axis(mut self, name: impl Into<String>, unit: impl Into<String>) -> Self {
        self.physical_time_name = Some(name.into());
        self.physical_time_unit = Some(unit.into());
        self
    }

    /// Converts public configuration into the private persisted representation.
    fn into_stored(self) -> StoredTimeAxis {
        StoredTimeAxis {
            iteration_name: self.iteration_name,
            iteration_unit: self.iteration_unit,
            physical_time_name: self.physical_time_name,
            physical_time_unit: self.physical_time_unit,
        }
    }
}

impl Default for TimeAxisMetadata {
    /// Uses `iteration` as the integer-time label and declares no units or
    /// physical coordinate.
    fn default() -> Self {
        Self::new("iteration")
    }
}

/// Immutable operational timing returned after successful recording completion.
///
/// These values describe host execution rather than scientific coordinates.
/// Scientific iteration and physical time remain part of each recorded
/// [`SystemState`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecordingTiming {
    created_at_utc: String,
    finalized_at_utc: String,
    active_duration_ns: u64,
    continuation_count: u64,
}

impl RecordingTiming {
    /// Converts the validated private wire representation into the public view.
    fn from_stored(
        timing: &jsonl_format::RecordingTiming,
        metadata_path: &Path,
    ) -> Result<Self, StorageError> {
        let finalized_at_utc =
            timing
                .finalized_at_utc
                .clone()
                .ok_or_else(|| StorageError::InvalidMetadata {
                    path: metadata_path.to_path_buf(),
                    reason: "completed recording lacks finalized timestamp".to_owned(),
                })?;
        Ok(Self {
            created_at_utc: timing.created_at_utc.clone(),
            finalized_at_utc,
            active_duration_ns: timing.active_duration_ns,
            continuation_count: timing.continuation_count,
        })
    }

    /// Returns the recording's original UTC creation timestamp in RFC 3339 form.
    pub fn created_at_utc(&self) -> &str {
        &self.created_at_utc
    }

    /// Returns the successful completion timestamp in UTC RFC 3339 form.
    pub fn finalized_at_utc(&self) -> &str {
        &self.finalized_at_utc
    }

    /// Returns the accumulated active writer duration as exact nanoseconds.
    pub fn active_duration_ns(&self) -> u64 {
        self.active_duration_ns
    }

    /// Returns the accumulated active writer duration as a standard duration.
    pub fn active_duration(&self) -> Duration {
        Duration::from_nanos(self.active_duration_ns)
    }

    /// Returns how many times this recording was reopened for continuation.
    pub fn continuation_count(&self) -> u64 {
        self.continuation_count
    }
}

/// Aggregate persisted facts for one stream in a completed recording.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompletedStreamSummary {
    name: String,
    chunk_count: u64,
    record_count: u64,
    encoded_bytes: u64,
    first_iteration: Option<u64>,
    last_iteration: Option<u64>,
}

impl CompletedStreamSummary {
    /// Returns the logical stream name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the number of immutable chunk files.
    pub fn chunk_count(&self) -> u64 {
        self.chunk_count
    }

    /// Returns the total number of recorded states.
    pub fn record_count(&self) -> u64 {
        self.record_count
    }

    /// Returns the exact total framed bytes across all chunks.
    pub fn encoded_bytes(&self) -> u64 {
        self.encoded_bytes
    }

    /// Returns the first recorded iteration, or `None` for an empty stream.
    pub fn first_iteration(&self) -> Option<u64> {
        self.first_iteration
    }

    /// Returns the final recorded iteration, or `None` for an empty stream.
    pub fn last_iteration(&self) -> Option<u64> {
        self.last_iteration
    }
}

/// Durable result of a successfully completed recording lifecycle.
///
/// The active writer has been consumed and all metadata and chunks are durable
/// before this handle is created. It cannot append data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompletedRecording {
    directory: PathBuf,
    timing: RecordingTiming,
    terminal_metadata: Map<String, Value>,
    streams: Vec<CompletedStreamSummary>,
}

impl CompletedRecording {
    /// Returns the completed recording directory.
    pub fn directory(&self) -> &Path {
        &self.directory
    }

    /// Returns automatically captured operational timing.
    pub fn timing(&self) -> &RecordingTiming {
        &self.timing
    }

    /// Returns caller-supplied terminal metadata committed with completion.
    pub fn terminal_metadata(&self) -> &Map<String, Value> {
        &self.terminal_metadata
    }

    /// Returns stream summaries in declaration order.
    pub fn stream_summaries(&self) -> &[CompletedStreamSummary] {
        &self.streams
    }

    /// Looks up one completed stream summary by exact name.
    pub fn stream_summary(&self, name: &str) -> Option<&CompletedStreamSummary> {
        self.streams.iter().find(|stream| stream.name == name)
    }
}

/// Coordinate-aware interval used to select states for one output stream.
///
/// The noun variant identifies the coordinate on which the interval is
/// measured. The current storage format supports iteration-based sampling;
/// adding physical-time sampling later will not require overloading the word
/// `step` or changing the surrounding stream API.
///
/// Human-authored configuration may use the concise JSON value `10` for every
/// ten iterations. Deserialization also accepts the stable tagged form
/// `{"iterations": 10}` emitted by serialization.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SamplingInterval {
    /// Select iteration zero and each iteration divisible by this interval.
    Iterations(NonZeroU64),
}

#[derive(Deserialize)]
#[serde(untagged)]
enum SamplingIntervalInput {
    /// Concise configuration form: `10` means every ten iterations.
    Iterations(NonZeroU64),
    /// Stable tagged form emitted by [`SamplingInterval`]'s serializer.
    Tagged { iterations: NonZeroU64 },
}

impl<'de> Deserialize<'de> for SamplingInterval {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match SamplingIntervalInput::deserialize(deserializer)? {
            SamplingIntervalInput::Iterations(interval)
            | SamplingIntervalInput::Tagged {
                iterations: interval,
            } => Ok(Self::Iterations(interval)),
        }
    }
}

impl SamplingInterval {
    /// Creates an iteration interval, returning `None` for zero.
    pub const fn iterations(interval: u64) -> Option<Self> {
        match NonZeroU64::new(interval) {
            Some(interval) => Some(Self::Iterations(interval)),
            None => None,
        }
    }

    /// Reports whether this interval selects `iteration`.
    const fn includes(self, iteration: u64) -> bool {
        match self {
            Self::Iterations(interval) => iteration.is_multiple_of(interval.get()),
        }
    }
}

/// Filesystem layout for one logical state stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum StateStreamLayout {
    /// Accumulate encoded records in memory until the rollover target is met.
    Chunked {
        /// Approximate encoded-byte threshold at which a chunk is sealed.
        target_bytes: NonZeroU64,
    },
    /// Publish every encoded record as its own immutable file.
    IndividualFiles,
}

/// Persistence and backpressure policy for one logical state stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StateStreamStorage {
    layout: StateStreamLayout,
    storage_queue_bytes: NonZeroU64,
}

impl StateStreamStorage {
    /// Creates an in-memory chunking policy with a strict queue-byte budget.
    pub const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
        Self {
            layout: StateStreamLayout::Chunked { target_bytes },
            storage_queue_bytes,
        }
    }

    /// Creates a one-file-per-record policy with a strict queue-byte budget.
    pub const fn individual_files(storage_queue_bytes: NonZeroU64) -> Self {
        Self {
            layout: StateStreamLayout::IndividualFiles,
            storage_queue_bytes,
        }
    }

    /// Returns the configured on-disk stream layout.
    pub const fn layout(self) -> StateStreamLayout {
        self.layout
    }

    /// Returns the strict byte capacity shared by queued records.
    pub const fn storage_queue_bytes(self) -> NonZeroU64 {
        self.storage_queue_bytes
    }
}

/// Configuration for one independently sampled logical output stream.
///
/// Field names are exact keys from the run's [`SystemStateSchema`]. Their input order
/// is irrelevant: the encoder writes them in canonical template order. Chunk
/// targets are rollover thresholds, while individual-file streams seal every
/// record immediately. The queue byte limit is strict in either layout.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StateStreamConfig {
    name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    directory: Option<String>,
    sampling_interval: SamplingInterval,
    fields: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    storage: Option<StateStreamStorage>,
}

impl StateStreamConfig {
    /// Creates a stream whose relative output directory initially equals its
    /// logical name.
    ///
    /// `storage == None` inherits writer-wide storage. Non-zero types make
    /// explicit limits valid by construction. Names, paths, duplicate
    /// fields, and state-key membership are validated together by
    /// [`SystemStateWriterBuilder::create_new_recording`].
    pub fn new<I, K>(
        name: impl Into<String>,
        fields: I,
        sampling_interval: SamplingInterval,
        storage: Option<StateStreamStorage>,
    ) -> Self
    where
        I: IntoIterator<Item = K>,
        K: Into<String>,
    {
        let name = name.into();
        Self {
            directory: None,
            name,
            sampling_interval,
            fields: fields.into_iter().map(Into::into).collect(),
            storage,
        }
    }

    /// Overrides the stream's relative directory beneath the run root.
    ///
    /// Absolute paths, empty paths, and `.` or `..` components are rejected at
    /// start. Distinct streams must use distinct directories.
    #[must_use]
    pub fn with_relative_directory(mut self, directory: impl Into<String>) -> Self {
        self.directory = Some(directory.into());
        self
    }

    /// Returns the logical stream name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the relative directory beneath the recording root.
    pub fn relative_directory(&self) -> &str {
        self.directory.as_deref().unwrap_or(&self.name)
    }

    /// Returns the sampling policy.
    pub const fn sampling_interval(&self) -> SamplingInterval {
        self.sampling_interval
    }

    /// Returns selected state fields in declaration order.
    pub fn fields(&self) -> &[String] {
        &self.fields
    }

    /// Returns stream-specific storage, or `None` when writer storage applies.
    pub const fn storage(&self) -> Option<StateStreamStorage> {
        self.storage
    }
}

/// Builder for one exclusive state-recording directory.
///
/// The builder owns only paths, immutable configuration, and a cheap shared
/// [`SystemStateSchema`] handle. It opens no files and starts no threads before
/// [`SystemStateWriterBuilder::create_new_recording`], [`SystemStateWriterBuilder::continue_existing_recording`], or
/// [`SystemStateWriterBuilder::continue_recording_from_latest_checkpoint`].
#[derive(Debug)]
pub struct SystemStateWriterBuilder {
    root: PathBuf,
    spec: SystemStateSchema,
    time: TimeAxisMetadata,
    user_metadata: Map<String, Value>,
    shared_stream_storage: Option<StateStreamStorage>,
    streams: Vec<StateStreamConfig>,
}

impl SystemStateWriterBuilder {
    /// Creates an empty run configuration using [`TimeAxisMetadata::default`].
    ///
    /// The schema is derived from a live [`SystemState`] or supplied directly
    /// as a [`SystemStateSchema`]. It is cloned only as an `Arc`-backed metadata
    /// handle; no scientific payload is cloned or retained.
    pub fn new<S>(root: impl Into<PathBuf>, source: &S) -> Self
    where
        S: StateSchemaSource + ?Sized,
    {
        Self {
            root: root.into(),
            spec: source.state_schema().clone(),
            time: TimeAxisMetadata::default(),
            user_metadata: Map::new(),
            shared_stream_storage: None,
            streams: Vec::new(),
        }
    }

    /// Replaces the run's temporal-coordinate documentation.
    #[must_use]
    pub fn with_time_axis_metadata(mut self, time: TimeAxisMetadata) -> Self {
        self.time = time;
        self
    }

    /// Merges caller-owned metadata persisted under `user_metadata`.
    ///
    /// Values must already be JSON-compatible. This metadata is structurally
    /// separate from scientific payloads and is written only to
    /// `metadata.json`.
    #[must_use]
    pub fn with_user_metadata(mut self, metadata: Map<String, Value>) -> Self {
        self.user_metadata.extend(metadata);
        self
    }

    /// Uses one persistence policy for concise stream declarations.
    ///
    /// Storage supplied directly through [`StateStreamConfig::new`] remains
    /// stream-specific and takes precedence. Streams constructed with
    /// `storage == None` require this shared policy.
    #[must_use]
    pub fn with_shared_stream_storage(mut self, storage: StateStreamStorage) -> Self {
        self.shared_stream_storage = Some(storage);
        self
    }

    /// Merges one resolved configuration into the recording's user metadata.
    ///
    /// Fixed and swept values retain their resolved JSON representation.
    /// The synthetic `ordinal` entry is always set from the configuration and
    /// therefore replaces any same-named input entry. Configuration values also replace
    /// same-named caller metadata, while unrelated metadata and RNG records are
    /// preserved. On a key collision, the most recently supplied source wins.
    #[must_use]
    pub fn with_configuration(mut self, configuration: &ResolvedConfiguration) -> Self {
        self.user_metadata
            .extend(configuration.resolved_object().clone());
        self.user_metadata
            .insert("ordinal".to_owned(), Value::from(configuration.ordinal()));
        self
    }

    /// Appends one logical stream declaration in deterministic metadata order.
    ///
    /// Duplicate names or directories are reported at start so fluent builder
    /// assembly remains infallible.
    #[must_use]
    pub fn add_state_stream(mut self, stream: StateStreamConfig) -> Self {
        self.streams.push(stream);
        self
    }

    /// Validates the complete run, creates its exclusive output root, starts
    /// each bounded writer, and publishes initial metadata atomically.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::RecordingDirectoryExists`] rather than replacing any
    /// existing filesystem entry. Configuration, state-key selection,
    /// directory creation, thread startup, JSON, and metadata durability
    /// failures retain their precise [`StorageError`] context. If startup fails
    /// after the root is created, the path is retained as diagnostic evidence
    /// and is never silently removed.
    pub fn create_new_recording(self) -> Result<SystemStateWriter, StorageError> {
        SystemStateWriter::create_new_recording(self)
    }

    /// Creates a new recording or automatically resumes matching incomplete
    /// output from its newest complete-state checkpoint.
    ///
    /// The checkpoint stream is inferred from the declared stream schemas.
    /// On continuation, records later than the restored checkpoint are removed
    /// from every stream before writing restarts. Existing output without a
    /// complete checkpoint is rejected.
    pub fn open_or_resume_from_latest_checkpoint(
        self,
        decoders: JsonPayloadDecoderRegistry,
    ) -> Result<(SystemStateWriter, Option<SystemState>), StorageError> {
        match self.root.try_exists() {
            Ok(false) => Self::create_new_recording(self).map(|writer| (writer, None)),
            Ok(true) => SystemStateWriter::continue_recording(
                self,
                Some(CheckpointRequest::LatestComplete(decoders)),
            ),
            Err(source) => Err(StorageError::Io {
                operation: "inspect recording root for automatic resume",
                path: self.root.clone(),
                source,
            }),
        }
    }

    /// Continues append writing in an existing running recording directory.
    ///
    /// The complete builder configuration is compared with authoritative
    /// metadata before temporary publication state is reconciled. Only the
    /// highest temporary chunk in each stream may be examined. This append-only entry point does not
    /// reconstruct scientific state; callers requiring a verified checkpoint
    /// must use [`Self::continue_recording_from_latest_checkpoint`].
    pub fn continue_existing_recording(self) -> Result<SystemStateWriter, StorageError> {
        SystemStateWriter::continue_recording(self, None).map(|(writer, _)| writer)
    }

    /// Resumes a run and reconstructs its newest complete checkpoint state.
    ///
    /// `stream` must cover the builder's complete state specification, and
    /// `decoders` must cover every field. The returned state owns all decoded
    /// payloads. When reconstruction selects a sealed chunk, its exact byte
    /// count and SHA-256 checksum are verified before its final record is
    /// decoded. Every stream is rewound to that checkpoint iteration. Writer
    /// threads begin only after reconstruction and rewind succeed.
    pub fn continue_recording_from_latest_checkpoint(
        self,
        stream: &str,
        decoders: JsonPayloadDecoderRegistry,
    ) -> Result<(SystemStateWriter, SystemState), StorageError> {
        let (writer, state) = SystemStateWriter::continue_recording(
            self,
            Some(CheckpointRequest::Named(stream.to_owned(), decoders)),
        )?;
        Ok((
            writer,
            state.expect("checkpoint-aware resume always reconstructs one state"),
        ))
    }
}

enum CheckpointRequest {
    Named(String, JsonPayloadDecoderRegistry),
    LatestComplete(JsonPayloadDecoderRegistry),
}

/// Exclusive queued writer for all persistent streams in one recording.
///
/// This type is intentionally non-Clone. It owns the only writer handles and
/// the only legal transition from `running` metadata to a terminal status.
/// It owns no [`SystemState`] and never extends a payload borrow beyond one
/// synchronous [`SystemStateWriter::observe_state`] call.
pub struct SystemStateWriter {
    root: PathBuf,
    stream_order: Vec<String>,
    manifest: Arc<RecordingManifest>,
    streams: HashMap<String, ScheduledStateStream>,
    writer: Option<StateWriterWorker>,
    session_started: Instant,
    /// Held after writers so normal field drop keeps the lease until every
    /// worker has drained and released its manifest handle.
    _lease: RecordingLease,
}

impl SystemStateWriter {
    /// Begins configuring a state recording from a live state or schema.
    pub fn builder<S>(root: impl Into<PathBuf>, source: &S) -> SystemStateWriterBuilder
    where
        S: StateSchemaSource + ?Sized,
    {
        SystemStateWriterBuilder::new(root, source)
    }

    /// Returns the recording directory exactly as configured.
    pub fn recording_directory(&self) -> &Path {
        &self.root
    }

    /// Iterates logical stream names in deterministic declaration order.
    pub fn stream_names(&self) -> impl ExactSizeIterator<Item = &str> {
        self.stream_order.iter().map(String::as_str)
    }

    /// Offers the current live state to every configured sampling stream.
    ///
    /// The writer first reads only the state's iteration. Streams that are
    /// not due perform no field lookup, payload borrow, serialization,
    /// allocation, or queue operation. Every due stream encodes its selected
    /// fields before bounded queue admission, so backpressure retains only
    /// owned bytes and never extends a scientific payload borrow.
    ///
    /// # Errors
    ///
    /// Returns state or payload serialization errors from a due stream,
    /// queue-limit and ordering errors, or the writer's authoritative terminal
    /// failure.
    pub fn observe_state(&mut self, state: &SystemState) -> Result<(), StorageError> {
        let iteration = state.simulation_time().iteration();
        let writer = self
            .writer
            .as_ref()
            .expect("an active recording owns its writer worker");
        for name in &self.stream_order {
            let stream = self
                .streams
                .get_mut(name)
                .expect("stream order contains every configured stream");
            if !stream.sampling_interval.includes(iteration)
                || stream.last_recorded_iteration == Some(iteration)
            {
                continue;
            }
            let record = stream.encoder.encode(state)?;
            writer.submit_record(name, record)?;
            stream.last_recorded_iteration = Some(iteration);
        }
        Ok(())
    }

    /// Durably seals every record accepted earlier by one logical stream.
    ///
    /// This is an ordered per-stream checkpoint barrier, not merely a buffered
    /// file flush. A non-empty userspace chunk is written once, synchronized,
    /// prepared in the sole metadata document, renamed to its sealed filename, and directory-synced
    /// before this method returns.
    pub fn flush_stream_to_storage(&self, stream: &str) -> Result<(), StorageError> {
        if !self.streams.contains_key(stream) {
            return Err(StorageError::UnknownStateStream {
                stream: stream.to_owned(),
            });
        }
        self.writer
            .as_ref()
            .expect("an active recording owns its writer worker")
            .flush_state_stream(stream)
    }

    /// Drains every stream, seals all chunks, and atomically publishes complete
    /// metadata.
    ///
    /// The method consumes the coordinator, making repeated finish or sampling
    /// impossible in safe Rust. If a writer fails, all remaining writers are
    /// still drained and a best-effort failed metadata transition is attempted
    /// before the originating writer error is returned.
    pub fn complete_recording(self) -> Result<CompletedRecording, StorageError> {
        self.complete_recording_with_terminal_metadata(Map::new())
    }

    /// Completes the recording and atomically commits values known only at the
    /// terminal boundary.
    ///
    /// Terminal values are stored separately from immutable creation-time user
    /// metadata and therefore cannot silently replace configuration parameters.
    pub fn complete_recording_with_terminal_metadata(
        mut self,
        terminal_metadata: Map<String, Value>,
    ) -> Result<CompletedRecording, StorageError> {
        if let Err(error) = self.finish_writer() {
            let _ = self.transition_terminal(
                RecordingStatus::Failed {
                    message: error.to_string(),
                },
                Map::new(),
            );
            return Err(error);
        }
        self.transition_terminal(RecordingStatus::Complete, terminal_metadata)?;
        self.completed_recording()
    }

    /// Records one final state to every stream exactly once, then completes.
    ///
    /// This terminal observation is independent of the sampling interval. A stream
    /// already recorded at the same iteration is skipped, while a non-aligned final
    /// iteration is encoded once. The writer therefore owns both interval-based and
    /// terminal sampling decisions; the simulation supplies only a borrowed state.
    pub fn complete_recording_with_final_state(
        mut self,
        state: &SystemState,
    ) -> Result<CompletedRecording, StorageError> {
        self.record_final_state(state)?;
        self.complete_recording()
    }

    /// Records the final state exactly once and atomically commits terminal
    /// user metadata with successful status and operational timing.
    pub fn complete_recording_with_final_state_and_terminal_metadata(
        mut self,
        state: &SystemState,
        terminal_metadata: Map<String, Value>,
    ) -> Result<CompletedRecording, StorageError> {
        self.record_final_state(state)?;
        self.complete_recording_with_terminal_metadata(terminal_metadata)
    }

    /// Encodes the supplied terminal state for streams that lack this iteration.
    fn record_final_state(&mut self, state: &SystemState) -> Result<(), StorageError> {
        let iteration = state.simulation_time().iteration();
        let writer = self
            .writer
            .as_ref()
            .expect("an active recording owns its writer worker");
        for name in &self.stream_order {
            let stream = self
                .streams
                .get_mut(name)
                .expect("stream order contains every configured stream");
            if stream.last_recorded_iteration == Some(iteration) {
                continue;
            }
            let record = stream.encoder.encode(state)?;
            writer.submit_record(name, record)?;
            stream.last_recorded_iteration = Some(iteration);
        }
        Ok(())
    }

    /// Drains every stream and atomically records an intentional failed run.
    ///
    /// This is appropriate when the simulation itself fails after storage has
    /// started. The supplied message is structural recording metadata and must not be
    /// empty or whitespace-only. Successfully accepted records remain as
    /// immutable chunks and are listed in the failed metadata, but
    /// [`StoredStateSeriesReader`] deliberately reconstructs only completed runs.
    ///
    /// If a writer also fails, its error takes precedence as the returned and
    /// persisted reason; the caller's message would no longer describe the
    /// authoritative storage termination.
    pub fn mark_recording_failed(self, message: impl Into<String>) -> Result<(), StorageError> {
        self.mark_recording_failed_with_terminal_metadata(message, Map::new())
    }

    /// Records an intentional failure with terminal-only user metadata.
    pub fn mark_recording_failed_with_terminal_metadata(
        mut self,
        message: impl Into<String>,
        terminal_metadata: Map<String, Value>,
    ) -> Result<(), StorageError> {
        let message = message.into();
        if message.trim().is_empty() {
            return Err(StorageError::InvalidConfiguration {
                setting: "failure_message",
                reason: "failed run message must not be empty".to_owned(),
            });
        }

        if let Err(error) = self.finish_writer() {
            let _ = self.transition_terminal(
                RecordingStatus::Failed {
                    message: error.to_string(),
                },
                Map::new(),
            );
            return Err(error);
        }
        self.transition_terminal(RecordingStatus::Failed { message }, terminal_metadata)
    }

    /// Performs complete validation before creating or mutating the run root.
    fn create_new_recording(builder: SystemStateWriterBuilder) -> Result<Self, StorageError> {
        ensure_absent(&builder.root)?;
        let prepared = PreparedRecording::from_builder(builder)?;
        create_root(&prepared.root)?;
        let lease = RecordingLease::acquire(&prepared.root)?;
        for stream in &prepared.streams {
            stream.writer.create_directory()?;
        }
        commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
        let manifest = Arc::new(RecordingManifest::new(
            prepared.root.clone(),
            prepared.metadata_path.clone(),
            prepared.metadata,
        ));
        Self::start_new_prepared(prepared.root, prepared.streams, manifest, lease)
    }

    /// Validates, recovers, optionally reconstructs, and starts an append run.
    fn continue_recording(
        builder: SystemStateWriterBuilder,
        checkpoint: Option<CheckpointRequest>,
    ) -> Result<(Self, Option<SystemState>), StorageError> {
        let prepared = PreparedRecording::from_builder(builder)?;
        let lease = RecordingLease::acquire(&prepared.root)?;
        remove_stale_metadata_temp(&prepared.root)?;
        let mut existing = load_metadata(&prepared.metadata_path)?;
        if !matches!(existing.status, RecordingStatus::Running) {
            return Err(StorageError::RecordingNotContinuable {
                path: prepared.metadata_path,
            });
        }
        ensure_resume_match(&prepared.metadata_path, &prepared.metadata, &existing)?;

        if checkpoint.is_some() {
            for stream in &prepared.streams {
                let declaration = existing
                    .stream(&stream.name)
                    .expect("matched metadata contains every prepared stream");
                StateWriterWorker::recover_state_stream(&stream.writer, declaration)?;
            }
        }

        let state = if let Some(checkpoint) = checkpoint {
            let (checkpoint_stream, decoders) = match checkpoint {
                CheckpointRequest::Named(stream, decoders) => (stream, decoders),
                CheckpointRequest::LatestComplete(decoders) => {
                    let stream = existing
                        .streams
                        .iter()
                        .filter(|stream| {
                            stored_state_series_reader::is_complete_checkpoint_stream(
                                stream,
                                &prepared.spec,
                            ) && !stream.chunks.is_empty()
                        })
                        .max_by_key(|stream| stream.chunks.last().map(|chunk| chunk.last_iteration))
                        .map(|stream| stream.name.clone())
                        .ok_or(StorageError::NoCompleteCheckpoint)?;
                    (stream, decoders)
                }
            };
            let declaration = existing.stream(&checkpoint_stream).ok_or_else(|| {
                StorageError::UnknownStateStream {
                    stream: checkpoint_stream.clone(),
                }
            })?;
            let state = stored_state_series_reader::decode_resume_state(
                &prepared.root,
                &prepared.metadata_path,
                declaration,
                &prepared.spec,
                &decoders,
            )?;
            resume::prepare_rewind_after_checkpoint(
                &prepared.root,
                &prepared.metadata_path,
                &mut existing,
                state.simulation_time().iteration(),
            )?;
            commit_metadata(&prepared.root, &prepared.metadata_path, &existing)?;
            Some(state)
        } else {
            None
        };

        let mut recovered = Vec::with_capacity(prepared.streams.len());
        for stream in prepared.streams {
            let declaration = existing
                .stream(&stream.name)
                .expect("matched metadata contains every prepared stream");
            let seed = StateWriterWorker::recover_state_stream(&stream.writer, declaration)?;
            recovered.push((stream, seed));
        }

        existing.timing.continuation_count = existing
            .timing
            .continuation_count
            .checked_add(1)
            .ok_or_else(|| StorageError::InvalidMetadata {
                path: prepared.metadata_path.clone(),
                reason: "timing.continuation_count overflowed".to_owned(),
            })?;
        commit_metadata(&prepared.root, &prepared.metadata_path, &existing)?;
        let manifest = Arc::new(RecordingManifest::new(
            prepared.root.clone(),
            prepared.metadata_path.clone(),
            existing,
        ));

        let output = Self::start_resumed_prepared(prepared.root, recovered, manifest, lease)?;
        Ok((output, state))
    }

    /// Spawns every empty writer after the initial manifest is durable.
    fn start_new_prepared(
        root: PathBuf,
        streams: Vec<PreparedStateStream>,
        manifest: Arc<RecordingManifest>,
        lease: RecordingLease,
    ) -> Result<Self, StorageError> {
        let mut scheduled = HashMap::with_capacity(streams.len());
        let mut configs = Vec::with_capacity(streams.len());
        let mut stream_order = Vec::with_capacity(streams.len());
        for prepared in streams {
            let name = prepared.name;
            stream_order.push(name.clone());
            scheduled.insert(
                name,
                ScheduledStateStream {
                    encoder: prepared.encoder,
                    sampling_interval: prepared.sampling_interval,
                    last_recorded_iteration: None,
                },
            );
            configs.push(prepared.writer);
        }
        let writer = StateWriterWorker::start_new_recording(configs, Arc::clone(&manifest))?;
        Ok(Self {
            root,
            stream_order,
            manifest,
            streams: scheduled,
            writer: Some(writer),
            session_started: Instant::now(),
            _lease: lease,
        })
    }

    /// Spawns every append writer from its recovered active owner and indices.
    fn start_resumed_prepared(
        root: PathBuf,
        streams: Vec<(PreparedStateStream, RecoveredStateStream)>,
        manifest: Arc<RecordingManifest>,
        lease: RecordingLease,
    ) -> Result<Self, StorageError> {
        let mut scheduled = HashMap::with_capacity(streams.len());
        let mut recovered_streams = Vec::with_capacity(streams.len());
        let mut stream_order = Vec::with_capacity(streams.len());
        for (prepared, seed) in streams {
            let name = prepared.name;
            stream_order.push(name.clone());
            scheduled.insert(
                name,
                ScheduledStateStream {
                    encoder: prepared.encoder,
                    sampling_interval: prepared.sampling_interval,
                    last_recorded_iteration: seed.last_iteration(),
                },
            );
            recovered_streams.push((prepared.writer, seed));
        }
        let writer = StateWriterWorker::continue_recovered_recording(
            recovered_streams,
            Arc::clone(&manifest),
        )?;
        Ok(Self {
            root,
            stream_order,
            manifest,
            streams: scheduled,
            writer: Some(writer),
            session_started: Instant::now(),
            _lease: lease,
        })
    }

    /// Drains and joins the recording's sole queued writer worker.
    fn finish_writer(&mut self) -> Result<(), StorageError> {
        let Some(writer) = self.writer.take() else {
            return Ok(());
        };
        writer.finish_recording()
    }

    /// Commits one terminal status, timestamp, duration, and metadata map.
    fn transition_terminal(
        &self,
        status: RecordingStatus,
        terminal_metadata: Map<String, Value>,
    ) -> Result<(), StorageError> {
        let finalized_at_utc =
            utc_now_rfc3339().map_err(|source| StorageError::OperationalTimestamp {
                operation: "finalize recording",
                source,
            })?;
        let active_duration_ns = duration_nanoseconds(self.session_started.elapsed())
            .ok_or(StorageError::OperationalDurationOverflow)?;
        self.manifest.transition_terminal(
            status,
            finalized_at_utc,
            active_duration_ns,
            terminal_metadata,
        )
    }

    /// Builds the immutable public result from the durable manifest snapshot.
    fn completed_recording(&self) -> Result<CompletedRecording, StorageError> {
        let metadata = self.manifest.snapshot();
        let timing = RecordingTiming::from_stored(&metadata.timing, &self.manifest.path)?;
        let streams = metadata
            .streams
            .iter()
            .map(completed_stream_summary)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(CompletedRecording {
            directory: self.root.clone(),
            timing,
            terminal_metadata: metadata.terminal_metadata,
            streams,
        })
    }
}

/// Derives one public stream aggregate without opening any chunk file.
fn completed_stream_summary(
    stream: &StateStreamMetadata,
) -> Result<CompletedStreamSummary, StorageError> {
    let overflow = || StorageError::ByteCountOverflow {
        stream: stream.name.clone(),
    };
    let chunk_count = u64::try_from(stream.chunks.len()).map_err(|_| overflow())?;
    let record_count = stream
        .chunks
        .iter()
        .try_fold(0_u64, |total, chunk| total.checked_add(chunk.records))
        .ok_or_else(&overflow)?;
    let encoded_bytes = stream
        .chunks
        .iter()
        .try_fold(0_u64, |total, chunk| total.checked_add(chunk.bytes))
        .ok_or_else(overflow)?;
    Ok(CompletedStreamSummary {
        name: stream.name.clone(),
        chunk_count,
        record_count,
        encoded_bytes,
        first_iteration: stream.chunks.first().map(|chunk| chunk.first_iteration),
        last_iteration: stream.chunks.last().map(|chunk| chunk.last_iteration),
    })
}

/// Fully validated builder output before any writer thread starts.
struct PreparedRecording {
    root: PathBuf,
    metadata_path: PathBuf,
    spec: SystemStateSchema,
    metadata: RecordingMetadata,
    streams: Vec<PreparedStateStream>,
}

impl PreparedRecording {
    /// Canonicalizes stream field order and builds expected persisted metadata.
    fn from_builder(builder: SystemStateWriterBuilder) -> Result<Self, StorageError> {
        let metadata_path = builder.root.join(METADATA_FILE);
        let stored_time = builder.time.into_stored();
        let mut names = HashSet::with_capacity(builder.streams.len());
        let mut directories = HashSet::with_capacity(builder.streams.len());
        let mut streams = Vec::with_capacity(builder.streams.len());
        let mut declarations = Vec::with_capacity(builder.streams.len());

        for config in builder.streams {
            if !names.insert(config.name.clone()) {
                return Err(StorageError::DuplicateStateStream {
                    stream: config.name,
                });
            }
            let directory = config.relative_directory().to_owned();
            if !directories.insert(directory.clone()) {
                return Err(StorageError::InvalidConfiguration {
                    setting: "stream.directory",
                    reason: format!("multiple streams use relative directory `{}`", directory),
                });
            }

            let storage = config
                .storage
                .or(builder.shared_stream_storage)
                .ok_or_else(|| StorageError::InvalidConfiguration {
                    setting: "stream.storage",
                    reason: format!(
                        "stream `{}` has no explicit storage and the writer has no shared storage",
                        config.name
                    ),
                })?;
            let encoder = JsonStateRecordEncoder::new(&config.name, &builder.spec, &config.fields)?;
            let fields = encoder
                .fields()
                .map(|name| {
                    let field = builder
                        .spec
                        .field_schema(name)
                        .expect("encoder fields were validated against this specification");
                    StateFieldMetadata {
                        name: name.to_owned(),
                        description: field.description().map(str::to_owned),
                    }
                })
                .collect::<Vec<_>>();
            declarations.push(StateStreamMetadata {
                name: config.name.clone(),
                directory: directory.clone(),
                sampling_interval: config.sampling_interval,
                fields,
                storage,
                chunks: Vec::new(),
            });
            streams.push(PreparedStateStream {
                name: config.name.clone(),
                encoder,
                sampling_interval: config.sampling_interval,
                writer: StateStreamStorageConfig::new(
                    &config.name,
                    builder.root.join(&directory),
                    storage,
                )?,
            });
        }

        let created_at_utc =
            utc_now_rfc3339().map_err(|source| StorageError::OperationalTimestamp {
                operation: "create recording",
                source,
            })?;
        let metadata = RecordingMetadata::running(
            stored_time,
            builder.user_metadata,
            declarations,
            created_at_utc,
        );
        metadata.validate(&metadata_path)?;
        Ok(Self {
            root: builder.root,
            metadata_path,
            spec: builder.spec,
            metadata,
            streams,
        })
    }
}

/// One canonical encoder paired with its immutable writer configuration.
struct PreparedStateStream {
    name: String,
    encoder: JsonStateRecordEncoder,
    sampling_interval: SamplingInterval,
    writer: StateStreamStorageConfig,
}

/// Sampling policy and encoder for one logical stream.
struct ScheduledStateStream {
    encoder: JsonStateRecordEncoder,
    sampling_interval: SamplingInterval,
    last_recorded_iteration: Option<u64>,
}

/// Serialized authority over the sole mutable metadata document.
///
/// Every worker shares this small coordinator. A transaction clones metadata,
/// validates and persists the candidate, then replaces the in-memory snapshot
/// only after the atomic filesystem commit succeeds.
pub(crate) struct RecordingManifest {
    root: PathBuf,
    path: PathBuf,
    metadata: Mutex<RecordingMetadata>,
}

impl RecordingManifest {
    /// Creates an authority from the exact snapshot already present on disk.
    fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
        Self {
            root,
            path,
            metadata: Mutex::new(metadata),
        }
    }

    /// Appends one prepared descriptor and commits it before filename sealing.
    pub(crate) fn prepare_chunk(
        &self,
        stream: &str,
        descriptor: jsonl_format::ChunkMetadata,
    ) -> Result<(), StorageError> {
        let mut current = lock_metadata(&self.metadata);
        if !matches!(current.status, RecordingStatus::Running) {
            return Err(StorageError::RecordingFinished);
        }
        let mut candidate = current.clone();
        let declaration =
            candidate
                .stream_mut(stream)
                .ok_or_else(|| StorageError::UnknownStateStream {
                    stream: stream.to_owned(),
                })?;
        let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
            StorageError::ByteCountOverflow {
                stream: stream.to_owned(),
            }
        })?;
        if descriptor.ordinal != expected {
            return Err(StorageError::InvalidMetadata {
                path: self.path.clone(),
                reason: format!(
                    "stream `{stream}` prepared chunk ordinal {}, expected {expected}",
                    descriptor.ordinal
                ),
            });
        }
        declaration.chunks.push(descriptor);
        commit_metadata(&self.root, &self.path, &candidate)?;
        *current = candidate;
        Ok(())
    }

    /// Atomically commits terminal lifecycle, timing, and user metadata.
    fn transition_terminal(
        &self,
        status: RecordingStatus,
        finalized_at_utc: String,
        active_duration_ns: u64,
        terminal_metadata: Map<String, Value>,
    ) -> Result<(), StorageError> {
        let mut current = lock_metadata(&self.metadata);
        let mut candidate = current.clone();
        candidate.status = status;
        candidate.timing.finalized_at_utc = Some(finalized_at_utc);
        candidate.timing.active_duration_ns = candidate
            .timing
            .active_duration_ns
            .checked_add(active_duration_ns)
            .ok_or(StorageError::OperationalDurationOverflow)?;
        candidate.terminal_metadata = terminal_metadata;
        commit_metadata(&self.root, &self.path, &candidate)?;
        *current = candidate;
        Ok(())
    }

    /// Clones the small durable metadata snapshot for a public terminal result.
    fn snapshot(&self) -> RecordingMetadata {
        lock_metadata(&self.metadata).clone()
    }
}

/// Advisory exclusive ownership of the output root directory itself.
///
/// Locking the directory handle creates no lockfile or status artifact and the
/// operating system releases the lease automatically after process death.
struct RecordingLease {
    _directory: File,
}

impl RecordingLease {
    /// Acquires non-blocking exclusive writer ownership.
    fn acquire(root: &Path) -> Result<Self, StorageError> {
        let directory = File::open(root).map_err(|source| StorageError::Io {
            operation: "open output root for exclusive ownership",
            path: root.to_path_buf(),
            source,
        })?;
        match FileExt::try_lock_exclusive(&directory) {
            Ok(()) => Ok(Self {
                _directory: directory,
            }),
            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
                Err(StorageError::RecordingDirectoryInUse {
                    path: root.to_path_buf(),
                })
            }
            Err(source) => Err(StorageError::Io {
                operation: "acquire exclusive output ownership",
                path: root.to_path_buf(),
                source,
            }),
        }
    }
}

/// Loads and semantically validates the authoritative metadata snapshot.
fn load_metadata(path: &Path) -> Result<RecordingMetadata, StorageError> {
    let bytes = fs::read(path).map_err(|source| StorageError::Io {
        operation: "read metadata for resume",
        path: path.to_path_buf(),
        source,
    })?;
    let metadata: RecordingMetadata =
        serde_json::from_slice(&bytes).map_err(|source| StorageError::Json {
            operation: "parse metadata for resume",
            path: path.to_path_buf(),
            source,
        })?;
    metadata.validate(path)?;
    Ok(metadata)
}

/// Compares every immutable run/stream setting while ignoring chunk progress.
fn ensure_resume_match(
    path: &Path,
    expected: &RecordingMetadata,
    existing: &RecordingMetadata,
) -> Result<(), StorageError> {
    let mut configuration = existing.clone();
    for stream in &mut configuration.streams {
        stream.chunks.clear();
    }
    configuration.status = RecordingStatus::Running;
    configuration.timing = expected.timing.clone();
    configuration.terminal_metadata.clear();
    if &configuration != expected {
        return Err(StorageError::RecordingConfigurationMismatch {
            path: path.to_path_buf(),
            reason: "builder time axis, user metadata, or stream declarations differ".to_owned(),
        });
    }
    Ok(())
}

/// Removes only the known atomic-replacement remnant after acquiring the lease.
fn remove_stale_metadata_temp(root: &Path) -> Result<(), StorageError> {
    let path = root.join(METADATA_TEMP_FILE);
    match fs::remove_file(&path) {
        Ok(()) => File::open(root)
            .and_then(|directory| directory.sync_all())
            .map_err(|source| StorageError::Io {
                operation: "synchronize stale metadata cleanup",
                path: root.to_path_buf(),
                source,
            }),
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(source) => Err(StorageError::Io {
            operation: "remove stale temporary metadata",
            path,
            source,
        }),
    }
}

/// Locks the metadata snapshot while recovering from a participant panic.
fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
    metadata
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Rejects every existing filesystem object and preserves IO inspection errors.
fn ensure_absent(root: &Path) -> Result<(), StorageError> {
    match root.try_exists() {
        Ok(false) => Ok(()),
        Ok(true) => Err(StorageError::RecordingDirectoryExists {
            path: root.to_path_buf(),
        }),
        Err(source) => Err(StorageError::Io {
            operation: "inspect output root",
            path: root.to_path_buf(),
            source,
        }),
    }
}

/// Exclusively creates the run root, closing the check/create race safely.
fn create_root(root: &Path) -> Result<(), StorageError> {
    if let Some(parent) = root.parent() {
        fs::create_dir_all(parent).map_err(|source| StorageError::Io {
            operation: "create recording parent directories",
            path: parent.to_path_buf(),
            source,
        })?;
    }
    match fs::create_dir(root) {
        Ok(()) => Ok(()),
        Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
            Err(StorageError::RecordingDirectoryExists {
                path: root.to_path_buf(),
            })
        }
        Err(source) => Err(StorageError::Io {
            operation: "create output root",
            path: root.to_path_buf(),
            source,
        }),
    }
}

/// Atomically replaces the sole authoritative metadata document.
///
/// The temporary file is created exclusively, serialized once, flushed with
/// `sync_all`, renamed over the previous snapshot, and followed by a directory
/// sync. A failed attempt removes only its precisely owned temporary path when
/// possible; the previous authoritative metadata remains untouched until the
/// rename succeeds.
fn commit_metadata(
    root: &Path,
    metadata_path: &Path,
    metadata: &RecordingMetadata,
) -> Result<(), StorageError> {
    metadata.validate(metadata_path)?;
    let mut bytes = serde_json::to_vec_pretty(metadata).map_err(|source| StorageError::Json {
        operation: "serialize metadata",
        path: metadata_path.to_path_buf(),
        source,
    })?;
    bytes.push(b'\n');

    let temporary_path = root.join(METADATA_TEMP_FILE);
    let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
    if result.is_err() {
        let _ = fs::remove_file(&temporary_path);
    }
    result
}

/// Performs the fallible filesystem portion of one metadata transaction.
fn write_and_replace_metadata(
    root: &Path,
    metadata_path: &Path,
    temporary_path: &Path,
    bytes: &[u8],
) -> Result<(), StorageError> {
    let mut temporary = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(temporary_path)
        .map_err(|source| StorageError::Io {
            operation: "create temporary metadata",
            path: temporary_path.to_path_buf(),
            source,
        })?;
    temporary
        .write_all(bytes)
        .map_err(|source| StorageError::Io {
            operation: "write temporary metadata",
            path: temporary_path.to_path_buf(),
            source,
        })?;
    temporary.sync_all().map_err(|source| StorageError::Io {
        operation: "sync temporary metadata",
        path: temporary_path.to_path_buf(),
        source,
    })?;
    drop(temporary);

    fs::rename(temporary_path, metadata_path).map_err(|source| StorageError::Io {
        operation: "publish metadata",
        path: metadata_path.to_path_buf(),
        source,
    })?;

    File::open(root)
        .and_then(|directory| directory.sync_all())
        .map_err(|source| StorageError::Io {
            operation: "sync output root",
            path: root.to_path_buf(),
            source,
        })
}