1use chrono::{DateTime, Utc};
7use datasynth_config::schema::GeneratorConfig;
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10use std::collections::HashMap;
11use std::fs::File;
12use std::io::{self, BufReader, Read as _, Write};
13use std::path::Path;
14use uuid::Uuid;
15
16use super::EnhancedGenerationStatistics;
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct RunManifest {
21 #[serde(default = "default_manifest_version")]
23 pub manifest_version: String,
24 pub run_id: String,
26 pub started_at: DateTime<Utc>,
28 pub completed_at: Option<DateTime<Utc>>,
30 pub config_hash: String,
32 pub config_snapshot: GeneratorConfig,
34 pub seed: u64,
36 #[serde(default)]
38 pub scenario_tags: Vec<String>,
39 #[serde(default)]
41 pub statistics: Option<EnhancedGenerationStatistics>,
42 pub duration_seconds: Option<f64>,
44 pub generator_version: String,
46 #[serde(default)]
48 pub metadata: HashMap<String, String>,
49 pub output_directory: Option<String>,
51 #[serde(default)]
53 pub output_files: Vec<OutputFileInfo>,
54 #[serde(default)]
56 pub warnings: Vec<String>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub lineage: Option<super::lineage::LineageGraph>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub quality_gate_result: Option<QualityGateResultSummary>,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub llm_enrichment: Option<LlmEnrichmentSummary>,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub diffusion_model: Option<DiffusionModelSummary>,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub causal_generation: Option<CausalGenerationSummary>,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct LlmEnrichmentSummary {
77 pub enabled: bool,
79 pub timing_ms: u64,
81 pub vendors_enriched: usize,
83 pub provider: String,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct DiffusionModelSummary {
90 pub enabled: bool,
92 pub timing_ms: u64,
94 pub samples_generated: usize,
96 pub n_steps: usize,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct CausalGenerationSummary {
103 pub enabled: bool,
105 pub timing_ms: u64,
107 pub samples_generated: usize,
109 pub template: String,
111 pub validation_passed: Option<bool>,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct QualityGateResultSummary {
118 pub passed: bool,
120 pub profile_name: String,
122 pub gates_passed: usize,
124 pub gates_total: usize,
126 pub failed_gates: Vec<String>,
128}
129
130fn default_manifest_version() -> String {
131 "2.0".to_string()
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct OutputFileInfo {
137 pub path: String,
139 pub format: String,
141 pub record_count: Option<usize>,
143 pub size_bytes: Option<u64>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub sha256_checksum: Option<String>,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub first_record_index: Option<u64>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub last_record_index: Option<u64>,
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct ChecksumVerificationResult {
159 pub path: String,
161 pub status: ChecksumStatus,
163 pub expected: Option<String>,
165 pub actual: Option<String>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub enum ChecksumStatus {
172 Ok,
174 Mismatch,
176 Missing,
178 NoChecksum,
180}
181
182pub fn compute_file_checksum(path: &Path) -> io::Result<String> {
184 let file = File::open(path)?;
185 let mut reader = BufReader::new(file);
186 let mut hasher = Sha256::new();
187 let mut buffer = [0u8; 8192];
188 loop {
189 let bytes_read = reader.read(&mut buffer)?;
190 if bytes_read == 0 {
191 break;
192 }
193 hasher.update(&buffer[..bytes_read]);
194 }
195 Ok(hex::encode(hasher.finalize()))
196}
197
198impl RunManifest {
199 pub fn new(config: &GeneratorConfig, seed: u64) -> Self {
201 let run_id = Uuid::new_v4().to_string();
202 let config_hash = Self::hash_config(config);
203
204 Self {
205 manifest_version: "2.0".to_string(),
206 run_id,
207 started_at: Utc::now(),
208 completed_at: None,
209 config_hash,
210 config_snapshot: config.clone(),
211 seed,
212 scenario_tags: Vec::new(),
213 statistics: None,
214 duration_seconds: None,
215 generator_version: env!("CARGO_PKG_VERSION").to_string(),
216 metadata: HashMap::new(),
217 output_directory: None,
218 output_files: Vec::new(),
219 warnings: Vec::new(),
220 lineage: None,
221 quality_gate_result: None,
222 llm_enrichment: None,
223 diffusion_model: None,
224 causal_generation: None,
225 }
226 }
227
228 fn hash_config(config: &GeneratorConfig) -> String {
230 let json = serde_json::to_string(config).unwrap_or_default();
231 let mut hasher = Sha256::new();
232 hasher.update(json.as_bytes());
233 let result = hasher.finalize();
234 hex::encode(result)
235 }
236
237 pub fn complete(&mut self, statistics: EnhancedGenerationStatistics) {
239 self.completed_at = Some(Utc::now());
240 self.duration_seconds = Some(
241 (self.completed_at.expect("completed_at just set above") - self.started_at)
242 .num_milliseconds() as f64
243 / 1000.0,
244 );
245 self.statistics = Some(statistics);
246 }
247
248 pub fn add_tag(&mut self, tag: &str) {
250 if !self.scenario_tags.contains(&tag.to_string()) {
251 self.scenario_tags.push(tag.to_string());
252 }
253 }
254
255 pub fn add_tags(&mut self, tags: &[String]) {
257 for tag in tags {
258 self.add_tag(tag);
259 }
260 }
261
262 pub fn set_output_directory(&mut self, path: &Path) {
264 self.output_directory = Some(path.display().to_string());
265 }
266
267 pub fn add_output_file(&mut self, info: OutputFileInfo) {
269 self.output_files.push(info);
270 }
271
272 pub fn add_warning(&mut self, warning: &str) {
274 self.warnings.push(warning.to_string());
275 }
276
277 pub fn add_metadata(&mut self, key: &str, value: &str) {
279 self.metadata.insert(key.to_string(), value.to_string());
280 }
281
282 pub fn populate_file_checksums(&mut self, base_dir: &Path) {
287 for file_info in &mut self.output_files {
288 let file_path = base_dir.join(&file_info.path);
289 if file_path.exists() {
290 if let Ok(checksum) = compute_file_checksum(&file_path) {
291 file_info.sha256_checksum = Some(checksum);
292 }
293 if file_info.size_bytes.is_none() {
294 if let Ok(metadata) = std::fs::metadata(&file_path) {
295 file_info.size_bytes = Some(metadata.len());
296 }
297 }
298 }
299 }
300 }
301
302 pub fn verify_file_checksums(&self, base_dir: &Path) -> Vec<ChecksumVerificationResult> {
304 self.output_files
305 .iter()
306 .map(|file_info| {
307 let file_path = base_dir.join(&file_info.path);
308
309 let expected = file_info.sha256_checksum.clone();
310 if expected.is_none() {
311 return ChecksumVerificationResult {
312 path: file_info.path.clone(),
313 status: ChecksumStatus::NoChecksum,
314 expected: None,
315 actual: None,
316 };
317 }
318
319 if !file_path.exists() {
320 return ChecksumVerificationResult {
321 path: file_info.path.clone(),
322 status: ChecksumStatus::Missing,
323 expected,
324 actual: None,
325 };
326 }
327
328 match compute_file_checksum(&file_path) {
329 Ok(actual) => {
330 let status = if expected.as_deref() == Some(actual.as_str()) {
331 ChecksumStatus::Ok
332 } else {
333 ChecksumStatus::Mismatch
334 };
335 ChecksumVerificationResult {
336 path: file_info.path.clone(),
337 status,
338 expected,
339 actual: Some(actual),
340 }
341 }
342 Err(_) => ChecksumVerificationResult {
343 path: file_info.path.clone(),
344 status: ChecksumStatus::Missing,
345 expected,
346 actual: None,
347 },
348 }
349 })
350 .collect()
351 }
352
353 pub fn write_to_file(&self, path: &Path) -> std::io::Result<()> {
355 let json = serde_json::to_string_pretty(self)?;
356 let mut file = File::create(path)?;
357 file.write_all(json.as_bytes())?;
358 Ok(())
359 }
360
361 pub fn run_id(&self) -> &str {
363 &self.run_id
364 }
365}
366
367#[cfg(test)]
371#[allow(clippy::unwrap_used)]
372mod tests {
373 use super::*;
374 use datasynth_config::schema::*;
375
376 fn create_test_config() -> GeneratorConfig {
377 GeneratorConfig {
378 global: GlobalConfig {
379 industry: datasynth_core::models::IndustrySector::Manufacturing,
380 start_date: "2024-01-01".to_string(),
381 period_months: 1,
382 seed: Some(42),
383 parallel: false,
384 group_currency: "USD".to_string(),
385 worker_threads: 1,
386 memory_limit_mb: 512,
387 },
388 companies: vec![CompanyConfig {
389 code: "TEST".to_string(),
390 name: "Test Company".to_string(),
391 currency: "USD".to_string(),
392 country: "US".to_string(),
393 annual_transaction_volume: TransactionVolume::TenK,
394 volume_weight: 1.0,
395 fiscal_year_variant: "K4".to_string(),
396 }],
397 chart_of_accounts: ChartOfAccountsConfig::default(),
398 transactions: TransactionConfig::default(),
399 output: OutputConfig::default(),
400 fraud: FraudConfig::default(),
401 internal_controls: InternalControlsConfig::default(),
402 business_processes: BusinessProcessConfig::default(),
403 user_personas: UserPersonaConfig::default(),
404 templates: TemplateConfig::default(),
405 approval: ApprovalConfig::default(),
406 departments: DepartmentConfig::default(),
407 master_data: MasterDataConfig::default(),
408 document_flows: DocumentFlowConfig::default(),
409 intercompany: IntercompanyConfig::default(),
410 balance: BalanceConfig::default(),
411 ocpm: OcpmConfig::default(),
412 audit: AuditGenerationConfig::default(),
413 banking: datasynth_banking::BankingConfig::default(),
414 data_quality: DataQualitySchemaConfig::default(),
415 scenario: ScenarioConfig::default(),
416 temporal: TemporalDriftConfig::default(),
417 graph_export: GraphExportConfig::default(),
418 streaming: StreamingSchemaConfig::default(),
419 rate_limit: RateLimitSchemaConfig::default(),
420 temporal_attributes: TemporalAttributeSchemaConfig::default(),
421 relationships: RelationshipSchemaConfig::default(),
422 accounting_standards: AccountingStandardsConfig::default(),
423 audit_standards: AuditStandardsConfig::default(),
424 distributions: Default::default(),
425 temporal_patterns: Default::default(),
426 vendor_network: VendorNetworkSchemaConfig::default(),
427 customer_segmentation: CustomerSegmentationSchemaConfig::default(),
428 relationship_strength: RelationshipStrengthSchemaConfig::default(),
429 cross_process_links: CrossProcessLinksSchemaConfig::default(),
430 organizational_events: OrganizationalEventsSchemaConfig::default(),
431 behavioral_drift: BehavioralDriftSchemaConfig::default(),
432 market_drift: MarketDriftSchemaConfig::default(),
433 drift_labeling: DriftLabelingSchemaConfig::default(),
434 anomaly_injection: Default::default(),
435 industry_specific: Default::default(),
436 fingerprint_privacy: Default::default(),
437 quality_gates: Default::default(),
438 compliance: Default::default(),
439 webhooks: Default::default(),
440 llm: Default::default(),
441 diffusion: Default::default(),
442 causal: Default::default(),
443 }
444 }
445
446 #[test]
447 fn test_run_manifest_creation() {
448 let config = create_test_config();
449 let manifest = RunManifest::new(&config, 42);
450
451 assert!(!manifest.run_id.is_empty());
452 assert_eq!(manifest.seed, 42);
453 assert!(!manifest.config_hash.is_empty());
454 assert!(manifest.completed_at.is_none());
455 }
456
457 #[test]
458 fn test_run_manifest_completion() {
459 let config = create_test_config();
460 let mut manifest = RunManifest::new(&config, 42);
461
462 std::thread::sleep(std::time::Duration::from_millis(10));
464
465 let stats = EnhancedGenerationStatistics {
466 total_entries: 100,
467 total_line_items: 500,
468 ..Default::default()
469 };
470 manifest.complete(stats);
471
472 assert!(manifest.completed_at.is_some());
473 assert!(manifest.duration_seconds.unwrap() >= 0.01);
474 assert_eq!(manifest.statistics.as_ref().unwrap().total_entries, 100);
475 }
476
477 #[test]
478 fn test_config_hash_consistency() {
479 let config = create_test_config();
480 let hash1 = RunManifest::hash_config(&config);
481 let hash2 = RunManifest::hash_config(&config);
482
483 assert_eq!(hash1, hash2);
484 }
485
486 #[test]
487 fn test_scenario_tags() {
488 let config = create_test_config();
489 let mut manifest = RunManifest::new(&config, 42);
490
491 manifest.add_tag("fraud_detection");
492 manifest.add_tag("retail");
493 manifest.add_tag("fraud_detection"); assert_eq!(manifest.scenario_tags.len(), 2);
496 assert!(manifest
497 .scenario_tags
498 .contains(&"fraud_detection".to_string()));
499 assert!(manifest.scenario_tags.contains(&"retail".to_string()));
500 }
501
502 #[test]
503 fn test_output_file_tracking() {
504 let config = create_test_config();
505 let mut manifest = RunManifest::new(&config, 42);
506
507 manifest.add_output_file(OutputFileInfo {
508 path: "journal_entries.csv".to_string(),
509 format: "csv".to_string(),
510 record_count: Some(1000),
511 size_bytes: Some(102400),
512 sha256_checksum: None,
513 first_record_index: None,
514 last_record_index: None,
515 });
516
517 assert_eq!(manifest.output_files.len(), 1);
518 assert_eq!(manifest.output_files[0].record_count, Some(1000));
519 }
520
521 #[test]
522 fn test_manifest_version() {
523 let config = create_test_config();
524 let manifest = RunManifest::new(&config, 42);
525 assert_eq!(manifest.manifest_version, "2.0");
526 }
527
528 #[test]
529 fn test_backward_compat_deserialize() {
530 let old_json = r#"{
532 "run_id": "test-123",
533 "started_at": "2024-01-01T00:00:00Z",
534 "completed_at": null,
535 "config_hash": "abc123",
536 "config_snapshot": null,
537 "seed": 42,
538 "duration_seconds": null,
539 "generator_version": "0.4.0",
540 "output_directory": null,
541 "output_files": [
542 {
543 "path": "data.csv",
544 "format": "csv",
545 "record_count": 100,
546 "size_bytes": 1024
547 }
548 ]
549 }"#;
550
551 let result: Result<serde_json::Value, _> = serde_json::from_str(old_json);
554 assert!(result.is_ok());
555 }
556
557 #[test]
558 fn test_checksum_computation() {
559 let dir = tempfile::tempdir().expect("create temp dir");
560 let file_path = dir.path().join("test.txt");
561 std::fs::write(&file_path, b"hello world").expect("write file");
562
563 let checksum = compute_file_checksum(&file_path).expect("compute checksum");
564 assert_eq!(
566 checksum,
567 "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
568 );
569 }
570
571 #[test]
572 fn test_populate_and_verify_checksums() {
573 let dir = tempfile::tempdir().expect("create temp dir");
574 let file_path = dir.path().join("data.csv");
575 std::fs::write(&file_path, b"id,name\n1,Alice\n2,Bob\n").expect("write file");
576
577 let config = create_test_config();
578 let mut manifest = RunManifest::new(&config, 42);
579 manifest.add_output_file(OutputFileInfo {
580 path: "data.csv".to_string(),
581 format: "csv".to_string(),
582 record_count: Some(2),
583 size_bytes: None,
584 sha256_checksum: None,
585 first_record_index: None,
586 last_record_index: None,
587 });
588
589 manifest.populate_file_checksums(dir.path());
590
591 assert!(manifest.output_files[0].sha256_checksum.is_some());
592 assert!(manifest.output_files[0].size_bytes.is_some());
593
594 let results = manifest.verify_file_checksums(dir.path());
596 assert_eq!(results.len(), 1);
597 assert_eq!(results[0].status, ChecksumStatus::Ok);
598 }
599
600 #[test]
601 fn test_verify_detects_mismatch() {
602 let dir = tempfile::tempdir().expect("create temp dir");
603 let file_path = dir.path().join("data.csv");
604 std::fs::write(&file_path, b"original content").expect("write file");
605
606 let config = create_test_config();
607 let mut manifest = RunManifest::new(&config, 42);
608 manifest.add_output_file(OutputFileInfo {
609 path: "data.csv".to_string(),
610 format: "csv".to_string(),
611 record_count: None,
612 size_bytes: None,
613 sha256_checksum: None,
614 first_record_index: None,
615 last_record_index: None,
616 });
617
618 manifest.populate_file_checksums(dir.path());
619
620 std::fs::write(&file_path, b"modified content").expect("write file");
622
623 let results = manifest.verify_file_checksums(dir.path());
624 assert_eq!(results[0].status, ChecksumStatus::Mismatch);
625 }
626
627 #[test]
628 fn test_verify_missing_file() {
629 let dir = tempfile::tempdir().expect("create temp dir");
630
631 let config = create_test_config();
632 let mut manifest = RunManifest::new(&config, 42);
633 manifest.add_output_file(OutputFileInfo {
634 path: "nonexistent.csv".to_string(),
635 format: "csv".to_string(),
636 record_count: None,
637 size_bytes: None,
638 sha256_checksum: Some("abc123".to_string()),
639 first_record_index: None,
640 last_record_index: None,
641 });
642
643 let results = manifest.verify_file_checksums(dir.path());
644 assert_eq!(results[0].status, ChecksumStatus::Missing);
645 }
646
647 #[test]
648 fn test_verify_no_checksum() {
649 let dir = tempfile::tempdir().expect("create temp dir");
650
651 let config = create_test_config();
652 let mut manifest = RunManifest::new(&config, 42);
653 manifest.add_output_file(OutputFileInfo {
654 path: "data.csv".to_string(),
655 format: "csv".to_string(),
656 record_count: None,
657 size_bytes: None,
658 sha256_checksum: None,
659 first_record_index: None,
660 last_record_index: None,
661 });
662
663 let results = manifest.verify_file_checksums(dir.path());
664 assert_eq!(results[0].status, ChecksumStatus::NoChecksum);
665 }
666}