Archive native training 2026-10-08 manifest 55e57f14c331c9a0a4cab71d6c237d5436e691a2f2862b2734844db400e284c8
b60a0ad verified Download native_training_20261008/native/source/owned_stream_controller.rs from TryDotAtwo/quantum-generator: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/datasets/TryDotAtwo/quantum-generator/resolve/main/native_training_20261008/native/source/owned_stream_controller.rs
- Command line
-
hf download hf://datasets/TryDotAtwo/quantum-generator/native_training_20261008/native/source/owned_stream_controller.rs
-
curl -L -o owned_stream_controller.rs https://huggingface.co/datasets/TryDotAtwo/quantum-generator/resolve/main/native_training_20261008/native/source/owned_stream_controller.rs
18.4 kB
| //! One Rust CUDA/compiler/registry owner for the normative 1000-epoch stream. | |
| //! Per-epoch stores are retained. Verified HF archival/rotation is not implemented here. | |
| use crate::{native_epoch_owner::{NativeEpochOwner,EpochOwnerConfig,BankMode},holdout_views}; | |
| use serde_json::{Value,json}; | |
| use std::{path::{Path,PathBuf},io::{Write,Read}}; | |
| fn read(path:&Path)->Result<Value,String>{serde_json::from_slice(&std::fs::read(path).map_err(|e|e.to_string())?).map_err(|e|e.to_string())} | |
| fn write_new(path:&Path,value:&Value)->Result<(),String>{let mut file=std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e|e.to_string())?;file.write_all(&serde_json::to_vec_pretty(value).map_err(|e|e.to_string())?).map_err(|e|e.to_string())?;file.sync_all().map_err(|e|e.to_string())} | |
| fn sha_file(path:&Path)->Result<String,String>{Ok(holdout_views::sha(&std::fs::read(path).map_err(|e|e.to_string())?))} | |
| fn sha_database(path:&Path)->Result<String,String>{ | |
| let mut wal=path.as_os_str().to_os_string();wal.push("-wal"); | |
| match std::fs::metadata(Path::new(&wal)){Ok(meta) if meta.len()!=0=>return Err("checkpointed database required; nonempty WAL remains".into()),Ok(_)=>(),Err(error) if error.kind()==std::io::ErrorKind::NotFound=>(),Err(error)=>return Err(error.to_string())} | |
| use sha2::Digest;let mut file=std::fs::File::open(path).map_err(|e|e.to_string())?;let mut hash=sha2::Sha256::new();let mut buffer=[0u8;65536];loop{let n=file.read(&mut buffer).map_err(|e|e.to_string())?;if n==0{break;}hash.update(&buffer[..n]);}Ok(format!("{:x}",hash.finalize())) | |
| } | |
| fn lock(path:&Path)->Result<std::fs::File,String>{ | |
| let mut options=std::fs::OpenOptions::new();options.read(true).write(true).create(true).truncate(false); | |
| {use std::os::windows::fs::OpenOptionsExt;options.share_mode(0);} | |
| let file=options.open(path).map_err(|e|format!("owned stream unavailable: {e}"))?; | |
| {use std::os::fd::AsRawFd;unsafe extern "C"{fn flock(fd:i32,operation:i32)->i32;}if unsafe{flock(file.as_raw_fd(),2|4)}!=0{return Err("owned stream already running".into());}} | |
| Ok(file) | |
| } | |
| fn validate_epoch(value:&Value,epoch:u32,bank:&Value,prefix:bool)->Result<(),String>{ | |
| let existing=value["already_present"].as_u64().ok_or("resume count absent")?; | |
| let fresh=value["new_roots"].as_u64().ok_or("fresh count absent")?; | |
| if value["completed"]!=true||value["epoch"]!=epoch||value["requested_roots"]!=10000||value["total_roots_in_epoch"]!=10000||existing.checked_add(fresh)!=Some(10000)||value["normative_epochs"]!=1000||value["new_unique_roots_per_epoch"]!=10000||value["source_files_verified"]!=44||value["bank_manifest_sha256"]!=bank["bank_manifest_sha256"]||value["python_executed"]!=false||value["admission_policy"]!=crate::mapped_publication::POLICY||value["reader_suffix_count"]!=1||value["reader_augment_suffix"]!=true||value["all_existing_resumed_rows_read_in_this_run"]!=true||value["reader_batches_admitted_before_any_record_returned"].as_u64()!=Some(fresh)||value["resumed_reader_batches_admitted"].as_u64().unwrap_or(0)!=existing||value["bank_admission_backend"]!=if prefix{"cuda_prefix_full_sha256"}else{"cuda_full_sha256"}{return Err("complete owned epoch receipt mismatch".into());}Ok(()) | |
| } | |
| fn receipt_slot(directory:&Path,epoch:u32,bank:&Value,prefix:bool)->Result<(PathBuf,bool),String>{ | |
| for attempt in 0..u32::MAX { | |
| let path=directory.join(format!("attempt_{attempt:08}.json")); | |
| if !path.exists(){if path.with_extension("heartbeat.json").exists()||path.with_extension("heartbeat.tmp").exists(){continue;}return Ok((path,false));} | |
| // A torn directly-written epoch receipt is retained. It never authorizes a | |
| // skip: the next attempt runs actual durable/registry/reader reconciliation. | |
| let raw=std::fs::read(&path).map_err(|e|e.to_string())?; | |
| let saved:Value=match serde_json::from_slice(&raw){Ok(value)=>value,Err(_)=>continue}; | |
| if saved["completed"]==true{validate_epoch(&saved,epoch,bank,prefix)?;return Ok((path,true));} | |
| }Err("epoch attempt space exhausted".into()) | |
| } | |
| fn config_binding(config:&EpochOwnerConfig)->Value{ let prefix=config.mode==BankMode::Prefix; let binding=json!({"schema":"own_native_owned_stream_v1","epochs":1000,"roots_per_epoch":10000, | |
| "bank":config.bank_directory,"proof":config.bank_proof,"source":config.source_root, | |
| "general":config.general_library,"shear":config.shear_library,"runtime":config.cuda_runtime, | |
| "gaussian":config.gaussian_kernel,"kernel":config.bank_kernel,"registry":config.registry_directory, | |
| "prefix":prefix,"approved_library_sha256":config.approved_library_sha256,"approved_bank_proof_sha256":config.approved_bank_proof_sha256}); | |
| binding} | |
| /// Explicit preparation phase for one already completed epoch; no upload or eviction. | |
| pub fn prepare_epoch_archive(config:EpochOwnerConfig,output:&Path,epoch:u32,archive_directory:&Path)->Result<Value,String>{ | |
| if epoch>=1000{return Err("normative archive epoch range is 0..999".into());} | |
| let output=crate::windows_path_policy::writable_target(output)?; | |
| if !output.join("owned_stream_manifest.json").is_file(){return Err("existing owned stream manifest required".into());} | |
| let _owner_lock=lock(&output.join("owned-stream.lock"))?;let prefix=config.mode==BankMode::Prefix;let expected_config=config_binding(&config); | |
| let mut owner=NativeEpochOwner::open(config)?; | |
| let expected=json!({"config":expected_config,"source_manifest":owner.source_manifest(),"bank_seal":owner.bank_seal()}); | |
| let manifest=output.join("owned_stream_manifest.json");if read(&manifest)?!=expected{return Err("archive preparation owned stream binding drift".into());} | |
| let epoch_directory=output.join(format!("epoch_{epoch:04}"));let(receipt,complete)=receipt_slot(&epoch_directory,epoch,owner.bank_seal(),prefix)?; | |
| if !complete{return Err("completed epoch receipt required before archive preparation".into());} | |
| let directory=crate::windows_path_policy::writable_target(archive_directory)?;std::fs::create_dir(&directory).map_err(|e|e.to_string())?; | |
| let snapshot=owner.snapshot_completed_epoch(&epoch_directory.join("train.sqlite"),epoch,&directory.join("snapshot.sqlite"))?; | |
| let prepared=json!({"schema":"own_native_controller_epoch_archive_preparation_v1","epoch":epoch,"owned_stream_manifest_sha256":sha_file(&manifest)?,"epoch_receipt_sha256":sha_file(&receipt)?,"owner_preparation":snapshot,"remote_http_verified":false,"durable_remote_anchor_created":false,"local_eviction_performed":false,"controller_resume_from_remote_verified":false}); | |
| write_new(&directory.join("preparation.json"),&prepared)?;Ok(prepared) | |
| }/// Restore only from a preparation receipt authenticated by a separate durable archive anchor. | |
| /// This does not authenticate arbitrary JSON, download HF data, or rewrite campaign completion. | |
| fn validate_restore_preparation(value:&Value,epoch:u32)->Result<(),String>{if epoch>=1000||value["schema"]!="own_native_controller_epoch_archive_preparation_v1"||value["epoch"]!=epoch||value["owner_preparation"]["epoch"]!=epoch||value["owner_preparation"]["all_four_reader_modes_verified"]!=true||value["owner_preparation"]["reader_mode_batches_verified"]!=40000||value["owner_preparation"]["snapshot"]["epoch"]!=epoch{return Err("trusted full epoch controller archive preparation required".into());}Ok(())} | |
| fn persist_revalidated_restore_receipt(receipt:&Path,result:&Value)->Result<(),String>{ | |
| match std::fs::symlink_metadata(receipt){ | |
| Err(e) if e.kind()==std::io::ErrorKind::NotFound=>write_new(receipt,result), | |
| Ok(meta) if meta.file_type().is_file()=>{if read(receipt)?!=*result{return Err("existing restore receipt differs from revalidated result".into());}Ok(())}, | |
| _=>Err("restore receipt path unavailable".into()) | |
| } | |
| } | |
| pub fn restore_epoch_archive(config:EpochOwnerConfig,output:&Path,epoch:u32,source:&Path,trusted_preparation:&Value)->Result<Value,String>{ | |
| validate_restore_preparation(trusted_preparation,epoch)?; | |
| let output=crate::windows_path_policy::writable_target(output)?;let manifest=output.join("owned_stream_manifest.json");if !manifest.is_file()||!config.registry_directory.join("index.sqlite").is_file(){return Err("existing stream manifest and exact registry required for restore".into());} | |
| let _owner_lock=lock(&output.join("owned-stream.lock"))?;let prefix=config.mode==BankMode::Prefix;let expected_config=config_binding(&config); | |
| let mut owner=NativeEpochOwner::open(config)?;let expected=json!({"config":expected_config,"source_manifest":owner.source_manifest(),"bank_seal":owner.bank_seal()}); | |
| if read(&manifest)?!=expected||trusted_preparation["owned_stream_manifest_sha256"]!=sha_file(&manifest)?{return Err("restore owned stream manifest binding drift".into());} | |
| let directory=output.join(format!("epoch_{epoch:04}"));let(receipt,complete)=receipt_slot(&directory,epoch,owner.bank_seal(),prefix)?; | |
| if !complete||trusted_preparation["epoch_receipt_sha256"]!=sha_file(&receipt)?{return Err("restore original complete epoch receipt required".into());} | |
| let target=directory.join("train.sqlite");let exists=match std::fs::symlink_metadata(&target){Err(e) if e.kind()==std::io::ErrorKind::NotFound=>false,Ok(meta) if meta.file_type().is_file()=>true,_=>return Err("restore requires regular owned SQLite or absent target".into())}; | |
| let restored=if exists{owner.verify_restored_completed_epoch(&target,&trusted_preparation["owner_preparation"]["snapshot"])?}else{owner.restore_completed_epoch(source,&target,&trusted_preparation["owner_preparation"]["snapshot"])?}; | |
| let result=json!({"schema":"own_native_controller_epoch_local_restore_v1","epoch":epoch,"owner_restore":restored,"owned_stream_manifest_sha256":sha_file(&manifest)?,"epoch_receipt_sha256":sha_file(&receipt)?,"controller_campaign_resume_verified":false,"remote_http_verified":false,"prior_campaign_complete_rewritten":false}); | |
| let receipt=directory.join("archive_local_restore.json");persist_revalidated_restore_receipt(&receipt,&result)?;Ok(result) | |
| }pub fn run_stream(config:EpochOwnerConfig,output:&Path)->Result<(),String>{ | |
| let output=crate::windows_path_policy::writable_target(output)?; | |
| std::fs::create_dir_all(&output).map_err(|e|e.to_string())?; | |
| let _owner_lock=lock(&output.join("owned-stream.lock"))?; | |
| let prefix=config.mode==BankMode::Prefix; | |
| // Configuration equality prevents a restart from changing approved libraries, | |
| // source paths, registry owner or mode while retaining old completed receipts. | |
| let binding=config_binding(&config); | |
| let mut owner=NativeEpochOwner::open(config)?; | |
| let binding=json!({"config":binding,"source_manifest":owner.source_manifest(),"bank_seal":owner.bank_seal()}); | |
| let manifest=output.join("owned_stream_manifest.json"); | |
| if manifest.exists(){if read(&manifest)?!=binding{return Err("immutable owned stream binding drift".into());}}else{write_new(&manifest,&binding)?;} | |
| let mut epochs=Vec::with_capacity(1000); | |
| for epoch in 0..1000u32 { | |
| let directory=output.join(format!("epoch_{epoch:04}"));std::fs::create_dir_all(&directory).map_err(|e|e.to_string())?; | |
| let database=directory.join("train.sqlite"); | |
| let (receipt,prior_complete)=receipt_slot(&directory,epoch,owner.bank_seal(),prefix)?; | |
| if prior_complete { | |
| let audit=owner.audit_completed_epoch(&database,epoch)?; | |
| let mut attempt=0u32;let audit_path=loop{let path=directory.join(format!("restart_audit_{attempt:08}.json"));if !path.exists(){break path;}attempt=attempt.checked_add(1).ok_or("restart audit attempt overflow")?;}; | |
| write_new(&audit_path,&json!({"epoch":epoch,"completed":true,"actual_mapped_main_reader_batches":10000,"durable_audit":audit,"receipt_sha256":sha_file(&receipt)?,"global_exact_registry_count":owner.global_committed_roots()?}))?; | |
| } | |
| else { | |
| owner.generate_complete_epoch(&database,epoch,&receipt)?; | |
| validate_epoch(&read(&receipt)?,epoch,owner.bank_seal(),prefix)?; | |
| } | |
| if owner.global_committed_roots()?<(epoch as u64+1)*10000{return Err("global exact root prefix incomplete".into());} | |
| let audit=crate::native_store::inspect_existing_train_v2(&database)?; | |
| if audit["rows"]!=10000||audit["epoch_prefixes"]!=json!({epoch.to_string():10000}){return Err("one complete normative epoch per database required".into());} | |
| epochs.push(json!({"epoch":epoch,"receipt":receipt,"receipt_sha256":sha_file(&receipt)?,"database":database,"database_sha256":sha_database(&database)?,"roots":10000})); | |
| } | |
| owner.verify_inputs()?; | |
| if owner.global_committed_roots()?!=10000000{return Err("normative 10M exact registry count required".into());} | |
| for entry in &epochs { | |
| let database=Path::new(entry["database"].as_str().ok_or("database path missing")?); | |
| let receipt=Path::new(entry["receipt"].as_str().ok_or("receipt path missing")?); | |
| if entry["database_sha256"]!=sha_database(database)?||entry["receipt_sha256"]!=sha_file(receipt)?{return Err("epoch changed after complete admission audit".into());} | |
| } | |
| let complete=json!({"schema":"own_native_owned_1000_epoch_receipt_v1","completed":true,"epochs":1000,"unique_train_roots":10000000, | |
| "manifest_sha256":sha_file(&manifest)?,"epoch_receipts":epochs,"one_compute_owner":true,"python_executed":false, | |
| "hf_archive_rotation_verified":false,"native_training_verified":false,"full_speedup_verified":false}); | |
| let destination=output.join("owned_stream_complete.json"); | |
| if destination.exists(){if read(&destination)?!=complete{return Err("prior owned completion drift".into());}}else{write_new(&destination,&complete)?;} | |
| Ok(()) | |
| } | |
| mod tests { | |
| fn revalidated_restore_receipt_is_idempotent_and_preserves_conflicts(){ | |
| let directory=std::env::temp_dir().join(format!("owned-restore-receipt-{}-{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));std::fs::create_dir(&directory).unwrap(); | |
| let receipt=directory.join("receipt.json");let good=json!({"epoch":7,"snapshot_sha256":"original","reader_modes":40000}); | |
| persist_revalidated_restore_receipt(&receipt,&good).unwrap();let original=std::fs::read(&receipt).unwrap();persist_revalidated_restore_receipt(&receipt,&good).unwrap();assert_eq!(std::fs::read(&receipt).unwrap(),original); | |
| let mut wrong=good.clone();wrong["epoch"]=json!(8);assert!(persist_revalidated_restore_receipt(&receipt,&wrong).is_err());assert_eq!(std::fs::read(&receipt).unwrap(),original); | |
| let torn=directory.join("torn.json");std::fs::write(&torn,b"{\"epoch\":7,").unwrap();assert!(persist_revalidated_restore_receipt(&torn,&good).is_err());assert_eq!(std::fs::read(&torn).unwrap(),b"{\"epoch\":7,"); | |
| let occupied=directory.join("occupied");std::fs::create_dir(&occupied).unwrap();assert!(persist_revalidated_restore_receipt(&occupied,&good).is_err());assert!(occupied.is_dir()); | |
| } | |
| use super::*; | |
| fn fixture()->Value{json!({"completed":true,"epoch":0,"requested_roots":10000,"total_roots_in_epoch":10000,"already_present":12,"new_roots":9988,"normative_epochs":1000,"new_unique_roots_per_epoch":10000,"source_files_verified":44,"bank_manifest_sha256":"bank","python_executed":false,"admission_policy":crate::mapped_publication::POLICY,"reader_suffix_count":1,"reader_augment_suffix":true,"all_existing_resumed_rows_read_in_this_run":true,"reader_batches_admitted_before_any_record_returned":9988,"resumed_reader_batches_admitted":12,"bank_admission_backend":"cuda_prefix_full_sha256"})} | |
| fn resumed_count_and_policy_cannot_mask_missing_admission(){let good=fixture();let bank=json!({"bank_manifest_sha256":"bank"});validate_epoch(&good,0,&bank,true).unwrap();for key in ["resumed_reader_batches_admitted","reader_batches_admitted_before_any_record_returned","source_files_verified","normative_epochs","reader_augment_suffix","bank_manifest_sha256"]{let mut bad=good.clone();bad[key]=Value::Null;assert!(validate_epoch(&bad,0,&bank,true).is_err());}assert!(validate_epoch(&good,1,&bank,true).is_err());assert!(validate_epoch(&good,0,&bank,false).is_err());} | |
| fn interrupted_attempt_evidence_retained(){let path=std::env::temp_dir().join(format!("owned-controller-attempt-{}-{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));std::fs::create_dir(&path).unwrap();let first=path.join("attempt_00000000.heartbeat.json");std::fs::write(&first,b"interrupted").unwrap();let (next,done)=receipt_slot(&path,0,&json!({"bank_manifest_sha256":"bank"}),true).unwrap();assert!(!done);assert_eq!(next.file_name().unwrap(),"attempt_00000001.json");assert_eq!(std::fs::read(&first).unwrap(),b"interrupted");} | |
| fn torn_receipt_never_authorizes_completed_skip(){let path=std::env::temp_dir().join(format!("owned-torn-receipt-{}-{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));std::fs::create_dir(&path).unwrap();let first=path.join("attempt_00000000.json");std::fs::write(&first,b"{\"completed\":true,").unwrap();let (next,done)=receipt_slot(&path,0,&json!({"bank_manifest_sha256":"bank"}),true).unwrap();assert!(!done);assert_eq!(next.file_name().unwrap(),"attempt_00000001.json");assert_eq!(std::fs::read(&first).unwrap(),b"{\"completed\":true,");} | |
| fn database_hash_refuses_uncheckpointed_wal_and_detects_drift(){let path=std::env::temp_dir().join(format!("owned-db-binding-{}-{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));std::fs::write(&path,b"snapshot").unwrap();let before=sha_database(&path).unwrap();let mut wal=path.as_os_str().to_os_string();wal.push("-wal");std::fs::write(Path::new(&wal),b"pending transaction").unwrap();assert!(sha_database(&path).is_err());std::fs::write(Path::new(&wal),b"").unwrap();assert_eq!(before,sha_database(&path).unwrap());std::fs::write(&path,b"changed snapshot").unwrap();assert_ne!(before,sha_database(&path).unwrap());} | |
| fn restore_receipt_requires_same_epoch_and_complete_reader_gate(){let good=json!({"schema":"own_native_controller_epoch_archive_preparation_v1","epoch":7,"owner_preparation":{"epoch":7,"all_four_reader_modes_verified":true,"reader_mode_batches_verified":40000,"snapshot":{"epoch":7}}});validate_restore_preparation(&good,7).unwrap();assert!(validate_restore_preparation(&good,8).is_err());assert!(validate_restore_preparation(&good,1000).is_err());for key in ["epoch","all_four_reader_modes_verified","reader_mode_batches_verified","snapshot"]{let mut changed=good.clone();changed["owner_preparation"][key]=Value::Null;assert!(validate_restore_preparation(&changed,7).is_err());}}} | |