diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ee401f0..c6ce81b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -224,14 +224,10 @@ jobs: run: cargo clippy --workspace --all-targets --locked -- -D warnings test-linux: - name: Tests / Linux / shard ${{ matrix.shard }}/4 + name: Tests / Linux needs: build-tests-linux runs-on: ubuntu-24.04 timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v7.0.1 - uses: taiki-e/install-action@v2.85.13 @@ -240,27 +236,23 @@ jobs: - uses: actions/download-artifact@v8.0.1 with: name: nextest-linux-${{ github.sha }} - - name: Run archived test shard - run: cargo-nextest nextest run -P ci --archive-file nextest-linux.tar.zst --workspace-remap "${{ github.workspace }}" --partition "hash:${{ matrix.shard }}/4" + - name: Run archived workspace tests + run: cargo-nextest nextest run -P ci --archive-file nextest-linux.tar.zst --workspace-remap "${{ github.workspace }}" - name: Upload JUnit report if: always() uses: actions/upload-artifact@v7.0.1 with: - name: junit-linux-${{ matrix.shard }}-${{ github.sha }} + name: junit-linux-${{ github.sha }} path: target/nextest/ci/junit.xml if-no-files-found: ignore overwrite: true retention-days: 7 test-windows: - name: Tests / Windows / shard ${{ matrix.shard }}/4 + name: Tests / Windows needs: build-tests-windows runs-on: windows-2025 timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v7.0.1 - uses: taiki-e/install-action@v2.85.13 @@ -269,13 +261,13 @@ jobs: - uses: actions/download-artifact@v8.0.1 with: name: nextest-windows-${{ github.sha }} - - name: Run archived test shard - run: cargo-nextest nextest run -P ci --archive-file nextest-windows.tar.zst --workspace-remap "${{ github.workspace }}" --partition "hash:${{ matrix.shard }}/4" + - name: Run archived workspace tests + run: cargo-nextest nextest run -P ci --archive-file nextest-windows.tar.zst --workspace-remap "${{ github.workspace }}" - name: Upload JUnit report if: always() uses: actions/upload-artifact@v7.0.1 with: - name: junit-windows-${{ matrix.shard }}-${{ github.sha }} + name: junit-windows-${{ github.sha }} path: target/nextest/ci/junit.xml if-no-files-found: ignore overwrite: true diff --git a/AGENTS.md b/AGENTS.md index b0bedaa..a57865b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,7 +93,7 @@ Shared APIs must expose domain semantics, not frontend mechanics. 3. Represent dependent work as one DAG batch where practical, including VFS work through `extra_tasks`. 4. Avoid duplicated runner branches. Build conditional task lists, then run the shared runner once. 5. `verify --repair --relink-reuse` requires an effective reuse source. This can be an explicit `--reuse-from` path or another compatible `--path` in the same batch. -6. `verify` must retain `--skip-vfs` parity with install and update flows. +6. `verify --scope core` must preserve the core-only resource scope of `install/update --resources package-only`. 7. Reuse policy: - the normal install/update game-file ensure flow and VFS sync use `prefer_reuse = false`; - explicit relink mode may use `prefer_reuse = true`. diff --git a/Cargo.lock b/Cargo.lock index 71adac6..eba9432 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -104,12 +104,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - [[package]] name = "arrayvec" version = "0.7.8" @@ -184,20 +178,6 @@ version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" -[[package]] -name = "blake3" -version = "1.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ae7bad254120e9e4c63bafc385310756f90c484eac0e36b8317cf09cb92a77" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if", - "constant_time_eq", - "cpufeatures 0.3.0", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -1122,7 +1102,6 @@ version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ - "crc32fast", "miniz_oxide", "zlib-rs", ] @@ -1383,7 +1362,6 @@ dependencies = [ "griffr-core", "griffr-hypergryph-api", "griffr-yostar-api", - "hdiffpatch-rs", "libc", "md5-many", "rapidhash", @@ -1394,6 +1372,7 @@ dependencies = [ "tracing", "windows-sys 0.59.0", "zip", + "zstd", ] [[package]] @@ -1417,24 +1396,6 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -[[package]] -name = "hdiffpatch-rs" -version = "2.0.0" -source = "git+https://github.com/TwintailTeam/hdiffpatch-rs?branch=master#d58f4553b7d45acccd0b8e3b57badc26b9b04b6e" -dependencies = [ - "blake3", - "bzip2", - "crc32fast", - "digest 0.11.3", - "flate2", - "liblzma", - "md-5", - "sha1 0.11.0", - "sha2", - "xxhash-rust", - "zstd", -] - [[package]] name = "heck" version = "0.5.0" @@ -1817,26 +1778,6 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" -[[package]] -name = "liblzma" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fe0a34ca854fd4f20c07f696fc8675aec78f87d88d29f5e10257a7490a1b2e1" -dependencies = [ - "liblzma-sys", -] - -[[package]] -name = "liblzma-sys" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0dad045e4b1b7b170be4b60b54b780cafb4490165461bac7d1cf7b703f61d5f" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - [[package]] name = "libredox" version = "0.1.20" @@ -1924,16 +1865,6 @@ dependencies = [ "regex-automata", ] -[[package]] -name = "md-5" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" -dependencies = [ - "cfg-if", - "digest 0.11.3", -] - [[package]] name = "md5-many" version = "0.1.0-alpha.4" @@ -3718,12 +3649,6 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" -[[package]] -name = "xxhash-rust" -version = "0.8.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6" - [[package]] name = "yoke" version = "0.8.3" diff --git a/crates/griffr-cli/src/commands/mod.rs b/crates/griffr-cli/src/commands/mod.rs index 5f19b6a..615a13b 100644 --- a/crates/griffr-cli/src/commands/mod.rs +++ b/crates/griffr-cli/src/commands/mod.rs @@ -33,8 +33,7 @@ pub use install::install; pub use launch::launch; pub use news::show as news_show; pub use predownload::{ - apply as predownload_apply, check as predownload_check, fetch as predownload_fetch, - resume as predownload_resume, + check as predownload_check, fetch as predownload_fetch, resume as predownload_resume, }; pub use setup_persistent_resources::setup_persistent_resources; pub use uninstall::uninstall; diff --git a/crates/griffr-cli/src/commands/predownload.rs b/crates/griffr-cli/src/commands/predownload.rs index 83adb6b..c94874f 100644 --- a/crates/griffr-cli/src/commands/predownload.rs +++ b/crates/griffr-cli/src/commands/predownload.rs @@ -280,22 +280,6 @@ pub async fn fetch( Ok(()) } -pub async fn apply( - path: PathBuf, - overrides: crate::InstallTargetOverrideArgs, - output_dir: Option, - patch_options: griffr_runtime::PatchApplyOptions, - opts: GlobalOptions, -) -> Result<()> { - if let Some(output_dir) = output_dir.as_ref() { - ui::print_info(format!( - "Using explicit stage directory: {}", - output_dir.display() - )); - } - super::update::apply_staged_predownload(path, overrides, output_dir, patch_options, opts).await -} - pub async fn resume(path: PathBuf, opts: GlobalOptions) -> Result<()> { let local = detect_local_install(&path).await?; let game_id = local.require_known_game()?; diff --git a/crates/griffr-cli/src/commands/update/mod.rs b/crates/griffr-cli/src/commands/update/mod.rs index 798530d..4a3ab58 100644 --- a/crates/griffr-cli/src/commands/update/mod.rs +++ b/crates/griffr-cli/src/commands/update/mod.rs @@ -10,5 +10,4 @@ use archives::*; use manifest_update::*; use package_selection::*; use post_update::*; -pub(crate) use run::apply_staged_predownload; pub use run::update; diff --git a/crates/griffr-cli/src/commands/update/post_update.rs b/crates/griffr-cli/src/commands/update/post_update.rs index e85d000..4471240 100644 --- a/crates/griffr-cli/src/commands/update/post_update.rs +++ b/crates/griffr-cli/src/commands/update/post_update.rs @@ -151,7 +151,7 @@ fn run_extra_tasks_without_integrity( .with_download(download_lane); let result = task_pool_runner .run_batch(extra_tasks, task_progress) - .context("Failed to run extra DAG tasks during skip-verify")?; + .context("Failed to run extra DAG tasks during deferred verification")?; progress_session.finish(); progress.finish(); diff --git a/crates/griffr-cli/src/commands/update/run.rs b/crates/griffr-cli/src/commands/update/run.rs index 7cfc5c9..b86f4ce 100644 --- a/crates/griffr-cli/src/commands/update/run.rs +++ b/crates/griffr-cli/src/commands/update/run.rs @@ -90,7 +90,8 @@ pub(super) async fn update_internal( )); return Ok(()); } - crate::commands::predownload::resume(local.install_path.clone(), opts).await?; + crate::commands::predownload::resume(local.install_path.clone(), opts.clone()) + .await?; local = detect_local_install(&path).await?; resumed_pending_patch = true; } @@ -427,18 +428,7 @@ pub(super) async fn update_internal( let package_kind = archive_kind.unwrap_or(ArchivePackageKind::Full); let predownload_stage_dir = if !use_manifest_update && use_predownload && package_kind == ArchivePackageKind::Patch { - Some( - recovery_stage_dir - .or(predownload_dir_override) - .unwrap_or_else(|| { - crate::commands::predownload::stage_dir_for_request( - &local.install_path, - &version_info, - &package_request_version, - &version_info.version, - ) - }), - ) + recovery_stage_dir.or(predownload_dir_override) } else { None }; @@ -779,7 +769,6 @@ pub async fn update( force_copy: bool, stage_dir: Option, require_staged: bool, - use_default_stage: bool, batch: crate::BatchArgs, patch_options: griffr_runtime::PatchApplyOptions, opts: GlobalOptions, @@ -886,11 +875,11 @@ pub async fn update( item.explicit_reuse, item.peer_reuse, force_copy, - use_default_stage || stage_dir.is_some(), + stage_dir.is_some(), patch_options.clone(), stage_dir.clone(), require_staged, - opts, + opts.clone(), ) .await; if let Err(error) = result { @@ -915,6 +904,7 @@ pub async fn update( parallel_jobs, |item| &item.volume_keys, |item| { + let opts = opts.clone(); let api_client = api_client.clone(); let runner_group = runner_group.clone(); let runner_config = runner_config.clone(); @@ -933,7 +923,7 @@ pub async fn update( item.explicit_reuse, item.peer_reuse, force_copy, - use_default_stage || stage_dir.is_some(), + stage_dir.is_some(), patch_options, stage_dir, require_staged, @@ -965,28 +955,3 @@ pub async fn update( Err(crate::commands::batch::batch_error("Update", &failures)) } } - -pub(crate) async fn apply_staged_predownload( - path: PathBuf, - overrides: crate::InstallTargetOverrideArgs, - predownload_dir_override: Option, - patch_options: griffr_runtime::PatchApplyOptions, - opts: GlobalOptions, -) -> Result<()> { - let mut task_pool_runner = TaskPoolRunner::new(opts.task_pool_config())?; - update_internal( - None, - &mut task_pool_runner, - path, - overrides, - Vec::new(), - Vec::new(), - false, - true, - patch_options, - predownload_dir_override, - true, - opts, - ) - .await -} diff --git a/crates/griffr-cli/src/commands/update/tests.rs b/crates/griffr-cli/src/commands/update/tests.rs index 3c97554..94327a4 100644 --- a/crates/griffr-cli/src/commands/update/tests.rs +++ b/crates/griffr-cli/src/commands/update/tests.rs @@ -35,6 +35,7 @@ fn test_global_options() -> GlobalOptions { volume_streaming_mode: griffr_runtime::task_pool::DEFAULT_VOLUME_STREAMING_MODE, reuse_queue_limit: griffr_runtime::task_pool::DEFAULT_REUSE_QUEUE_LIMIT, output: OutputFormat::Text, + workload_capture: None, } } mod archives; diff --git a/crates/griffr-cli/src/commands/verify.rs b/crates/griffr-cli/src/commands/verify.rs index ac3c1cc..b378573 100644 --- a/crates/griffr-cli/src/commands/verify.rs +++ b/crates/griffr-cli/src/commands/verify.rs @@ -838,7 +838,7 @@ pub async fn verify( force_copy, relink_reuse, scope, - opts, + opts.clone(), ) .await { @@ -866,6 +866,7 @@ pub async fn verify( parallel_jobs, |item| &item.volume_keys, |item| { + let opts = opts.clone(); let api_client = api_client.clone(); let runner_group = runner_group.clone(); let runner_config = runner_config.clone(); diff --git a/crates/griffr-cli/src/main/cli.rs b/crates/griffr-cli/src/main/cli.rs index 300eba4..31a171b 100644 --- a/crates/griffr-cli/src/main/cli.rs +++ b/crates/griffr-cli/src/main/cli.rs @@ -24,6 +24,10 @@ pub(crate) struct Cli { #[arg(short, long, global = true, conflicts_with = "verbose")] pub(crate) quiet: bool, + /// Write a strict, content-free scheduler workload trace to this path + #[arg(long = "scheduler-trace-out", global = true, value_name = "PATH")] + pub(crate) scheduler_trace_out: Option, + #[command(subcommand)] pub(crate) command: Box, } @@ -308,18 +312,9 @@ pub(crate) enum Commands { reuse: ReuseSourcesArg, /// Choose how launcher resource-index files are sourced - #[arg( - long = "resources", - alias = "resource-policy", - value_enum, - conflicts_with = "skip_vfs" - )] + #[arg(long = "resources", alias = "resource-policy", value_enum)] resource_policy: Option, - /// Skip launcher resource-index sync. Package and game_files resource entries are still installed and verified. - #[arg(long, hide = true, conflicts_with = "resource_policy")] - skip_vfs: bool, - /// Keep downloaded package archives after successful extraction #[arg(long)] keep_pack_archives: bool, @@ -361,7 +356,7 @@ pub(crate) enum Commands { reuse: ReuseSourcesArg, /// Commit downloaded content but keep the install blocked until a later verify --repair - #[arg(long = "defer-verification", alias = "skip-verify")] + #[arg(long = "defer-verification")] defer_verification: bool, /// Force full package instead of patch @@ -376,23 +371,10 @@ pub(crate) enum Commands { #[arg(long, requires = "stage_dir")] require_staged: bool, - /// Deprecated alias that uses Griffr's default stage directory - #[arg(long, hide = true)] - use_predownload: bool, - /// Choose how launcher resource-index files are sourced - #[arg( - long = "resources", - alias = "resource-policy", - value_enum, - conflicts_with = "skip_vfs" - )] + #[arg(long = "resources", alias = "resource-policy", value_enum)] resource_policy: Option, - /// Skip launcher resource-index sync. Package and game_files resource entries are still installed and verified. - #[arg(long, hide = true, conflicts_with = "resource_policy")] - skip_vfs: bool, - /// Keep downloaded package archives after successful extraction #[arg(long)] keep_pack_archives: bool, @@ -473,13 +455,9 @@ pub(crate) enum Commands { relink_reuse: bool, /// Select integrity scope. Without this option, unfinished changes reuse their saved resource policy; other verifies use all files. - #[arg(long, value_enum, conflicts_with = "skip_vfs")] + #[arg(long, value_enum)] scope: Option, - /// Deprecated alias for --scope core - #[arg(long, hide = true, conflicts_with = "scope")] - skip_vfs: bool, - /// Do not read game/region/channel from local install metadata; requires --game and --region #[arg(long, requires = "game", requires = "region")] skip_local_detect: bool, @@ -493,13 +471,6 @@ pub(crate) enum Commands { command: ResourceCommands, }, - /// Legacy alias for `resources sync` - #[command(hide = true)] - SetupPersistentResources { - #[command(flatten)] - args: PersistentResourceArgs, - }, - /// Print native local launcher metadata and optionally the matching remote state Info { #[command(flatten)] @@ -548,17 +519,6 @@ pub enum ResourcePolicyArg { } impl ResourcePolicyArg { - pub const fn resolve(value: Option, skip_vfs: bool) -> Self { - if skip_vfs { - Self::PackageOnly - } else { - match value { - Some(value) => value, - None => Self::Auto, - } - } - } - pub const fn uses_resource_index(self) -> bool { matches!(self, Self::Auto) } diff --git a/crates/griffr-cli/src/main/debug_cli.rs b/crates/griffr-cli/src/main/debug_cli.rs index 7b5eae7..b223bdf 100644 --- a/crates/griffr-cli/src/main/debug_cli.rs +++ b/crates/griffr-cli/src/main/debug_cli.rs @@ -328,63 +328,9 @@ pub(crate) enum StageCommands { overrides: InstallTargetOverrideArgs, /// Directory for downloaded staged archives - #[arg(long = "stage-dir", alias = "output-dir")] + #[arg(long = "stage-dir")] stage_dir: Option, }, - /// Legacy alias for `update --stage-dir ... --require-staged` - #[command(hide = true)] - Apply { - #[command(flatten)] - mutation: MutationArgs, - - #[command(flatten)] - path: PathArg, - - #[command(flatten)] - overrides: InstallTargetOverrideArgs, - - /// Directory containing staged archives - #[arg(long = "stage-dir", alias = "output-dir")] - stage_dir: Option, - - /// Commit content but defer final verification - #[arg(long = "defer-verification", alias = "skip-verify")] - defer_verification: bool, - - /// Choose how launcher resource-index files are sourced - #[arg( - long = "resources", - alias = "resource-policy", - value_enum, - conflicts_with = "skip_vfs" - )] - resource_policy: Option, - - /// Skip launcher resource-index sync. Package and game_files resource entries are still installed and verified. - #[arg(long, conflicts_with = "resource_policy")] - skip_vfs: bool, - - /// Keep archive files after successful extraction - #[arg(long)] - keep_pack_archives: bool, - - /// Put extraction staging and patch temporary files under this directory - #[arg(long)] - work_dir: Option, - - /// Persist the patch-managed asset tree under this directory and link it into the install root - #[arg(long)] - external_asset_root: Option, - }, - /// Legacy alias for the top-level recover command - #[command(hide = true)] - Resume { - #[command(flatten)] - mutation: MutationArgs, - - #[command(flatten)] - path: PathArg, - }, } #[derive(Subcommand)] @@ -459,7 +405,7 @@ pub(crate) enum AccountCommands { /// Runtime options shared across command implementations. User-facing I/O /// tuning is configured through `GRIFFR_*` environment variables so normal /// command help stays focused on operation semantics. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] pub struct GlobalOptions { pub dry_run: bool, pub verbose: bool, @@ -476,6 +422,7 @@ pub struct GlobalOptions { pub volume_streaming_mode: griffr_runtime::task_pool::VolumeStreamingMode, pub reuse_queue_limit: usize, pub output: OutputFormat, + pub workload_capture: Option, } impl GlobalOptions { @@ -536,6 +483,7 @@ impl GlobalOptions { DEFAULT_REUSE_QUEUE_LIMIT, ), output, + workload_capture: None, } } @@ -543,6 +491,20 @@ impl GlobalOptions { Self { output, ..self } } + pub fn with_workload_capture(mut self, path: std::path::PathBuf, source_tree: String) -> Self { + self.workload_capture = Some( + griffr_runtime::task_pool::WorkloadCaptureConfig::streaming_strict(path, source_tree), + ); + self + } + + pub fn with_workload_kind(mut self, kind: &'static str) -> Self { + if let Some(capture) = self.workload_capture.as_mut() { + capture.workload_kind = Some(kind.to_owned()); + } + self + } + pub fn with_dry_run(self, dry_run: bool) -> Self { Self { dry_run, ..self } } @@ -553,26 +515,18 @@ impl GlobalOptions { pub fn task_pool_config_for_batch( &self, - target_jobs: usize, + _target_jobs: usize, ) -> griffr_runtime::task_pool::TaskPoolConfig { use griffr_runtime::task_pool::{TaskPoolConfig, VolumeIoPolicy}; - let target_jobs = target_jobs.max(1); - let share = |value: usize| value.div_ceil(target_jobs).max(1); let mut config = TaskPoolConfig::with_progress_buffers( self.extraction_progress_buffer_bytes, self.download_progress_buffer_bytes, ); - config.dispatcher_threads = share(config.dispatcher_threads); - config.network_slots = share(config.network_slots); - config.cpu_slots = share(config.cpu_slots); - config.blocking_slots = share(config.blocking_slots); - config.fit_blocking_pool(); - config.extract_slots = share(config.extract_slots); - config.extract_shards = share(config.extract_shards); - // Batch targets that share a physical volume are serialized by the - // outer dependency scheduler. Keep the full per-volume policy so a - // target on an independent volume is not throttled by unrelated jobs. + // Scalar resource limits remain command-wide hard capacities. The + // TaskPoolRunnerGroup owns their shared accounting, so per-runner + // div_ceil partitions would both waste idle capacity and create odd- + // capacity over-admission when summed across runners. config.default_volume_policy = VolumeIoPolicy::new( self.volume_read_limit, self.volume_write_limit, @@ -580,7 +534,8 @@ impl GlobalOptions { self.volume_streaming_pressure_limit, self.volume_streaming_mode, ); - config.reuse_queue_limit = share(self.reuse_queue_limit); + config.reuse_queue_limit = self.reuse_queue_limit; + config.workload_capture = self.workload_capture.clone(); config } @@ -597,20 +552,15 @@ impl GlobalOptions { pub fn task_pool_batch( &self, - target_jobs: usize, + _target_jobs: usize, ) -> griffr_runtime::error::Result<( griffr_runtime::task_pool::TaskPoolRunnerGroup, griffr_runtime::task_pool::TaskPoolConfig, )> { use griffr_runtime::task_pool::TaskPoolRunnerGroup; - let target_jobs = target_jobs.max(1); - let runner_config = self.task_pool_config_for_batch(target_jobs); - let mut dispatcher_config = self.task_pool_config(); - dispatcher_config.cpu_slots = runner_config.cpu_slots; - dispatcher_config.blocking_slots = runner_config.blocking_slots; - dispatcher_config.fit_blocking_pool_for_runners(target_jobs); - let group = TaskPoolRunnerGroup::new(dispatcher_config)?; + let runner_config = self.task_pool_config(); + let group = TaskPoolRunnerGroup::new(runner_config.clone())?; Ok((group, runner_config)) } diff --git a/crates/griffr-cli/src/main/entrypoint/mod.rs b/crates/griffr-cli/src/main/entrypoint/mod.rs index e98262a..6cff446 100644 --- a/crates/griffr-cli/src/main/entrypoint/mod.rs +++ b/crates/griffr-cli/src/main/entrypoint/mod.rs @@ -10,6 +10,48 @@ use tracing::debug; mod account; mod debug; +fn validate_workload_capture_cli(cli: &Cli) -> Result<()> { + if cli.scheduler_trace_out.is_none() { + return Ok(()); + } + match cli.command.as_ref() { + Commands::Install { .. } => Ok(()), + Commands::Update { batch, paths, .. } | Commands::Verify { batch, paths, .. } + if batch.jobs == 1 && paths.paths.len() == 1 => + { + Ok(()) + } + Commands::Update { .. } | Commands::Verify { .. } => anyhow::bail!( + "--scheduler-trace-out currently requires exactly one --path and --jobs 1" + ), + _ => anyhow::bail!( + "--scheduler-trace-out currently supports install, update, and verify commands" + ), + } +} + +fn resolve_source_tree() -> Result { + let mut candidates = vec![std::env::current_dir()?]; + candidates.push(std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))); + for cwd in candidates { + let output = std::process::Command::new("git") + .args(["rev-parse", "HEAD^{tree}"]) + .current_dir(cwd) + .output(); + if let Ok(output) = output { + if output.status.success() { + let tree = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + if tree.len() == 40 && tree.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Ok(tree); + } + } + } + } + anyhow::bail!( + "--scheduler-trace-out requires a Git checkout so the source tree can be recorded" + ) +} + #[cfg(test)] mod tests; @@ -89,6 +131,7 @@ pub(crate) async fn run() -> Result<()> { .join() .map_err(|_| anyhow::anyhow!("cli parser thread panicked"))?; + validate_workload_capture_cli(&cli)?; crate::ui::set_quiet(cli.quiet); let default_level = if cli.verbose { "warn,griffr=debug,griffr_core=debug,griffr_hypergryph_api=debug,griffr_yostar_api=debug,griffr_runtime=debug" @@ -106,7 +149,10 @@ pub(crate) async fn run() -> Result<()> { .without_time() .init(); - let opts = GlobalOptions::from_environment(false, cli.verbose, OutputFormat::Text); + let mut opts = GlobalOptions::from_environment(false, cli.verbose, OutputFormat::Text); + if let Some(path) = cli.scheduler_trace_out.clone() { + opts = opts.with_workload_capture(path, resolve_source_tree()?); + } if opts.verbose { debug!("Griffr CLI started"); @@ -122,10 +168,11 @@ pub(crate) async fn run() -> Result<()> { force, reuse, resource_policy, - skip_vfs, keep_pack_archives, } => { - let opts = opts.with_dry_run(mutation.dry_run); + let opts = opts + .with_dry_run(mutation.dry_run) + .with_workload_kind("install"); let target = parse_remote_args(remote)?; let PathArg { path } = path; let ReuseSourcesArg { @@ -133,7 +180,7 @@ pub(crate) async fn run() -> Result<()> { force_copy, } = reuse; - let resource_policy = ResourcePolicyArg::resolve(resource_policy, skip_vfs); + let resource_policy = resource_policy.unwrap_or(ResourcePolicyArg::Auto); let opts = GlobalOptions { resource_policy, keep_pack_archives, @@ -171,20 +218,20 @@ pub(crate) async fn run() -> Result<()> { full_package, stage_dir, require_staged, - use_predownload, resource_policy, - skip_vfs, keep_pack_archives, work_dir, external_asset_root, } => { - let opts = opts.with_dry_run(mutation.dry_run); + let opts = opts + .with_dry_run(mutation.dry_run) + .with_workload_kind("update"); let TargetPathsArg { paths } = paths; let ReuseSourcesArg { reuse_from, force_copy, } = reuse; - let resource_policy = ResourcePolicyArg::resolve(resource_policy, skip_vfs); + let resource_policy = resource_policy.unwrap_or(ResourcePolicyArg::Auto); let opts = GlobalOptions { skip_verify: defer_verification, force_full_package: full_package, @@ -192,10 +239,9 @@ pub(crate) async fn run() -> Result<()> { keep_pack_archives, ..opts }; - let use_default_stage = use_predownload && stage_dir.is_none(); opts.verbose(format!( - "Update paths: {:?}, reuse_from={:?}, force_copy={}, stage_dir={:?}, require_staged={}, use_default_stage={}", - paths, reuse_from, force_copy, stage_dir, require_staged, use_default_stage + "Update paths: {:?}, reuse_from={:?}, force_copy={}, stage_dir={:?}, require_staged={}", + paths, reuse_from, force_copy, stage_dir, require_staged )); commands::update( paths, @@ -204,7 +250,6 @@ pub(crate) async fn run() -> Result<()> { force_copy, stage_dir, require_staged, - use_default_stage, batch, griffr_runtime::PatchApplyOptions { work_dir, @@ -235,49 +280,6 @@ pub(crate) async fn run() -> Result<()> { )); commands::predownload_fetch(path, overrides, stage_dir, opts).await?; } - StageCommands::Apply { - mutation, - path, - overrides, - stage_dir, - defer_verification, - resource_policy, - skip_vfs, - keep_pack_archives, - work_dir, - external_asset_root, - } => { - let opts = opts.with_dry_run(mutation.dry_run); - let PathArg { path } = path; - let resource_policy = ResourcePolicyArg::resolve(resource_policy, skip_vfs); - let opts = GlobalOptions { - skip_verify: defer_verification, - resource_policy, - keep_pack_archives, - ..opts - }; - opts.verbose(format!( - "Legacy stage apply path: {:?}, stage_dir={:?}", - path, stage_dir - )); - commands::predownload_apply( - path, - overrides, - stage_dir, - griffr_runtime::PatchApplyOptions { - work_dir, - external_asset_root, - }, - opts, - ) - .await?; - } - StageCommands::Resume { mutation, path } => { - let opts = opts.with_dry_run(mutation.dry_run); - let PathArg { path } = path; - opts.verbose(format!("Predownload resume path: {:?}", path)); - commands::predownload_resume(path, opts).await?; - } }, Commands::Recover { mutation, path } => { @@ -312,7 +314,6 @@ pub(crate) async fn run() -> Result<()> { reuse, relink_reuse, scope, - skip_vfs, skip_local_detect, report, } => { @@ -325,11 +326,6 @@ pub(crate) async fn run() -> Result<()> { force_copy, } = reuse; let remote = parse_optional_remote_args(remote)?; - let scope = if skip_vfs { - Some(VerifyScopeArg::Core) - } else { - scope - }; opts.verbose(format!( "Verify paths: {:?}, remote={:?}, repair={}, reuse_from={:?}, force_copy={}, relink_reuse={}, scope={:?}, skip_local_detect={}", paths, remote, repair, reuse_from, force_copy, relink_reuse, scope, skip_local_detect @@ -354,10 +350,6 @@ pub(crate) async fn run() -> Result<()> { dispatch_resource_sync(args, opts).await?; } }, - Commands::SetupPersistentResources { args } => { - dispatch_resource_sync(args, opts).await?; - } - Commands::Info { selector } => { let opts = opts.with_output(selector.report.output); opts.verbose("Info query"); diff --git a/crates/griffr-cli/src/main/entrypoint/tests.rs b/crates/griffr-cli/src/main/entrypoint/tests.rs index d052f17..50c085f 100644 --- a/crates/griffr-cli/src/main/entrypoint/tests.rs +++ b/crates/griffr-cli/src/main/entrypoint/tests.rs @@ -217,7 +217,7 @@ fn verify_batch_peers_can_satisfy_relink_parse_requirements() { } #[test] -fn skip_vfs_keeps_install_and_verify_cli_parity() { +fn package_only_and_core_scope_are_explicit() { let install = Cli::try_parse_from([ "griffr", "install", @@ -226,58 +226,67 @@ fn skip_vfs_keeps_install_and_verify_cli_parity() { "--region", "sg", "--path", - r"C:\Games\Endfield", - "--skip-vfs", + "install", + "--resources", + "package-only", ]) .unwrap(); - let Commands::Install { - resource_policy, - skip_vfs, - .. - } = *install.command - else { - panic!("expected install command"); - }; - assert!(resource_policy.is_none()); - assert!(skip_vfs); - assert_eq!( - ResourcePolicyArg::resolve(resource_policy, skip_vfs), - ResourcePolicyArg::PackageOnly - ); - - let verify = Cli::try_parse_from([ + assert!(matches!( + *install.command, + Commands::Install { + resource_policy: Some(ResourcePolicyArg::PackageOnly), + .. + } + )); + let update = Cli::try_parse_from([ "griffr", - "verify", + "update", "--path", - r"C:\Games\Endfield", - "--skip-vfs", + "install", + "--resources", + "package-only", ]) .unwrap(); - let Commands::Verify { - scope, skip_vfs, .. - } = *verify.command - else { - panic!("expected verify command"); - }; - assert!(scope.is_none()); - assert!(skip_vfs); + assert!(matches!( + *update.command, + Commands::Update { + resource_policy: Some(ResourcePolicyArg::PackageOnly), + .. + } + )); + let verify = + Cli::try_parse_from(["griffr", "verify", "--path", "install", "--scope", "core"]).unwrap(); + assert!(matches!( + *verify.command, + Commands::Verify { + scope: Some(VerifyScopeArg::Core), + .. + } + )); } #[test] -fn explicit_resource_policy_conflicts_with_skip_vfs() { - let Err(error) = Cli::try_parse_from([ - "griffr", - "update", - "--path", - r"C:\Games\Endfield", - "--resource-policy", - "auto", - "--skip-vfs", - ]) else { - panic!("expected argument conflict error"); - }; - - assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); +fn removed_command_aliases_are_rejected() { + for args in [ + vec!["griffr", "update", "--path", "install", "--skip-vfs"], + vec!["griffr", "verify", "--path", "install", "--skip-vfs"], + vec!["griffr", "update", "--path", "install", "--use-predownload"], + vec!["griffr", "update", "--path", "install", "--skip-verify"], + vec!["griffr", "stage", "apply", "--help"], + vec!["griffr", "stage", "resume", "--help"], + vec!["griffr", "setup-persistent-resources", "--help"], + vec![ + "griffr", + "stage", + "fetch", + "--path", + "install", + "--output-dir", + "stage", + ], + ] { + assert!(Cli::try_parse_from(args.clone()).is_err(), "{args:?}"); + } } #[test] @@ -485,6 +494,11 @@ fn batch_targets_keep_full_disjoint_volume_policy() { let batch = options.task_pool_config_for_batch(options.batch_parallelism_limit()); assert_eq!(batch.default_volume_policy, base.default_volume_policy); + assert_eq!(batch.network_slots, base.network_slots); + assert_eq!(batch.cpu_slots, base.cpu_slots); + assert_eq!(batch.blocking_slots, base.blocking_slots); + assert_eq!(batch.extract_slots, base.extract_slots); + assert_eq!(batch.reuse_queue_limit, base.reuse_queue_limit); assert!(options.batch_parallelism_limit() <= base.cpu_slots); assert!(options.batch_parallelism_limit() <= base.blocking_slots); assert!(options.batch_parallelism_limit() <= base.network_slots); @@ -493,10 +507,16 @@ fn batch_targets_keep_full_disjoint_volume_policy() { #[test] fn batch_task_pool_configs_keep_required_blocking_headroom() { let options = GlobalOptions::from_environment(false, false, OutputFormat::Text); + let base = options.task_pool_config(); for jobs in [1, 2, 3, 8, 16] { let (group, config) = options .task_pool_batch(jobs) .unwrap_or_else(|error| panic!("invalid shared task pool for {jobs} jobs: {error}")); + assert_eq!(config.network_slots, base.network_slots); + assert_eq!(config.cpu_slots, base.cpu_slots); + assert_eq!(config.blocking_slots, base.blocking_slots); + assert_eq!(config.extract_slots, base.extract_slots); + assert_eq!(config.reuse_queue_limit, base.reuse_queue_limit); group .runner(config) .unwrap_or_else(|error| panic!("invalid task-pool config for {jobs} jobs: {error}")); @@ -521,3 +541,40 @@ fn quiet_is_global_and_conflicts_with_verbose() { }; assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); } + +#[test] +fn scheduler_trace_out_parses_as_global_capture_flag() { + let cli = Cli::try_parse_from([ + "griffr", + "--scheduler-trace-out", + "capture.ndjson", + "verify", + "--path", + r"C:\Games\Endfield", + ]) + .unwrap(); + assert_eq!( + cli.scheduler_trace_out.as_deref(), + Some(std::path::Path::new("capture.ndjson")) + ); + validate_workload_capture_cli(&cli).unwrap(); +} + +#[test] +fn scheduler_trace_out_rejects_parallel_multi_target_capture() { + let cli = Cli::try_parse_from([ + "griffr", + "verify", + "--scheduler-trace-out", + "capture.ndjson", + "--jobs", + "2", + "--path", + r"C:\Games\A", + "--path", + r"D:\Games\B", + ]) + .unwrap(); + let error = validate_workload_capture_cli(&cli).unwrap_err().to_string(); + assert!(error.contains("exactly one --path")); +} diff --git a/crates/griffr-cli/tests/cli_e2e.rs b/crates/griffr-cli/tests/cli_e2e.rs index fce3708..f326ec3 100644 --- a/crates/griffr-cli/tests/cli_e2e.rs +++ b/crates/griffr-cli/tests/cli_e2e.rs @@ -772,14 +772,11 @@ fn every_command_surface_has_a_working_help_contract() { &["stage", "--help"], &["stage", "inspect", "--help"], &["stage", "fetch", "--help"], - &["stage", "apply", "--help"], - &["stage", "resume", "--help"], &["recover", "--help"], &["launch", "--help"], &["verify", "--help"], &["resources", "--help"], &["resources", "sync", "--help"], - &["setup-persistent-resources", "--help"], &["info", "--help"], &["news", "--help"], &["debug", "--help"], @@ -1006,18 +1003,18 @@ fn local_launcher_service_drives_install_repair_stage_update_and_uninstall() { } assert!(stage.join(v2.archive_name).is_file()); - let mut stage_apply_args = args(&[ + let mut staged_update_args = args(&[ "--quiet", - "stage", - "apply", + "update", + "--require-staged", "--resources", "package-only", "--gateway", &server.base, ]); - push_path(&mut stage_apply_args, "--path", &install); - push_path(&mut stage_apply_args, "--stage-dir", &stage); - command(stage_apply_args); + push_path(&mut staged_update_args, "--path", &install); + push_path(&mut staged_update_args, "--stage-dir", &stage); + command(staged_update_args); assert_eq!( fs::read(install.join("core.bin")).unwrap(), v2.files["core.bin"] @@ -1086,18 +1083,6 @@ fn local_launcher_service_drives_install_repair_stage_update_and_uninstall() { let resource_path = persistent.join(resources.file_name); assert_eq!(fs::read(&resource_path).unwrap(), resources.file); - let mut legacy_resource_args = args(&[ - "--quiet", - "setup-persistent-resources", - "--allow-download", - "--file-set", - "initial", - "--gateway", - &server.base, - ]); - push_path(&mut legacy_resource_args, "--path", &install); - command(legacy_resource_args); - let mut decrypt_index_args = args(&["debug", "decrypt-res-index"]); push_path(&mut decrypt_index_args, "--path", &persistent); command(decrypt_index_args); @@ -1144,10 +1129,6 @@ fn local_launcher_service_drives_install_repair_stage_update_and_uninstall() { push_path(&mut recover_args, "--path", &install); command_fails(recover_args, "No install change marker found"); - let mut legacy_resume_args = args(&["--quiet", "stage", "resume"]); - push_path(&mut legacy_resume_args, "--path", &install); - command_fails(legacy_resume_args, "No install change marker found"); - let mut detach_args = args(&["--quiet", "uninstall", "--detach", "--yes"]); push_path(&mut detach_args, "--path", &install); command(detach_args); diff --git a/crates/griffr-runtime/Cargo.toml b/crates/griffr-runtime/Cargo.toml index ee8cbc4..7172590 100644 --- a/crates/griffr-runtime/Cargo.toml +++ b/crates/griffr-runtime/Cargo.toml @@ -9,7 +9,7 @@ description = "Filesystem, install, update, verification, and launch runtime for [features] default = ["hdiff-patch"] -hdiff-patch = ["dep:hdiffpatch-rs"] +hdiff-patch = ["dep:zstd"] [dependencies] griffr-core = { workspace = true } @@ -28,7 +28,7 @@ futures-util = { workspace = true } zip = { workspace = true } md5 = { workspace = true } -hdiffpatch-rs = { git = "https://github.com/TwintailTeam/hdiffpatch-rs", branch = "master", optional = true } +zstd = { version = "0.13", optional = true } base64 = "0.22" dirs = { workspace = true } diff --git a/crates/griffr-runtime/src/artifact.rs b/crates/griffr-runtime/src/artifact.rs index 8ea710d..5d54780 100644 --- a/crates/griffr-runtime/src/artifact.rs +++ b/crates/griffr-runtime/src/artifact.rs @@ -81,14 +81,6 @@ impl ArtifactExpectation { &self.expected_hash } - /// Compatibility accessor for Hypergryph/Gryphline manifest-only code. - pub fn expected_md5(&self) -> &str { - match &self.expected_hash { - ContentHash::Md5(value) => value, - ContentHash::Crc64Xz(_) => panic!("expected MD5 artifact, found CRC64-XZ"), - } - } - pub fn expected_size(&self) -> Option { self.expected_size } @@ -192,10 +184,6 @@ impl ArtifactProof { self.expectation.expected_hash() } - pub fn expected_md5(&self) -> &str { - self.expectation.expected_md5() - } - pub fn expected_size(&self) -> Option { self.expectation.expected_size() } diff --git a/crates/griffr-runtime/src/content_plan.rs b/crates/griffr-runtime/src/content_plan.rs index 4ef5a7e..5fae441 100644 --- a/crates/griffr-runtime/src/content_plan.rs +++ b/crates/griffr-runtime/src/content_plan.rs @@ -223,7 +223,7 @@ impl ContentPlan { || crate::is_resource_baseline_path(claim.expectation().logical_path()) || crate::is_resource_baseline_path(previous.expectation.logical_path()); if !is_res_baseline - && (previous.expectation.expected_md5() != claim.expectation().expected_md5() + && (previous.expectation.expected_hash() != claim.expectation().expected_hash() || previous.expectation.expected_size() != claim.expectation().expected_size()) { diff --git a/crates/griffr-runtime/src/file_allocation.rs b/crates/griffr-runtime/src/file_allocation.rs index 98198b0..37fc16a 100644 --- a/crates/griffr-runtime/src/file_allocation.rs +++ b/crates/griffr-runtime/src/file_allocation.rs @@ -9,19 +9,22 @@ use crate::error::Result; /// Windows uses FILE_ALLOCATION_INFO so large sequential writes do not grow the /// allocation one cluster at a time. Other platforms keep their existing write /// behavior until an equivalent allocation contract is selected explicitly. +/// Returns true when the filesystem reports the requested allocation; false +/// when allocation is unavailable or could not be confirmed. #[cfg(windows)] -pub(crate) fn preallocate_file(file: &T, path: &Path, bytes: u64) -> Result<()> +pub(crate) fn preallocate_file(file: &T, path: &Path, bytes: u64) -> Result where T: std::os::windows::io::AsRawHandle + ?Sized, { use std::ffi::c_void; use std::mem::size_of; use windows_sys::Win32::Storage::FileSystem::{ - FileAllocationInfo, SetFileInformationByHandle, FILE_ALLOCATION_INFO, + FileAllocationInfo, FileStandardInfo, GetFileInformationByHandleEx, + SetFileInformationByHandle, FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, }; if bytes == 0 { - return Ok(()); + return Ok(true); } let allocation_size = i64::try_from(bytes).map_err(|_| Error::IoAt { action: "write to file", @@ -49,16 +52,28 @@ where source: std::io::Error::last_os_error(), }); } - Ok(()) + let mut standard = std::mem::MaybeUninit::::uninit(); + // The borrowed handle remains open; only a successful query initializes + // the output. Fall back to conservative growth accounting on failure. + let confirmed = unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle() as _, + FileStandardInfo, + standard.as_mut_ptr().cast(), + size_of::() as u32, + ) != 0 + && standard.assume_init().AllocationSize >= allocation_size + }; + Ok(confirmed) } #[cfg(target_os = "linux")] -pub(crate) fn preallocate_file(file: &T, path: &Path, bytes: u64) -> Result<()> +pub(crate) fn preallocate_file(file: &T, path: &Path, bytes: u64) -> Result where T: std::os::fd::AsRawFd + ?Sized, { if bytes == 0 { - return Ok(()); + return Ok(true); } let length = libc::off_t::try_from(bytes).map_err(|_| crate::error::Error::IoAt { @@ -76,7 +91,7 @@ where let result = unsafe { libc::fallocate(file.as_raw_fd(), libc::FALLOC_FL_KEEP_SIZE, 0, length) }; if result == 0 { - return Ok(()); + return Ok(true); } let source = std::io::Error::last_os_error(); @@ -85,7 +100,7 @@ where // Some filesystems do not implement KEEP_SIZE. Preserve the former // no-op behavior there instead of making downloads unusable. Some(libc::EOPNOTSUPP | libc::ENOSYS | libc::EINVAL) => { - return Ok(()); + return Ok(false); } _ => { return Err(crate::error::Error::IoAt { @@ -99,8 +114,8 @@ where } #[cfg(all(not(windows), not(target_os = "linux")))] -pub(crate) fn preallocate_file(_file: &T, _path: &Path, _bytes: u64) -> Result<()> { - Ok(()) +pub(crate) fn preallocate_file(_file: &T, _path: &Path, _bytes: u64) -> Result { + Ok(false) } #[cfg(test)] diff --git a/crates/griffr-runtime/src/files/vfs/sync.rs b/crates/griffr-runtime/src/files/vfs/sync.rs index ae33e3e..c34bb51 100644 --- a/crates/griffr-runtime/src/files/vfs/sync.rs +++ b/crates/griffr-runtime/src/files/vfs/sync.rs @@ -67,7 +67,7 @@ fn register_resource_claim( if let Some(previous) = claims_by_path.get(&key) { let previous_expectation = previous.expectation(); let expectation = claim.expectation(); - if previous_expectation.expected_md5() != expectation.expected_md5() + if previous_expectation.expected_hash() != expectation.expected_hash() || previous_expectation.expected_size() != expectation.expected_size() { return Err(Error::Message { @@ -251,9 +251,15 @@ pub async fn plan_vfs_tasks( ), }); }; + let crate::ContentHash::Md5(md5) = claim.expectation().expected_hash() else { + return Err(Error::Message { + context: "VFS error: ", + detail: format!("Resource claim {} does not use MD5", claim.path().display()), + }); + }; managed_files.push(ManagedResourceFile { path: claim.expectation().logical_path().to_string(), - md5: claim.expectation().expected_md5().to_string(), + md5: md5.clone(), size, }); } diff --git a/crates/griffr-runtime/src/patch_apply/build_plan.rs b/crates/griffr-runtime/src/patch_apply/build_plan.rs index 8b436ce..b1a1ff7 100644 --- a/crates/griffr-runtime/src/patch_apply/build_plan.rs +++ b/crates/griffr-runtime/src/patch_apply/build_plan.rs @@ -352,110 +352,14 @@ pub(crate) fn build_patch_plan_with_probe_cache( Some(size.saturating_sub(existing)) }) .sum::(); - let mut entries = Vec::with_capacity(manifest.files.len()); - let mut missing = Vec::new(); - let mut final_delta: i128 = 0; - - for entry in &manifest.files { - let relative = parse_safe_relative_path("patch.json file name", &entry.name)?; - let destination = vfs_destination.join(&relative); - let logical_destination = logical_vfs_destination.join(&relative); - let logical = relative.to_string_lossy().replace('\\', "/"); - let existing_path = if options.external_asset_root.is_some() { - &logical_destination - } else { - &destination - }; - let existing_size = metadata_len(existing_path); - final_delta += i128::from(entry.size) - i128::from(existing_size); - - let source = if verification_cache - .build_issue(existing_path, &logical, &entry.md5, Some(entry.size)) - .is_none() - { - PlannedPatchSource::AlreadyPresent - } else if let Some(local_path) = entry.effective_local_path() { - let archive_path = archive_payload_path(PATCH_FILES_STAGE_DIR, local_path)?; - if !archive_entries.contains_key(&normalized_archive_path(&archive_path)) { - missing.push(format!( - "{} (missing local payload {})", - entry.name, - archive_path.display() - )); - continue; - } - PlannedPatchSource::Local { - payload: archive_path, - } - } else { - let mut selected = None; - let mut failures = Vec::new(); - for diff in &entry.patch { - let base_relative = - parse_safe_relative_path("patch.json base_file", diff.effective_base_file())?; - let verified_base = logical_vfs_destination.join(&base_relative); - let planned_base = vfs_destination.join(&base_relative); - let base_logical = base_relative.to_string_lossy().replace('\\', "/"); - let payload = - archive_payload_path(PATCH_DIFF_STAGE_DIR, diff.effective_patch_path())?; - if verification_cache - .build_issue( - &verified_base, - &base_logical, - &diff.base_md5, - Some(diff.base_size), - ) - .is_some() - { - failures.push(format!("{} (base mismatch)", base_relative.display())); - continue; - } - if !archive_entries.contains_key(&normalized_archive_path(&payload)) { - failures.push(format!("{} (payload missing)", payload.display())); - continue; - } - selected = Some(PlannedPatchSource::Hdiff { - base: planned_base, - payload, - base_md5: diff.base_md5.clone(), - base_size: diff.base_size, - }); - break; - } - match selected { - Some(source) => source, - None => { - missing.push(format!( - "{} ({})", - entry.name, - if failures.is_empty() { - "no patch candidates".to_string() - } else { - failures.join("; ") - } - )); - continue; - } - } - }; - entries.push(PlannedPatchEntry { - name: entry.name.clone(), - destination, - expected_md5: entry.md5.clone(), - expected_size: entry.size, - source, - }); - } - - if !missing.is_empty() { - return Err(Error::Message { - context: "VFS error: ", - detail: format!( - "The patch check found entries that cannot be repaired: {}", - missing.join(", ") - ), - }); - } + let (entries, final_delta) = select_patch_entries( + manifest, + &logical_vfs_destination, + &vfs_destination, + verification_cache, + |path| archive_entries.contains_key(&normalized_archive_path(path)), + |path| path, + )?; let logical_outputs = entries .iter() @@ -571,6 +475,176 @@ pub(crate) fn build_patch_plan_with_probe_cache( Ok((plan, report)) } +fn select_patch_entries( + manifest: &griffr_hypergryph_api::ResourcePatch, + logical_vfs_destination: &Path, + vfs_destination: &Path, + verification_cache: &VerifiedArtifactCache, + payload_exists: impl Fn(&Path) -> bool, + payload_relative: impl Fn(PathBuf) -> PathBuf, +) -> Result<(Vec, i128)> { + let mut entries = Vec::with_capacity(manifest.files.len()); + let mut missing = Vec::new(); + let mut final_delta: i128 = 0; + + for entry in &manifest.files { + let relative = parse_safe_relative_path("patch.json file name", &entry.name)?; + let destination = vfs_destination.join(&relative); + let logical_destination = logical_vfs_destination.join(&relative); + let logical = relative.to_string_lossy().replace('\\', "/"); + let existing_path = &logical_destination; + let existing_size = metadata_len(existing_path); + final_delta += i128::from(entry.size) - i128::from(existing_size); + + let source = if verification_cache + .build_issue(existing_path, &logical, &entry.md5, Some(entry.size)) + .is_none() + { + PlannedPatchSource::AlreadyPresent + } else if let Some(local_path) = entry.effective_local_path() { + let archive_path = archive_payload_path(PATCH_FILES_STAGE_DIR, local_path)?; + if !payload_exists(&archive_path) { + missing.push(format!( + "{} (missing local payload {})", + entry.name, + archive_path.display() + )); + continue; + } + PlannedPatchSource::Local { + payload: payload_relative(archive_path), + } + } else { + let mut selected = None; + let mut failures = Vec::new(); + for diff in &entry.patch { + let base_relative = + parse_safe_relative_path("patch.json base_file", diff.effective_base_file())?; + let verified_base = logical_vfs_destination.join(&base_relative); + let planned_base = vfs_destination.join(&base_relative); + let base_logical = base_relative.to_string_lossy().replace('\\', "/"); + let payload = + archive_payload_path(PATCH_DIFF_STAGE_DIR, diff.effective_patch_path())?; + if verification_cache + .build_issue( + &verified_base, + &base_logical, + &diff.base_md5, + Some(diff.base_size), + ) + .is_some() + { + failures.push(format!("{} (base mismatch)", base_relative.display())); + continue; + } + if !payload_exists(&payload) { + failures.push(format!("{} (payload missing)", payload.display())); + continue; + } + selected = Some(PlannedPatchSource::Hdiff { + base: planned_base, + payload: payload_relative(payload), + base_md5: diff.base_md5.clone(), + base_size: diff.base_size, + }); + break; + } + match selected { + Some(source) => source, + None => { + missing.push(format!( + "{} ({})", + entry.name, + if failures.is_empty() { + "no patch candidates".to_string() + } else { + failures.join("; ") + } + )); + continue; + } + } + }; + entries.push(PlannedPatchEntry { + name: logical, + destination, + expected_md5: entry.md5.clone(), + expected_size: entry.size, + source, + }); + } + + if !missing.is_empty() { + return Err(Error::Message { + context: "VFS error: ", + detail: format!( + "The patch check found entries that cannot be repaired: {}", + missing.join(", ") + ), + }); + } + + Ok((entries, final_delta)) +} + +pub(crate) fn plan_extracted_patch(install_root: &Path) -> Result> { + let manifest_path = install_root.join(PATCH_MANIFEST_NAME); + let stage_root = install_root.join(PATCH_STAGE_DIR); + let manifest: griffr_hypergryph_api::ResourcePatch = match std::fs::read(&manifest_path) { + Ok(bytes) => serde_json::from_slice(&bytes)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound && !stage_root.exists() => { + return Ok(None); + } + Err(source) => { + return Err(Error::IoAt { + action: "open file", + path: manifest_path, + source, + }) + } + }; + let vfs_base_path = + parse_safe_relative_path("patch.json vfs_base_path", manifest.vfs_base_path.trim())?; + let vfs_destination = install_root.join(&vfs_base_path); + let (entries, _) = select_patch_entries( + &manifest, + &vfs_destination, + &vfs_destination, + &VerifiedArtifactCache::default(), + |path| install_root.join(path).is_file(), + |path| { + path.strip_prefix(PATCH_STAGE_DIR) + .expect("patch payload prefix") + .to_path_buf() + }, + )?; + let delete_manifest = install_root.join(DELETE_FILES_MANIFEST_NAME); + let delete_paths = match std::fs::read_to_string(&delete_manifest) { + Ok(contents) => parse_delete_files_manifest(&contents)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(), + Err(source) => { + return Err(Error::IoAt { + action: "open file", + path: delete_manifest, + source, + }) + } + }; + let plan = PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: install_root.to_path_buf(), + stage_root, + vfs_base_path, + vfs_destination, + work_dir: None, + entries, + delete_paths, + deferred_paths: Vec::new(), + }; + plan.validate()?; + Ok(Some(plan)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/griffr-runtime/src/patch_apply/dependency.rs b/crates/griffr-runtime/src/patch_apply/dependency.rs index ff269ad..596ce2f 100644 --- a/crates/griffr-runtime/src/patch_apply/dependency.rs +++ b/crates/griffr-runtime/src/patch_apply/dependency.rs @@ -1,5 +1,4 @@ use std::collections::{BTreeMap, BTreeSet}; -use std::path::PathBuf; use crate::error::{Error, Result}; @@ -11,14 +10,15 @@ use super::{PatchPlan, PlannedPatchSource}; /// writer will replace. Entries with no such conflict have no dependencies and /// may run together. pub(crate) fn entry_dependency_indices(plan: &PatchPlan) -> Result>> { - let mut destination_writers = BTreeMap::::new(); + let mut destination_writers = BTreeMap::::new(); for (index, entry) in plan.entries.iter().enumerate() { let logical_destination = plan .install_root .join(&plan.vfs_base_path) .join(&entry.name); - let aliases = [entry.destination.clone(), logical_destination] + let aliases = [&entry.destination, &logical_destination] .into_iter() + .map(|path| crate::artifact::physical_path_key(path)) .collect::>(); for destination in aliases { if destination_writers @@ -27,10 +27,7 @@ pub(crate) fn entry_dependency_indices(plan: &PatchPlan) -> Result Result Result>> { #[cfg(test)] mod tests { + #[cfg(test)] use std::path::PathBuf; use super::*; diff --git a/crates/griffr-runtime/src/patch_apply/hdiff_sf20.rs b/crates/griffr-runtime/src/patch_apply/hdiff_sf20.rs new file mode 100644 index 0000000..db0d181 --- /dev/null +++ b/crates/griffr-runtime/src/patch_apply/hdiff_sf20.rs @@ -0,0 +1,990 @@ +//! Native HDIFFSF20 single-stream decoder with compio positional I/O. +//! The TaskPool owns source verification, staging and atomic output commit; +//! this module only materializes a temporary candidate. +use std::io::{self, ErrorKind}; +use std::path::Path; + +use compio::io::{AsyncReadAt, AsyncWriteAtExt}; +use zstd::stream::raw::{Decoder as ZstdDecoder, Operation}; + +mod checkpoint; +pub use checkpoint::HdiffCheckpoint; + +const IO_CHUNK: usize = 256 * 1024; +const MAX_STEP_MEMORY: usize = 64 * 1024 * 1024; + +fn bad(message: &'static str) -> io::Error { + io::Error::new(ErrorKind::InvalidData, message) +} + +fn packed_uint(bytes: &mut &[u8], tag_bits: u8) -> io::Result { + let Some((&first, rest)) = bytes.split_first() else { + return Err(bad("truncated packed integer")); + }; + let continuation_bit = 1u8 << (7 - tag_bits); + let mut value = u64::from(first & (continuation_bit - 1)); + let mut remaining = rest; + if first & continuation_bit != 0 { + loop { + let Some((&byte, rest)) = remaining.split_first() else { + return Err(bad("truncated packed integer")); + }; + if value > (u64::MAX >> 7) { + return Err(bad("packed integer overflow")); + } + value = (value << 7) | u64::from(byte & 0x7f); + remaining = rest; + if byte & 0x80 == 0 { + break; + } + } + } + *bytes = remaining; + Ok(value) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Compression { + None, + Zstd, +} + +struct Header { + new_size: u64, + old_size: u64, + cover_count: u64, + step_mem_size: usize, + diff_size: u64, + encoded_size: u64, + is_compressed: bool, + data_offset: u64, +} + +impl Header { + fn parse(prefix: &[u8], patch_size: u64) -> io::Result { + let terminator = prefix + .iter() + .position(|&b| b == 0) + .ok_or(bad("missing HDiff magic terminator"))?; + let magic = + std::str::from_utf8(&prefix[..terminator]).map_err(|_| bad("invalid HDiff magic"))?; + let compression = match magic { + "HDIFFSF20&" => Compression::None, + "HDIFFSF20&zstd" => Compression::Zstd, + _ => { + return Err(io::Error::new( + ErrorKind::Unsupported, + format!("unsupported HDiff format or compression: {magic}"), + )) + } + }; + let mut fields = &prefix[terminator + 1..]; + let new_size = packed_uint(&mut fields, 0)?; + let old_size = packed_uint(&mut fields, 0)?; + let cover_count = packed_uint(&mut fields, 0)?; + let step_mem_size = usize::try_from(packed_uint(&mut fields, 0)?) + .map_err(|_| bad("invalid step memory size"))?; + let diff_size = packed_uint(&mut fields, 0)?; + let compressed_size = packed_uint(&mut fields, 0)?; + if step_mem_size == 0 || step_mem_size > MAX_STEP_MEMORY { + return Err(bad("invalid HDiff step memory bound")); + } + if cover_count == 0 { + return Err(bad("HDiff contains no covers")); + } + let consumed = prefix.len() - fields.len(); + let data_offset = consumed as u64; + let encoded_size = if compressed_size == 0 { + diff_size + } else { + compressed_size + }; + if data_offset.checked_add(encoded_size) != Some(patch_size) { + return Err(bad("HDiff payload length does not match patch file size")); + } + if compressed_size > 0 && compression == Compression::None { + return Err(bad("compressed payload without declared codec")); + } + Ok(Self { + new_size, + old_size, + cover_count, + step_mem_size, + diff_size, + encoded_size, + is_compressed: compressed_size > 0, + data_offset, + }) + } +} + +/// Validate the canonical wire header before allowing install mutation. +pub(super) fn validate_input(path: &Path, old_size: u64, new_size: u64) -> io::Result<()> { + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let size = file.metadata()?.len(); + let mut prefix = vec![0; size.min(512) as usize]; + file.read_exact(&mut prefix)?; + let header = Header::parse(&prefix, size)?; + if header.old_size != old_size || header.new_size != new_size { + return Err(bad( + "HDiff header sizes differ from the selected patch plan", + )); + } + Ok(()) +} + +/// HDiff cover positions are relative to the preceding cover's end, NOT the +/// current step's beginning. Resetting this state at a step boundary causes +/// the "cover oldPos underflow" failure with negative cross-step deltas. +#[derive(Default)] +struct Covers { + old_pos: u64, + new_pos: u64, + length: u64, +} + +struct Cover { + old_pos: u64, + new_pos: u64, + new_gap_start: u64, + length: u64, +} + +impl Covers { + fn next(&mut self, data: &mut &[u8]) -> io::Result { + let is_negative = data.first().ok_or(bad("missing cover"))? & 0x80 != 0; + let old_end = self + .old_pos + .checked_add(self.length) + .ok_or(bad("old cover end overflow"))?; + let new_end = self + .new_pos + .checked_add(self.length) + .ok_or(bad("new cover end overflow"))?; + let delta = packed_uint(data, 1)?; + let old_pos = if is_negative { + old_end + .checked_sub(delta) + .ok_or(bad("cover oldPos underflow"))? + } else { + old_end + .checked_add(delta) + .ok_or(bad("cover oldPos overflow"))? + }; + let new_pos = new_end + .checked_add(packed_uint(data, 0)?) + .ok_or(bad("cover newPos overflow"))?; + let length = packed_uint(data, 0)?; + self.old_pos = old_pos; + self.new_pos = new_pos; + self.length = length; + Ok(Cover { + old_pos, + new_pos, + new_gap_start: new_end, + length, + }) + } +} + +struct Rle0 { + offset: usize, + zero_remaining: u64, + value_remaining: u64, + decode_zero: bool, +} + +impl Rle0 { + fn new(offset: usize) -> Self { + Self { + offset, + zero_remaining: 0, + value_remaining: 0, + decode_zero: true, + } + } + + fn add(&mut self, step: &[u8], target: &mut [u8]) -> io::Result<()> { + let mut codes = &step[self.offset..]; + let mut pos = 0; + while pos < target.len() { + if self.zero_remaining != 0 { + let n = self.zero_remaining.min((target.len() - pos) as u64); + self.zero_remaining -= n; + pos += n as usize; + } else if self.value_remaining != 0 { + let n = self.value_remaining.min((target.len() - pos) as u64) as usize; + if n > codes.len() { + return Err(bad("RLE value data exhausted")); + } + for (dst, source) in target[pos..pos + n].iter_mut().zip(&codes[..n]) { + *dst = dst.wrapping_add(*source); + } + codes = &codes[n..]; + self.value_remaining -= n as u64; + pos += n; + } else if self.decode_zero { + self.decode_zero = false; + self.zero_remaining = packed_uint(&mut codes, 0)?; + } else { + self.decode_zero = true; + self.value_remaining = packed_uint(&mut codes, 0)?; + if self.value_remaining > codes.len() as u64 { + return Err(bad("RLE value run exceeds step buffer")); + } + } + } + self.offset = step.len() - codes.len(); + Ok(()) + } +} + +struct AsyncDiff { + file_offset: u64, + bytes_left: u64, + expected: u64, + delivered: u64, + decoder: Option>, + encoded: Vec, + encoded_pos: usize, + decoded: Vec, + decoded_pos: usize, + frame_finished: bool, +} + +impl AsyncDiff { + fn new(header: &Header) -> io::Result { + let mut decoder = if header.is_compressed { + Some(ZstdDecoder::new()?) + } else { + None + }; + if let Some(ref mut decoder) = decoder { + decoder.set_parameter(zstd::zstd_safe::DParameter::WindowLogMax(27))?; + } + Ok(Self { + file_offset: header.data_offset, + bytes_left: header.encoded_size, + expected: header.diff_size, + delivered: 0, + decoder, + encoded: Vec::new(), + encoded_pos: 0, + decoded: Vec::new(), + decoded_pos: 0, + frame_finished: false, + }) + } + + async fn refill_encoded(&mut self, input: &compio::fs::File) -> io::Result { + if self.bytes_left == 0 { + return Ok(false); + } + let request = self.bytes_left.min(IO_CHUNK as u64) as usize; + let compio::BufResult(result, data) = + input.read_at(vec![0; request], self.file_offset).await; + let count = result?; + if count == 0 { + return Err(io::Error::new( + ErrorKind::UnexpectedEof, + "truncated HDiff input", + )); + } + self.file_offset += count as u64; + self.bytes_left -= count as u64; + self.encoded = data[..count].to_vec(); + self.encoded_pos = 0; + Ok(true) + } + + async fn refill_decoded(&mut self, input: &compio::fs::File) -> io::Result<()> { + if self.frame_finished { + return Err(io::Error::new( + ErrorKind::UnexpectedEof, + "HDiff compressed frame ended before declared output", + )); + } + self.decoded_pos = 0; + self.decoded.clear(); + loop { + if self.encoded_pos == self.encoded.len() && !self.refill_encoded(input).await? { + return Err(io::Error::new( + ErrorKind::UnexpectedEof, + "HDiff decoded stream ended prematurely", + )); + } + if let Some(ref mut decoder) = self.decoder { + let mut dest = vec![0u8; IO_CHUNK]; + let status = + decoder.run_on_buffers(&self.encoded[self.encoded_pos..], &mut dest)?; + self.encoded_pos += status.bytes_read; + if status.remaining == 0 { + self.frame_finished = true; + if self.bytes_left != 0 || self.encoded_pos != self.encoded.len() { + return Err(bad("HDiff contains trailing compressed frame data")); + } + } + dest.truncate(status.bytes_written); + if !dest.is_empty() { + self.decoded = dest; + return Ok(()); + } + if status.bytes_read == 0 { + return Err(bad("compressed HDiff stream made no decoding progress")); + } + } else { + self.decoded = self.encoded[self.encoded_pos..].to_vec(); + self.encoded_pos = self.encoded.len(); + return Ok(()); + } + } + } + + async fn exact(&mut self, input: &compio::fs::File, output: &mut [u8]) -> io::Result<()> { + if (output.len() as u64) > self.expected.saturating_sub(self.delivered) { + return Err(bad("HDiff decoded data exceeds declared size")); + } + let mut copied = 0; + while copied < output.len() { + if self.decoded_pos == self.decoded.len() { + self.refill_decoded(input).await?; + } + let n = (output.len() - copied).min(self.decoded.len() - self.decoded_pos); + output[copied..copied + n] + .copy_from_slice(&self.decoded[self.decoded_pos..self.decoded_pos + n]); + self.decoded_pos += n; + copied += n; + } + self.delivered += output.len() as u64; + Ok(()) + } + + async fn uint(&mut self, input: &compio::fs::File) -> io::Result { + let mut first = [0u8; 1]; + self.exact(input, &mut first).await?; + let mut value = u64::from(first[0] & 0x7f); + if first[0] & 0x80 != 0 { + loop { + let mut next = [0u8; 1]; + self.exact(input, &mut next).await?; + if value > (u64::MAX >> 7) { + return Err(bad("HDiff packed integer overflow")); + } + value = (value << 7) | u64::from(next[0] & 0x7f); + if next[0] & 0x80 == 0 { + break; + } + } + } + Ok(value) + } + + async fn finish(&mut self, input: &compio::fs::File) -> io::Result<()> { + if self.delivered != self.expected || self.decoded_pos != self.decoded.len() { + return Err(bad( + "HDiff stream contains trailing or missing decoded bytes", + )); + } + if self.decoder.is_none() { + if self.bytes_left != 0 || self.encoded_pos != self.encoded.len() { + return Err(bad("HDiff uncompressed stream has unread input")); + } + return Ok(()); + } + // Reaching the advertised byte count is not enough: validate the + // compressed frame trailer/checksum and reject additional frames. + while !self.frame_finished { + if self.encoded_pos == self.encoded.len() && !self.refill_encoded(input).await? { + return Err(io::Error::new( + ErrorKind::UnexpectedEof, + "HDiff zstd frame trailer is truncated", + )); + } + let mut probe = [0u8; 1]; + let status = self + .decoder + .as_mut() + .expect("checked decoder") + .run_on_buffers(&self.encoded[self.encoded_pos..], &mut probe)?; + self.encoded_pos += status.bytes_read; + if status.bytes_written != 0 { + return Err(bad("HDiff decoded beyond declared size")); + } + if status.remaining == 0 { + self.frame_finished = true; + } else if status.bytes_read == 0 { + return Err(bad("HDiff zstd frame could not finish")); + } + } + if self.bytes_left != 0 || self.encoded_pos != self.encoded.len() { + return Err(bad("HDiff contains trailing compressed frame data")); + } + Ok(()) + } +} + +struct Step { + buffer: Vec, + expected_len: usize, + cover_end: usize, + cover_offset: usize, + rle: Rle0, +} + +struct Decoder { + header: Header, + diff: AsyncDiff, + covers: Covers, + remaining_covers: u64, + written: u64, + step: Option, + cover: Option, +} + +impl Decoder { + async fn start(base: &compio::fs::File, patch: &compio::fs::File) -> io::Result { + let patch_size = patch.metadata().await?.len(); + let compio::BufResult(result, prefix) = patch.read_at(vec![0u8; 512], 0).await; + let header = Header::parse(&prefix[..result?], patch_size)?; + if base.metadata().await?.len() != header.old_size { + return Err(bad("HDiff base file size differs from header")); + } + Ok(Self { + diff: AsyncDiff::new(&header)?, + covers: Covers::default(), + remaining_covers: header.cover_count, + header, + written: 0, + step: None, + cover: None, + }) + } + + async fn advance( + &mut self, + base: &compio::fs::File, + patch: &compio::fs::File, + output: &mut compio::fs::File, + mut budget: usize, + ) -> io::Result { + while budget != 0 { + if self.step.is_none() { + if self.remaining_covers == 0 { + if self.written != self.header.new_size { + return Err(bad("HDiff output size differs from header")); + } + self.diff.finish(patch).await?; + return Ok(true); + } + let cover_end = usize::try_from(self.diff.uint(patch).await?) + .map_err(|_| bad("cover buffer too large"))?; + let rle_len = usize::try_from(self.diff.uint(patch).await?) + .map_err(|_| bad("RLE buffer too large"))?; + let total = cover_end + .checked_add(rle_len) + .ok_or(bad("step buffer overflow"))?; + if cover_end == 0 || total > self.header.step_mem_size { + return Err(bad("invalid HDiff step buffer lengths")); + } + self.step = Some(Step { + buffer: Vec::with_capacity(total), + expected_len: total, + cover_end, + cover_offset: 0, + rle: Rle0::new(cover_end), + }); + } + let step = self.step.as_mut().unwrap(); + let filled = step.buffer.len(); + if filled < step.expected_len { + let length = (step.expected_len - filled).min(budget).min(IO_CHUNK); + step.buffer.resize(filled + length, 0); + self.diff.exact(patch, &mut step.buffer[filled..]).await?; + budget -= length; + continue; + } + if self.cover.is_none() { + if step.cover_offset == step.cover_end { + self.step = None; + continue; + } + if self.remaining_covers == 0 { + return Err(bad("too many HDiff covers")); + } + let mut remaining = &step.buffer[step.cover_offset..step.cover_end]; + let cover = self.covers.next(&mut remaining)?; + step.cover_offset = step.cover_end - remaining.len(); + if cover.new_gap_start != self.written { + return Err(bad("HDiff covers overlap or skip output")); + } + if cover + .new_pos + .checked_add(cover.length) + .is_none_or(|end| end > self.header.new_size) + { + return Err(bad("HDiff cover exceeds expected output")); + } + if cover + .old_pos + .checked_add(cover.length) + .is_none_or(|end| end > self.header.old_size) + { + return Err(bad("HDiff cover exceeds base")); + } + self.remaining_covers -= 1; + if cover.length == 0 && self.remaining_covers != 0 { + return Err(bad("zero-length non-final HDiff cover")); + } + self.cover = Some(cover); + // Cover parsing also consumes a quantum when covers are tiny. + budget = budget.saturating_sub(32); + continue; + } + let cover = self.cover.as_ref().unwrap(); + let max_chunk = budget.min(IO_CHUNK) as u64; + let bytes = if self.written < cover.new_pos { + let length = (cover.new_pos - self.written).min(max_chunk) as usize; + let mut bytes = vec![0; length]; + self.diff.exact(patch, &mut bytes).await?; + bytes + } else if self.written < cover.new_pos + cover.length { + let offset = self.written - cover.new_pos; + let length = (cover.length - offset).min(max_chunk) as usize; + let compio::BufResult(result, mut bytes) = + base.read_at(vec![0; length], cover.old_pos + offset).await; + let len = result?; + if len == 0 { + return Err(io::Error::new( + ErrorKind::UnexpectedEof, + "HDiff base ended mid-cover", + )); + } + bytes.truncate(len); + step.rle.add(&step.buffer, &mut bytes)?; + bytes + } else { + self.cover = None; + continue; + }; + let written = bytes.len(); + let compio::BufResult(result, _) = output.write_all_at(bytes, self.written).await; + result?; + self.written += written as u64; + budget -= written; + } + Ok(false) + } +} + +/// Create a new temporary candidate for the decoder tests. +#[cfg(test)] +async fn apply(base: &Path, patch: &Path, temporary: &Path) -> io::Result<()> { + let base = compio::fs::File::open(base).await?; + let patch = compio::fs::File::open(patch).await?; + let mut decoder = Decoder::start(&base, &patch).await?; + let mut output = compio::fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(temporary) + .await?; + decoder + .advance(&base, &patch, &mut output, usize::MAX) + .await?; + output.sync_all().await?; + output.close().await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn enc(mut n: u64) -> Vec { + let mut result = vec![(n & 0x7f) as u8]; + n >>= 7; + while n > 0 { + result.push((n & 0x7f) as u8); + n >>= 7; + } + result.reverse(); + let prefix_len = result.len().saturating_sub(1); + for b in &mut result[..prefix_len] { + *b |= 0x80; + } + result + } + + fn cover(delta: u8, negative: bool, new_gap: u64, length: u64) -> Vec { + assert!(delta < 64); + let mut result = vec![delta | if negative { 0x80 } else { 0 }]; + result.extend(enc(new_gap)); + result.extend(enc(length)); + result + } + + fn step(covers: &[u8], rle: &[u8], literals: &[u8], out: &mut Vec) { + out.extend(enc(covers.len() as u64)); + out.extend(enc(rle.len() as u64)); + out.extend(covers); + out.extend(rle); + out.extend(literals); + } + + fn patch_data(old_size: u64, new_size: u64, payload: &[u8], compressed: bool) -> Vec { + let (encoding, encoded) = if compressed { + ("zstd", zstd::bulk::compress(payload, 1).unwrap()) + } else { + ("", payload.to_vec()) + }; + let mut bytes = format!("HDIFFSF20&{encoding}\0").into_bytes(); + for n in [ + new_size, + old_size, + 2, + 4096, + payload.len() as u64, + if compressed { encoded.len() as u64 } else { 0 }, + ] { + bytes.extend(enc(n)); + } + bytes.extend(encoded); + bytes + } + + #[test] + fn keeps_old_and_new_positions_across_steps() { + let mut covers = Covers::default(); + let first = cover(2, false, 0, 4); + let a = covers.next(&mut first.as_slice()).unwrap(); + assert_eq!((a.old_pos, a.new_pos, a.length), (2, 0, 4)); + let next = cover(3, true, 1, 3); + let b = covers.next(&mut next.as_slice()).unwrap(); + assert_eq!((b.old_pos, b.new_pos, b.length), (3, 5, 3)); + let mut invalid = next.as_slice(); + assert!(Covers::default().next(&mut invalid).is_err()); + } + + #[compio::test] + async fn patches_cross_step_negative_delta_uncompressed() { + round_trip(false).await; + } + + #[compio::test] + async fn patches_cross_step_negative_delta_zstd() { + round_trip(true).await; + } + + async fn round_trip(compressed: bool) { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path().join("base.bin"); + let patch = tmp.path().join("delta.patch"); + let output = tmp.path().join("new.bin"); + let original = b"0123456789abcdef"; + std::fs::write(&base, original).unwrap(); + let mut data = Vec::new(); + // Cover #1: base[2..6] => "2345". + step(&cover(2, false, 0, 4), &enc(4), &[], &mut data); + // Cover #2: base[3..6], with literal "X" before its new position. + step(&cover(3, true, 1, 3), &enc(3), b"X", &mut data); + std::fs::write( + &patch, + patch_data(original.len() as u64, 8, &data, compressed), + ) + .unwrap(); + apply(&base, &patch, &output).await.unwrap(); + assert_eq!(std::fs::read(output).unwrap(), b"2345X345"); + } + + #[test] + fn rle_values_wrap_and_signed_cover_positions_are_checked() { + let mut bytes = Vec::new(); + bytes.extend(enc(0)); + bytes.extend(enc(3)); + bytes.extend([1u8, 255, 3]); + let mut rle = Rle0::new(0); + let mut target = [255u8, 1, 254]; + rle.add(&bytes, &mut target).unwrap(); + assert_eq!(target, [0, 0, 1]); + let invalid = [0x81, 0, 1]; + assert!(Covers::default().next(&mut invalid.as_slice()).is_err()); + } + + #[compio::test] + async fn streams_more_than_one_io_buffer_through_zstd() { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path().join("base"); + let patch = tmp.path().join("patch"); + let output = tmp.path().join("out"); + std::fs::write(&base, b"abcdefgh").unwrap(); + let literal = vec![0x42u8; IO_CHUNK * 2 + 33]; + let mut data = Vec::new(); + step(&cover(0, false, 0, 1), &enc(1), &[], &mut data); + step( + &cover(0, false, literal.len() as u64, 0), + &[], + &literal, + &mut data, + ); + std::fs::write(&patch, patch_data(8, literal.len() as u64 + 1, &data, true)).unwrap(); + apply(&base, &patch, &output).await.unwrap(); + let actual = std::fs::read(output).unwrap(); + assert_eq!(&actual[..1], b"a"); + assert_eq!(&actual[1..], literal); + } + + #[compio::test] + async fn rejects_mismatched_old_file_without_creating_temporary() { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path().join("base"); + let patch = tmp.path().join("patch"); + let output = tmp.path().join("out"); + std::fs::write(&base, b"short").unwrap(); + std::fs::write(&patch, patch_data(20, 1, &[1, 0, 0], false)).unwrap(); + assert!(apply(&base, &patch, &output).await.is_err()); + assert!(!output.exists()); + } + + #[test] + fn rejects_non_sf20_and_unbounded_step_allocation() { + let mut bad_magic = b"HDIFF13&zstd\0".to_vec(); + bad_magic.extend([1, 1, 1, 8, 1, 0, 0]); + assert_eq!( + Header::parse(&bad_magic, bad_magic.len() as u64) + .err() + .unwrap() + .kind(), + ErrorKind::Unsupported + ); + let mut too_large = b"HDIFFSF20&\0".to_vec(); + for n in [1, 1, 1, MAX_STEP_MEMORY as u64 + 1, 1, 0] { + too_large.extend(enc(n)); + } + too_large.push(0); + assert!(Header::parse(&too_large, too_large.len() as u64).is_err()); + } + #[compio::test] + async fn official_hdiffz_sf20_zstd_matches_hpatchz() { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path().join("base"); + let patch = tmp.path().join("patch"); + let output = tmp.path().join("output"); + let old = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + let mut expected = old.clone(); + for (i, value) in expected.iter_mut().enumerate().skip(2550).take(300) { + *value = (((i - 2550) * 17) % 256) as u8; + } + std::fs::write(&base, old).unwrap(); + std::fs::write(&patch, include_bytes!("hdiff_sf20_reference_zstd.patch")).unwrap(); + apply(&base, &patch, &output).await.unwrap(); + assert_eq!(std::fs::read(output).unwrap(), expected); + } + #[compio::test] + async fn official_hdiffz_handles_zero_old_and_trailing_literals() { + for (old, expected, patch_data) in [ + ( + Vec::new(), + (0..13007) + .map(|i| ((i * 197 + 17) % 256) as u8) + .collect::>(), + include_bytes!("hdiff_sf20_reference_empty.patch").as_slice(), + ), + ( + (0..8192).map(|i| ((i * 47 + 13) % 256) as u8).collect(), + { + let mut result = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + result.extend((0..901).map(|i| ((i * 13 + 3) % 256) as u8)); + result + }, + include_bytes!("hdiff_sf20_reference_tail.patch").as_slice(), + ), + ( + (0..8192).map(|i| ((i * 47 + 13) % 256) as u8).collect(), + { + let mut result = (100..600) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + result.extend((0..591).map(|i| ((i * 13 + 3) % 256) as u8)); + result + }, + include_bytes!("hdiff_sf20_reference_small.patch").as_slice(), + ), + ] { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().join("old"); + let patch = temp.path().join("patch"); + let output = temp.path().join("output"); + std::fs::write(&base, old).unwrap(); + std::fs::write(&patch, patch_data).unwrap(); + apply(&base, &patch, &output).await.unwrap(); + assert_eq!(std::fs::read(output).unwrap(), expected); + } + } + + #[compio::test] + async fn rejects_trailing_patch_bytes_even_with_valid_output() { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().join("base"); + let patch = temp.path().join("patch"); + let output = temp.path().join("output"); + std::fs::write(&base, std::iter::repeat_n(0u8, 8192).collect::>()).unwrap(); + let mut input = include_bytes!("hdiff_sf20_reference_tail.patch").to_vec(); + input.extend_from_slice(b"ignored trailing data"); + std::fs::write(&patch, input).unwrap(); + assert!(apply(&base, &patch, &output).await.is_err()); + assert!(!output.exists()); + } + + fn override_encoded_size(patch: &mut Vec, next: u64) { + let offset = patch.iter().position(|byte| *byte == 0).unwrap() + 1; + let mut input = &patch[offset..]; + for _ in 0..5 { + packed_uint(&mut input, 0).unwrap(); + } + let start = patch.len() - input.len(); + packed_uint(&mut input, 0).unwrap(); + let end = patch.len() - input.len(); + patch.splice(start..end, enc(next)); + } + + #[compio::test] + async fn rejects_truncated_zstd_trailer_and_concatenated_frame() { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().join("base"); + let patch = temp.path().join("patch"); + let output = temp.path().join("output"); + let old = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + std::fs::write(&base, old).unwrap(); + let reference = include_bytes!("hdiff_sf20_reference_tail.patch"); + let mut extra_frame = reference.to_vec(); + let extension = zstd::bulk::compress(b"extra", 1).unwrap(); + extra_frame.extend(&extension); + // The extra frame is included *inside* the declared compressed input + // rather than rejected only because bytes follow the patch boundary. + let old_size = Header::parse(reference, reference.len() as u64) + .unwrap() + .encoded_size; + override_encoded_size(&mut extra_frame, old_size + extension.len() as u64); + std::fs::write(&patch, &extra_frame).unwrap(); + let error = apply(&base, &patch, &output).await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::InvalidData); + assert_eq!( + error.to_string(), + "HDiff contains trailing compressed frame data" + ); + + // A reference frame need not have a checksum. Re-encode the same + // diff with one so the truncated byte is known to be in the trailer. + let header = Header::parse(reference, reference.len() as u64).unwrap(); + let diff = zstd::decode_all(&reference[header.data_offset as usize..]).unwrap(); + let mut encoder = zstd::stream::Encoder::new(Vec::new(), 1).unwrap(); + encoder.include_checksum(true).unwrap(); + std::io::Write::write_all(&mut encoder, &diff).unwrap(); + let mut checksummed = encoder.finish().unwrap(); + checksummed.pop(); + let mut truncated = reference[..header.data_offset as usize].to_vec(); + override_encoded_size(&mut truncated, checksummed.len() as u64); + truncated.extend(checksummed); + std::fs::write(&patch, truncated).unwrap(); + let error = apply(&base, &patch, &temp.path().join("truncated-output")) + .await + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::UnexpectedEof); + assert_eq!(error.to_string(), "HDiff zstd frame trailer is truncated"); + } + + #[compio::test] + async fn checkpoint_generations_have_one_consumer() { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().join("base.bin"); + let patch = temp.path().join("delta.patch"); + let output = temp.path().join("output"); + std::fs::write(&base, b"0123456789").unwrap(); + let mut data = Vec::new(); + step(&cover(1, false, 0, 3), &enc(3), &[], &mut data); + step(&cover(1, true, 0, 3), &enc(3), &[], &mut data); + std::fs::write(&patch, patch_data(10, 6, &data, true)).unwrap(); + + let initial = HdiffCheckpoint::default(); + let stale = initial.clone(); + // Four step bytes, one cover's bookkeeping, then two output bytes. + let next = initial + .advance(&base, &patch, &output, 6, 38) + .await + .unwrap() + .unwrap(); + assert_eq!(next.written(), 2); + let error = stale + .advance(&base, &patch, &output, 6, 2) + .await + .unwrap_err(); + assert_eq!(error.to_string(), "HDiff checkpoint was already consumed"); + + let stale = next.clone(); + assert!(next + .advance(&base, &patch, &output, 6, usize::MAX) + .await + .unwrap() + .is_none()); + assert_eq!(std::fs::read(&output).unwrap(), b"123345"); + assert!(stale.advance(&base, &patch, &output, 6, 2).await.is_err()); + } + + #[compio::test] + async fn checkpoint_rejects_replaced_inputs_and_output() { + for file in ["base.bin", "delta.patch", "output"] { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().join("base.bin"); + let patch = temp.path().join("delta.patch"); + let output = temp.path().join("output"); + std::fs::write(&base, b"0123456789").unwrap(); + let mut data = Vec::new(); + step(&cover(1, false, 0, 3), &enc(3), &[], &mut data); + step(&cover(1, true, 0, 3), &enc(3), &[], &mut data); + std::fs::write(&patch, patch_data(10, 6, &data, false)).unwrap(); + let checkpoint = HdiffCheckpoint::default() + .advance(&base, &patch, &output, 6, 2) + .await + .unwrap() + .unwrap(); + + let changed = temp.path().join(file); + let old = temp.path().join("old"); + std::fs::rename(&changed, &old).unwrap(); + std::fs::copy(&old, &changed).unwrap(); + let stale = checkpoint.clone(); + let error = checkpoint + .advance(&base, &patch, &output, 6, 2) + .await + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::InvalidData); + assert!(error.to_string().contains("changed between WorkUnits")); + let error = stale + .advance(&base, &patch, &output, 6, 2) + .await + .unwrap_err(); + assert_eq!(error.to_string(), "HDiff checkpoint was already consumed"); + } + } + + #[compio::test] + async fn rejects_truncated_payload() { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path().join("base.bin"); + let patch = tmp.path().join("bad.patch"); + let output = tmp.path().join("out.bin"); + std::fs::write(&base, b"0123456789").unwrap(); + let mut data = Vec::new(); + step(&cover(1, false, 0, 3), &enc(3), &[], &mut data); + step(&cover(1, true, 0, 3), &enc(3), &[], &mut data); + let mut encoded = patch_data(10, 6, &data, true); + encoded.truncate(encoded.len() - 2); + std::fs::write(&patch, encoded).unwrap(); + assert!(apply(&base, &patch, &output).await.is_err()); + } +} diff --git a/crates/griffr-runtime/src/patch_apply/hdiff_sf20/checkpoint.rs b/crates/griffr-runtime/src/patch_apply/hdiff_sf20/checkpoint.rs new file mode 100644 index 0000000..c15b336 --- /dev/null +++ b/crates/griffr-runtime/src/patch_apply/hdiff_sf20/checkpoint.rs @@ -0,0 +1,318 @@ +use std::io; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use compio::fs::File; + +use super::{bad, Decoder}; + +/// A checkpoint generation can be consumed once. Cloning a task does not +/// allow it to resume the same generation or take a later generation's state. +#[doc(hidden)] +#[derive(Clone)] +pub struct HdiffCheckpoint { + state: Arc>>, + initial: bool, + #[cfg(test)] + panic_after_take: bool, + #[cfg(test)] + storage_full_on_allocate: bool, +} + +struct Cursor { + resume: Option, +} + +struct Resume { + decoder: Decoder, + base: FileStamp, + patch: FileStamp, + output_id: (u64, u128), + allocation: std::fs::File, + allocation_confirmed: bool, +} + +impl Default for HdiffCheckpoint { + fn default() -> Self { + Self { + state: Arc::new(Mutex::new(Some(Cursor { resume: None }))), + initial: true, + #[cfg(test)] + panic_after_take: false, + #[cfg(test)] + storage_full_on_allocate: false, + } + } +} + +impl std::fmt::Debug for HdiffCheckpoint { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("HdiffCheckpoint") + .field("initial", &self.initial) + .finish_non_exhaustive() + } +} + +impl HdiffCheckpoint { + pub(crate) fn is_initial(&self) -> bool { + self.initial + } + + pub(crate) fn written(&self) -> u64 { + self.state + .lock() + .unwrap() + .as_ref() + .and_then(|cursor| cursor.resume.as_ref()) + .map_or(0, |resume| resume.decoder.written) + } + + pub(crate) fn has_preallocated_output(&self) -> bool { + self.state + .lock() + .unwrap() + .as_ref() + .and_then(|cursor| cursor.resume.as_ref()) + .is_some_and(|resume| resume.allocation_confirmed) + } + + #[cfg(test)] + pub(crate) fn inject_panic_after_take(&mut self) { + self.panic_after_take = true; + } + + #[cfg(test)] + pub(crate) fn inject_storage_full_on_allocate(&mut self) { + self.storage_full_on_allocate = true; + } + + /// Take exclusive ownership before any I/O. Error or cancellation consumes + /// the checkpoint. Recovery rebuilds the unpublished output from the plan. + pub(crate) async fn advance( + self, + base_path: &Path, + patch_path: &Path, + output_path: &Path, + expected_size: u64, + budget: usize, + ) -> io::Result> { + let cursor = self + .state + .lock() + .unwrap() + .take() + .ok_or_else(|| bad("HDiff checkpoint was already consumed"))?; + #[cfg(test)] + assert!( + !self.panic_after_take, + "injected panic after taking HDiff cursor" + ); + + // File handles are reopened on each dispatcher runtime so no driver + // registration crosses a WorkUnit boundary. + let base = File::open(base_path).await?; + let patch = File::open(patch_path).await?; + let original_base = FileStamp::read(&base).await?; + let original_patch = FileStamp::read(&patch).await?; + let (mut decoder, expected_output_id, allocation, allocation_confirmed) = + match cursor.resume { + Some(resume) => { + if resume.decoder.header.new_size != expected_size { + return Err(bad("HDiff output size differs from planned size")); + } + if resume.base != original_base || resume.patch != original_patch { + return Err(bad("HDiff base or patch changed between WorkUnits")); + } + ( + resume.decoder, + Some(resume.output_id), + resume.allocation, + resume.allocation_confirmed, + ) + } + None => { + let decoder = Decoder::start(&base, &patch).await?; + if decoder.header.new_size != expected_size { + return Err(bad("HDiff output size differs from planned size")); + } + let (allocation, confirmed) = allocate_output( + output_path, + expected_size, + #[cfg(test)] + self.storage_full_on_allocate, + ) + .await?; + (decoder, None, allocation, confirmed) + } + }; + let mut output = compio::fs::OpenOptions::new() + .write(true) + .open(output_path) + .await?; + let stamp = FileStamp::read(&output).await?; + if expected_output_id.is_some_and(|id| id != stamp.id) || stamp.len != decoder.written { + return Err(bad("HDiff temporary output changed between WorkUnits")); + } + + let result = match decoder.advance(&base, &patch, &mut output, budget).await { + Ok(true) => output.sync_all().await.map(|()| true), + result => result, + }; + let closed = output.close().await; + let completed = result?; + closed?; + if completed { + return Ok(None); + } + + Ok(Some(Self { + state: Arc::new(Mutex::new(Some(Cursor { + resume: Some(Resume { + decoder, + base: original_base, + patch: original_patch, + output_id: stamp.id, + allocation, + allocation_confirmed, + }), + }))), + initial: false, + #[cfg(test)] + panic_after_take: false, + #[cfg(test)] + storage_full_on_allocate: false, + })) + } +} + +/// Keep an unregistered handle so the Windows allocation survives closing +/// the compio execution handles. It is owned by the decoder until the last +/// byte is written (or until an error/cancellation discards the candidate). +async fn allocate_output( + path: &Path, + bytes: u64, + #[cfg(test)] storage_full_on_allocate: bool, +) -> io::Result<(std::fs::File, bool)> { + let path = path.to_path_buf(); + use crate::error::Error; + + // The decode WorkUnit owns a CPU slot. The shared blocking pool is + // sized for CPU + non-CPU blocking work plus compio fallback headroom. + crate::compat_fs::run_blocking("HDiff output allocation", move || { + let file = create_allocated_output( + &path, + bytes, + #[cfg(test)] + storage_full_on_allocate, + )?; + Ok(file) + }) + .await + .map_err(|error| match error { + Error::IoAt { source, .. } | Error::Io(source) => source, + other => io::Error::other(other), + }) +} + +fn create_allocated_output( + path: &Path, + bytes: u64, + #[cfg(test)] storage_full_on_allocate: bool, +) -> crate::error::Result<(std::fs::File, bool)> { + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path)?; + #[cfg(test)] + if storage_full_on_allocate { + // Exercise the error boundary after creating the unpublished file, + // without filling a shared physical volume or requiring a mount. + return Err(crate::error::Error::IoAt { + action: "write to file", + path: path.to_path_buf(), + source: io::Error::new( + io::ErrorKind::StorageFull, + "injected allocation storage full", + ), + }); + } + let confirmed = crate::preallocate_file(&file, path, bytes)?; + Ok((file, confirmed)) +} + +#[derive(PartialEq, Eq)] +struct FileStamp { + id: (u64, u128), + len: u64, + #[cfg(windows)] + modified: u64, + #[cfg(unix)] + modified: std::time::SystemTime, +} + +impl FileStamp { + #[cfg(windows)] + async fn read(file: &File) -> io::Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED}; + use windows_sys::Win32::Storage::FileSystem::{ + FileIdInfo, GetFileInformationByHandle, GetFileInformationByHandleEx, + BY_HANDLE_FILE_INFORMATION, FILE_ID_INFO, + }; + + let mut info = std::mem::MaybeUninit::::uninit(); + // The open compio file owns the borrowed handle throughout this call. + if unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) } == 0 { + return Err(io::Error::last_os_error()); + } + let info = unsafe { info.assume_init() }; + let combine = |hi, lo| (u64::from(hi) << 32) | u64::from(lo); + // ReFS needs the full 128-bit ID. Older file systems can return + // only the legacy 64-bit ID from BY_HANDLE_FILE_INFORMATION. + let mut file_id = std::mem::MaybeUninit::::uninit(); + let id = if unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle(), + FileIdInfo, + file_id.as_mut_ptr().cast(), + std::mem::size_of::() as u32, + ) + } != 0 + { + let file_id = unsafe { file_id.assume_init() }; + ( + file_id.VolumeSerialNumber, + u128::from_le_bytes(file_id.FileId.Identifier), + ) + } else { + let error = io::Error::last_os_error(); + match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_INVALID_PARAMETER | ERROR_NOT_SUPPORTED) => ( + u64::from(info.dwVolumeSerialNumber), + u128::from(combine(info.nFileIndexHigh, info.nFileIndexLow)), + ), + _ => return Err(error), + } + }; + Ok(Self { + id, + len: combine(info.nFileSizeHigh, info.nFileSizeLow), + modified: combine( + info.ftLastWriteTime.dwHighDateTime, + info.ftLastWriteTime.dwLowDateTime, + ), + }) + } + + #[cfg(unix)] + async fn read(file: &File) -> io::Result { + use std::os::unix::fs::MetadataExt; + let metadata = file.metadata().await?; + Ok(Self { + id: (metadata.dev(), u128::from(metadata.ino())), + len: metadata.len(), + modified: metadata.modified()?, + }) + } +} diff --git a/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_empty.patch b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_empty.patch new file mode 100644 index 0000000..2fcb133 Binary files /dev/null and b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_empty.patch differ diff --git a/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_small.patch b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_small.patch new file mode 100644 index 0000000..9b39070 Binary files /dev/null and b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_small.patch differ diff --git a/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_tail.patch b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_tail.patch new file mode 100644 index 0000000..92b9b0c Binary files /dev/null and b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_tail.patch differ diff --git a/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_zstd.patch b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_zstd.patch new file mode 100644 index 0000000..0e836a2 Binary files /dev/null and b/crates/griffr-runtime/src/patch_apply/hdiff_sf20_reference_zstd.patch differ diff --git a/crates/griffr-runtime/src/patch_apply/mod.rs b/crates/griffr-runtime/src/patch_apply/mod.rs index e91bd0f..ff218cb 100644 --- a/crates/griffr-runtime/src/patch_apply/mod.rs +++ b/crates/griffr-runtime/src/patch_apply/mod.rs @@ -1,5 +1,8 @@ mod build_plan; +pub(crate) use build_plan::plan_extracted_patch; mod dependency; +#[cfg(feature = "hdiff-patch")] +pub(crate) mod hdiff_sf20; mod metadata; mod plan; mod plan_file; @@ -27,6 +30,29 @@ pub use space::available_space; pub(crate) use storage::write_asset_storage_layout; pub use storage::{read_asset_storage_layout, AssetStorageLayout}; +/// Check the same wire contract at archive staging and recovery. +pub(crate) fn validate_hdiff_input( + path: &std::path::Path, + old_size: u64, + new_size: u64, +) -> crate::error::Result<()> { + #[cfg(feature = "hdiff-patch")] + let result = hdiff_sf20::validate_input(path, old_size, new_size); + #[cfg(not(feature = "hdiff-patch"))] + let result = { + let _ = (old_size, new_size); + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "HDiff patch feature is disabled", + )) + }; + result.map_err(|source| crate::error::Error::IoAt { + action: "validate HDiff input", + path: path.to_path_buf(), + source, + }) +} + pub const PATCH_DEFERRED_DIR: &str = "deferred"; pub const PATCH_PLAN_NAME: &str = "plan.json"; pub const ASSET_STORAGE_METADATA_NAME: &str = ".griffr-storage.json"; diff --git a/crates/griffr-runtime/src/patch_apply/plan.rs b/crates/griffr-runtime/src/patch_apply/plan.rs index 1ed2cc6..ad2bc13 100644 --- a/crates/griffr-runtime/src/patch_apply/plan.rs +++ b/crates/griffr-runtime/src/patch_apply/plan.rs @@ -145,6 +145,20 @@ pub struct PatchPlan { pub deferred_paths: Vec, } +fn validate_plan_relative(label: &str, path: &Path) -> Result<()> { + let parsed = parse_safe_relative_path(label, &path.to_string_lossy())?; + if parsed != path { + return Err(Error::Message { + context: "Configuration error: ", + detail: format!( + "{label} must be a normalized relative path: {}", + path.display() + ), + }); + } + Ok(()) +} + impl PatchPlan { pub const SCHEMA_VERSION: u32 = 2; @@ -152,6 +166,10 @@ impl PatchPlan { griffr_patch_path(&self.install_root).join(PATCH_PLAN_NAME) } + pub(crate) fn is_extracted_manifest(&self) -> bool { + self.stage_root == self.install_root.join(crate::PATCH_STAGE_DIR) + } + pub fn validate(&self) -> Result<()> { if self.schema_version != Self::SCHEMA_VERSION { return Err(Error::Message { @@ -184,15 +202,29 @@ impl PatchPlan { ), }); } - let vfs_base_path = parse_safe_relative_path( - "patch plan vfs_base_path", - &self.vfs_base_path.to_string_lossy(), - )?; + validate_plan_relative("patch plan vfs_base_path", &self.vfs_base_path)?; + if is_griffr_private_path(&self.vfs_base_path) { + return Err(Error::Message { + context: "Configuration error: ", + detail: "Patch VFS destination overlaps the private Griffr namespace".to_string(), + }); + } + let logical_vfs_root = self.install_root.join(&self.vfs_base_path); + if [logical_vfs_root.as_path(), self.vfs_destination.as_path()] + .iter() + .any(|path| path.starts_with(&self.stage_root) || self.stage_root.starts_with(path)) + { + return Err(Error::Message { + context: "Configuration error: ", + detail: "Patch staging and VFS destination overlap".to_string(), + }); + } let mut names = BTreeSet::new(); let mut destinations = BTreeSet::new(); for entry in &self.entries { - let relative = parse_safe_relative_path("patch plan entry name", &entry.name)?; - if entry.expected_md5.trim().is_empty() || entry.expected_size == 0 { + let relative = Path::new(&entry.name); + validate_plan_relative("patch plan entry name", relative)?; + if entry.expected_md5.trim().is_empty() { return Err(Error::Message { context: "Configuration error: ", detail: format!( @@ -208,7 +240,7 @@ impl PatchPlan { detail: format!("Patch plan contains a duplicate writer for {}", entry.name), }); } - let expected_destination = self.vfs_destination.join(&relative); + let expected_destination = self.vfs_destination.join(relative); if entry.destination != expected_destination { return Err(Error::Message { context: "Configuration error: ", @@ -222,18 +254,26 @@ impl PatchPlan { match &entry.source { PlannedPatchSource::AlreadyPresent => {} PlannedPatchSource::Local { payload } => { - parse_safe_relative_path( - "patch plan local payload", - &payload.to_string_lossy(), - )?; + validate_plan_relative("patch plan local payload", payload)?; } PlannedPatchSource::Hdiff { base, payload, base_md5, - base_size, + .. } => { - if !base.starts_with(&self.vfs_destination) { + let valid_base = + base.strip_prefix(&self.vfs_destination) + .ok() + .and_then(|suffix| { + parse_safe_relative_path( + "patch plan base", + &suffix.to_string_lossy(), + ) + .ok() + .filter(|relative| relative == suffix) + }); + if valid_base.is_none() { return Err(Error::Message { context: "Configuration error: ", detail: format!( @@ -243,11 +283,8 @@ impl PatchPlan { ), }); } - parse_safe_relative_path( - "patch plan HDiff payload", - &payload.to_string_lossy(), - )?; - if base_md5.trim().is_empty() || *base_size == 0 { + validate_plan_relative("patch plan HDiff payload", payload)?; + if base_md5.trim().is_empty() { return Err(Error::Message { context: "Configuration error: ", detail: format!( @@ -260,50 +297,58 @@ impl PatchPlan { } } - let logical_vfs_root = self.install_root.join(vfs_base_path); let logical_outputs = self .entries .iter() - .map(|entry| logical_vfs_root.join(&entry.name)) + .filter(|_| !self.delete_paths.is_empty()) + .map(|entry| { + PathBuf::from(crate::artifact::physical_path_key( + &logical_vfs_root.join(&entry.name), + )) + }) .collect::>(); let mut delete_paths = BTreeSet::new(); for relative in &self.delete_paths { - let parsed = - parse_safe_relative_path("patch plan delete path", &relative.to_string_lossy())?; - if is_griffr_private_path(&parsed) { + validate_plan_relative("patch plan delete path", relative)?; + if is_griffr_private_path(relative) { return Err(Error::Message { context: "Configuration error: ", detail: format!( "Patch plan cannot delete private Griffr namespace {}", - parsed.display() + relative.display() ), }); } - if !delete_paths.insert(parsed.clone()) { + if !delete_paths.insert(relative) { return Err(Error::Message { context: "Configuration error: ", detail: format!( "Patch plan contains duplicate delete path {}", - parsed.display() + relative.display() ), }); } - if logical_outputs.contains(&self.install_root.join(&parsed)) { + let target = self.install_root.join(relative); + let key = PathBuf::from(crate::artifact::physical_path_key(&target)); + let contains_output = logical_outputs + .range(key.clone()..) + .next() + .is_some_and(|output| output.starts_with(&key)); + if contains_output || self.stage_root.starts_with(&target) { return Err(Error::Message { context: "Configuration error: ", - detail: format!("Patch plan deletes planned output {}", parsed.display()), + detail: format!("Patch plan deletes planned output {}", relative.display()), }); } } for relative in &self.deferred_paths { - let parsed = - parse_safe_relative_path("patch plan deferred path", &relative.to_string_lossy())?; - if is_griffr_private_path(&parsed) { + validate_plan_relative("patch plan deferred path", relative)?; + if is_griffr_private_path(relative) { return Err(Error::Message { context: "Configuration error: ", detail: format!( "Patch plan cannot replace private Griffr namespace {}", - parsed.display() + relative.display() ), }); } @@ -331,6 +376,38 @@ pub struct PatchCheckReport { mod tests { use super::*; + #[test] + fn persisted_paths_reject_rooted_payloads_and_controls() { + let root = tempfile::tempdir().unwrap(); + let install_root = root.path().join("install"); + let mut plan = PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: install_root.clone(), + stage_root: root.path().join("stage"), + vfs_base_path: PathBuf::from("VFS"), + vfs_destination: install_root.join("VFS"), + work_dir: None, + entries: Vec::new(), + delete_paths: vec![PathBuf::from("/outside")], + deferred_paths: Vec::new(), + }; + assert!(plan.validate().is_err()); + plan.delete_paths.clear(); + plan.deferred_paths.push(PathBuf::from("/outside")); + assert!(plan.validate().is_err()); + plan.deferred_paths.clear(); + plan.entries.push(PlannedPatchEntry { + name: "entry.bin".into(), + destination: plan.vfs_destination.join("entry.bin"), + expected_md5: "0".repeat(32), + expected_size: 1, + source: PlannedPatchSource::Local { + payload: PathBuf::from("/outside"), + }, + }); + assert!(plan.validate().is_err()); + } + #[test] fn plan_rejects_delete_of_griffr_state() { let temp = tempfile::tempdir().unwrap(); @@ -368,12 +445,29 @@ mod tests { work_dir: None, entries: Vec::new(), delete_paths: Vec::new(), - deferred_paths: vec![PathBuf::from(".GRIFFR\\PATCH\\PLAN.JSON")], + deferred_paths: vec![PathBuf::from(".GRIFFR").join("PATCH").join("PLAN.JSON")], }; let error = plan.validate().unwrap_err(); - assert!(error - .to_string() - .contains("replace private Griffr namespace")); + assert!( + error + .to_string() + .contains("replace private Griffr namespace"), + "{error}" + ); + } + + #[cfg(not(windows))] + #[test] + fn persisted_plan_rejects_non_native_separators() { + let error = validate_plan_relative( + "patch plan deferred path", + Path::new(".GRIFFR\\PATCH\\PLAN.JSON"), + ) + .unwrap_err(); + assert!( + error.to_string().contains("normalized relative path"), + "{error}" + ); } } diff --git a/crates/griffr-runtime/src/patch_apply/plan_file.rs b/crates/griffr-runtime/src/patch_apply/plan_file.rs index 2d3aded..36bf6a0 100644 --- a/crates/griffr-runtime/src/patch_apply/plan_file.rs +++ b/crates/griffr-runtime/src/patch_apply/plan_file.rs @@ -27,5 +27,16 @@ pub(crate) fn read_patch_plan(install_root: &Path) -> Result { source, })?)?; plan.validate()?; + if crate::artifact::physical_path_key(&plan.install_root) + != crate::artifact::physical_path_key(install_root) + { + return Err(Error::Message { + context: "Configuration error: ", + detail: format!( + "Patch plan {} belongs to a different install", + path.display() + ), + }); + } Ok(plan) } diff --git a/crates/griffr-runtime/src/patch_apply/recovery.rs b/crates/griffr-runtime/src/patch_apply/recovery.rs index 031f8cd..e04c763 100644 --- a/crates/griffr-runtime/src/patch_apply/recovery.rs +++ b/crates/griffr-runtime/src/patch_apply/recovery.rs @@ -95,6 +95,16 @@ fn entry_is_recoverable( /// rebuild its plan and replay archive ranges. Files already committed to the /// install remain in place and will be recognized as valid by the next plan. pub fn discard_incomplete_patch_apply(install_root: &Path) -> Result<()> { + let plan_path = griffr_patch_path(install_root).join(PATCH_PLAN_NAME); + let plan = if plan_path.is_file() { + Some(read_patch_plan(install_root)?) + } else { + None + }; + #[cfg(feature = "hdiff-patch")] + if let Some(plan) = &plan { + crate::task_pool::fs_ops::reclaim_hdiff_outputs(plan)?; + } let manifest_path = install_root.join(PATCH_MANIFEST_NAME); if manifest_path.is_file() { std::fs::remove_file(&manifest_path).map_err(|source| Error::IoAt { @@ -119,9 +129,7 @@ pub fn discard_incomplete_patch_apply(install_root: &Path) -> Result<()> { source, })?; } - let plan_path = griffr_patch_path(install_root).join(PATCH_PLAN_NAME); - if plan_path.is_file() { - let plan = read_patch_plan(install_root)?; + if let Some(plan) = plan { if plan.stage_root.exists() { std::fs::remove_dir_all(&plan.stage_root).map_err(|source| Error::IoAt { action: "remove file or directory", diff --git a/crates/griffr-runtime/src/patch_apply/space_use.rs b/crates/griffr-runtime/src/patch_apply/space_use.rs index 6f72971..3acfb0b 100644 --- a/crates/griffr-runtime/src/patch_apply/space_use.rs +++ b/crates/griffr-runtime/src/patch_apply/space_use.rs @@ -7,10 +7,6 @@ use crate::{DELETE_FILES_MANIFEST_NAME, PATCH_MANIFEST_NAME, PATCH_STAGE_DIR}; use super::{entry_wave_indices, PatchPlan, PlannedPatchSource}; -fn normalized_archive_path(path: &Path) -> String { - path.to_string_lossy().replace('\\', "/") -} - fn is_patch_archive_control_path(path: &Path) -> bool { path == Path::new(PATCH_MANIFEST_NAME) || path == Path::new(DELETE_FILES_MANIFEST_NAME) @@ -63,13 +59,6 @@ pub(super) struct SimulatedSpacePeaks { pub(super) work: u64, } -fn payload_size(archive_entries: &BTreeMap, payload: &Path) -> u64 { - archive_entries - .get(&normalized_archive_path(payload)) - .copied() - .unwrap_or(0) -} - fn logical_vfs_root(plan: &PatchPlan) -> PathBuf { plan.install_root.join(&plan.vfs_base_path) } @@ -190,20 +179,10 @@ pub(super) fn simulate_space_peaks( } for wave in entry_wave_indices(plan)? { - reserve_wave_outputs( - plan, - archive_entries, - &wave, - &stage_key, - &vfs_key, - work_key.as_deref(), - &mut ledger, - ); + reserve_wave_outputs(plan, &wave, &vfs_key, work_key.as_deref(), &mut ledger); commit_wave_outputs( plan, - archive_entries, wave, - &stage_key, &vfs_key, &outputs, &delete_set, @@ -222,9 +201,7 @@ pub(super) fn simulate_space_peaks( fn reserve_wave_outputs( plan: &PatchPlan, - archive_entries: &BTreeMap, wave: &[usize], - stage_key: &str, vfs_key: &str, work_key: Option<&str>, ledger: &mut VolumeSpaceLedger, @@ -235,13 +212,10 @@ fn reserve_wave_outputs( let entry = &plan.entries[*index]; match &entry.source { PlannedPatchSource::AlreadyPresent => {} - PlannedPatchSource::Local { payload } => { - let staged = payload_size(archive_entries, payload); - if stage_key != vfs_key { - ledger.add(vfs_key, entry.expected_size); - } else if entry.expected_size > staged { - ledger.add(vfs_key, entry.expected_size - staged); - } + PlannedPatchSource::Local { .. } => { + // A same-volume hard link normally costs no file data. Model + // the copy fallback and retain all staged payloads until cleanup. + ledger.add(vfs_key, entry.expected_size); } PlannedPatchSource::Hdiff { .. } => { ledger.add(work_key.unwrap_or(vfs_key), entry.expected_size); @@ -270,9 +244,7 @@ fn reserve_wave_outputs( #[allow(clippy::too_many_arguments)] fn commit_wave_outputs( plan: &PatchPlan, - archive_entries: &BTreeMap, wave: Vec, - stage_key: &str, vfs_key: &str, outputs: &BTreeSet, delete_set: &BTreeSet, @@ -288,18 +260,11 @@ fn commit_wave_outputs( .unwrap_or_else(|| metadata_len(&logical_path_for_physical(plan, &entry.destination))); match &entry.source { PlannedPatchSource::AlreadyPresent => {} - PlannedPatchSource::Local { payload } => { - let staged = payload_size(archive_entries, payload); - if stage_key != vfs_key { - ledger.remove(stage_key, staged); - } else if staged > entry.expected_size { - ledger.remove(stage_key, staged - entry.expected_size); - } + PlannedPatchSource::Local { .. } => { ledger.remove(vfs_key, existing); current_sizes.insert(entry.destination.clone(), entry.expected_size); } - PlannedPatchSource::Hdiff { base, payload, .. } => { - ledger.remove(stage_key, payload_size(archive_entries, payload)); + PlannedPatchSource::Hdiff { base, .. } => { ledger.remove(vfs_key, existing); current_sizes.insert(entry.destination.clone(), entry.expected_size); release_last_deleted_base( diff --git a/crates/griffr-runtime/src/patch_apply/storage.rs b/crates/griffr-runtime/src/patch_apply/storage.rs index 75fe264..4d9280e 100644 --- a/crates/griffr-runtime/src/patch_apply/storage.rs +++ b/crates/griffr-runtime/src/patch_apply/storage.rs @@ -14,10 +14,8 @@ pub struct AssetStorageLayout { pub schema_version: u32, pub asset_link: PathBuf, pub external_asset_root: PathBuf, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub storage_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub install_root: Option, + pub storage_id: String, + pub install_root: PathBuf, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -43,8 +41,8 @@ impl AssetStorageLayout { schema_version: Self::SCHEMA_VERSION, asset_link, external_asset_root: canonical_external_root, - storage_id: Some(storage_id), - install_root: Some(canonical_install_root), + storage_id, + install_root: canonical_install_root, }; layout.validate()?; Ok(layout) @@ -67,44 +65,27 @@ impl AssetStorageLayout { detail: "External asset root must be an absolute path".to_string(), }); } - match (&self.storage_id, &self.install_root) { - (Some(storage_id), Some(install_root)) => { - if storage_id.is_empty() { - return Err(Error::Message { - context: "Configuration error: ", - detail: "External asset storage ID must not be empty".to_string(), - }); - } - if !install_root.is_absolute() { - return Err(Error::Message { - context: "Configuration error: ", - detail: "External asset owner install root must be absolute".to_string(), - }); - } - } - (None, None) => {} - _ => { - return Err(Error::Message { - context: "Configuration error: ", - detail: "External asset ownership metadata is incomplete".to_string(), - }) - } + if self.storage_id.is_empty() { + return Err(Error::Message { + context: "Configuration error: ", + detail: "External asset storage ID must not be empty".to_string(), + }); + } + if !self.install_root.is_absolute() { + return Err(Error::Message { + context: "Configuration error: ", + detail: "External asset owner install root must be absolute".to_string(), + }); } Ok(()) } /// Return true only when both the install-side metadata and the external /// root sentinel prove that the storage belongs to this exact install. - /// Legacy layouts without ownership fields deliberately return false. pub fn owns_external_root(&self, install_root: &Path) -> Result { self.validate()?; - let (Some(storage_id), Some(expected_install_root)) = - (&self.storage_id, &self.install_root) - else { - return Ok(false); - }; let actual_install_root = canonical_existing_path(install_root)?; - if &actual_install_root != expected_install_root { + if actual_install_root != self.install_root { return Ok(false); } @@ -122,7 +103,7 @@ impl AssetStorageLayout { }; let owner: AssetStorageOwner = serde_json::from_slice(&payload)?; Ok(owner.schema_version == Self::OWNER_SCHEMA_VERSION - && owner.storage_id == *storage_id + && owner.storage_id == self.storage_id && owner.install_root == actual_install_root) } @@ -142,12 +123,12 @@ impl AssetStorageLayout { } } - fn owner(&self) -> Option { - Some(AssetStorageOwner { + fn owner(&self) -> AssetStorageOwner { + AssetStorageOwner { schema_version: Self::OWNER_SCHEMA_VERSION, - storage_id: self.storage_id.clone()?, - install_root: self.install_root.clone()?, - }) + storage_id: self.storage_id.clone(), + install_root: self.install_root.clone(), + } } } @@ -171,20 +152,17 @@ pub(crate) fn write_asset_storage_layout( storage_layout: &AssetStorageLayout, ) -> Result<()> { storage_layout.validate()?; - if let Some(owner) = storage_layout.owner() { - std::fs::create_dir_all(&storage_layout.external_asset_root).map_err(|source| { - Error::IoAt { - action: "create directory", - path: storage_layout.external_asset_root.clone(), - source, - } - })?; - let owner_path = storage_layout - .external_asset_root - .join(ASSET_STORAGE_OWNER_NAME); - let owner_payload = serde_json::to_vec_pretty(&owner)?; - crate::task_pool::fs_ops::write_atomic_bytes(&owner_path, &owner_payload)?; - } + let owner = storage_layout.owner(); + std::fs::create_dir_all(&storage_layout.external_asset_root).map_err(|source| Error::IoAt { + action: "create directory", + path: storage_layout.external_asset_root.clone(), + source, + })?; + let owner_path = storage_layout + .external_asset_root + .join(ASSET_STORAGE_OWNER_NAME); + let owner_payload = serde_json::to_vec_pretty(&owner)?; + crate::task_pool::fs_ops::write_atomic_bytes(&owner_path, &owner_payload)?; let path = install_root.join(ASSET_STORAGE_METADATA_NAME); let payload = serde_json::to_vec_pretty(storage_layout)?; @@ -222,21 +200,25 @@ mod tests { use super::*; #[test] - fn legacy_layout_is_readable_but_not_owned() { + fn ownershipless_layout_is_rejected_without_mutation() { let temp = tempfile::tempdir().unwrap(); let install = temp.path().join("install"); let external = temp.path().join("external"); std::fs::create_dir_all(&install).unwrap(); std::fs::create_dir_all(&external).unwrap(); - let layout = AssetStorageLayout { - schema_version: AssetStorageLayout::SCHEMA_VERSION, - asset_link: PathBuf::from("Data/StreamingAssets"), - external_asset_root: external, - storage_id: None, - install_root: None, - }; - - assert!(!layout.owns_external_root(&install).unwrap()); + let keep = external.join("keep.bin"); + std::fs::write(&keep, b"unowned").unwrap(); + let metadata = install.join(ASSET_STORAGE_METADATA_NAME); + let payload = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "asset_link": "Data/StreamingAssets", + "external_asset_root": external, + })) + .unwrap(); + std::fs::write(&metadata, &payload).unwrap(); + assert!(read_asset_storage_layout(&install).is_err()); + assert_eq!(std::fs::read(&keep).unwrap(), b"unowned"); + assert_eq!(std::fs::read(&metadata).unwrap(), payload); } #[test] diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/artifact.rs b/crates/griffr-runtime/src/task_pool/fs_ops/artifact.rs index 0cc42d5..917692c 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/artifact.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/artifact.rs @@ -1,4 +1,4 @@ -use std::io::ErrorKind; +use std::io::{ErrorKind, Write}; use std::path::Path; use crate::error::{Error, Result}; @@ -145,31 +145,31 @@ pub(crate) fn write_atomic_bytes(path: &Path, bytes: &[u8]) -> Result<()> { })?; } let temp = make_temp_write_path(path)?; - let result = (|| -> Result<()> { - use std::io::Write; - let mut output = std::fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(&temp) - .map_err(|source| Error::IoAt { - action: "write to file", - path: temp.clone(), - source, - })?; - output.write_all(bytes).map_err(|source| Error::IoAt { + let mut output = std::fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&temp) + .map_err(|source| Error::IoAt { action: "write to file", path: temp.clone(), source, })?; + let temp_for_write = &temp; + let result = (move || -> Result<()> { + output.write_all(bytes).map_err(|source| Error::IoAt { + action: "write to file", + path: temp_for_write.clone(), + source, + })?; output.sync_all().map_err(|source| Error::IoAt { action: "write to file", - path: temp.clone(), + path: temp_for_write.clone(), source, })?; drop(output); #[cfg(test)] crate::test_checkpoint::hit("atomic_write.after_sync"); - move_path_replace(&temp, path) + move_path_replace(temp_for_write, path) })(); if result.is_err() { match std::fs::remove_file(&temp) { diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/extract.rs b/crates/griffr-runtime/src/task_pool/fs_ops/extract.rs index a172ee8..5fc2539 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/extract.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/extract.rs @@ -208,12 +208,6 @@ pub(crate) fn move_path_replace(src: &Path, dest: &Path) -> Result<()> { } } -#[cfg(feature = "hdiff-patch")] -pub(crate) struct CopiedFileDigest { - pub(crate) bytes: u64, - pub(crate) md5: String, -} - /// Copies a file while calculating the selected content hash from the same /// buffers written to the destination. pub(crate) fn copy_file_with_hash( @@ -279,20 +273,6 @@ pub(crate) fn copy_file_with_hash( copy_result } -/// MD5-specific compatibility wrapper for patch/archive code whose wire schema -/// is defined in terms of MD5. -#[cfg(feature = "hdiff-patch")] -pub(crate) fn copy_file_with_md5(src: &Path, dest: &Path) -> Result { - let digest = copy_file_with_hash(src, dest, &ContentHash::Md5(String::new()))?; - let ContentHash::Md5(md5) = digest.hash else { - unreachable!("MD5 copy selected the MD5 hasher"); - }; - Ok(CopiedFileDigest { - bytes: digest.bytes, - md5, - }) -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum MovePathReplaceOutcome { Renamed, diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs b/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs index ecde893..7523d3d 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/mod.rs @@ -13,9 +13,11 @@ pub(crate) use delete_manifest::{apply_delete_files_manifest_async, parse_delete pub(crate) use extract::{ commit_deferred_paths, commit_file_job, create_extract_staging_dir, CommitFileJob, }; +#[cfg(feature = "hdiff-patch")] +pub(crate) use patch_manifest::reclaim_hdiff_outputs; pub(crate) use patch_manifest::{ - apply_extracted_vfs_patch_manifest, apply_patch_deletes, apply_patch_entry, clean_patch_apply, - commit_deferred_patch_files, prepare_patch_apply, release_patch_base, resume_patch_apply, + apply_patch_deletes, clean_patch_apply, commit_deferred_patch_files, commit_hdiff_patch_entry, + prepare_patch_apply, prepare_patch_entry, release_patch_base, PatchEntryPreparation, }; pub(crate) use reuse::{ classify_reuse_mode, commit_partial_download, copy_verified_file_async, create_hardlink, diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply.rs b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply.rs index 3ccfbfe..737d233 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply.rs @@ -1,185 +1,191 @@ use std::path::Path; #[cfg(feature = "hdiff-patch")] -use std::path::PathBuf; -#[cfg(feature = "hdiff-patch")] use std::sync::atomic::{AtomicUsize, Ordering}; use crate::error::{Error, Result}; +use crate::{task_pool::types::PreparedHdiffPatchOutput, ArtifactProof}; +use crate::{ArtifactExpectation, ArtifactSource}; -use crate::task_pool::verify::build_issue; -use griffr_hypergryph_api::ResourcePatchEntry; +use super::super::artifact::commit_observed_artifact; +use super::super::artifact::commit_verified_artifact; +use super::super::extract::copy_file_with_hash; +use super::super::reuse::make_temp_write_path; +fn stage_local_patch_output(dest_path: &Path) -> Result { + if let Some(parent) = dest_path.parent() { + std::fs::create_dir_all(parent)?; + } + Ok(PreparedHdiffPatchOutput::create_local( + make_temp_write_path(dest_path)?, + )?) +} #[cfg(feature = "hdiff-patch")] -use super::super::artifact::commit_observed_artifact; -use super::super::artifact::{commit_verified_artifact, verify_artifact}; +pub(super) fn stage_hdiff_output( + install_root: &Path, + destination: &Path, + work_dir: Option<&Path>, +) -> Result { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let parent = work_dir.or_else(|| destination.parent()).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "HDiff output has no parent", + ) + })?; + std::fs::create_dir_all(parent)?; + let scope = hdiff_scope(install_root)?; + let prefix = hdiff_directory_prefix(&scope); + loop { + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); + let directory = parent.join(format!("{prefix}{}-{counter}.tmp", std::process::id())); + match PreparedHdiffPatchOutput::create_recoverable(directory, work_dir.is_some(), &scope) { + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + result => return Ok(result?), + } + } +} + #[cfg(feature = "hdiff-patch")] -use super::super::extract::copy_file_with_md5; -use super::super::path_safety::parse_safe_relative_path; +fn hdiff_scope(install_root: &Path) -> Result> { + let canonical = std::fs::canonicalize(install_root)?; + let mut scope = b"griffr-hdiff-scratch-v1\0".to_vec(); + scope.extend_from_slice(canonical.as_os_str().as_encoded_bytes()); + Ok(scope) +} + #[cfg(feature = "hdiff-patch")] -use super::super::reuse::make_temp_write_path; -use super::resolve_patch_stage_path; +fn hdiff_directory_prefix(scope: &[u8]) -> String { + use md5::Digest; + format!( + ".griffr-hdiff-{}-", + griffr_core::to_hex(&md5::Md5::digest(scope)) + ) +} + #[cfg(feature = "hdiff-patch")] -use crate::ArtifactDigest; -use crate::{ - ArtifactExpectation, ArtifactProof, ArtifactSource, PATCH_DIFF_STAGE_DIR, PATCH_FILES_STAGE_DIR, -}; +pub(crate) fn reclaim_hdiff_outputs(plan: &crate::PatchPlan) -> Result<()> { + use std::collections::BTreeSet; + use std::io::ErrorKind; -fn manifest_path<'a>(alternate: Option<&'a str>, primary: &'a str) -> &'a str { - alternate - .map(str::trim) - .filter(|path| !path.is_empty()) - .unwrap_or(primary) + if plan.entries.is_empty() { + return Ok(()); + } + let scope = hdiff_scope(&plan.install_root)?; + let prefix = hdiff_directory_prefix(&scope); + let parents = plan + .entries + .iter() + .filter_map(|entry| entry.destination.parent()) + .chain(plan.work_dir.as_deref()) + .collect::>(); + for parent in parents { + let children = match std::fs::read_dir(parent) { + Ok(children) => children, + Err(error) if error.kind() == ErrorKind::NotFound => continue, + Err(error) => return Err(error.into()), + }; + for child in children { + let child = child?; + let name = child.file_name(); + let Some((pid, counter)) = name + .to_str() + .and_then(|name| name.strip_prefix(&prefix)) + .and_then(|name| name.strip_suffix(".tmp")) + .and_then(|name| name.split_once('-')) + else { + continue; + }; + if pid.parse::().is_err() + || counter.parse::().is_err() + || !child.file_type()?.is_dir() + { + continue; + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT; + if child.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + continue; + } + } + PreparedHdiffPatchOutput::reclaim_orphan(&child.path(), &scope)?; + } + } + Ok(()) } -fn apply_local_patch_entry( - install_root: &Path, - stage_root: &Path, - dest_root: &Path, - logical_root: &Path, - entry: &ResourcePatchEntry, - local_path: &str, +pub(super) fn commit_local_patch_output( + source: &Path, + destination: &Path, + expectation: &ArtifactExpectation, ) -> Result { - let source_path = resolve_patch_stage_path( - install_root, - stage_root, - PATCH_FILES_STAGE_DIR, - "patch.json local_path", - local_path, - )?; - let dest_relative = parse_safe_relative_path("patch.json file name", &entry.name)?; - let dest_path = dest_root.join(&dest_relative); - let logical_path = logical_root - .join(&dest_relative) - .to_string_lossy() - .replace('\\', "/"); - - if !source_path.is_file() { - return Err(Error::Message { - context: "VFS error: ", - detail: format!( - "patch.json local payload is missing for {}: {}", - entry.name, - source_path.display() - ), - }); + let temporary = stage_local_patch_output(destination)?; + if std::fs::hard_link(source, temporary.path()).is_ok() { + return commit_verified_artifact( + temporary.path(), + destination, + expectation, + ArtifactSource::LocalPatch, + ); } - let expectation = ArtifactExpectation::new(&logical_path, &entry.md5, Some(entry.size)); - commit_verified_artifact( - &source_path, - &dest_path, - &expectation, + let copied = copy_file_with_hash(source, temporary.path(), expectation.expected_hash())?; + commit_observed_artifact( + temporary.path(), + destination, + expectation, ArtifactSource::LocalPatch, + &copied, ) } #[cfg(feature = "hdiff-patch")] -fn make_patch_work_path(work_dir: &Path, destination: &Path) -> Result { - static COUNTER: AtomicUsize = AtomicUsize::new(0); - std::fs::create_dir_all(work_dir).map_err(|source| Error::IoAt { - action: "create directory", - path: work_dir.to_path_buf(), - source, - })?; - let counter = COUNTER.fetch_add(1, Ordering::Relaxed); - let file_name = destination - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or("patch-output"); - Ok(work_dir.join(format!(".{file_name}.griffr-patch-{counter}.tmp"))) -} - -#[cfg(feature = "hdiff-patch")] -pub(super) fn apply_hdiff_patch( - base_path: &Path, - patch_path: &Path, +pub(super) fn commit_hdiff_patch_output( + install_root: &Path, + temp_path: &Path, dest_path: &Path, logical_path: &str, expected_md5: &str, expected_size: u64, - work_dir: Option<&Path>, + copy_to_destination_temp: bool, ) -> Result { if let Some(parent) = dest_path.parent() { - std::fs::create_dir_all(parent).map_err(|e| Error::IoAt { + std::fs::create_dir_all(parent).map_err(|source| Error::IoAt { action: "create directory", path: parent.to_path_buf(), - source: e, + source, })?; } - let temp_path = match work_dir { - Some(work_dir) => make_patch_work_path(work_dir, dest_path)?, - None => make_temp_write_path(dest_path)?, - }; - let _ = std::fs::remove_file(&temp_path); - let mut patcher = hdiffpatch_rs::patchers::HDiff::new( - base_path.to_string_lossy().into_owned(), - patch_path.to_string_lossy().into_owned(), - temp_path.to_string_lossy().into_owned(), - ); - if !patcher.apply() { - let _ = std::fs::remove_file(&temp_path); - return Err(Error::Message { - context: "Extraction error: ", - detail: format!( - "hdiffpatch-rs failed to apply {} using base {}", - patch_path.display(), - base_path.display() - ), - }); - } - if work_dir.is_some() { - let local_temp = make_temp_write_path(dest_path)?; - let _ = std::fs::remove_file(&local_temp); - let copied = match copy_file_with_md5(&temp_path, &local_temp) { - Ok(copied) => copied, - Err(error) => { - let _ = std::fs::remove_file(&temp_path); - let _ = std::fs::remove_file(&local_temp); - return Err(error); - } - }; - let expectation = ArtifactExpectation::new(logical_path, expected_md5, Some(expected_size)); - let digest = ArtifactDigest::new(copied.bytes, copied.md5); - let proof = match commit_observed_artifact( - &local_temp, + let expectation = ArtifactExpectation::new(logical_path, expected_md5, Some(expected_size)); + if copy_to_destination_temp { + let local_temp = stage_hdiff_output(install_root, dest_path, None)?; + let digest = + copy_file_with_hash(temp_path, local_temp.path(), expectation.expected_hash())?; + return commit_observed_artifact( + local_temp.path(), dest_path, &expectation, ArtifactSource::HdiffPatch, &digest, - ) { - Ok(proof) => proof, - Err(error) => { - let _ = std::fs::remove_file(&temp_path); - let _ = std::fs::remove_file(&local_temp); - return Err(error); - } - }; - let _ = std::fs::remove_file(&temp_path); - return Ok(proof); + ); } - let expectation = ArtifactExpectation::new(logical_path, expected_md5, Some(expected_size)); - match commit_verified_artifact( - &temp_path, + commit_verified_artifact( + temp_path, dest_path, &expectation, ArtifactSource::HdiffPatch, - ) { - Ok(proof) => Ok(proof), - Err(error) => { - let _ = std::fs::remove_file(&temp_path); - Err(error) - } - } + ) } #[cfg(not(feature = "hdiff-patch"))] -pub(super) fn apply_hdiff_patch( - _base_path: &Path, - _patch_path: &Path, +pub(super) fn commit_hdiff_patch_output( + _install_root: &Path, + _temp_path: &Path, _dest_path: &Path, _logical_path: &str, _expected_md5: &str, _expected_size: u64, - _work_dir: Option<&Path>, + _copy_to_destination_temp: bool, ) -> Result { Err(Error::Message { context: "Patch support unavailable: ", @@ -187,144 +193,102 @@ pub(super) fn apply_hdiff_patch( }) } -fn apply_patch_entry( - install_root: &Path, - stage_root: &Path, - dest_root: &Path, - logical_root: &Path, - entry: &ResourcePatchEntry, -) -> Result { - let dest_relative = parse_safe_relative_path("patch.json file name", &entry.name)?; - let dest_path = dest_root.join(&dest_relative); - let logical_path = logical_root - .join(&dest_relative) - .to_string_lossy() - .replace('\\', "/"); - let mut candidate_failures = Vec::new(); - - for diff in &entry.patch { - let base_relative_raw = manifest_path(diff.base_file_path.as_deref(), &diff.base_file); - let base_relative = parse_safe_relative_path("patch.json base_file", base_relative_raw)?; - let base_path = dest_root.join(&base_relative); - let base_logical_path = base_relative.to_string_lossy().replace('\\', "/"); +#[cfg(all(test, feature = "hdiff-patch"))] +mod tests { + use super::*; + use std::path::PathBuf; + use std::process::Command; + use std::time::{Duration, Instant}; - if let Some(issue) = build_issue( - &base_path, - &base_logical_path, - &diff.base_md5, - Some(diff.base_size), - ) { - candidate_failures.push(format!("{} ({:?})", base_relative.display(), issue.kind)); - continue; + #[test] + fn recovery_reclaims_only_its_unlocked_output_after_process_termination() { + const CHILD: &str = "GRIFFR_HDIFF_ORPHAN_TEST_ROOT"; + const SIGNAL: &str = "hdiff.after_preparing_private_output"; + if let Some(root) = std::env::var_os(CHILD) { + let root = PathBuf::from(root); + let output = + stage_hdiff_output(&root.join("install"), &root.join("work/target"), None).unwrap(); + std::fs::write(output.path(), b"abandoned output").unwrap(); + std::fs::write(root.join("abandoned-path"), output.path().to_str().unwrap()).unwrap(); + crate::test_checkpoint::hit(SIGNAL); + unreachable!("fixture must terminate abruptly"); } - let patch_relative_raw = manifest_path(diff.patch_path.as_deref(), &diff.patch); - let patch_path = resolve_patch_stage_path( - install_root, - stage_root, - PATCH_DIFF_STAGE_DIR, - "patch.json patch path", - patch_relative_raw, - )?; - if !patch_path.is_file() { - candidate_failures.push(format!( - "{} (missing patch payload {})", - base_relative.display(), - patch_path.display() - )); - continue; + let temp = tempfile::tempdir().unwrap(); + let install = temp.path().join("install"); + let other_install = temp.path().join("other-install"); + let work = temp.path().join("work"); + let destination = work.join("target"); + std::fs::create_dir(&install).unwrap(); + std::fs::create_dir(&other_install).unwrap(); + let live = stage_hdiff_output(&install, &destination, None).unwrap(); + let foreign = stage_hdiff_output(&other_install, &destination, None).unwrap(); + std::fs::write(live.path(), b"active").unwrap(); + std::fs::write(foreign.path(), b"other install").unwrap(); + let ready = temp.path().join("ready"); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "task_pool::fs_ops::patch_manifest::apply::tests::recovery_reclaims_only_its_unlocked_output_after_process_termination", + ]) + .env(CHILD, temp.path()) + .env("GRIFFR_TEST_CHECKPOINT", SIGNAL) + .env("GRIFFR_TEST_CHECKPOINT_READY", &ready) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(8); + let mut checkpoint_reached = false; + while Instant::now() < deadline { + if ready.is_file() { + checkpoint_reached = true; + break; + } + if child.try_wait().unwrap().is_some() { + panic!("fixture exited before its checkpoint"); + } + std::thread::sleep(Duration::from_millis(10)); } - - return apply_hdiff_patch( - &base_path, - &patch_path, - &dest_path, - &logical_path, - &entry.md5, - entry.size, - None, - ) - .map_err(|err| Error::Message { - context: "", - detail: format!( - "Failed to patch {} from base {}: {err}", - entry.name, - base_relative.display() - ), - }); - } - - if candidate_failures.is_empty() { - return Err(Error::Message { - context: "VFS error: ", - detail: format!( - "patch.json entry {} has no applicable patch candidates", - entry.name - ), - }); - } - - Err(Error::Message { - context: "VFS error: ", - detail: format!( - "patch.json entry {} has no verified base file to patch: {}", - entry.name, - candidate_failures.join("; ") - ), - }) -} - -pub(super) fn apply_vfs_patch_entry( - install_root: &Path, - stage_root: &Path, - dest_root: &Path, - logical_root: &Path, - entry: &ResourcePatchEntry, -) -> Result { - let dest_relative = parse_safe_relative_path("patch.json file name", &entry.name)?; - let dest_path = dest_root.join(&dest_relative); - let logical_path = logical_root - .join(&dest_relative) - .to_string_lossy() - .replace('\\', "/"); - let expectation = ArtifactExpectation::new(&logical_path, &entry.md5, Some(entry.size)); - if build_issue(&dest_path, &logical_path, &entry.md5, Some(entry.size)).is_none() { - return verify_artifact(&dest_path, &expectation, ArtifactSource::Existing); - } - - if let Some(local_path) = entry - .local_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - { - return apply_local_patch_entry( - install_root, - stage_root, - dest_root, - logical_root, - entry, - local_path, + child.kill().unwrap(); + child.wait().unwrap(); + assert!( + checkpoint_reached, + "isolated fixture did not reach its checkpoint" ); - } - apply_patch_entry(install_root, stage_root, dest_root, logical_root, entry) -} - -#[cfg(test)] -mod tests { - use super::manifest_path; - - #[test] - fn manifest_path_falls_back_when_alternate_is_empty() { - assert_eq!(manifest_path(Some(""), "primary/path"), "primary/path"); - assert_eq!(manifest_path(Some(" "), "primary/path"), "primary/path"); - } - #[test] - fn manifest_path_prefers_non_empty_alternate() { - assert_eq!( - manifest_path(Some(" alternate/path "), "primary/path"), - "alternate/path" - ); + let abandoned = + PathBuf::from(std::fs::read_to_string(temp.path().join("abandoned-path")).unwrap()); + assert!(abandoned.is_file()); + let scope = hdiff_scope(&install).unwrap(); + let foreign_dir = foreign.path().parent().unwrap().to_path_buf(); + let plan = crate::PatchPlan { + schema_version: crate::PatchPlan::SCHEMA_VERSION, + install_root: install, + stage_root: temp.path().join("stage"), + vfs_base_path: "VFS".into(), + vfs_destination: work.clone(), + work_dir: Some(work), + entries: vec![crate::PlannedPatchEntry { + name: "target".into(), + destination, + expected_md5: String::new(), + expected_size: 0, + source: crate::PlannedPatchSource::AlreadyPresent, + }], + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + }; + reclaim_hdiff_outputs(&plan).unwrap(); + assert!(!abandoned.parent().unwrap().exists()); + assert_eq!(std::fs::read(live.path()).unwrap(), b"active"); + assert_eq!(std::fs::read(foreign.path()).unwrap(), b"other install"); + assert!(foreign_dir.exists()); + assert!(live + .path() + .parent() + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .starts_with(&hdiff_directory_prefix(&scope))); } } diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/filesystem.rs b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/filesystem.rs index f1c2b74..084504b 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/filesystem.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/filesystem.rs @@ -216,6 +216,15 @@ pub(super) fn commit_top_level_files( plan: &PatchPlan, callback: Option<&mut dyn FnMut(&Path, usize, usize)>, ) -> Result<()> { + if plan.is_extracted_manifest() + || !plan.stage_root.try_exists().map_err(|source| Error::IoAt { + action: "query file metadata/stat for", + path: plan.stage_root.clone(), + source, + })? + { + return Ok(()); + } let files = collect_staged_files(&plan.stage_root)?; let deferred = plan.deferred_paths.iter().cloned().collect::>(); let commit_files = files diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/mod.rs b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/mod.rs index 1bbe699..e86d377 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/mod.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/mod.rs @@ -1,12 +1,11 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::path::{Path, PathBuf}; +use std::collections::BTreeSet; +use std::path::Path; use crate::error::{Error, Result}; -use crate::patch_apply::{ - read_patch_plan, write_patch_plan, PatchCheckReport, PatchPlan, PlannedPatchSource, -}; +use crate::patch_apply::{write_patch_plan, PatchPlan}; use crate::task_pool::verify::VerifiedArtifactCache; use crate::ArtifactProof; +pub(crate) use steps::PatchEntryPreparation; mod filesystem; mod steps; @@ -15,9 +14,9 @@ use filesystem::{commit_top_level_files, prepare_external_asset_root}; #[cfg(test)] use steps::ordered_entries; use steps::{ - apply_planned_entry, apply_remaining_deletes, cleanup_staging, commit_deferred_files, - delete_unreferenced_paths_before_patch, entry_waves, final_output_paths, - release_base_if_unused, remove_patch_state_dir, + apply_remaining_deletes, cleanup_staging, commit_deferred_files, commit_prepared_hdiff_entry, + delete_unreferenced_paths_before_patch, final_output_paths, prepare_planned_entry, + remove_patch_state_dir, }; pub(crate) fn prepare_patch_apply( @@ -25,17 +24,44 @@ pub(crate) fn prepare_patch_apply( commit_callback: Option<&mut dyn FnMut(&Path, usize, usize)>, ) -> Result<()> { plan.validate()?; + for entry in &plan.entries { + if let crate::PlannedPatchSource::Hdiff { + payload, base_size, .. + } = &entry.source + { + let result = crate::patch_apply::validate_hdiff_input( + &plan.stage_root.join(payload), + *base_size, + entry.expected_size, + ); + if let Err(error) = result { + // Already committed entries no longer require a base or payload. + if crate::task_pool::verify::build_issue( + &entry.destination, + &entry.name, + &entry.expected_md5, + Some(entry.expected_size), + ) + .is_some() + { + return Err(error); + } + } + } + } + #[cfg(feature = "hdiff-patch")] + super::apply::reclaim_hdiff_outputs(plan)?; write_patch_plan(plan)?; prepare_external_asset_root(plan)?; commit_top_level_files(plan, commit_callback)?; delete_unreferenced_paths_before_patch(plan) } -pub(crate) fn apply_patch_entry( +pub(crate) fn prepare_patch_entry( plan: &PatchPlan, entry_index: usize, verification_cache: &VerifiedArtifactCache, -) -> Result { +) -> Result { let entry = plan .entries .get(entry_index) @@ -43,12 +69,33 @@ pub(crate) fn apply_patch_entry( context: "Task pool error: ", detail: format!("patch entry index {entry_index} is out of range"), })?; - apply_planned_entry(plan, entry, verification_cache).map_err(|error| Error::Message { + prepare_planned_entry(plan, entry, verification_cache).map_err(|error| Error::Message { context: "", detail: format!("Failed to apply patch entry {}: {}", entry.name, error), }) } +pub(crate) fn commit_hdiff_patch_entry( + plan: &PatchPlan, + entry_index: usize, + temp_path: &Path, + copy_to_destination_temp: bool, +) -> Result { + let entry = plan + .entries + .get(entry_index) + .ok_or_else(|| Error::Message { + context: "Task pool error: ", + detail: format!("patch entry index {entry_index} is out of range"), + })?; + commit_prepared_hdiff_entry(plan, entry, temp_path, copy_to_destination_temp).map_err(|error| { + Error::Message { + context: "", + detail: format!("Failed to apply patch entry {}: {}", entry.name, error), + } + }) +} + pub(crate) fn release_patch_base(plan: &PatchPlan, base: &Path) -> Result<()> { let delete_set = plan.delete_paths.iter().cloned().collect::>(); let outputs = final_output_paths(plan); @@ -69,87 +116,31 @@ pub(crate) fn apply_patch_deletes( } pub(crate) fn commit_deferred_patch_files(plan: &PatchPlan) -> Result<()> { + cleanup_staging(plan)?; commit_deferred_files(plan) } pub(crate) fn clean_patch_apply(plan: &PatchPlan) -> Result<()> { - cleanup_staging(plan)?; - remove_patch_state_dir(plan) -} - -pub(crate) fn run_patch_apply( - plan: &PatchPlan, - _report: Option<&PatchCheckReport>, - commit_callback: Option<&mut dyn FnMut(&Path, usize, usize)>, - mut patch_callback: Option<&mut dyn FnMut(&str, usize, usize)>, - delete_callback: Option<&mut dyn FnMut(&Path, usize, usize)>, - verification_cache: &VerifiedArtifactCache, -) -> Result> { - prepare_patch_apply(plan, commit_callback)?; - - let delete_set = plan.delete_paths.iter().cloned().collect::>(); - let outputs = final_output_paths(plan); - let mut remaining = BTreeMap::::new(); - for entry in &plan.entries { - if let PlannedPatchSource::Hdiff { base, .. } = &entry.source { - *remaining.entry(base.clone()).or_default() += 1; - } - } - let waves = entry_waves(plan)?; - let total = waves.iter().map(Vec::len).sum::(); - if total > 0 { - if let Some(callback) = patch_callback.as_deref_mut() { - callback("", 0, total); - } - } - let mut finished = 0usize; - let mut proofs = Vec::with_capacity(total); - for wave in waves { - for entry in &wave { - let proof = apply_planned_entry(plan, entry, verification_cache).map_err(|error| { - Error::Message { - context: "", - detail: format!("Failed to apply patch entry {}: {}", entry.name, error), + if plan.is_extracted_manifest() { + for name in [ + crate::PATCH_MANIFEST_NAME, + crate::DELETE_FILES_MANIFEST_NAME, + ] { + let path = plan.install_root.join(name); + match std::fs::remove_file(&path) { + Ok(()) => {} + Err(source) if source.kind() == std::io::ErrorKind::NotFound => {} + Err(source) => { + return Err(Error::IoAt { + action: "remove file", + path, + source, + }) } - })?; - proofs.push(proof); - if let PlannedPatchSource::Hdiff { base, .. } = &entry.source { - release_base_if_unused(plan, base, &mut remaining, &delete_set, &outputs)?; - } - finished = finished.saturating_add(1); - if let Some(callback) = patch_callback.as_deref_mut() { - let logical_path = plan.vfs_base_path.join(&entry.name); - callback( - &logical_path.to_string_lossy().replace('\\', "/"), - finished, - total, - ); } } } - apply_remaining_deletes(plan, delete_callback)?; - commit_deferred_files(plan)?; - cleanup_staging(plan)?; - remove_patch_state_dir(plan)?; - Ok(proofs) -} - -pub(crate) fn resume_patch_apply( - install_root: &Path, - commit_callback: Option<&mut dyn FnMut(&Path, usize, usize)>, - patch_callback: Option<&mut dyn FnMut(&str, usize, usize)>, - delete_callback: Option<&mut dyn FnMut(&Path, usize, usize)>, -) -> Result> { - let plan = read_patch_plan(install_root)?; - let verification_cache = VerifiedArtifactCache::default(); - run_patch_apply( - &plan, - None, - commit_callback, - patch_callback, - delete_callback, - &verification_cache, - ) + remove_patch_state_dir(plan) } #[cfg(test)] diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/steps.rs b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/steps.rs index 33cf2e0..19d38bb 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/steps.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/steps.rs @@ -1,29 +1,37 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use crate::error::{Error, Result}; -use crate::patch_apply::{ - entry_wave_indices, PatchPlan, PlannedPatchEntry, PlannedPatchSource, PATCH_DEFERRED_DIR, -}; +use crate::patch_apply::{PatchPlan, PlannedPatchEntry, PlannedPatchSource, PATCH_DEFERRED_DIR}; use crate::task_pool::verify::VerifiedArtifactCache; use crate::{griffr_patch_path, ArtifactExpectation, ArtifactProof, ArtifactSource}; -use super::super::super::artifact::{ - commit_unchecked_artifact, commit_verified_artifact, verify_artifact, -}; -use super::super::apply::apply_hdiff_patch; +use super::super::super::artifact::verify_artifact; +#[cfg(feature = "hdiff-patch")] +use super::super::apply::stage_hdiff_output; +use super::super::apply::{commit_hdiff_patch_output, commit_local_patch_output}; use super::filesystem::remove_path_if_exists; -pub(super) fn apply_planned_entry( +#[derive(Debug)] +pub(crate) enum PatchEntryPreparation { + Complete(ArtifactProof), + #[cfg(feature = "hdiff-patch")] + Hdiff(crate::task_pool::types::PreparedHdiffPatchOutput), +} + +fn entry_logical_path(plan: &PatchPlan, entry: &PlannedPatchEntry) -> String { + plan.vfs_base_path + .join(&entry.name) + .to_string_lossy() + .replace('\\', "/") +} + +pub(super) fn prepare_planned_entry( plan: &PatchPlan, entry: &PlannedPatchEntry, verification_cache: &VerifiedArtifactCache, -) -> Result { - let logical_path = plan - .vfs_base_path - .join(&entry.name) - .to_string_lossy() - .replace('\\', "/"); +) -> Result { + let logical_path = entry_logical_path(plan, entry); let expectation = ArtifactExpectation::new( &logical_path, &entry.expected_md5, @@ -38,7 +46,8 @@ pub(super) fn apply_planned_entry( ) .is_none() { - return verify_artifact(&entry.destination, &expectation, ArtifactSource::Existing); + return verify_artifact(&entry.destination, &expectation, ArtifactSource::Existing) + .map(PatchEntryPreparation::Complete); } match &entry.source { PlannedPatchSource::AlreadyPresent => Err(Error::Message { @@ -60,12 +69,8 @@ pub(super) fn apply_planned_entry( ), }); } - commit_verified_artifact( - &source, - &entry.destination, - &expectation, - ArtifactSource::LocalPatch, - ) + commit_local_patch_output(&source, &entry.destination, &expectation) + .map(PatchEntryPreparation::Complete) } PlannedPatchSource::Hdiff { base, @@ -101,21 +106,46 @@ pub(super) fn apply_planned_entry( ), }); } - let proof = apply_hdiff_patch( - base, - &payload_path, + #[cfg(not(feature = "hdiff-patch"))] + return Err(Error::Message { + context: "Patch support unavailable: ", + detail: "griffr-runtime was built without the hdiff-patch feature".to_string(), + }); + #[cfg(feature = "hdiff-patch")] + stage_hdiff_output( + &plan.install_root, &entry.destination, - &logical_path, - &entry.expected_md5, - entry.expected_size, plan.work_dir.as_deref(), - )?; - remove_path_if_exists(&payload_path)?; - Ok(proof) + ) + .map(PatchEntryPreparation::Hdiff) } } } +pub(super) fn commit_prepared_hdiff_entry( + plan: &PatchPlan, + entry: &PlannedPatchEntry, + temp_path: &Path, + copy_to_destination_temp: bool, +) -> Result { + let PlannedPatchSource::Hdiff { .. } = &entry.source else { + return Err(Error::Message { + context: "Task pool error: ", + detail: format!("patch entry {} is not an HDiff continuation", entry.name), + }); + }; + let logical_path = entry_logical_path(plan, entry); + commit_hdiff_patch_output( + &plan.install_root, + temp_path, + &entry.destination, + &logical_path, + &entry.expected_md5, + entry.expected_size, + copy_to_destination_temp, + ) +} + pub(super) fn logical_vfs_root(plan: &PatchPlan) -> PathBuf { plan.install_root.join(&plan.vfs_base_path) } @@ -145,8 +175,9 @@ pub(super) fn final_output_paths(plan: &PatchPlan) -> BTreeSet { .collect() } -pub(super) fn entry_waves(plan: &PatchPlan) -> Result>> { - entry_wave_indices(plan).map(|waves| { +#[cfg(test)] +fn entry_waves(plan: &PatchPlan) -> Result>> { + crate::patch_apply::entry_wave_indices(plan).map(|waves| { waves .into_iter() .map(|wave| wave.into_iter().map(|index| &plan.entries[index]).collect()) @@ -160,51 +191,42 @@ pub(super) fn ordered_entries(plan: &PatchPlan) -> Result Result<()> { + if plan.delete_paths.is_empty() { + return Ok(()); + } let bases = plan .entries .iter() .filter_map(|entry| match &entry.source { - PlannedPatchSource::Hdiff { base, .. } => Some(base.clone()), + PlannedPatchSource::Hdiff { base, .. } => { + Some(PathBuf::from(crate::artifact::physical_path_key(base))) + } PlannedPatchSource::AlreadyPresent | PlannedPatchSource::Local { .. } => None, }) .collect::>(); let outputs = plan .entries .iter() - .map(|entry| entry.destination.clone()) + .map(|entry| PathBuf::from(crate::artifact::physical_path_key(&entry.destination))) .collect::>(); for relative in &plan.delete_paths { let path = physical_delete_path(plan, relative); - if !bases.contains(&path) && !outputs.contains(&path) { + let key = PathBuf::from(crate::artifact::physical_path_key(&path)); + if !bases + .range(key.clone()..) + .next() + .is_some_and(|base| base.starts_with(&key)) + && !outputs + .range(key.clone()..) + .next() + .is_some_and(|output| output.starts_with(&key)) + { remove_path_if_exists(&path)?; } } Ok(()) } -pub(super) fn release_base_if_unused( - plan: &PatchPlan, - base: &Path, - remaining: &mut BTreeMap, - delete_set: &BTreeSet, - outputs: &BTreeSet, -) -> Result<()> { - let Some(count) = remaining.get_mut(base) else { - return Ok(()); - }; - *count = count.saturating_sub(1); - if *count != 0 { - return Ok(()); - } - let Some(relative) = relative_install_path(plan, base) else { - return Ok(()); - }; - if delete_set.contains(&relative) && !outputs.contains(&relative) { - remove_path_if_exists(base)?; - } - Ok(()) -} - pub(super) fn apply_remaining_deletes( plan: &PatchPlan, mut callback: Option<&mut dyn FnMut(&Path, usize, usize)>, @@ -248,7 +270,14 @@ pub(super) fn commit_deferred_files(plan: &PatchPlan) -> Result<()> { source: source_error, })?; } - commit_unchecked_artifact(&source, &target)?; + // Preserve the private marker until final state cleanup. A crash after + // the atomic replace can resume with the same persisted plan. + let bytes = std::fs::read(&source).map_err(|error| Error::IoAt { + action: "open file", + path: source, + source: error, + })?; + super::super::super::artifact::write_atomic_bytes(&target, &bytes)?; } Ok(()) } diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/tests.rs b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/tests.rs index 3d5012b..9264a73 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/tests.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/apply_steps/tests.rs @@ -25,6 +25,119 @@ fn plan( } } +#[cfg(feature = "hdiff-patch")] +#[test] +fn resume_patch_apply_decodes_hdiff_with_compio() { + resume_hdiff_contract_case(false); +} + +#[cfg(feature = "hdiff-patch")] +#[test] +fn unsupported_hdiff_recovery_rejects_before_mutation() { + resume_hdiff_contract_case(true); +} + +#[cfg(feature = "hdiff-patch")] +fn resume_hdiff_contract_case(unsupported: bool) { + let temp = tempdir().unwrap(); + let install_root = temp.path().join("install"); + let stage_root = temp.path().join("staging"); + let base = install_root.join("Game_Data/StreamingAssets/VFS/base.bin"); + let payload_relative = PathBuf::from("vfs_files/vfs_patch/output.hdiff"); + let payload = stage_root.join(&payload_relative); + let destination = install_root.join("Game_Data/StreamingAssets/VFS/output.bin"); + std::fs::create_dir_all(base.parent().unwrap()).unwrap(); + std::fs::create_dir_all(payload.parent().unwrap()).unwrap(); + let old = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + let mut expected = old.clone(); + expected.extend((0..901).map(|i| ((i * 13 + 3) % 256) as u8)); + std::fs::write(&base, &old).unwrap(); + std::fs::write( + &payload, + if unsupported { + &b"HDIFFSF20&zlib\0"[..] + } else { + &include_bytes!("../../../../patch_apply/hdiff_sf20_reference_tail.patch")[..] + }, + ) + .unwrap(); + std::fs::write(install_root.join("obsolete.bin"), b"keep until accepted").unwrap(); + let expected_path = temp.path().join("expected.bin"); + std::fs::write(&expected_path, &expected).unwrap(); + let entry = PlannedPatchEntry { + name: "output.bin".to_string(), + destination: destination.clone(), + expected_md5: file_md5(&expected_path).unwrap(), + expected_size: expected.len() as u64, + source: PlannedPatchSource::Hdiff { + base: base.clone(), + payload: payload_relative, + base_md5: file_md5(&base).unwrap(), + base_size: old.len() as u64, + }, + }; + let existing = destination.with_file_name("already.bin"); + std::fs::write(&existing, &expected).unwrap(); + let already_committed = PlannedPatchEntry { + name: "already.bin".to_string(), + destination: existing, + expected_md5: entry.expected_md5.clone(), + expected_size: entry.expected_size, + source: PlannedPatchSource::Hdiff { + base: base.with_file_name("removed-base.bin"), + payload: PathBuf::from("vfs_files/vfs_patch/removed-payload.hdiff"), + base_md5: file_md5(&base).unwrap(), + base_size: old.len() as u64, + }, + }; + let plan = plan( + &install_root, + &stage_root, + vec![already_committed, entry], + vec![PathBuf::from("obsolete.bin")], + Vec::new(), + ); + + write_patch_plan(&plan).unwrap(); + let result = crate::task_pool::run_tasks( + vec![crate::task_pool::Task::ApplyExtractedVfsPatchManifest { + install_root: install_root.clone(), + }], + crate::task_pool::TaskPoolConfig::default(), + ) + .unwrap(); + if unsupported { + assert!(result.metrics.graph.failed_nodes > 0, "{result:?}"); + assert!(format!("{:?}", result.outcomes).contains("unsupported HDiff format")); + assert_eq!( + std::fs::read(install_root.join("obsolete.bin")).unwrap(), + b"keep until accepted" + ); + assert_eq!(std::fs::read(&base).unwrap(), old); + assert!(payload.exists()); + assert!(!destination.exists()); + return; + } + assert_eq!(result.metrics.graph.failed_nodes, 0, "{result:?}"); + let proofs = result + .outcomes + .into_iter() + .filter_map(|outcome| match outcome { + crate::task_pool::TaskOutcome::Committed { proof } => Some(proof), + _ => None, + }) + .collect::>(); + + assert_eq!(proofs.len(), 2); + assert!(proofs + .iter() + .any(|proof| proof.source() == crate::ArtifactSource::Existing)); + assert_eq!(std::fs::read(destination).unwrap(), expected); + assert!(!griffr_patch_path(&install_root).exists()); +} + #[test] fn patch_apply_defers_version_marker_and_preserves_final_output() { let temp = tempdir().unwrap(); @@ -52,15 +165,23 @@ fn patch_apply_defers_version_marker_and_preserves_final_output() { vec![PathBuf::from("config.ini")], ); - let proofs = run_patch_apply( - &plan, - None, - None, - None, - None, - &VerifiedArtifactCache::default(), + write_patch_plan(&plan).unwrap(); + let result = crate::task_pool::run_tasks( + vec![crate::task_pool::Task::ApplyExtractedVfsPatchManifest { + install_root: install_root.clone(), + }], + crate::task_pool::TaskPoolConfig::default(), ) .unwrap(); + assert_eq!(result.metrics.graph.failed_nodes, 0, "{result:?}"); + let proofs = result + .outcomes + .into_iter() + .filter_map(|outcome| match outcome { + crate::task_pool::TaskOutcome::Committed { proof } => Some(proof), + _ => None, + }) + .collect::>(); assert_eq!(proofs.len(), 1); assert_eq!( @@ -104,31 +225,6 @@ fn plan_rejects_delete_manifest_conflict_with_output() { assert!(plan.validate().is_err()); } -#[test] -fn base_is_released_only_after_last_consumer() { - let temp = tempdir().unwrap(); - let install_root = temp.path().join("install"); - let stage_root = temp.path().join("stage"); - let base = install_root.join("Game_Data/StreamingAssets/VFS/old.bin"); - std::fs::create_dir_all(base.parent().unwrap()).unwrap(); - std::fs::write(&base, b"old").unwrap(); - let plan = plan( - &install_root, - &stage_root, - Vec::new(), - vec![PathBuf::from("Game_Data/StreamingAssets/VFS/old.bin")], - Vec::new(), - ); - let mut remaining = BTreeMap::from([(base.clone(), 2usize)]); - let deletes = plan.delete_paths.iter().cloned().collect(); - let outputs = BTreeSet::new(); - - release_base_if_unused(&plan, &base, &mut remaining, &deletes, &outputs).unwrap(); - assert!(base.exists()); - release_base_if_unused(&plan, &base, &mut remaining, &deletes, &outputs).unwrap(); - assert!(!base.exists()); -} - #[test] fn application_revalidates_persisted_base_metadata() { let temp = tempdir().unwrap(); @@ -158,12 +254,154 @@ fn application_revalidates_persisted_base_metadata() { Vec::new(), ); - let error = apply_planned_entry(&plan, &entry, &VerifiedArtifactCache::default()).unwrap_err(); + let error = + prepare_planned_entry(&plan, &entry, &VerifiedArtifactCache::default()).unwrap_err(); assert!(error .to_string() .contains("failed verification before applying")); } +#[test] +fn prepared_hdiff_commit_preserves_bytes_and_integrity() { + let temp = tempdir().unwrap(); + let install_root = temp.path().join("install"); + let stage_root = temp.path().join("stage"); + let destination = install_root.join("Game_Data/StreamingAssets/VFS/output.bin"); + let payload_relative = PathBuf::from("patch/output.hdiff"); + let payload = stage_root.join(&payload_relative); + let prepared = destination.parent().unwrap().join("prepared.tmp"); + let bytes = b"phase-split-output"; + std::fs::create_dir_all(destination.parent().unwrap()).unwrap(); + std::fs::create_dir_all(payload.parent().unwrap()).unwrap(); + std::fs::write(&payload, b"patch-payload").unwrap(); + std::fs::write(&prepared, bytes).unwrap(); + let entry = PlannedPatchEntry { + name: "output.bin".to_string(), + destination: destination.clone(), + expected_md5: griffr_core::to_hex(&md5::Md5::digest(bytes)), + expected_size: bytes.len() as u64, + source: PlannedPatchSource::Hdiff { + base: destination.parent().unwrap().join("base.bin"), + payload: payload_relative, + base_md5: "11".repeat(16), + base_size: 1, + }, + }; + let plan = plan( + &install_root, + &stage_root, + vec![entry.clone()], + Vec::new(), + Vec::new(), + ); + + let proof = commit_prepared_hdiff_entry(&plan, &entry, &prepared, false).unwrap(); + + assert_eq!(std::fs::read(&destination).unwrap(), bytes); + assert_eq!(proof.source(), crate::ArtifactSource::HdiffPatch); + assert_eq!(proof.observed_size(), bytes.len() as u64); + assert!(!prepared.exists()); + assert!(payload.exists()); +} + +#[test] +fn prepared_hdiff_commit_primitive_preserves_inputs_for_caller_managed_retry() { + let temp = tempdir().unwrap(); + let install_root = temp.path().join("install"); + let stage_root = temp.path().join("stage"); + let destination = install_root.join("Game_Data/StreamingAssets/VFS/output.bin"); + let payload_relative = PathBuf::from("patch/output.hdiff"); + let payload = stage_root.join(&payload_relative); + let prepared = destination.parent().unwrap().join("prepared.tmp"); + std::fs::create_dir_all(destination.parent().unwrap()).unwrap(); + std::fs::create_dir_all(payload.parent().unwrap()).unwrap(); + std::fs::write(&destination, b"old-output").unwrap(); + std::fs::write(&payload, b"patch-payload").unwrap(); + std::fs::write(&prepared, b"corrupt-output").unwrap(); + let entry = PlannedPatchEntry { + name: "output.bin".to_string(), + destination: destination.clone(), + expected_md5: griffr_core::to_hex(&md5::Md5::digest(b"expected-output")), + expected_size: b"expected-output".len() as u64, + source: PlannedPatchSource::Hdiff { + base: destination.parent().unwrap().join("base.bin"), + payload: payload_relative, + base_md5: "11".repeat(16), + base_size: 1, + }, + }; + let plan = plan( + &install_root, + &stage_root, + vec![entry.clone()], + Vec::new(), + Vec::new(), + ); + + let error = commit_prepared_hdiff_entry(&plan, &entry, &prepared, false).unwrap_err(); + + assert!(error.to_string().contains("failed verification")); + assert_eq!(std::fs::read(&destination).unwrap(), b"old-output"); + assert!(prepared.exists()); + assert!(payload.exists()); + + // The low-level primitive leaves both the prepared output and patch payload + // intact while its caller retains ownership, so a caller-managed retry can + // reuse that artifact. The production runner consumes the continuation + // owner and cleans the prepared temp on failure; that ownership contract is + // covered separately in runner tests. + std::fs::write(&prepared, b"expected-output").unwrap(); + let proof = commit_prepared_hdiff_entry(&plan, &entry, &prepared, false).unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"expected-output"); + assert_eq!(proof.source(), crate::ArtifactSource::HdiffPatch); + assert!(!prepared.exists()); + assert!(payload.exists()); +} + +#[test] +fn prepared_hdiff_external_work_commit_copies_then_commits() { + let temp = tempdir().unwrap(); + let install_root = temp.path().join("install"); + let stage_root = temp.path().join("stage"); + let work_dir = temp.path().join("work"); + let destination = install_root.join("Game_Data/StreamingAssets/VFS/output.bin"); + let payload_relative = PathBuf::from("patch/output.hdiff"); + let payload = stage_root.join(&payload_relative); + let prepared = work_dir.join("prepared.tmp"); + let bytes = b"external-work-output"; + std::fs::create_dir_all(&work_dir).unwrap(); + std::fs::create_dir_all(payload.parent().unwrap()).unwrap(); + std::fs::write(&payload, b"patch-payload").unwrap(); + std::fs::write(&prepared, bytes).unwrap(); + let entry = PlannedPatchEntry { + name: "output.bin".to_string(), + destination: destination.clone(), + expected_md5: griffr_core::to_hex(&md5::Md5::digest(bytes)), + expected_size: bytes.len() as u64, + source: PlannedPatchSource::Hdiff { + base: install_root.join("Game_Data/StreamingAssets/VFS/base.bin"), + payload: payload_relative, + base_md5: "11".repeat(16), + base_size: 1, + }, + }; + let mut plan = plan( + &install_root, + &stage_root, + vec![entry.clone()], + Vec::new(), + Vec::new(), + ); + plan.work_dir = Some(work_dir); + + let proof = commit_prepared_hdiff_entry(&plan, &entry, &prepared, true).unwrap(); + + assert_eq!(std::fs::read(&destination).unwrap(), bytes); + assert_eq!(proof.source(), crate::ArtifactSource::HdiffPatch); + assert!(prepared.exists()); + assert!(payload.exists()); +} + #[test] fn dependency_order_uses_logical_path_for_external_assets() { let temp = tempdir().unwrap(); @@ -235,7 +473,8 @@ fn corrupt_local_payload_does_not_replace_existing_destination() { Vec::new(), ); - let error = apply_planned_entry(&plan, &entry, &VerifiedArtifactCache::default()).unwrap_err(); + let error = + prepare_planned_entry(&plan, &entry, &VerifiedArtifactCache::default()).unwrap_err(); assert!(error.to_string().contains("failed verification")); assert_eq!(std::fs::read(&destination).unwrap(), b"old output"); diff --git a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/mod.rs b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/mod.rs index 7c61de7..4eeed7d 100644 --- a/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/mod.rs +++ b/crates/griffr-runtime/src/task_pool/fs_ops/patch_manifest/mod.rs @@ -1,117 +1,165 @@ -use std::path::{Path, PathBuf}; - -use crate::error::{Error, Result}; -use crate::{ArtifactProof, PATCH_MANIFEST_NAME, PATCH_STAGE_DIR}; - -use griffr_hypergryph_api::ResourcePatch; - -use super::path_safety::parse_safe_relative_path; - mod apply; mod apply_steps; +#[cfg(feature = "hdiff-patch")] +pub(crate) use apply::reclaim_hdiff_outputs; + pub(crate) use apply_steps::{ - apply_patch_deletes, apply_patch_entry, clean_patch_apply, commit_deferred_patch_files, - prepare_patch_apply, release_patch_base, resume_patch_apply, + apply_patch_deletes, clean_patch_apply, commit_deferred_patch_files, commit_hdiff_patch_entry, + prepare_patch_apply, prepare_patch_entry, release_patch_base, PatchEntryPreparation, }; -fn resolve_patch_stage_path( - install_root: &Path, - stage_root: &Path, - stage_subdir: &str, - label: &str, - raw: &str, -) -> Result { - let relative = parse_safe_relative_path(label, raw)?; - let subdir_path = Path::new(stage_subdir); - if relative.starts_with(PATCH_STAGE_DIR) { - return Ok(install_root.join(relative)); - } - if relative.starts_with(subdir_path) { - return Ok(stage_root.join(relative)); - } - Ok(stage_root.join(stage_subdir).join(relative)) -} +#[cfg(test)] +mod tests { + use crate::task_pool::{run_tasks, Task, TaskPoolConfig, TaskPoolResult}; + use std::path::Path; -pub(crate) fn apply_extracted_vfs_patch_manifest( - install_root: &Path, - mut progress_callback: Option<&mut dyn FnMut(&str, usize, usize)>, -) -> Result> { - let manifest_path = install_root.join(PATCH_MANIFEST_NAME); - let stage_root = install_root.join(PATCH_STAGE_DIR); - if !manifest_path.exists() && !stage_root.exists() { - return Ok(Vec::new()); - } - if !manifest_path.is_file() { - return Err(Error::Message { - context: "VFS error: ", - detail: format!( - "Extracted VFS patch manifest is missing required data: missing {}", - manifest_path.display() - ), - }); + fn apply(install_root: &Path) -> TaskPoolResult { + run_tasks( + vec![Task::ApplyExtractedVfsPatchManifest { + install_root: install_root.to_path_buf(), + }], + TaskPoolConfig::default(), + ) + .unwrap() } + #[cfg(feature = "hdiff-patch")] + use crate::PATCH_DIFF_STAGE_DIR; + use crate::{PATCH_MANIFEST_NAME, PATCH_STAGE_DIR}; - let manifest: ResourcePatch = - serde_json::from_slice(&std::fs::read(&manifest_path).map_err(|e| Error::IoAt { - action: "open file", - path: manifest_path.clone(), - source: e, - })?)?; - - let vfs_base_path = - parse_safe_relative_path("patch.json vfs_base_path", manifest.vfs_base_path.trim())?; - let dest_root = install_root.join(&vfs_base_path); + #[cfg(feature = "hdiff-patch")] + #[test] + fn extracted_patch_manifest_decodes_hdiff_with_compio() { + extracted_hdiff_contract_case(false); + } - let total_entries = manifest.files.len(); - if total_entries > 0 { - if let Some(cb) = progress_callback.as_deref_mut() { - cb("", 0, total_entries); - } + #[cfg(feature = "hdiff-patch")] + #[test] + fn unsupported_hdiff_extracted_manifest_preserves_pending_outputs() { + extracted_hdiff_contract_case(true); } - let mut proofs = Vec::with_capacity(total_entries); - for (index, entry) in manifest.files.iter().enumerate() { - let proof = apply::apply_vfs_patch_entry( - install_root, - &stage_root, - &dest_root, - &vfs_base_path, - entry, + + #[cfg(feature = "hdiff-patch")] + fn extracted_hdiff_contract_case(unsupported: bool) { + let temp = tempfile::tempdir().unwrap(); + let install_root = temp.path().join("install"); + let vfs_root = install_root.join("VFS"); + let base = vfs_root.join("base.bin"); + let stage_patch = install_root + .join(PATCH_STAGE_DIR) + .join(PATCH_DIFF_STAGE_DIR) + .join("output.hdiff"); + std::fs::create_dir_all(base.parent().unwrap()).unwrap(); + std::fs::create_dir_all(stage_patch.parent().unwrap()).unwrap(); + let old = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + let mut expected = old.clone(); + expected.extend((0..901).map(|i| ((i * 13 + 3) % 256) as u8)); + use md5::Digest; + let md5_hex = |bytes: &[u8]| { + md5::Md5::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::() + }; + let old_md5 = md5_hex(&old); + let expected_md5 = md5_hex(&expected); + std::fs::write(&base, &old).unwrap(); + std::fs::write( + &stage_patch, + if unsupported { + &b"HDIFFW26&\0"[..] + } else { + &include_bytes!("../../../patch_apply/hdiff_sf20_reference_tail.patch")[..] + }, ) - .map_err(|e| Error::Message { - context: "", - detail: format!("Failed to apply patch entry {}: {e}", entry.name), - })?; - proofs.push(proof); - if let Some(cb) = progress_callback.as_deref_mut() { - let logical_path = vfs_base_path.join(&entry.name); - cb( - &logical_path.to_string_lossy().replace('\\', "/"), - index + 1, - total_entries, + .unwrap(); + let mut manifest = griffr_hypergryph_api::ResourcePatch { + version: "test".to_string(), + vfs_base_path: "VFS".to_string(), + files: vec![griffr_hypergryph_api::ResourcePatchEntry { + name: "output.bin".to_string(), + md5: expected_md5, + size: expected.len() as u64, + local_path: None, + diff_type: 1, + patch: vec![griffr_hypergryph_api::ResourcePatchDiff { + base_file: "base.bin".to_string(), + base_file_path: None, + base_md5: old_md5, + base_size: old.len() as u64, + patch: format!("{PATCH_DIFF_STAGE_DIR}/output.hdiff"), + patch_path: None, + patch_size: std::fs::metadata(&stage_patch).unwrap().len(), + }], + }], + }; + let mut second = manifest.files[0].clone(); + second.name = "second.bin".to_string(); + manifest.files.push(second); + let local_payload = install_root + .join(PATCH_STAGE_DIR) + .join("files/replacement.bin"); + std::fs::create_dir_all(local_payload.parent().unwrap()).unwrap(); + std::fs::write(&local_payload, b"replacement base").unwrap(); + for name in ["base.bin", "local-copy.bin"] { + manifest.files.insert( + 0, + griffr_hypergryph_api::ResourcePatchEntry { + name: name.to_string(), + md5: md5_hex(b"replacement base"), + size: 16, + local_path: Some("files/replacement.bin".to_string()), + diff_type: 0, + patch: Vec::new(), + }, ); } - } + std::fs::write( + install_root.join(PATCH_MANIFEST_NAME), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); - std::fs::remove_file(&manifest_path).map_err(|e| Error::IoAt { - action: "remove file or directory", - path: manifest_path.clone(), - source: e, - })?; - if stage_root.exists() { - std::fs::remove_dir_all(&stage_root).map_err(|e| Error::IoAt { - action: "remove file or directory", - path: stage_root.clone(), - source: e, - })?; - } - Ok(proofs) -} + let result = apply(&install_root); + if unsupported { + assert!(result.metrics.graph.failed_nodes > 0, "{result:?}"); + assert!(format!("{:?}", result.outcomes).contains("unsupported HDiff format")); + assert_eq!(std::fs::read(&base).unwrap(), old); + assert!(!vfs_root.join("output.bin").exists()); + assert!(!vfs_root.join("local-copy.bin").exists()); + assert!(stage_patch.exists()); + assert!(install_root.join(PATCH_MANIFEST_NAME).exists()); + return; + } + assert_eq!(result.metrics.graph.failed_nodes, 0, "{result:?}"); + let proofs = result + .outcomes + .into_iter() + .filter_map(|outcome| match outcome { + crate::task_pool::TaskOutcome::Committed { proof } => Some(proof), + _ => None, + }) + .collect::>(); -#[cfg(test)] -mod tests { - use super::apply_extracted_vfs_patch_manifest; - use crate::{PATCH_MANIFEST_NAME, PATCH_STAGE_DIR}; + assert_eq!(proofs.len(), 4); + assert_eq!( + std::fs::read(vfs_root.join("output.bin")).unwrap(), + expected + ); + assert_eq!( + std::fs::read(vfs_root.join("second.bin")).unwrap(), + expected + ); + assert_eq!(std::fs::read(base).unwrap(), b"replacement base"); + assert_eq!( + std::fs::read(vfs_root.join("local-copy.bin")).unwrap(), + b"replacement base" + ); + assert!(!install_root.join(PATCH_MANIFEST_NAME).exists()); + assert!(!install_root.join(PATCH_STAGE_DIR).exists()); + } #[test] fn corrupt_local_payload_does_not_replace_existing_vfs_file() { @@ -147,7 +195,11 @@ mod tests { ) .unwrap(); - assert!(apply_extracted_vfs_patch_manifest(&install_root, None).is_err()); + let result = apply(&install_root); + assert!(result.outcomes.iter().any(|outcome| matches!( + outcome, crate::task_pool::TaskOutcome::Failed { reason, .. } + if reason.contains("failed verification") + ))); assert_eq!(std::fs::read(destination).unwrap(), b"old usable bytes"); assert!(staged_file.exists()); } @@ -182,12 +234,16 @@ mod tests { ) .unwrap(); - let mut progress = Vec::new(); - let mut on_progress = |path: &str, finished: usize, total: usize| { - progress.push((path.to_string(), finished, total)); - }; - let proofs = - apply_extracted_vfs_patch_manifest(&install_root, Some(&mut on_progress)).unwrap(); + let result = apply(&install_root); + assert_eq!(result.metrics.graph.failed_nodes, 0, "{result:?}"); + let proofs = result + .outcomes + .into_iter() + .filter_map(|outcome| match outcome { + crate::task_pool::TaskOutcome::Committed { proof } => Some(proof), + _ => None, + }) + .collect::>(); assert_eq!(proofs.len(), 1); assert_eq!( @@ -195,17 +251,6 @@ mod tests { "Arknights_Data/StreamingAssets/AB/Windows/ui/direct.ab" ); assert_eq!(proofs[0].source(), crate::ArtifactSource::LocalPatch); - assert_eq!( - progress, - vec![ - ("".to_string(), 0, 1), - ( - "Arknights_Data/StreamingAssets/AB/Windows/ui/direct.ab".to_string(), - 1, - 1, - ), - ] - ); assert_eq!( std::fs::read( install_root.join("Arknights_Data/StreamingAssets/AB/Windows/ui/direct.ab") diff --git a/crates/griffr-runtime/src/task_pool/graph/builder.rs b/crates/griffr-runtime/src/task_pool/graph/builder.rs index c53d945..cea6b38 100644 --- a/crates/griffr-runtime/src/task_pool/graph/builder.rs +++ b/crates/griffr-runtime/src/task_pool/graph/builder.rs @@ -1,4 +1,5 @@ use std::collections::{BTreeSet, HashMap}; +use std::num::NonZeroU64; use super::super::types::Task; use crate::error::{Error, Result}; @@ -13,7 +14,7 @@ pub(crate) struct TaskDependencyToken(pub(super) u64); pub struct NodeId(u32); impl NodeId { - pub(super) fn new(index: usize) -> Result { + pub(crate) fn new(index: usize) -> Result { let raw = u32::try_from(index).map_err(|_| Error::Message { context: "Task pool error: ", detail: "task graph contains more than u32::MAX nodes".into(), @@ -31,6 +32,38 @@ impl NodeId { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum TaskOrigin { + Root, + StaticDependency, + DynamicExpansion, + Continuation, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct DagHint { + pub(crate) origin: TaskOrigin, + pub(crate) depth: u32, + pub(crate) local_rank: Option, +} + +impl DagHint { + pub(crate) const fn new(origin: TaskOrigin, depth: u32) -> Self { + Self { + origin, + depth, + local_rank: None, + } + } + + pub(crate) const fn uses_continuation_lane(self) -> bool { + matches!( + self.origin, + TaskOrigin::DynamicExpansion | TaskOrigin::Continuation + ) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NodeState { Pending, @@ -65,6 +98,7 @@ pub struct TaskGraphSummary { struct BuilderNode { task: Task, dependencies: Vec, + dag_hint: DagHint, } /// Builds a command-scoped DAG. A newly added node may depend only on nodes @@ -108,7 +142,22 @@ impl TaskGraphBuilder { }); } } - self.nodes.push(BuilderNode { task, dependencies }); + let dag_hint = if dependencies.is_empty() { + DagHint::new(TaskOrigin::Root, 0) + } else { + let depth = dependencies + .iter() + .map(|dependency| self.nodes[dependency.index()].dag_hint.depth) + .max() + .unwrap_or(0) + .saturating_add(1); + DagHint::new(TaskOrigin::StaticDependency, depth) + }; + self.nodes.push(BuilderNode { + task, + dependencies, + dag_hint, + }); Ok(id) } @@ -128,7 +177,7 @@ impl TaskGraphBuilder { dependents: Vec::new(), waiters: Vec::new(), waiting_remaining: 0, - continuation: false, + dag_hint: node.dag_hint, }) .collect::>(); diff --git a/crates/griffr-runtime/src/task_pool/graph/exec/node_exec.rs b/crates/griffr-runtime/src/task_pool/graph/exec/node_exec.rs index 64329de..f9cdc28 100644 --- a/crates/griffr-runtime/src/task_pool/graph/exec/node_exec.rs +++ b/crates/griffr-runtime/src/task_pool/graph/exec/node_exec.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeSet, HashMap}; use super::super::super::types::Task; use super::super::builder::{ - NodeId, NodeState, TaskDependencyToken, TaskGraphBuilder, TaskGraphSummary, + DagHint, NodeId, NodeState, TaskDependencyToken, TaskGraphBuilder, TaskGraphSummary, TaskOrigin, }; use super::expansion::{GraphExpansion, TaskRun}; use crate::error::{Error, Result}; @@ -15,7 +15,7 @@ pub(crate) struct TaskNode { pub(crate) dependents: Vec, pub(crate) waiters: Vec, pub(crate) waiting_remaining: usize, - pub(crate) continuation: bool, + pub(crate) dag_hint: DagHint, } /// A command-scoped, append-only task DAG. @@ -62,6 +62,34 @@ impl TaskGraph { self.nodes.get(id.index()).map(|node| node.state) } + pub(crate) fn trace_task(&self, id: NodeId) -> Option<&Task> { + self.nodes + .get(id.index()) + .and_then(|node| node.task.as_ref()) + } + + pub(crate) fn trace_dag_hint(&self, id: NodeId) -> Option { + self.nodes.get(id.index()).map(|node| node.dag_hint) + } + + pub(crate) fn trace_edges_touching_range( + &self, + start: usize, + end: usize, + ) -> Vec<(NodeId, NodeId)> { + let mut edges = Vec::new(); + for (from_index, node) in self.nodes.iter().enumerate() { + for &to in &node.dependents { + if (start..end).contains(&from_index) || (start..end).contains(&to.index()) { + let from = + NodeId::new(from_index).expect("existing graph node id must fit u32"); + edges.push((from, to)); + } + } + } + edges + } + pub fn summary(&self) -> TaskGraphSummary { let mut summary = TaskGraphSummary { total_nodes: self.nodes.len(), @@ -276,6 +304,8 @@ impl TaskGraph { resolved_dependencies.push(dependencies); } + let expansion_root_depth = self.nodes[parent.index()].dag_hint.depth.saturating_add(1); + let mut expansion_depths = Vec::with_capacity(nodes.len()); for (local_index, node) in nodes.iter().enumerate() { let unresolved_dependencies = resolved_dependencies[local_index] .iter() @@ -284,6 +314,18 @@ impl TaskGraph { || self.nodes[dependency.index()].state != NodeState::Succeeded }) .count(); + let depth = resolved_dependencies[local_index] + .iter() + .map(|dependency| { + if dependency.index() >= base { + expansion_depths[dependency.index() - base] + } else { + self.nodes[dependency.index()].dag_hint.depth + } + .saturating_add(1) + }) + .fold(expansion_root_depth, u32::max); + expansion_depths.push(depth); self.nodes.push(TaskNode { task: None, state: NodeState::Pending, @@ -291,7 +333,7 @@ impl TaskGraph { dependents: Vec::new(), waiters: Vec::new(), waiting_remaining: 0, - continuation: true, + dag_hint: DagHint::new(TaskOrigin::DynamicExpansion, depth), }); if let Some(binding) = node.binding { self.bindings.insert(binding, global_ids[local_index]); @@ -358,7 +400,7 @@ impl TaskGraph { ready.push(ReadyTask { id, task, - continuation: node.continuation, + dag_hint: node.dag_hint, }); } @@ -367,11 +409,12 @@ impl TaskGraph { node.state = NodeState::Ready; node.waiting_remaining = 0; node.task = None; - node.continuation = true; + node.dag_hint.origin = TaskOrigin::Continuation; + node.dag_hint.local_rank = None; ready.push(ReadyTask { id, task, - continuation: true, + dag_hint: node.dag_hint, }); } @@ -473,5 +516,5 @@ impl TaskGraph { pub(crate) struct ReadyTask { pub(crate) id: NodeId, pub(crate) task: Task, - pub(crate) continuation: bool, + pub(crate) dag_hint: DagHint, } diff --git a/crates/griffr-runtime/src/task_pool/graph/mod.rs b/crates/griffr-runtime/src/task_pool/graph/mod.rs index c6b6010..88c21c5 100644 --- a/crates/griffr-runtime/src/task_pool/graph/mod.rs +++ b/crates/griffr-runtime/src/task_pool/graph/mod.rs @@ -5,6 +5,7 @@ mod exec; mod tests; pub(crate) use builder::TaskDependencyToken; +pub(crate) use builder::{DagHint, TaskOrigin}; pub use builder::{NodeId, NodeState, TaskGraphBuilder, TaskGraphSummary}; pub use exec::TaskGraph; pub(crate) use exec::{GraphExpansion, ReadyTask, TaskRun}; diff --git a/crates/griffr-runtime/src/task_pool/graph/tests.rs b/crates/griffr-runtime/src/task_pool/graph/tests.rs index cabd907..99676ba 100644 --- a/crates/griffr-runtime/src/task_pool/graph/tests.rs +++ b/crates/griffr-runtime/src/task_pool/graph/tests.rs @@ -1,7 +1,10 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; -use super::{GraphExpansion, NodeId, NodeState, TaskDependencyToken, TaskGraphBuilder, TaskRun}; +use super::{ + DagHint, GraphExpansion, NodeId, NodeState, TaskDependencyToken, TaskGraphBuilder, TaskOrigin, + TaskRun, +}; use crate::task_pool::Task; static TEST_DEPENDENCY_TOKEN_COUNTER: AtomicU64 = AtomicU64::new(1); @@ -32,6 +35,65 @@ fn task(name: &str) -> Task { } } +#[test] +fn static_nodes_receive_typed_origin_and_depth() { + let mut builder = TaskGraphBuilder::new(); + let root = builder.add_root(task("root")); + let child = builder.add_task(task("child"), [root]).unwrap(); + let grandchild = builder.add_task(task("grandchild"), [child]).unwrap(); + let mut graph = builder.build_checked().unwrap(); + + let ready = graph.start(); + assert_eq!(ready.len(), 1); + assert_eq!(ready[0].id, root); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::Root); + assert_eq!(ready[0].dag_hint.depth, 0); + assert_eq!(ready[0].dag_hint.local_rank, None); + + graph.mark_running(root).unwrap(); + let ready = graph.finish(root, TaskRun::succeeded()).unwrap(); + assert_eq!(ready[0].id, child); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::StaticDependency); + assert_eq!(ready[0].dag_hint.depth, 1); + + graph.mark_running(child).unwrap(); + let ready = graph.finish(child, TaskRun::succeeded()).unwrap(); + assert_eq!(ready[0].id, grandchild); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::StaticDependency); + assert_eq!(ready[0].dag_hint.depth, 2); +} + +#[test] +fn dynamic_expansion_receives_typed_origin_and_local_depth() { + let mut builder = TaskGraphBuilder::new(); + let parent = builder.add_root(task("parent")); + let mut graph = builder.build_checked().unwrap(); + let _ = graph.start(); + graph.mark_running(parent).unwrap(); + + let mut expansion = GraphExpansion::new(); + let first = expansion.add_root(task("first")); + expansion.add_task(task("second"), [first]).unwrap(); + let ready = graph.finish(parent, TaskRun::expand(expansion)).unwrap(); + + assert_eq!(ready.len(), 1); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::DynamicExpansion); + assert_eq!(ready[0].dag_hint.depth, 1); + assert_eq!(ready[0].dag_hint.local_rank, None); + let first_id = ready[0].id; + graph.mark_running(first_id).unwrap(); + let ready = graph.finish(first_id, TaskRun::succeeded()).unwrap(); + assert_eq!(ready.len(), 1); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::DynamicExpansion); + assert_eq!(ready[0].dag_hint.depth, 2); +} + +#[test] +fn dag_hint_is_inline_and_small() { + assert!(std::mem::size_of::() <= 16); + assert!(!std::mem::needs_drop::()); +} + #[test] fn fan_in_releases_only_after_all_dependencies_succeed() { let mut builder = TaskGraphBuilder::new(); @@ -65,7 +127,7 @@ fn sequential_continuation_reuses_the_running_node() { assert_eq!(ready.len(), 1); assert_eq!(ready[0].id, root); - assert!(ready[0].continuation); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::Continuation); assert_eq!(graph.node_count(), 1); assert_eq!(graph.node_state(root), Some(NodeState::Ready)); assert_eq!(graph.summary().dynamic_expansions, 0); @@ -124,7 +186,7 @@ fn fan_out_then_continuation_reuses_the_parent_node() { let ready = graph.finish(right, TaskRun::succeeded()).unwrap(); assert_eq!(ready.len(), 1); assert_eq!(ready[0].id, parent); - assert!(ready[0].continuation); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::Continuation); assert_eq!(graph.node_state(parent), Some(NodeState::Ready)); assert_eq!(graph.node_state(dependent), Some(NodeState::Pending)); @@ -367,3 +429,67 @@ fn token_dependency_cannot_wait_on_a_dynamic_ancestor() { .unwrap_err(); assert!(error.to_string().contains("creates a cycle")); } + +#[test] +fn hdiff_commit_continuation_keeps_node_incomplete_and_cleans_prepared_state() { + use crate::task_pool::types::{PatchApplyWork, PreparedHdiffPatchOutput}; + use crate::{PatchPlan, PlannedPatchEntry, PlannedPatchSource}; + + let temp = tempfile::tempdir().unwrap(); + let prepared_path = temp.path().join("prepared-hdiff.tmp"); + std::fs::write(&prepared_path, b"prepared").unwrap(); + + let destination = temp.path().join("game/file.bin"); + let plan = PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: temp.path().join("game"), + stage_root: temp.path().join("stage"), + vfs_base_path: temp.path().join("base"), + vfs_destination: temp.path().join("vfs"), + work_dir: Some(temp.path().join("work")), + entries: vec![PlannedPatchEntry { + name: "file.bin".to_string(), + destination, + expected_md5: "00".repeat(16), + expected_size: 8, + source: PlannedPatchSource::Hdiff { + base: temp.path().join("base.bin"), + payload: temp.path().join("patch.hdiff"), + base_md5: "11".repeat(16), + base_size: 8, + }, + }], + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + }; + let patch = PatchApplyWork::new(plan); + + let mut builder = TaskGraphBuilder::new(); + let root = builder.add_root(task("root")); + let dependent = builder.add_task(task("dependent"), [root]).unwrap(); + let mut graph = builder.build_checked().unwrap(); + let _ = graph.start(); + + graph.mark_running(root).unwrap(); + let ready = graph + .finish( + root, + TaskRun::then(Task::CommitHdiffPatchEntry { + patch, + entry_index: 0, + prepared: PreparedHdiffPatchOutput::new(prepared_path.clone(), true), + }), + ) + .unwrap(); + + assert_eq!(ready.len(), 1); + assert_eq!(ready[0].id, root); + assert_eq!(ready[0].dag_hint.origin, TaskOrigin::Continuation); + assert_eq!(graph.node_count(), 2); + assert_eq!(graph.node_state(root), Some(NodeState::Ready)); + assert_eq!(graph.node_state(dependent), Some(NodeState::Pending)); + assert!(prepared_path.exists()); + + drop(ready); + assert!(!prepared_path.exists()); +} diff --git a/crates/griffr-runtime/src/task_pool/mod.rs b/crates/griffr-runtime/src/task_pool/mod.rs index 9a6088b..c72314d 100644 --- a/crates/griffr-runtime/src/task_pool/mod.rs +++ b/crates/griffr-runtime/src/task_pool/mod.rs @@ -8,6 +8,7 @@ mod runner; pub mod scheduler; pub mod types; pub(crate) mod verify; +pub mod workload; pub use archive_plan::{plan_archive_groups, ArchiveGroup}; pub use download::{download_and_discard, StreamingDownloadReport}; @@ -20,14 +21,20 @@ pub fn storage_volume_key(path: impl AsRef) -> String { fs_ops::storage_volume_group_key(path.as_ref()) } pub use types::{ - archive_expected_files, ArchivePart, ArchiveRangePriority, ArchiveRetention, ArchiveSource, - DownloadResumeState, FileEnsureTask, FinalFileRef, Task, TaskOutcome, TaskPoolConfig, - TaskPoolMetrics, TaskPoolResult, TaskPoolRunner, TaskPoolRunnerGroup, TaskProgress, - TransferClass, VolumeIoPolicy, VolumeStreamingMode, VolumeTaskMetrics, + archive_expected_files, AdmissionBlockReason, ArchivePart, ArchiveRangePriority, + ArchiveRetention, ArchiveSource, DownloadResumeState, FileEnsureTask, FinalFileRef, + GlobalCapacityMetrics, ResourceOccupancy, ResourceOccupancyAction, SchedulerCompletion, + SchedulerDecision, SchedulerNetworkClass, SchedulerResourceDemand, SchedulerRunClass, + SchedulerTaskPriority, SchedulerTrace, SchedulerTraceEvent, SchedulerTraceEventKind, + ServiceEstimate, StorageReservationDemand, Task, TaskOutcome, TaskPoolConfig, TaskPoolMetrics, + TaskPoolResult, TaskPoolRunner, TaskPoolRunnerGroup, TaskProgress, TransferClass, + VolumeIoPolicy, VolumeResourceOccupancy, VolumeStreamingMode, VolumeTaskMetrics, DEFAULT_PROGRESS_BUFFER_BYTES, DEFAULT_REUSE_QUEUE_LIMIT, DEFAULT_VOLUME_METADATA_LIMIT, DEFAULT_VOLUME_READ_LIMIT, DEFAULT_VOLUME_STREAMING_MODE, DEFAULT_VOLUME_STREAMING_PRESSURE_LIMIT, DEFAULT_VOLUME_WRITE_LIMIT, + SCHEDULER_TRACE_SCHEMA_VERSION, }; +pub use workload::*; #[cfg(test)] #[path = "test/mod.rs"] diff --git a/crates/griffr-runtime/src/task_pool/runner/archive/extract.rs b/crates/griffr-runtime/src/task_pool/runner/archive/extract.rs index f0cfc06..5980a55 100644 --- a/crates/griffr-runtime/src/task_pool/runner/archive/extract.rs +++ b/crates/griffr-runtime/src/task_pool/runner/archive/extract.rs @@ -295,6 +295,12 @@ fn build_archive_extraction_expansion( )); let commit_tokens = work.all_tokens(); + // Stage and validate selected patch inputs before publishing ordinary files. + let patch_archive = archive_index.patch_manifest.is_some(); + let mut planned_shards = planned_shards; + if patch_archive { + planned_shards.sort_by_key(|(_, direct)| *direct); + } let plan_ranges = planned_shards .iter() .map(|(plan, _)| { @@ -307,11 +313,12 @@ fn build_archive_extraction_expansion( let mut expansion = GraphExpansion::new(); let mut shard_nodes = Vec::with_capacity(planned_shards.len()); let mut volume_shards = vec![Vec::new(); work.layout.volume_count()]; + let mut staged_nodes = Vec::new(); for (shard_index, ((plan, commits_directly), ranges)) in planned_shards.into_iter().zip(plan_ranges).enumerate() { - let local_dependencies = if work.layout.is_remote() { + let mut local_dependencies = if work.layout.is_remote() { work.layout .missing_range_requests(ranges.clone())? .into_iter() @@ -327,6 +334,9 @@ fn build_archive_extraction_expansion( } else { Vec::new() }; + if patch_archive && commits_directly { + local_dependencies.extend(staged_nodes.iter().copied()); + } let external_dependencies = work.tokens_for_indices(&plan.volume_indices); let shard_volume_indices = plan.volume_indices.clone(); let node = expansion.add_task_with_tokens( @@ -358,6 +368,9 @@ fn build_archive_extraction_expansion( readers.push(node); } } + if patch_archive && !commits_directly { + staged_nodes.push(node); + } shard_nodes.push(node); } @@ -578,7 +591,7 @@ pub(crate) fn run_extract_archive_shard( Ok(()) }, ) - } else { + } else if archive_index.patch_manifest.is_none() { extractor.extract_entries_with_progress( &staging_dir, work.password.as_deref(), @@ -588,6 +601,49 @@ pub(crate) fn run_extract_archive_shard( extraction_progress_buffer_bytes, &mut on_extract_progress, ) + } else { + let hdiff_inputs = { + let prepared = work.prepared.lock().unwrap(); + let mut inputs = std::collections::BTreeMap::>::new(); + if let Some((plan, _)) = prepared + .as_ref() + .and_then(|state| state.patch_plan.as_ref()) + { + for entry in &plan.entries { + if let PlannedPatchSource::Hdiff { + payload, base_size, .. + } = &entry.source + { + let key = payload + .to_string_lossy() + .replace('\\', "/") + .to_ascii_lowercase(); + inputs + .entry(key) + .or_default() + .push((*base_size, entry.expected_size)); + } + } + } + inputs + }; + extractor.extract_entries_with_progress_and_file( + &staging_dir, + work.password.as_deref(), + &archive_index, + &entries, + &work.expected_files, + extraction_progress_buffer_bytes, + &mut on_extract_progress, + |source, normalized, _| { + if let Some(sizes) = hdiff_inputs.get(&normalized.to_ascii_lowercase()) { + for &(old_size, new_size) in sizes { + crate::patch_apply::validate_hdiff_input(source, old_size, new_size)?; + } + } + Ok(()) + }, + ) }; let succeeded = result.is_ok(); @@ -629,7 +685,7 @@ pub(crate) fn run_finish_archive(work: std::sync::Arc) -> TaskRun { } }; if let Some((plan, _report)) = prepared.patch_plan { - return super::patch::schedule_patch_apply(work, PatchApplyWork::new(plan)); + return super::patch::schedule_patch_apply(Some(work), PatchApplyWork::new(plan)); } super::commit::finish_archive(work, prepared.staging_dir, prepared.deferred_commit_paths) } diff --git a/crates/griffr-runtime/src/task_pool/runner/archive/patch.rs b/crates/griffr-runtime/src/task_pool/runner/archive/patch.rs index c6aa26f..dd0d4ff 100644 --- a/crates/griffr-runtime/src/task_pool/runner/archive/patch.rs +++ b/crates/griffr-runtime/src/task_pool/runner/archive/patch.rs @@ -4,15 +4,17 @@ use std::sync::Arc; use crate::error::Result; use crate::task_pool::fs_ops::{ - apply_patch_deletes, apply_patch_entry, clean_patch_apply, commit_deferred_patch_files, - prepare_patch_apply, release_patch_base, + apply_patch_deletes, clean_patch_apply, commit_deferred_patch_files, commit_hdiff_patch_entry, + prepare_patch_apply, prepare_patch_entry, release_patch_base, PatchEntryPreparation, }; use crate::task_pool::graph::{GraphExpansion, TaskRun}; -use crate::task_pool::types::{ArchiveWork, PatchApplyWork, Task, WorkerEvent}; +use crate::task_pool::types::{ + ArchiveWork, PatchApplyWork, PreparedHdiffPatchOutput, Task, WorkerEvent, +}; use crate::{entry_dependency_indices, entry_wave_indices, ArtifactSource, PlannedPatchSource}; pub(crate) fn schedule_patch_apply( - archive: Arc, + archive: Option>, patch: Arc, ) -> TaskRun { let result: Result = (|| { @@ -108,34 +110,123 @@ pub(crate) fn run_prepare_patch_apply( } } +fn finish_patch_entry( + patch: &PatchApplyWork, + entry_index: usize, + proof: crate::ArtifactProof, + event_tx: &flume::Sender, +) -> TaskRun { + let Some(entry) = patch.entry(entry_index) else { + return TaskRun::failed(format!("patch entry index {entry_index} is out of range")); + }; + let (finished, report_progress) = patch.finish_entry(); + let logical = patch.plan().vfs_base_path.join(&entry.name); + let path = logical.to_string_lossy().replace('\\', "/"); + if proof.source() != ArtifactSource::Existing { + let _ = event_tx.send(WorkerEvent::changed(path.clone())); + } + let _ = event_tx.send(WorkerEvent::committed(proof)); + if report_progress { + let _ = event_tx.send(WorkerEvent::progress( + crate::ProgressPhase::Patch, + path, + finished as u64, + patch.entry_count() as u64, + false, + )); + } + TaskRun::succeeded() +} + pub(crate) fn run_apply_patch_entry( patch: Arc, entry_index: usize, event_tx: &flume::Sender, +) -> TaskRun { + match prepare_patch_entry(patch.plan(), entry_index, patch.verification_cache()) { + Ok(PatchEntryPreparation::Complete(proof)) => { + finish_patch_entry(&patch, entry_index, proof, event_tx) + } + #[cfg(feature = "hdiff-patch")] + Ok(PatchEntryPreparation::Hdiff(prepared)) => TaskRun::then(Task::DecodeHdiffPatchEntry { + patch, + entry_index, + prepared, + #[cfg(feature = "hdiff-patch")] + checkpoint: Default::default(), + #[cfg(feature = "hdiff-patch")] + retained: None, + }), + Err(error) => TaskRun::failed(error.to_string()), + } +} + +#[cfg(feature = "hdiff-patch")] +pub(crate) async fn run_decode_hdiff_patch_entry( + patch: Arc, + entry_index: usize, + prepared: PreparedHdiffPatchOutput, + checkpoint: crate::patch_apply::hdiff_sf20::HdiffCheckpoint, + retained: Option, ) -> TaskRun { let Some(entry) = patch.entry(entry_index) else { return TaskRun::failed(format!("patch entry index {entry_index} is out of range")); }; - match apply_patch_entry(patch.plan(), entry_index, patch.verification_cache()) { - Ok(proof) => { - let (finished, report_progress) = patch.finish_entry(); - let logical = patch.plan().vfs_base_path.join(&entry.name); - let path = logical.to_string_lossy().replace('\\', "/"); - if proof.source() != ArtifactSource::Existing { - let _ = event_tx.send(WorkerEvent::changed(path.clone())); - } - let _ = event_tx.send(WorkerEvent::committed(proof)); - if report_progress { - let _ = event_tx.send(WorkerEvent::progress( - crate::ProgressPhase::Patch, - path, - finished as u64, - patch.entry_count() as u64, - false, - )); - } - TaskRun::succeeded() - } + let PlannedPatchSource::Hdiff { base, payload, .. } = &entry.source else { + return TaskRun::failed(format!("patch entry {entry_index} is not HDiff")); + }; + let payload_path = patch.plan().stage_root.join(payload); + match checkpoint + .advance( + base, + &payload_path, + prepared.path(), + entry.expected_size, + patch.hdiff_budget(), + ) + .await + { + Ok(None) => TaskRun::then(Task::CommitHdiffPatchEntry { + patch, + entry_index, + prepared, + }), + Ok(Some(checkpoint)) => TaskRun::then(Task::DecodeHdiffPatchEntry { + patch, + entry_index, + prepared, + checkpoint, + retained, + }), + Err(error) => TaskRun::failed(format!( + "HDIFFSF20 decoding failed for {}: {error}", + payload_path.display() + )), + } +} + +#[cfg(not(feature = "hdiff-patch"))] +pub(crate) async fn run_decode_hdiff_patch_entry( + _patch: Arc, + _entry_index: usize, + _prepared: PreparedHdiffPatchOutput, +) -> TaskRun { + TaskRun::failed("HDiff patch feature is disabled") +} + +pub(crate) fn run_commit_hdiff_patch_entry( + patch: Arc, + entry_index: usize, + prepared: PreparedHdiffPatchOutput, + event_tx: &flume::Sender, +) -> TaskRun { + match commit_hdiff_patch_entry( + patch.plan(), + entry_index, + prepared.path(), + prepared.copy_to_destination_temp(), + ) { + Ok(proof) => finish_patch_entry(&patch, entry_index, proof, event_tx), Err(error) => TaskRun::failed(error.to_string()), } } @@ -194,11 +285,14 @@ pub(crate) fn run_commit_patch_deferred( pub(crate) fn run_clean_patch_apply( patch: Arc, - archive: Arc, + archive: Option>, ) -> TaskRun { if let Err(error) = clean_patch_apply(patch.plan()) { return TaskRun::failed(error.to_string()); } + let Some(archive) = archive else { + return TaskRun::succeeded(); + }; archive.prepared.lock().unwrap().take(); let mut expansion = GraphExpansion::new(); match expansion.add_root_with_tokens( @@ -211,3 +305,299 @@ pub(crate) fn run_clean_patch_apply( Err(error) => TaskRun::failed(error.to_string()), } } +#[cfg(test)] +mod tests { + use super::run_commit_hdiff_patch_entry; + use crate::task_pool::graph::TaskRun; + use crate::task_pool::types::{PatchApplyWork, PreparedHdiffPatchOutput}; + use crate::{PatchPlan, PlannedPatchEntry, PlannedPatchSource}; + use md5::Digest; + use std::path::PathBuf; + + #[cfg(feature = "hdiff-patch")] + #[compio::test] + async fn native_hdiff_workunits_commit_official_reference_patch() { + use super::{run_apply_patch_entry, run_decode_hdiff_patch_entry}; + + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("install"); + let stage = temp.path().join("stage"); + let vfs = std::path::Path::new("Game_Data/StreamingAssets/VFS"); + let base = root.join(vfs).join("base.bin"); + let target = root.join(vfs).join("target.bin"); + let payload_rel = PathBuf::from("patch/reference.hdiff"); + let payload = stage.join(&payload_rel); + std::fs::create_dir_all(base.parent().unwrap()).unwrap(); + std::fs::create_dir_all(payload.parent().unwrap()).unwrap(); + let old = (0..8192) + .map(|n| ((n * 47 + 13) % 256) as u8) + .collect::>(); + let mut expected = old.clone(); + for (i, value) in expected.iter_mut().enumerate().skip(2550).take(300) { + *value = (((i - 2550) * 17) % 256) as u8; + } + std::fs::write(&base, &old).unwrap(); + std::fs::write(&target, b"previous-committed-output").unwrap(); + std::fs::write( + &payload, + include_bytes!("../../../patch_apply/hdiff_sf20_reference_zstd.patch"), + ) + .unwrap(); + let patch = PatchApplyWork::new(PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: root.clone(), + stage_root: stage, + vfs_base_path: vfs.to_path_buf(), + vfs_destination: root.join(vfs), + work_dir: None, + entries: vec![PlannedPatchEntry { + name: "target.bin".into(), + destination: target.clone(), + expected_md5: griffr_core::to_hex(&md5::Md5::digest(&expected)), + expected_size: expected.len() as u64, + source: PlannedPatchSource::Hdiff { + base: base.clone(), + payload: payload_rel, + base_md5: griffr_core::to_hex(&md5::Md5::digest(&old)), + base_size: old.len() as u64, + }, + }], + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + }); + let (tx, _rx) = flume::unbounded(); + let patch_for_graph = patch.clone(); + let next = run_apply_patch_entry(patch.clone(), 0, &tx); + let TaskRun::Continue(crate::task_pool::types::Task::DecodeHdiffPatchEntry { + patch, + entry_index, + prepared, + checkpoint, + .. + }) = next + else { + panic!("HDiff stage must continue into compio decoder: {next:?}"); + }; + assert_eq!( + std::fs::read(&target).unwrap(), + b"previous-committed-output" + ); + let temporary = prepared.path().to_path_buf(); + let decoded = + run_decode_hdiff_patch_entry(patch, entry_index, prepared, checkpoint, None).await; + let TaskRun::Continue(crate::task_pool::types::Task::CommitHdiffPatchEntry { + patch, + entry_index, + prepared, + }) = decoded + else { + panic!("decoded output must continue into commit: {decoded:?}"); + }; + assert_eq!( + std::fs::read(&target).unwrap(), + b"previous-committed-output" + ); + let committed = run_commit_hdiff_patch_entry(patch, entry_index, prepared, &tx); + assert!(matches!(committed, TaskRun::Succeeded), "{committed:?}"); + assert_eq!(std::fs::read(&target).unwrap(), expected); + assert!(!temporary.exists()); + assert!(payload.exists()); + + // Exercise actual Dispatcher admission and same-node continuation, + // not only the individual runner methods. + std::fs::write(&target, b"outdated-output").unwrap(); + std::fs::write( + &payload, + include_bytes!("../../../patch_apply/hdiff_sf20_reference_zstd.patch"), + ) + .unwrap(); + let patch_for_failure = patch_for_graph.clone(); + let result = crate::task_pool::run_tasks( + vec![crate::task_pool::Task::ApplyPatchEntry { + patch: patch_for_graph, + entry_index: 0, + }], + crate::task_pool::TaskPoolConfig::default(), + ) + .unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), expected); + assert!(payload.exists()); + assert_eq!(result.metrics.graph.total_nodes, 1); + assert_eq!(result.metrics.graph.succeeded_nodes, 1); + assert_eq!(result.metrics.graph.failed_nodes, 0); + + // An invalid compressed frame must not replace a previously committed + // destination, delete the recoverable patch input, or leak its temporary. + std::fs::write(&target, b"keep-existing-output").unwrap(); + let mut damaged = + include_bytes!("../../../patch_apply/hdiff_sf20_reference_zstd.patch").to_vec(); + let zstd_magic = [0x28, 0xb5, 0x2f, 0xfd]; + let offset = damaged + .windows(4) + .position(|window| window == zstd_magic) + .unwrap(); + damaged[offset] = 0; + std::fs::write(&payload, damaged).unwrap(); + let failure = crate::task_pool::run_tasks( + vec![crate::task_pool::Task::ApplyPatchEntry { + patch: patch_for_failure, + entry_index: 0, + }], + crate::task_pool::TaskPoolConfig::default(), + ) + .unwrap(); + assert_eq!(failure.metrics.graph.failed_nodes, 1); + assert_eq!(std::fs::read(&target).unwrap(), b"keep-existing-output"); + assert!(payload.exists()); + let temporary_count = std::fs::read_dir(target.parent().unwrap()) + .unwrap() + .filter_map(std::result::Result::ok) + .filter(|entry| entry.file_name().to_string_lossy().contains(".griffr.tmp.")) + .count(); + assert_eq!(temporary_count, 0); + } + + #[cfg(feature = "hdiff-patch")] + #[compio::test] + async fn queued_decode_cancellation_removes_partial_candidate() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("install"); + let vfs = root.join("VFS"); + let stage = temp.path().join("stage"); + std::fs::create_dir_all(&vfs).unwrap(); + std::fs::create_dir_all(&stage).unwrap(); + let base = vfs.join("base.bin"); + let old = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + std::fs::write(&base, &old).unwrap(); + let destination = vfs.join("target.bin"); + std::fs::write(&destination, b"existing").unwrap(); + let payload = stage.join("patch.hdiff"); + std::fs::write( + &payload, + include_bytes!("../../../patch_apply/hdiff_sf20_reference_tail.patch"), + ) + .unwrap(); + let patch = PatchApplyWork::with_hdiff_budget( + PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: root, + stage_root: stage, + vfs_base_path: PathBuf::from("VFS"), + vfs_destination: vfs, + work_dir: None, + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + entries: vec![PlannedPatchEntry { + name: "target.bin".to_string(), + destination: destination.clone(), + expected_md5: "0".repeat(32), + expected_size: 9093, + source: PlannedPatchSource::Hdiff { + base, + base_size: old.len() as u64, + base_md5: griffr_core::to_hex(&md5::Md5::digest(&old)), + payload: PathBuf::from("patch.hdiff"), + }, + }], + }, + 64, + ); + let (tx, _rx) = flume::unbounded(); + let TaskRun::Continue(super::Task::DecodeHdiffPatchEntry { + patch, + entry_index, + prepared, + checkpoint, + .. + }) = super::run_apply_patch_entry(patch, 0, &tx) + else { + panic!("expected preparation to yield to decode"); + }; + let candidate = prepared.path().to_path_buf(); + let queued = + super::run_decode_hdiff_patch_entry(patch, entry_index, prepared, checkpoint, None) + .await; + assert!(matches!( + &queued, + TaskRun::Continue(super::Task::DecodeHdiffPatchEntry { .. }) + )); + assert!(std::fs::metadata(&candidate).unwrap().len() > 0); + drop(queued); + assert!(!candidate.parent().unwrap().exists()); + assert_eq!(std::fs::read(destination).unwrap(), b"existing"); + assert!(payload.exists()); + } + + #[test] + fn hdiff_commit_runner_failure_cleans_prepared_and_preserves_regeneration_inputs() { + let temp = tempfile::tempdir().unwrap(); + let install_root = temp.path().join("install"); + let stage_root = temp.path().join("stage"); + let destination = install_root.join("Game_Data/StreamingAssets/VFS/output.bin"); + let payload_relative = PathBuf::from("patch/output.hdiff"); + let payload = stage_root.join(&payload_relative); + let prepared = destination.parent().unwrap().join("prepared.tmp"); + let expected = b"expected-output"; + + std::fs::create_dir_all(destination.parent().unwrap()).unwrap(); + std::fs::create_dir_all(payload.parent().unwrap()).unwrap(); + std::fs::write(&destination, b"old-output").unwrap(); + std::fs::write(&payload, b"patch-payload").unwrap(); + std::fs::write(&prepared, b"corrupt-output").unwrap(); + + let vfs_base_path = PathBuf::from("Game_Data/StreamingAssets/VFS"); + let patch = PatchApplyWork::new(PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: install_root.clone(), + stage_root: stage_root.clone(), + vfs_base_path: vfs_base_path.clone(), + vfs_destination: install_root.join(&vfs_base_path), + work_dir: None, + entries: vec![PlannedPatchEntry { + name: "output.bin".to_string(), + destination: destination.clone(), + expected_md5: griffr_core::to_hex(&md5::Md5::digest(expected)), + expected_size: expected.len() as u64, + source: PlannedPatchSource::Hdiff { + base: install_root.join("Game_Data/StreamingAssets/VFS/base.bin"), + payload: payload_relative, + base_md5: "11".repeat(16), + base_size: 1, + }, + }], + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + }); + let (event_tx, _event_rx) = flume::unbounded(); + + let failed = run_commit_hdiff_patch_entry( + patch.clone(), + 0, + PreparedHdiffPatchOutput::new(prepared.clone(), false), + &event_tx, + ); + + assert!(matches!(failed, TaskRun::Failed { .. })); + assert_eq!(std::fs::read(&destination).unwrap(), b"old-output"); + assert!(payload.exists()); + assert!(!prepared.exists()); + + // A higher-level retry can regenerate phase A because the destination + // and patch payload survived the failed phase-B continuation. Model the + // regenerated prepared artifact and run the normal phase-B runner again. + std::fs::write(&prepared, expected).unwrap(); + let retried = run_commit_hdiff_patch_entry( + patch, + 0, + PreparedHdiffPatchOutput::new(prepared.clone(), false), + &event_tx, + ); + + assert!(matches!(retried, TaskRun::Succeeded)); + assert_eq!(std::fs::read(&destination).unwrap(), expected); + assert!(payload.exists()); + assert!(!prepared.exists()); + } +} diff --git a/crates/griffr-runtime/src/task_pool/runner/mod.rs b/crates/griffr-runtime/src/task_pool/runner/mod.rs index 7d5e4b5..22d0807 100644 --- a/crates/griffr-runtime/src/task_pool/runner/mod.rs +++ b/crates/griffr-runtime/src/task_pool/runner/mod.rs @@ -1,8 +1,6 @@ -use super::fs_ops::{ - apply_delete_files_manifest_async, apply_extracted_vfs_patch_manifest, resume_patch_apply, -}; +use super::fs_ops::apply_delete_files_manifest_async; use super::graph::TaskRun; -use super::types::{should_report_item_progress, Task, WorkerEvent}; +use super::types::{Task, WorkerEvent}; mod archive; mod transfer; @@ -13,6 +11,7 @@ pub(crate) fn run_blocking_task( extraction_progress_buffer_bytes: usize, extract_shards: usize, event_tx: &flume::Sender, + observed_storage_read_bytes: &mut Option, ) -> TaskRun { match task { Task::OpenArchive { @@ -40,14 +39,18 @@ pub(crate) fn run_blocking_task( expected_hash, expected_size, on_fail, - } => super::verify::run_verify( - &path, - &logical_path, - &expected_hash, - expected_size, - on_fail, - event_tx, - ), + } => { + let (run, read_bytes) = super::verify::run_verify( + &path, + &logical_path, + &expected_hash, + expected_size, + on_fail, + event_tx, + ); + *observed_storage_read_bytes = Some(read_bytes); + run + } Task::VerifyMetadata { path, logical_path, @@ -122,6 +125,11 @@ pub(crate) fn run_blocking_task( Task::ApplyPatchEntry { patch, entry_index } => { archive::run_apply_patch_entry(patch, entry_index, event_tx) } + Task::CommitHdiffPatchEntry { + patch, + entry_index, + prepared, + } => archive::run_commit_hdiff_patch_entry(patch, entry_index, prepared, event_tx), Task::ReleasePatchBase { patch, base } => archive::run_release_patch_base(patch, base), Task::ApplyPatchDeletes { patch } => archive::run_apply_patch_deletes(patch, event_tx), Task::CommitPatchDeferred { patch } => archive::run_commit_patch_deferred(patch, event_tx), @@ -131,7 +139,7 @@ pub(crate) fn run_blocking_task( } => archive::run_clean_patch_apply(patch, archive_work), Task::CleanupArchive { work } => archive::run_clean_archive(work, event_tx), Task::ApplyExtractedVfsPatchManifest { install_root } => { - run_apply_patch_manifest(install_root, event_tx) + run_apply_patch_manifest(install_root) } task @ Task::ReuseFile { copy_only: false, .. @@ -144,7 +152,8 @@ pub(crate) fn run_blocking_task( | Task::ReuseFile { copy_only: true, .. } - | Task::ApplyDeleteManifest { .. } => { + | Task::ApplyDeleteManifest { .. } + | Task::DecodeHdiffPatchEntry { .. } => { unreachable!("async I/O task routed to blocking runner") } } @@ -204,6 +213,27 @@ pub(crate) async fn run_async_task( Task::ReuseFile { copy_only: false, .. } => unreachable!("hardlink reuse routed to async I/O runner"), + Task::DecodeHdiffPatchEntry { + patch, + entry_index, + prepared, + #[cfg(feature = "hdiff-patch")] + checkpoint, + #[cfg(feature = "hdiff-patch")] + retained, + .. + } => { + archive::run_decode_hdiff_patch_entry( + patch, + entry_index, + prepared, + #[cfg(feature = "hdiff-patch")] + checkpoint, + #[cfg(feature = "hdiff-patch")] + retained, + ) + .await + } Task::ApplyDeleteManifest { install_root } => { run_apply_delete_manifest(install_root, event_tx).await } @@ -211,89 +241,18 @@ pub(crate) async fn run_async_task( } } -fn run_apply_patch_manifest( - install_root: std::path::PathBuf, - event_tx: &flume::Sender, -) -> TaskRun { +fn run_apply_patch_manifest(install_root: std::path::PathBuf) -> TaskRun { let plan_path = crate::griffr_patch_path(&install_root).join(crate::PATCH_PLAN_NAME); - let has_patch_plan = plan_path.is_file(); - let result = if has_patch_plan { - let mut on_commit = |path: &std::path::Path, finished: usize, total: usize| { - let normalized = path.to_string_lossy().replace('\\', "/"); - if finished > 0 { - let _ = event_tx.send(WorkerEvent::changed(normalized.clone())); - } - if should_report_item_progress(finished, total) { - let _ = event_tx.send(WorkerEvent::progress( - crate::ProgressPhase::Commit, - normalized, - finished as u64, - total as u64, - false, - )); - } - }; - let mut on_patch = |path: &str, finished: usize, total: usize| { - if should_report_item_progress(finished, total) { - let _ = event_tx.send(WorkerEvent::progress( - crate::ProgressPhase::Patch, - path.to_string(), - finished as u64, - total as u64, - false, - )); - } - }; - let mut on_delete = |path: &std::path::Path, finished: usize, total: usize| { - let normalized = path.to_string_lossy().replace('\\', "/"); - if finished > 0 { - let _ = event_tx.send(WorkerEvent::changed(normalized.clone())); - } - if should_report_item_progress(finished, total) { - let _ = event_tx.send(WorkerEvent::progress( - crate::ProgressPhase::Delete, - normalized, - finished as u64, - total as u64, - false, - )); - } - }; - resume_patch_apply( - &install_root, - Some(&mut on_commit), - Some(&mut on_patch), - Some(&mut on_delete), - ) + let plan = if plan_path.is_file() { + crate::patch_apply::read_patch_plan(&install_root).map(Some) } else { - let mut on_progress = |path: &str, finished: usize, total: usize| { - if should_report_item_progress(finished, total) { - let _ = event_tx.send(WorkerEvent::progress( - crate::ProgressPhase::Patch, - path.to_string(), - finished as u64, - total as u64, - false, - )); - } - }; - apply_extracted_vfs_patch_manifest(&install_root, Some(&mut on_progress)) + crate::patch_apply::plan_extracted_patch(&install_root) }; - - match result { - Ok(proofs) => { - for proof in proofs { - if proof.source() != crate::ArtifactSource::Existing { - let _ = event_tx.send(WorkerEvent::changed(proof.logical_path().to_string())); - } - let _ = event_tx.send(WorkerEvent::committed(proof)); - } - if has_patch_plan { - TaskRun::succeeded() - } else { - TaskRun::then(Task::ApplyDeleteManifest { install_root }) - } + match plan { + Ok(Some(plan)) => { + archive::schedule_patch_apply(None, super::types::PatchApplyWork::new(plan)) } + Ok(None) => TaskRun::then(Task::ApplyDeleteManifest { install_root }), Err(error) => TaskRun::failed(error.to_string()), } } diff --git a/crates/griffr-runtime/src/task_pool/scheduler.rs b/crates/griffr-runtime/src/task_pool/scheduler.rs index 168ea09..08e4fa7 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler.rs @@ -23,12 +23,22 @@ const MAX_IDLE_BLOCKING_DISPATCH_RETRIES: usize = 100; const MAX_WORKER_EVENTS_PER_TICK: usize = 256; const MAX_TASK_FINISHES_PER_TICK: usize = 256; +mod global_capacity; + +#[cfg(feature = "hdiff-patch")] +pub(crate) use global_capacity::HdiffMemoryLease; +pub(crate) use global_capacity::{GlobalCapacityAuthority, GlobalCapacityRunner}; mod metrics; +mod observatory; mod progress; mod queue; +#[cfg(all(test, feature = "hdiff-patch"))] +#[path = "scheduler/tests/retention.rs"] +mod retention_tests; mod routing; use metrics::SchedulerMetrics; +use observatory::SchedulerTraceRecorder; use progress::TaskProgressReducer; use queue::{ScheduledTask, SchedulerQueue}; use routing::{ @@ -42,11 +52,13 @@ pub(crate) enum TaskPriority { } struct TaskFinish { + global_lease: Option, node_id: super::graph::NodeId, path: String, resources: ResourceRequest, queue_wait: Duration, run_time: Duration, + observed_storage_read_bytes: Option, run: TaskRun, } @@ -82,7 +94,7 @@ impl ReadyBacklog { fn extend(&mut self, ready: Vec) { for ready in ready { let class = run_class_index(run_class(&ready.task)); - if ready.continuation { + if ready.dag_hint.uses_continuation_lane() { self.continuation[class].push_back(ready); } else { self.bulk[class].push_back(ready); @@ -148,16 +160,48 @@ fn complete_task( graph: &mut TaskGraph, event_tx: &flume::Sender, ready_backlog: &mut ReadyBacklog, + config: &TaskPoolConfig, + scheduler_trace: &mut SchedulerTraceRecorder, ) -> Result<()> { + let TaskFinish { + global_lease, + node_id, + path, + resources, + queue_wait, + run_time, + observed_storage_read_bytes, + run, + } = finish; *in_flight = (*in_flight).saturating_sub(1); - queue.release(&finish.resources); - metrics.record(finish.queue_wait, finish.run_time, &finish.resources); - if let Some((reason, report)) = finish.run.failure_details() { + queue.release_observed(node_id, &resources, config, scheduler_trace); + drop(global_lease); + metrics.record(queue_wait, run_time, &resources); + scheduler_trace.finished( + node_id, + &run, + queue_wait, + run_time, + observed_storage_read_bytes, + ); + if let Some((reason, report)) = run.failure_details() { if report { - let _ = event_tx.send(WorkerEvent::failed(finish.path.clone(), reason.to_string())); + let _ = event_tx.send(WorkerEvent::failed(path.clone(), reason.to_string())); } } - let ready = graph.finish(finish.node_id, finish.run)?; + let expansion_parent = + matches!(&run, TaskRun::Expand(_) | TaskRun::ExpandThen { .. }).then_some(node_id); + let previous_node_count = graph.node_count(); + let ready = graph.finish(node_id, run)?; + scheduler_trace.capture_graph_range( + graph, + previous_node_count, + graph.node_count(), + &ready, + expansion_parent, + ); + scheduler_trace.created_range(previous_node_count, graph.node_count()); + scheduler_trace.ready_tasks(&ready); ready_backlog.extend(ready); Ok(()) } @@ -171,6 +215,8 @@ fn complete_task_batch( graph: &mut TaskGraph, event_tx: &flume::Sender, ready_backlog: &mut ReadyBacklog, + config: &TaskPoolConfig, + scheduler_trace: &mut SchedulerTraceRecorder, ) -> Result<()> { complete_task( first, @@ -180,6 +226,8 @@ fn complete_task_batch( graph, event_tx, ready_backlog, + config, + scheduler_trace, )?; for _ in 1..MAX_TASK_FINISHES_PER_TICK { let Ok(finish) = finish_rx.try_recv() else { @@ -193,6 +241,8 @@ fn complete_task_batch( graph, event_tx, ready_backlog, + config, + scheduler_trace, )?; } Ok(()) @@ -221,14 +271,13 @@ fn build_dispatcher(config: &TaskPoolConfig) -> Result> { fn runner_with_dispatcher( config: TaskPoolConfig, dispatcher: Arc, + global_capacity: GlobalCapacityRunner, ) -> Result { validate_config(&config)?; - let (event_tx, event_rx) = flume::unbounded::(); Ok(TaskPoolRunner { config, dispatcher, - event_tx, - event_rx, + global_capacity, }) } @@ -239,13 +288,15 @@ impl TaskPoolRunnerGroup { dispatcher: build_dispatcher(&config)?, dispatcher_threads: config.dispatcher_threads, blocking_pool_limit: config.blocking_pool_limit, + global_capacity: GlobalCapacityAuthority::new(&config), }) } pub fn runner(&self, mut config: TaskPoolConfig) -> Result { config.dispatcher_threads = self.dispatcher_threads; config.blocking_pool_limit = self.blocking_pool_limit; - runner_with_dispatcher(config, self.dispatcher.clone()) + let global_capacity = self.global_capacity.register(); + runner_with_dispatcher(config, self.dispatcher.clone(), global_capacity) } } @@ -253,7 +304,8 @@ impl TaskPoolRunner { pub fn new(config: TaskPoolConfig) -> Result { validate_config(&config)?; let dispatcher = build_dispatcher(&config)?; - runner_with_dispatcher(config, dispatcher) + let global_capacity = GlobalCapacityAuthority::new(&config).register(); + runner_with_dispatcher(config, dispatcher, global_capacity) } pub fn run_batch( @@ -269,14 +321,30 @@ impl TaskPoolRunner { mut graph: TaskGraph, progress: TaskProgress, ) -> Result { - while self.event_rx.try_recv().is_ok() {} + let _waiters = self.global_capacity.clear_waiters_on_run_exit(); + // Keep late events from a failed coordinator isolated to its batch. + let (event_tx, event_rx) = flume::unbounded::(); let run_started_at = Instant::now(); let metrics = SchedulerMetrics::default(); + let mut scheduler_trace = SchedulerTraceRecorder::new_for_runner( + self.config.scheduler_trace, + run_started_at, + self.global_capacity.id(), + ); + scheduler_trace.enable_workload_capture( + self.config.workload_capture.as_ref(), + &self.config, + self.global_capacity.hdiff_decoder_limit(), + )?; + scheduler_trace.capture_graph_range(&graph, 0, graph.node_count(), &[], None); + scheduler_trace.created_range(0, graph.node_count()); let mut queue = SchedulerQueue::default(); let mut volume_keys = VolumeKeyCache::default(); let mut ready_backlog = ReadyBacklog::default(); let graph_start_started_at = Instant::now(); - ready_backlog.extend(graph.start()); + let initial_ready = graph.start(); + scheduler_trace.ready_tasks(&initial_ready); + ready_backlog.extend(initial_ready); let initial_graph_time = graph_start_started_at.elapsed(); let ready_frontier_limit = self.config.ready_frontier_limit(); let initial_routing_started_at = Instant::now(); @@ -285,6 +353,7 @@ impl TaskPoolRunner { &mut ready_backlog, &mut volume_keys, ready_frontier_limit, + &mut scheduler_trace, ); let initial_routing_time = initial_routing_started_at.elapsed(); let (initial_volume_cache_hits, initial_volume_cache_misses) = volume_keys.stats(); @@ -314,10 +383,11 @@ impl TaskPoolRunner { &mut volume_keys, ready_frontier_limit, in_flight, + &mut scheduler_trace, ); let mut worker_events_handled = 0usize; for _ in 0..MAX_WORKER_EVENTS_PER_TICK { - let Ok(event) = self.event_rx.try_recv() else { + let Ok(event) = event_rx.try_recv() else { break; }; record_worker_event(&mut progress, &mut outcomes, event); @@ -329,9 +399,20 @@ impl TaskPoolRunner { let mut blocking_pool_busy = false; let mut blocking_dispatch_available = true; - while let Some(scheduled) = queue.pop_next(&self.config, blocking_dispatch_available) { + while let Some(scheduled) = queue.pop_next_observed_global( + &self.config, + blocking_dispatch_available, + &self.global_capacity, + &mut scheduler_trace, + ready_backlog.len, + ) { if !graph.is_ready(scheduled.node_id) { - queue.release(&scheduled.resources); + queue.release_observed( + scheduled.node_id, + &scheduled.resources, + &self.config, + &mut scheduler_trace, + ); continue; } @@ -339,13 +420,23 @@ impl TaskPoolRunner { if super::verify::is_md5_verify_task(&scheduled[0].task) { let capacity = super::verify::md5_verify_batch_capacity(); while scheduled.len() < capacity { - let Some(next) = queue.pop_md5_verify_batch_member(&self.config) else { + let Some(next) = queue.pop_md5_verify_batch_member_observed_global( + &self.config, + &self.global_capacity, + &mut scheduler_trace, + ready_backlog.len, + ) else { break; }; if graph.is_ready(next.node_id) { scheduled.push(next); } else { - queue.release(&next.resources); + queue.release_observed( + next.node_id, + &next.resources, + &self.config, + &mut scheduler_trace, + ); } } } @@ -356,17 +447,19 @@ impl TaskPoolRunner { .collect::>(); let task_count = scheduled.len(); let attempt = if task_count > 1 { - self.dispatch_md5_verify_batch(scheduled, finish_tx.clone())? + self.dispatch_md5_verify_batch(scheduled, finish_tx.clone(), &event_tx)? } else { self.dispatch_scheduled( scheduled.pop().expect("single scheduled task missing"), finish_tx.clone(), + &event_tx, )? }; match attempt { DispatchAttempt::Submitted => { for node_id in node_ids { graph.mark_running(node_id)?; + scheduler_trace.started(node_id); } in_flight = in_flight.saturating_add(task_count); first_task_start.get_or_insert_with(|| run_started_at.elapsed()); @@ -374,7 +467,11 @@ impl TaskPoolRunner { } DispatchAttempt::BlockingPoolBusy(scheduled) => { for scheduled in scheduled.into_iter().rev() { - queue.restore_front(scheduled); + queue.restore_front_observed( + scheduled, + &self.config, + &mut scheduler_trace, + ); } blocking_pool_busy = true; blocking_dispatch_available = false; @@ -393,10 +490,16 @@ impl TaskPoolRunner { &mut ready_backlog, &mut volume_keys, ready_frontier_limit, + &mut scheduler_trace, ) > 0 { continue; } + if let Some(generation) = self.global_capacity.waiting_generation() { + self.global_capacity + .wait_for_change(generation, COORDINATOR_POLL_INTERVAL); + continue; + } if blocking_pool_busy { idle_blocking_dispatch_retries = idle_blocking_dispatch_retries.saturating_add(1); @@ -431,8 +534,10 @@ impl TaskPoolRunner { &mut queue, &metrics, &mut graph, - &self.event_tx, + &event_tx, &mut ready_backlog, + &self.config, + &mut scheduler_trace, )?; continue; } @@ -449,8 +554,10 @@ impl TaskPoolRunner { &mut queue, &metrics, &mut graph, - &self.event_tx, + &event_tx, &mut ready_backlog, + &self.config, + &mut scheduler_trace, )?; } Err(flume::RecvTimeoutError::Timeout) @@ -474,7 +581,7 @@ impl TaskPoolRunner { } } - while let Ok(event) = self.event_rx.try_recv() { + while let Ok(event) = event_rx.try_recv() { record_worker_event(&mut progress, &mut outcomes, event); } progress.finish(); @@ -487,6 +594,7 @@ impl TaskPoolRunner { metrics.ready_frontier_limit = ready_frontier_limit; metrics.ready_backlog_peak = ready_backlog.peak_len; (metrics.volume_cache_hits, metrics.volume_cache_misses) = volume_keys.stats(); + metrics.global_capacity = self.global_capacity.metrics(); debug!( finished_tasks = metrics.finished_tasks, graph_nodes = graph_summary.total_nodes, @@ -512,13 +620,18 @@ impl TaskPoolRunner { volume_count = metrics.volumes.len(), "task graph batch metrics" ); - Ok(TaskPoolResult { outcomes, metrics }) + Ok(TaskPoolResult { + outcomes, + metrics, + scheduler_trace: scheduler_trace.finish()?, + }) } fn dispatch_md5_verify_batch( &self, scheduled: Vec, finish_tx: flume::Sender, + event_tx: &flume::Sender, ) -> Result { debug_assert!(scheduled.len() >= 2); debug_assert!(scheduled @@ -528,7 +641,7 @@ impl TaskPoolRunner { let rejected_path = task_path(&scheduled[0].task); let job = Arc::new(Mutex::new(Some(scheduled))); let job_for_task = Arc::clone(&job); - let event_tx = self.event_tx.clone(); + let event_tx = event_tx.clone(); match self.dispatcher.dispatch_blocking(move || { let mut scheduled = job_for_task .lock() @@ -545,22 +658,27 @@ impl TaskPoolRunner { })) { Ok(runs) => runs, Err(_) => (0..scheduled.len()) - .map(|_| TaskRun::failed("MD5 verify batch panicked")) + .map(|_| super::verify::Md5VerifyBatchResult { + run: TaskRun::failed("MD5 verify batch panicked"), + storage_read_bytes: 0, + }) .collect(), }; let run_time = started_at.elapsed(); - for (scheduled, run) in scheduled.into_iter().zip(runs) { + for (scheduled, result) in scheduled.into_iter().zip(runs) { let path = task_path(&scheduled.task); let queue_wait = scheduled .started_at .saturating_duration_since(scheduled.enqueued_at); let _ = finish_tx.send(TaskFinish { + global_lease: scheduled.global_lease, node_id: scheduled.node_id, path, resources: scheduled.resources, queue_wait, run_time, - run, + observed_storage_read_bytes: Some(result.storage_read_bytes), + run: result.run, }); } }) { @@ -589,20 +707,35 @@ impl TaskPoolRunner { &self, scheduled: ScheduledTask, finish_tx: flume::Sender, + event_tx: &flume::Sender, ) -> Result { match scheduled.resources.run { RunClass::AsyncIo => { let rejected_path = task_path(&scheduled.task); - let event_tx = self.event_tx.clone(); + let event_tx = event_tx.clone(); let config = self.config.clone(); match self.dispatcher.dispatch(move || async move { let ScheduledTask { node_id, + #[cfg(feature = "hdiff-patch")] + mut task, + #[cfg(not(feature = "hdiff-patch"))] task, resources, enqueued_at, started_at, + global_lease, } = scheduled; + #[cfg(feature = "hdiff-patch")] + let global_lease = { + let mut lease = global_lease; + if let Task::DecodeHdiffPatchEntry { retained, .. } = &mut task { + if let Some(lease) = &mut lease { + lease.bind_hdiff_memory(retained); + } + } + lease + }; let path = task_path(&task); let queue_wait = started_at.saturating_duration_since(enqueued_at); let run = match AssertUnwindSafe(run_async_task( @@ -619,11 +752,13 @@ impl TaskPoolRunner { Err(_) => TaskRun::failed("task run panicked"), }; let _ = finish_tx.send(TaskFinish { + global_lease, node_id, path, resources, queue_wait, run_time: started_at.elapsed(), + observed_storage_read_bytes: None, run, }); }) { @@ -647,7 +782,7 @@ impl TaskPoolRunner { // task outside the closure so the coordinator can restore it. let job = Arc::new(Mutex::new(Some(scheduled))); let job_for_task = Arc::clone(&job); - let event_tx = self.event_tx.clone(); + let event_tx = event_tx.clone(); let config = self.config.clone(); match self.dispatcher.dispatch_blocking(move || { let scheduled = job_for_task @@ -661,9 +796,11 @@ impl TaskPoolRunner { resources, enqueued_at, started_at, + global_lease, } = scheduled; let path = task_path(&task); let queue_wait = started_at.saturating_duration_since(enqueued_at); + let mut observed_storage_read_bytes = None; let run = match catch_unwind(AssertUnwindSafe(|| { run_blocking_task( task, @@ -671,17 +808,20 @@ impl TaskPoolRunner { config.extraction_progress_buffer_bytes, config.extract_shards, &event_tx, + &mut observed_storage_read_bytes, ) })) { Ok(run) => run, Err(_) => TaskRun::failed("task run panicked"), }; let _ = finish_tx.send(TaskFinish { + global_lease, node_id, path, resources, queue_wait, run_time: started_at.elapsed(), + observed_storage_read_bytes, run, }); }) { @@ -769,6 +909,7 @@ fn refill_ready_frontier( volume_keys: &mut VolumeKeyCache, frontier_limit: usize, in_flight: usize, + scheduler_trace: &mut SchedulerTraceRecorder, ) -> usize { let routed = queue.queued_len().saturating_add(in_flight); route_ready_tasks( @@ -776,6 +917,7 @@ fn refill_ready_frontier( ready, volume_keys, frontier_limit.saturating_sub(routed), + scheduler_trace, ) } @@ -784,6 +926,7 @@ fn route_ready_tasks( ready: &mut ReadyBacklog, volume_keys: &mut VolumeKeyCache, max_tasks: usize, + scheduler_trace: &mut SchedulerTraceRecorder, ) -> usize { let mut routed = 0usize; while routed < max_tasks { @@ -791,11 +934,12 @@ fn route_ready_tasks( break; }; let resources = task_resources_cached(&ready.task, volume_keys); - let priority = if ready.continuation { + let priority = if ready.dag_hint.uses_continuation_lane() { TaskPriority::Continuation } else { TaskPriority::Bulk }; + scheduler_trace.routed(ready.id, priority, &resources); queue.push(ready.id, ready.task, resources, priority); routed = routed.saturating_add(1); } @@ -818,6 +962,36 @@ mod frontier_tests { } } + #[test] + fn typed_dag_hints_preserve_ready_backlog_lane_order() { + use crate::task_pool::graph::{DagHint, ReadyTask, TaskOrigin}; + use crate::task_pool::NodeId; + + let temp = tempfile::tempdir().unwrap(); + let mut backlog = ReadyBacklog::default(); + backlog.extend(vec![ + ReadyTask { + id: NodeId::from_index(0), + task: verify_task(temp.path().join("bulk.bin")), + dag_hint: DagHint::new(TaskOrigin::Root, 0), + }, + ReadyTask { + id: NodeId::from_index(1), + task: verify_task(temp.path().join("dynamic.bin")), + dag_hint: DagHint::new(TaskOrigin::DynamicExpansion, 1), + }, + ReadyTask { + id: NodeId::from_index(2), + task: verify_task(temp.path().join("continuation.bin")), + dag_hint: DagHint::new(TaskOrigin::Continuation, 0), + }, + ]); + + assert_eq!(backlog.pop().unwrap().id, NodeId::from_index(1)); + assert_eq!(backlog.pop().unwrap().id, NodeId::from_index(2)); + assert_eq!(backlog.pop().unwrap().id, NodeId::from_index(0)); + } + #[test] fn ready_frontier_routes_only_the_requested_window() { let temp = tempfile::tempdir().unwrap(); @@ -830,7 +1004,8 @@ mod frontier_tests { let mut queue = SchedulerQueue::default(); let mut volumes = VolumeKeyCache::default(); - let routed = route_ready_tasks(&mut queue, &mut backlog, &mut volumes, 256); + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + let routed = route_ready_tasks(&mut queue, &mut backlog, &mut volumes, 256, &mut trace); assert_eq!(routed, 256); assert_eq!(queue.queued_len(), 256); @@ -843,8 +1018,12 @@ mod frontier_tests { let mut backlog = ReadyBacklog::default(); let mut graph = TaskGraph::from_tasks(vec![ verify_task(PathBuf::from("cpu.bin")), - Task::ApplyExtractedVfsPatchManifest { - install_root: PathBuf::from("blocking"), + Task::VerifyMetadata { + path: PathBuf::from("blocking"), + logical_path: "blocking".to_string(), + expected_hash: crate::ContentHash::md5("00000000000000000000000000000000").unwrap(), + expected_size: 0, + on_fail: None, }, Task::ApplyDeleteManifest { install_root: PathBuf::from("async"), @@ -855,6 +1034,12 @@ mod frontier_tests { assert_eq!(run_class(&backlog.pop().unwrap().task), RunClass::AsyncIo); assert_eq!(run_class(&backlog.pop().unwrap().task), RunClass::Cpu); assert_eq!(run_class(&backlog.pop().unwrap().task), RunClass::Blocking); + assert_eq!( + run_class(&Task::ApplyExtractedVfsPatchManifest { + install_root: PathBuf::from("patch-root"), + }), + RunClass::Cpu + ); } } @@ -913,3 +1098,533 @@ mod admission_config_tests { assert!(error.contains("reserved compio fallback lanes")); } } + +#[cfg(test)] +mod observatory_tests { + use super::*; + use crate::task_pool::graph::GraphExpansion; + use crate::task_pool::{ + ResourceOccupancyAction, SchedulerCompletion, SchedulerTrace, SchedulerTraceEventKind, + TaskGraphBuilder, + }; + use std::path::PathBuf; + + fn delete_manifest_task(path: PathBuf) -> Task { + Task::ApplyDeleteManifest { install_root: path } + } + + fn blocking_task(path: PathBuf) -> Task { + Task::VerifyMetadata { + path, + logical_path: "blocking".to_string(), + expected_hash: crate::ContentHash::md5("00000000000000000000000000000000").unwrap(), + expected_size: 0, + on_fail: None, + } + } + + fn traced_config() -> TaskPoolConfig { + TaskPoolConfig::default().with_scheduler_trace(true) + } + + fn prepare_paths(temp: &tempfile::TempDir, count: usize) -> Vec { + (0..count) + .map(|index| { + let path = temp.path().join(format!("node-{index}")); + std::fs::create_dir_all(&path).unwrap(); + path + }) + .collect() + } + + fn event_position( + trace: &SchedulerTrace, + predicate: impl Fn(&SchedulerTraceEventKind) -> bool, + ) -> usize { + trace + .events + .iter() + .position(|event| predicate(&event.kind)) + .expect("expected trace event") + } + + fn assert_dependency_finishes_before_ready( + trace: &SchedulerTrace, + dependency: usize, + dependent: usize, + ) { + let finished = event_position( + trace, + |kind| matches!(kind, SchedulerTraceEventKind::Finished { node_id, .. } if *node_id == dependency), + ); + let ready = event_position( + trace, + |kind| matches!(kind, SchedulerTraceEventKind::Ready { node_id, .. } if *node_id == dependent), + ); + assert!(finished < ready); + } + + #[test] + fn traced_chain_records_lifecycle_and_resource_occupancy() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 3); + + let mut builder = TaskGraphBuilder::new(); + let first = builder.add_root(delete_manifest_task(paths[0].clone())); + let second = builder + .add_task(delete_manifest_task(paths[1].clone()), [first]) + .unwrap(); + builder + .add_task(delete_manifest_task(paths[2].clone()), [second]) + .unwrap(); + + let result = run_task_graph(builder.build(), traced_config()).unwrap(); + assert_eq!(result.metrics.graph.succeeded_nodes, 3); + let trace = result.scheduler_trace.expect("trace enabled"); + + for node_id in 0..3 { + let mut created = false; + let mut ready = false; + let mut routed = false; + let mut admitted = false; + let mut started = false; + let mut finished = false; + for event in &trace.events { + match &event.kind { + SchedulerTraceEventKind::Created { node_id: id } if *id == node_id => { + created = true; + } + SchedulerTraceEventKind::Ready { node_id: id, .. } if *id == node_id => { + assert!(created); + ready = true; + } + SchedulerTraceEventKind::Routed { + node_id: id, + demand, + .. + } if *id == node_id => { + assert!(ready); + assert_eq!(demand.network_class, None); + assert_eq!(demand.metadata_volumes.len(), 1); + assert_eq!(demand.mutation_paths.len(), 1); + routed = true; + } + SchedulerTraceEventKind::Admitted { node_id: id, .. } if *id == node_id => { + assert!(routed); + admitted = true; + } + SchedulerTraceEventKind::Started { node_id: id } if *id == node_id => { + assert!(admitted); + started = true; + } + SchedulerTraceEventKind::Finished { node_id: id, .. } if *id == node_id => { + assert!(started); + finished = true; + } + _ => {} + } + } + assert!(created && ready && routed && admitted && started && finished); + } + + assert_dependency_finishes_before_ready(&trace, 0, 1); + assert_dependency_finishes_before_ready(&trace, 1, 2); + assert!(trace.events.iter().any(|event| matches!( + &event.kind, + SchedulerTraceEventKind::Occupancy { + action: ResourceOccupancyAction::Acquire, + occupancy, + .. + } if occupancy.mutation_paths_used >= 1 + && occupancy.volumes.iter().any(|volume| volume.metadata_used >= 1) + ))); + let final_release = trace + .events + .iter() + .rev() + .find_map(|event| match &event.kind { + SchedulerTraceEventKind::Occupancy { + action: ResourceOccupancyAction::Release, + occupancy, + .. + } => Some(occupancy), + _ => None, + }); + let final_release = final_release.expect("finished task must release resources"); + assert_eq!(final_release.cpu_used, 0); + assert_eq!(final_release.network_used, 0); + assert_eq!(final_release.blocking_used, 0); + assert_eq!(final_release.extract_used, 0); + assert_eq!(final_release.mutation_paths_used, 0); + assert!(final_release.storage_reserved_bytes.is_empty()); + assert!(final_release.volumes.is_empty()); + } + + #[test] + fn m5_capture_path_keeps_existing_run_and_uses_unique_sibling() { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().join("capture.ndjson"); + std::fs::write(&base, "existing").unwrap(); + let sibling = observatory::unique_capture_path(&base, 42); + assert_eq!(sibling, temp.path().join("capture.run-42.ndjson")); + assert_eq!(std::fs::read_to_string(base).unwrap(), "existing"); + } + + #[test] + fn m5_streaming_capture_round_trips_through_validate_compact_and_replay() { + use crate::task_pool::{ + replay_workload, validate_workload_trace, CompactWorkload, ReplayPolicy, + WorkloadCaptureConfig, WorkloadTrace, + }; + + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 3); + let trace_path = temp.path().join("synthetic-chain.ndjson"); + + let mut builder = TaskGraphBuilder::new(); + let first = builder.add_root(delete_manifest_task(paths[0].clone())); + let second = builder + .add_task(delete_manifest_task(paths[1].clone()), [first]) + .unwrap(); + builder + .add_task(delete_manifest_task(paths[2].clone()), [second]) + .unwrap(); + + let config = TaskPoolConfig { + workload_capture: Some( + WorkloadCaptureConfig::streaming_strict(&trace_path, "synthetic-source-tree") + .with_workload_kind("synthetic-chain"), + ), + ..TaskPoolConfig::default() + }; + let result = run_task_graph(builder.build(), config).unwrap(); + assert!( + result.scheduler_trace.is_none(), + "M5 capture must not enable the M1 Vec trace" + ); + + let trace = WorkloadTrace::from_path(&trace_path).unwrap(); + let report = validate_workload_trace(&trace).unwrap(); + assert!(report.replay_authority); + let compact = CompactWorkload::from_trace(&trace).unwrap(); + assert_eq!(compact.nodes.len(), 3); + let first = replay_workload(&compact, ReplayPolicy::CurrentProduction).unwrap(); + let second = replay_workload(&compact, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(first.summary, second.summary); + assert_eq!(first.summary.completed_work_units, 3); + + let raw = std::fs::read_to_string(&trace_path).unwrap(); + assert!(!raw.contains(temp.path().to_string_lossy().as_ref())); + assert!(raw.contains("path#")); + assert!(raw.contains("\"record\":\"footer\"")); + } + + #[test] + fn synthetic_long_chain_preserves_dependency_order() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 5); + let mut builder = TaskGraphBuilder::new(); + let mut previous = builder.add_root(delete_manifest_task(paths[0].clone())); + for path in paths.iter().skip(1) { + previous = builder + .add_task(delete_manifest_task(path.clone()), [previous]) + .unwrap(); + } + + let result = run_task_graph(builder.build(), traced_config()).unwrap(); + let trace = result.scheduler_trace.unwrap(); + assert_eq!(trace.aggregate().finished, 5); + for node in 1..5 { + assert_dependency_finishes_before_ready(&trace, node - 1, node); + } + } + + #[test] + fn synthetic_wide_fan_out_records_frontier() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 5); + let mut builder = TaskGraphBuilder::new(); + let root = builder.add_root(delete_manifest_task(paths[0].clone())); + for path in paths.iter().skip(1) { + builder + .add_task(delete_manifest_task(path.clone()), [root]) + .unwrap(); + } + + let result = run_task_graph(builder.build(), traced_config()).unwrap(); + let trace = result.scheduler_trace.unwrap(); + let aggregate = trace.aggregate(); + assert_eq!(aggregate.created, 5); + assert_eq!(aggregate.finished, 5); + for child in 1..5 { + assert_dependency_finishes_before_ready(&trace, 0, child); + } + assert!(aggregate.max_ready_frontier_len >= 4); + } + + #[test] + fn synthetic_diamond_waits_for_both_parents() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 4); + let mut builder = TaskGraphBuilder::new(); + let a = builder.add_root(delete_manifest_task(paths[0].clone())); + let b = builder + .add_task(delete_manifest_task(paths[1].clone()), [a]) + .unwrap(); + let c = builder + .add_task(delete_manifest_task(paths[2].clone()), [a]) + .unwrap(); + builder + .add_task(delete_manifest_task(paths[3].clone()), [b, c]) + .unwrap(); + + let result = run_task_graph(builder.build(), traced_config()).unwrap(); + let trace = result.scheduler_trace.unwrap(); + assert_dependency_finishes_before_ready(&trace, 0, 1); + assert_dependency_finishes_before_ready(&trace, 0, 2); + assert_dependency_finishes_before_ready(&trace, 1, 3); + assert_dependency_finishes_before_ready(&trace, 2, 3); + } + + #[test] + fn synthetic_critical_chain_plus_bulk_is_measurement_only_baseline() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 104); + let mut builder = TaskGraphBuilder::new(); + let a = builder.add_root(delete_manifest_task(paths[0].clone())); + let b = builder + .add_task(delete_manifest_task(paths[1].clone()), [a]) + .unwrap(); + let c = builder + .add_task(delete_manifest_task(paths[2].clone()), [b]) + .unwrap(); + builder + .add_task(delete_manifest_task(paths[3].clone()), [c]) + .unwrap(); + for path in paths.iter().skip(4) { + builder.add_root(delete_manifest_task(path.clone())); + } + + let result = run_task_graph(builder.build(), traced_config()).unwrap(); + let trace = result.scheduler_trace.unwrap(); + let aggregate = trace.aggregate(); + assert_eq!(aggregate.created, 104); + assert_eq!(aggregate.finished, 104); + assert!(aggregate.max_ready_frontier_len >= 101); + assert_eq!(aggregate.decisions, 104); + assert_eq!( + aggregate.selected_candidate_indices.values().sum::(), + aggregate.decisions + ); + assert_dependency_finishes_before_ready(&trace, 0, 1); + assert_dependency_finishes_before_ready(&trace, 1, 2); + assert_dependency_finishes_before_ready(&trace, 2, 3); + } + + #[test] + fn synthetic_dynamic_expansion_traces_inserted_nodes_without_unlocking_child_early() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 5); + let config = traced_config(); + let mut graph = TaskGraph::from_tasks(vec![delete_manifest_task(paths[0].clone())]); + let started_at = Instant::now(); + let mut trace = SchedulerTraceRecorder::new(true, started_at); + trace.created_range(0, graph.node_count()); + let initial_ready = graph.start(); + trace.ready_tasks(&initial_ready); + let mut backlog = ReadyBacklog::default(); + backlog.extend(initial_ready); + let mut queue = SchedulerQueue::default(); + let mut volumes = VolumeKeyCache::default(); + assert_eq!( + route_ready_tasks(&mut queue, &mut backlog, &mut volumes, 1, &mut trace), + 1 + ); + let scheduled = queue + .pop_next_observed(&config, true, &mut trace, backlog.len) + .unwrap(); + graph.mark_running(scheduled.node_id).unwrap(); + trace.started(scheduled.node_id); + + let mut expansion = GraphExpansion::new(); + let b = expansion.add_root(delete_manifest_task(paths[1].clone())); + expansion + .add_task(delete_manifest_task(paths[2].clone()), [b]) + .unwrap(); + expansion.add_root(delete_manifest_task(paths[3].clone())); + expansion.add_root(delete_manifest_task(paths[4].clone())); + + let (event_tx, _event_rx) = flume::unbounded(); + let metrics = SchedulerMetrics::default(); + let mut in_flight = 1; + complete_task( + TaskFinish { + global_lease: scheduled.global_lease, + node_id: scheduled.node_id, + path: paths[0].display().to_string(), + resources: scheduled.resources, + queue_wait: Duration::ZERO, + run_time: Duration::from_nanos(1), + observed_storage_read_bytes: None, + run: TaskRun::expand(expansion), + }, + &mut in_flight, + &mut queue, + &metrics, + &mut graph, + &event_tx, + &mut backlog, + &config, + &mut trace, + ) + .unwrap(); + + assert_eq!(graph.node_count(), 5); + assert_eq!(in_flight, 0); + assert_eq!( + backlog.len, 3, + "B and two bulk roots become ready; C waits for B" + ); + assert_eq!( + route_ready_tasks(&mut queue, &mut backlog, &mut volumes, 8, &mut trace), + 3 + ); + let trace = trace.finish().unwrap().unwrap(); + let aggregate = trace.aggregate(); + assert_eq!(aggregate.created, 5); + assert_eq!(aggregate.ready, 4); + assert_eq!(aggregate.routed, 4); + assert!(trace.events.iter().any(|event| matches!( + event.kind, + SchedulerTraceEventKind::Finished { + node_id: 0, + completion: SchedulerCompletion::Expanded, + .. + } + ))); + assert!(!trace.events.iter().any(|event| matches!( + event.kind, + SchedulerTraceEventKind::Ready { node_id: 2, .. } + ))); + } + + #[test] + fn tracing_preserves_failed_descendant_cancellation() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 2); + let config = traced_config(); + let mut builder = TaskGraphBuilder::new(); + let root = builder.add_root(blocking_task(paths[0].clone())); + builder + .add_task(delete_manifest_task(paths[1].clone()), [root]) + .unwrap(); + let mut graph = builder.build(); + let mut trace = SchedulerTraceRecorder::new(true, Instant::now()); + trace.created_range(0, graph.node_count()); + let ready = graph.start(); + trace.ready_tasks(&ready); + let mut backlog = ReadyBacklog::default(); + backlog.extend(ready); + let mut queue = SchedulerQueue::default(); + let mut volumes = VolumeKeyCache::default(); + route_ready_tasks(&mut queue, &mut backlog, &mut volumes, 1, &mut trace); + let authority = global_capacity::GlobalCapacityAuthority::new(&config); + let runner = authority.register(); + let scheduled = queue + .pop_next_observed_global(&config, true, &runner, &mut trace, backlog.len) + .unwrap(); + assert_eq!(authority.snapshot().0.blocking, 1); + graph.mark_running(scheduled.node_id).unwrap(); + trace.started(scheduled.node_id); + + let (event_tx, _event_rx) = flume::unbounded(); + let mut in_flight = 1; + complete_task( + TaskFinish { + global_lease: scheduled.global_lease, + node_id: scheduled.node_id, + path: paths[0].display().to_string(), + resources: scheduled.resources, + queue_wait: Duration::ZERO, + run_time: Duration::from_nanos(1), + observed_storage_read_bytes: None, + run: TaskRun::failed("synthetic failure"), + }, + &mut in_flight, + &mut queue, + &SchedulerMetrics::default(), + &mut graph, + &event_tx, + &mut backlog, + &config, + &mut trace, + ) + .unwrap(); + assert_eq!(authority.snapshot().0.blocking, 0); + + let summary = graph.summary(); + assert_eq!(summary.failed_nodes, 1); + assert_eq!(summary.cancelled_nodes, 1); + assert!(backlog.is_empty()); + let trace = trace.finish().unwrap().unwrap(); + assert!(!trace.events.iter().any(|event| matches!( + event.kind, + SchedulerTraceEventKind::Ready { node_id: 1, .. } + | SchedulerTraceEventKind::Started { node_id: 1 } + ))); + } + #[test] + fn global_capacity_releases_before_graph_finish_error() { + let temp = tempfile::tempdir().unwrap(); + let paths = prepare_paths(&temp, 2); + let config = traced_config(); + let mut graph = TaskGraph::from_tasks(vec![blocking_task(paths[0].clone())]); + let mut trace = SchedulerTraceRecorder::new(true, Instant::now()); + trace.created_range(0, graph.node_count()); + let ready = graph.start(); + trace.ready_tasks(&ready); + let mut backlog = ReadyBacklog::default(); + backlog.extend(ready); + let mut queue = SchedulerQueue::default(); + let mut volumes = VolumeKeyCache::default(); + route_ready_tasks(&mut queue, &mut backlog, &mut volumes, 1, &mut trace); + let authority = global_capacity::GlobalCapacityAuthority::new(&config); + let runner = authority.register(); + let scheduled = queue + .pop_next_observed_global(&config, true, &runner, &mut trace, backlog.len) + .unwrap(); + assert_eq!(authority.snapshot().0.blocking, 1); + + // Deliberately leave the node in Ready instead of Running. complete_task + // releases local and global admission before graph.finish(), so even a + // graph/dynamic-completion error cannot leak command-wide capacity. + let mut expansion = GraphExpansion::new(); + expansion.add_root(delete_manifest_task(paths[1].clone())); + let (event_tx, _event_rx) = flume::unbounded(); + let mut in_flight = 1; + let error = complete_task( + TaskFinish { + global_lease: scheduled.global_lease, + node_id: scheduled.node_id, + path: paths[0].display().to_string(), + resources: scheduled.resources, + queue_wait: Duration::ZERO, + run_time: Duration::from_nanos(1), + observed_storage_read_bytes: None, + run: TaskRun::expand(expansion), + }, + &mut in_flight, + &mut queue, + &SchedulerMetrics::default(), + &mut graph, + &event_tx, + &mut backlog, + &config, + &mut trace, + ) + .unwrap_err(); + assert!(!error.to_string().is_empty()); + assert_eq!(authority.snapshot().0.blocking, 0); + assert_eq!(in_flight, 0); + } +} diff --git a/crates/griffr-runtime/src/task_pool/scheduler/global_capacity.rs b/crates/griffr-runtime/src/task_pool/scheduler/global_capacity.rs new file mode 100644 index 0000000..3c5553b --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/scheduler/global_capacity.rs @@ -0,0 +1,976 @@ +use std::collections::{BTreeMap, VecDeque}; +use std::sync::atomic::{AtomicU64, Ordering}; +#[cfg(test)] +use std::sync::TryLockError; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use super::routing::{ResourceRequest, RunClass}; +use crate::task_pool::{AdmissionBlockReason, GlobalCapacityMetrics, TaskPoolConfig}; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(super) struct SharedCapacity { + pub(super) cpu: usize, + pub(super) blocking: usize, + pub(super) network: usize, + pub(super) extract: usize, + pub(super) reuse_probe: usize, +} + +impl SharedCapacity { + fn from_limits(config: &TaskPoolConfig) -> Self { + Self { + cpu: config.cpu_slots, + blocking: config.blocking_slots, + network: config.network_slots, + extract: config.extract_slots, + reuse_probe: config.reuse_queue_limit.max(1), + } + } + + fn from_request(request: &ResourceRequest) -> Self { + Self { + cpu: usize::from(request.uses_cpu()), + blocking: usize::from(request.run == RunClass::Blocking), + network: usize::from(request.network.is_some()), + extract: usize::from(request.extract), + reuse_probe: usize::from(request.reuse_probe), + } + } + + fn overlaps(self, other: Self) -> bool { + (self.cpu > 0 && other.cpu > 0) + || (self.blocking > 0 && other.blocking > 0) + || (self.network > 0 && other.network > 0) + || (self.extract > 0 && other.extract > 0) + || (self.reuse_probe > 0 && other.reuse_probe > 0) + } + + fn add(&mut self, demand: Self) { + self.cpu = self.cpu.saturating_add(demand.cpu); + self.blocking = self.blocking.saturating_add(demand.blocking); + self.network = self.network.saturating_add(demand.network); + self.extract = self.extract.saturating_add(demand.extract); + self.reuse_probe = self.reuse_probe.saturating_add(demand.reuse_probe); + } + + fn subtract(&mut self, demand: Self) { + debug_assert!(self.cpu >= demand.cpu); + debug_assert!(self.blocking >= demand.blocking); + debug_assert!(self.network >= demand.network); + debug_assert!(self.extract >= demand.extract); + debug_assert!(self.reuse_probe >= demand.reuse_probe); + self.cpu = self.cpu.saturating_sub(demand.cpu); + self.blocking = self.blocking.saturating_sub(demand.blocking); + self.network = self.network.saturating_sub(demand.network); + self.extract = self.extract.saturating_sub(demand.extract); + self.reuse_probe = self.reuse_probe.saturating_sub(demand.reuse_probe); + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct AdmissionDemand { + execution: SharedCapacity, + starts_hdiff: bool, +} + +impl AdmissionDemand { + fn from_request(request: &ResourceRequest) -> Self { + Self { + execution: SharedCapacity::from_request(request), + starts_hdiff: request.hdiff_decoder_start, + } + } + + fn overlaps(self, other: Self) -> bool { + (self.starts_hdiff && other.starts_hdiff) || self.execution.overlaps(other.execution) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Waiter { + runner_id: u64, + demand: AdmissionDemand, + seen_probe: u64, +} + +#[derive(Debug, Default)] +struct RunnerState { + usage: SharedCapacity, + peak: SharedCapacity, + probe: u64, + borrow_events: u64, + admission_denials: u64, +} + +#[derive(Debug, Default)] +struct GlobalCapacityState { + used: SharedCapacity, + hdiff_decoders: usize, + peak: SharedCapacity, + runners: BTreeMap, + waiters: VecDeque, + generation: u64, + borrow_events: u64, + admission_denials: u64, +} + +#[derive(Debug)] +pub(crate) struct GlobalCapacityAuthority { + limit: SharedCapacity, + hdiff_decoder_limit: usize, + state: Mutex, + next_runner_id: AtomicU64, + #[cfg(test)] + contention_events: AtomicU64, +} + +impl GlobalCapacityAuthority { + pub(super) fn new(config: &TaskPoolConfig) -> Arc { + Self::with_decoder_limit(config, config.cpu_slots.clamp(1, 2)) + } + + pub(super) fn with_decoder_limit( + config: &TaskPoolConfig, + hdiff_decoder_limit: usize, + ) -> Arc { + Arc::new(Self { + limit: SharedCapacity::from_limits(config), + hdiff_decoder_limit, + state: Mutex::new(GlobalCapacityState::default()), + next_runner_id: AtomicU64::new(1), + #[cfg(test)] + contention_events: AtomicU64::new(0), + }) + } + + pub(super) fn register(self: &Arc) -> GlobalCapacityRunner { + let runner_id = self.next_runner_id.fetch_add(1, Ordering::Relaxed); + let mut state = self.lock_state(); + state.runners.entry(runner_id).or_default(); + drop(state); + GlobalCapacityRunner { + authority: Arc::clone(self), + runner_id, + } + } + + fn lock_state(&self) -> MutexGuard<'_, GlobalCapacityState> { + #[cfg(test)] + match self.state.try_lock() { + Ok(state) => return state, + Err(TryLockError::Poisoned(poisoned)) => return poisoned.into_inner(), + Err(TryLockError::WouldBlock) => { + self.contention_events.fetch_add(1, Ordering::Relaxed); + } + } + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn release(&self, runner_id: u64, demand: SharedCapacity) { + let mut state = self.lock_state(); + state.used.subtract(demand); + if let Some(runner) = state.runners.get_mut(&runner_id) { + runner.usage.subtract(demand); + } + state.generation = state.generation.wrapping_add(1); + drop(state); + } + + #[cfg(test)] + pub(super) fn snapshot(&self) -> (SharedCapacity, SharedCapacity) { + let state = self.lock_state(); + (state.used, state.peak) + } + + #[cfg(test)] + fn contention_count(&self) -> u64 { + self.contention_events.load(Ordering::Relaxed) + } +} + +#[derive(Debug)] +pub(crate) struct GlobalCapacityRunner { + authority: Arc, + runner_id: u64, +} + +impl GlobalCapacityRunner { + pub(super) fn with_admission(&self, f: impl FnOnce(&mut GlobalAdmission<'_>) -> T) -> T { + let mut state = self.authority.lock_state(); + let probe = { + let runner = state.runners.entry(self.runner_id).or_default(); + runner.probe = runner.probe.wrapping_add(1).max(1); + runner.probe + }; + let mut admission = GlobalAdmission { + authority: Arc::clone(&self.authority), + runner_id: self.runner_id, + probe, + state: &mut state, + }; + let result = f(&mut admission); + admission.finish_probe(); + result + } + + pub(crate) fn id(&self) -> u64 { + self.runner_id + } + + pub(super) fn hdiff_decoder_limit(&self) -> usize { + self.authority.hdiff_decoder_limit + } + + pub(crate) fn metrics(&self) -> GlobalCapacityMetrics { + let state = self.authority.lock_state(); + let runner = state.runners.get(&self.runner_id); + let runner_peak = runner.map_or(SharedCapacity::default(), |runner| runner.peak); + GlobalCapacityMetrics { + runner_id: self.runner_id, + cpu_capacity: self.authority.limit.cpu, + blocking_capacity: self.authority.limit.blocking, + network_capacity: self.authority.limit.network, + extract_capacity: self.authority.limit.extract, + reuse_probe_capacity: self.authority.limit.reuse_probe, + global_cpu_peak: state.peak.cpu, + global_blocking_peak: state.peak.blocking, + global_network_peak: state.peak.network, + global_extract_peak: state.peak.extract, + global_reuse_probe_peak: state.peak.reuse_probe, + runner_cpu_peak: runner_peak.cpu, + runner_blocking_peak: runner_peak.blocking, + runner_network_peak: runner_peak.network, + runner_extract_peak: runner_peak.extract, + runner_reuse_probe_peak: runner_peak.reuse_probe, + global_borrow_events: state.borrow_events, + global_admission_denials: state.admission_denials, + borrow_events: runner.map_or(0, |runner| runner.borrow_events), + admission_denials: runner.map_or(0, |runner| runner.admission_denials), + } + } + + pub(super) fn waiting_generation(&self) -> Option { + let state = self.authority.lock_state(); + state + .waiters + .iter() + .any(|waiter| waiter.runner_id == self.runner_id) + .then_some(state.generation) + } + + pub(super) fn clear_waiters_on_run_exit(&self) -> RunWaiters<'_> { + RunWaiters(self) + } + + pub(super) fn wait_for_change(&self, generation: u64, timeout: Duration) { + let state = self.authority.lock_state(); + if state.generation != generation { + return; + } + drop(state); + std::thread::sleep(timeout); + } +} + +/// Claims belong to an active scheduling pass. An early graph exit may +/// leave the runner registered for later batches. +pub(super) struct RunWaiters<'a>(&'a GlobalCapacityRunner); + +impl Drop for RunWaiters<'_> { + fn drop(&mut self) { + let mut state = self.0.authority.lock_state(); + let previous = state.waiters.len(); + state + .waiters + .retain(|waiter| waiter.runner_id != self.0.runner_id); + if state.waiters.len() != previous { + state.generation = state.generation.wrapping_add(1); + } + } +} + +impl Drop for GlobalCapacityRunner { + fn drop(&mut self) { + let mut state = self.authority.lock_state(); + state + .waiters + .retain(|waiter| waiter.runner_id != self.runner_id); + // A worker may still own execution capacity after a coordinator + // exits on a dispatch error. Its lease releases global usage on drop. + state.runners.remove(&self.runner_id); + state.generation = state.generation.wrapping_add(1); + drop(state); + } +} + +pub(super) struct GlobalAdmission<'a> { + authority: Arc, + runner_id: u64, + probe: u64, + state: &'a mut GlobalCapacityState, +} + +impl GlobalAdmission<'_> { + pub(super) fn allows(&mut self, request: &ResourceRequest) -> bool { + self.check(request, |_| {}) + } + + pub(super) fn explain_block(&mut self, request: &ResourceRequest) -> Vec { + let mut reasons = Vec::new(); + self.check(request, |reason| reasons.push(reason)); + reasons + } + + fn check( + &mut self, + request: &ResourceRequest, + mut on_block: impl FnMut(AdmissionBlockReason), + ) -> bool { + let demand = AdmissionDemand::from_request(request); + if demand == AdmissionDemand::default() { + return true; + } + + let mut blocks = self.capacity_blocks(demand).peekable(); + if blocks.peek().is_some() { + blocks.for_each(on_block); + } else if !self.has_fair_turn(demand) { + on_block(AdmissionBlockReason::GlobalFairness); + } else { + return true; + } + self.record_waiter(demand); + false + } + + fn capacity_blocks( + &self, + demand: AdmissionDemand, + ) -> impl Iterator + use<> { + use AdmissionBlockReason::*; + let used = self.state.used; + let limit = self.authority.limit; + let execution = demand.execution; + [ + ( + demand.starts_hdiff + && self.state.hdiff_decoders >= self.authority.hdiff_decoder_limit, + HdiffDecoderMemory, + ), + ( + used.cpu.saturating_add(execution.cpu) > limit.cpu, + GlobalCpu, + ), + ( + used.blocking.saturating_add(execution.blocking) > limit.blocking, + GlobalBlocking, + ), + ( + used.network.saturating_add(execution.network) > limit.network, + GlobalNetwork, + ), + ( + used.extract.saturating_add(execution.extract) > limit.extract, + GlobalExtract, + ), + ( + used.reuse_probe.saturating_add(execution.reuse_probe) > limit.reuse_probe, + GlobalReuseQueue, + ), + ] + .into_iter() + .filter_map(|(blocked, reason)| blocked.then_some(reason)) + } + + fn record_waiter(&mut self, demand: AdmissionDemand) { + self.state.admission_denials = self.state.admission_denials.saturating_add(1); + if let Some(runner) = self.state.runners.get_mut(&self.runner_id) { + runner.admission_denials = runner.admission_denials.saturating_add(1); + } + if let Some(waiter) = self + .state + .waiters + .iter_mut() + .find(|waiter| waiter.runner_id == self.runner_id && waiter.demand == demand) + { + waiter.seen_probe = self.probe; + } else { + self.state.waiters.push_back(Waiter { + runner_id: self.runner_id, + demand, + seen_probe: self.probe, + }); + } + } + + pub(super) fn acquire(&mut self, request: &ResourceRequest) -> GlobalCapacityLease { + let bundle = AdmissionDemand::from_request(request); + debug_assert!(self.capacity_blocks(bundle).next().is_none()); + debug_assert!(self.has_fair_turn(bundle)); + let demand = bundle.execution; + + let runner_count = self.state.runners.len().max(1); + let runner_usage = self + .state + .runners + .get(&self.runner_id) + .map_or(SharedCapacity::default(), |runner| runner.usage); + let was_borrowed = borrowed(demand, runner_usage, self.authority.limit, runner_count); + + self.state.used.add(demand); + self.state.peak.cpu = self.state.peak.cpu.max(self.state.used.cpu); + self.state.peak.blocking = self.state.peak.blocking.max(self.state.used.blocking); + self.state.peak.network = self.state.peak.network.max(self.state.used.network); + self.state.peak.extract = self.state.peak.extract.max(self.state.used.extract); + self.state.peak.reuse_probe = self.state.peak.reuse_probe.max(self.state.used.reuse_probe); + let runner = self.state.runners.entry(self.runner_id).or_default(); + runner.usage.add(demand); + runner.peak.cpu = runner.peak.cpu.max(runner.usage.cpu); + runner.peak.blocking = runner.peak.blocking.max(runner.usage.blocking); + runner.peak.network = runner.peak.network.max(runner.usage.network); + runner.peak.extract = runner.peak.extract.max(runner.usage.extract); + runner.peak.reuse_probe = runner.peak.reuse_probe.max(runner.usage.reuse_probe); + if was_borrowed { + self.state.borrow_events = self.state.borrow_events.saturating_add(1); + runner.borrow_events = runner.borrow_events.saturating_add(1); + } + self.state + .waiters + .retain(|waiter| !(waiter.runner_id == self.runner_id && waiter.demand == bundle)); + + let hdiff_memory = bundle.starts_hdiff.then(|| { + self.state.hdiff_decoders += 1; + HdiffMemoryLease { + _owner: Arc::new(HdiffMemoryLeaseInner(Arc::clone(&self.authority))), + } + }); + GlobalCapacityLease { + hdiff_memory, + authority: Arc::clone(&self.authority), + runner_id: self.runner_id, + demand, + } + } + + fn has_fair_turn(&self, demand: AdmissionDemand) -> bool { + for waiter in &self.state.waiters { + if !waiter.demand.overlaps(demand) { + continue; + } + if self.capacity_blocks(waiter.demand).next().is_some() { + continue; + } + return waiter.runner_id == self.runner_id; + } + true + } + + fn finish_probe(&mut self) { + self.state + .waiters + .retain(|waiter| waiter.runner_id != self.runner_id || waiter.seen_probe == self.probe); + } +} + +#[derive(Debug)] +pub(super) struct GlobalCapacityLease { + hdiff_memory: Option, + authority: Arc, + runner_id: u64, + demand: SharedCapacity, +} + +impl GlobalCapacityLease { + /// Keep the slot alive through coordinator completion. The worker may + /// free its decoder before its finish reaches the coordinator, which + /// must record the release before admitting another decoder in this run. + #[cfg(feature = "hdiff-patch")] + pub(super) fn bind_hdiff_memory(&mut self, retained: &mut Option) { + if let Some(memory) = &self.hdiff_memory { + debug_assert!(retained.is_none()); + *retained = Some(memory.clone()); + } else { + debug_assert!(retained.is_some()); + self.hdiff_memory = retained.clone(); + } + } + + #[cfg(all(test, feature = "hdiff-patch"))] + pub(super) fn take_hdiff_memory(&mut self) -> Option { + self.hdiff_memory.take() + } +} + +#[doc(hidden)] +#[derive(Clone, Debug)] +pub struct HdiffMemoryLease { + _owner: Arc, +} + +#[derive(Debug)] +struct HdiffMemoryLeaseInner(Arc); + +impl Drop for HdiffMemoryLeaseInner { + fn drop(&mut self) { + let mut state = self.0.lock_state(); + state.hdiff_decoders -= 1; + state.generation = state.generation.wrapping_add(1); + } +} + +impl Drop for GlobalCapacityLease { + fn drop(&mut self) { + self.authority.release(self.runner_id, self.demand); + self.hdiff_memory.take(); + } +} + +fn borrowed( + demand: SharedCapacity, + usage: SharedCapacity, + limit: SharedCapacity, + runners: usize, +) -> bool { + let soft = |capacity: usize| capacity.div_ceil(runners.max(1)); + (demand.cpu > 0 && usage.cpu >= soft(limit.cpu)) + || (demand.blocking > 0 && usage.blocking >= soft(limit.blocking)) + || (demand.network > 0 && usage.network >= soft(limit.network)) + || (demand.extract > 0 && usage.extract >= soft(limit.extract)) + || (demand.reuse_probe > 0 && usage.reuse_probe >= soft(limit.reuse_probe)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::task_pool::scheduler::routing::NetworkClass; + + fn config(capacity: usize) -> TaskPoolConfig { + TaskPoolConfig { + cpu_slots: capacity, + blocking_slots: capacity, + network_slots: capacity, + extract_slots: capacity, + reuse_queue_limit: capacity, + ..TaskPoolConfig::default() + } + } + + #[cfg(feature = "hdiff-patch")] + #[test] + fn decoder_retention_survives_execution_lease_without_blocking_continuation() { + let authority = GlobalCapacityAuthority::new(&config(1)); + let runner = authority.register(); + let start = ResourceRequest { + run: RunClass::AsyncIo, + cpu_on_async: true, + hdiff_decoder_start: true, + ..ResourceRequest::default() + }; + let continuation = ResourceRequest { + hdiff_decoder_start: false, + ..start.clone() + }; + let mut execution = runner.with_admission(|admission| { + assert!(admission.allows(&start)); + admission.acquire(&start) + }); + let retained = execution.take_hdiff_memory().unwrap(); + drop(execution); + runner.with_admission(|admission| { + assert!(!admission.allows(&start)); + assert!(admission.allows(&continuation)); + }); + drop(retained); + assert!(runner.with_admission(|admission| admission.allows(&start))); + } + + #[cfg(feature = "hdiff-patch")] + #[test] + fn decoder_waiter_registers_without_claiming_cpu_until_retention_is_available() { + for traced in [false, true] { + let authority = GlobalCapacityAuthority::new(&config(1)); + let holder = authority.register(); + let waiter = authority.register(); + let start = ResourceRequest { + hdiff_decoder_start: true, + ..cpu() + }; + let mut execution = holder.with_admission(|a| a.acquire(&start)); + let retained = execution.take_hdiff_memory().unwrap(); + drop(execution); + + waiter.with_admission(|a| { + if traced { + assert_eq!( + a.explain_block(&start), + [AdmissionBlockReason::HdiffDecoderMemory] + ); + } else { + assert!(!a.allows(&start)); + } + }); + let generation = waiter + .waiting_generation() + .expect("wait for retained decoder"); + assert!(holder.with_admission(|a| a.allows(&cpu()))); + drop(retained); + assert_ne!(waiter.waiting_generation(), Some(generation)); + assert!(!holder.with_admission(|a| a.allows(&cpu()))); + assert!(waiter.with_admission(|a| a.allows(&start))); + } + } + + #[test] + fn abandoned_pass_clears_waiters_and_worker_keeps_its_lease() { + let authority = GlobalCapacityAuthority::new(&config(1)); + let owner = authority.register(); + let idle = authority.register(); + let execution = owner.with_admission(|a| a.acquire(&cpu())); + let pass = idle.clear_waiters_on_run_exit(); + assert!(!idle.with_admission(|a| a.allows(&cpu()))); + drop(pass); + assert!(idle.waiting_generation().is_none()); + + drop(owner); + assert_eq!(authority.snapshot().0.cpu, 1); + drop(execution); + assert_eq!(authority.snapshot().0, SharedCapacity::default()); + assert!(idle.with_admission(|a| a.allows(&cpu()))); + } + + fn cpu() -> ResourceRequest { + ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + } + } + + fn network() -> ResourceRequest { + ResourceRequest { + run: RunClass::AsyncIo, + network: Some(NetworkClass::General), + ..ResourceRequest::default() + } + } + + fn cpu_extract() -> ResourceRequest { + ResourceRequest { + run: RunClass::Cpu, + extract: true, + ..ResourceRequest::default() + } + } + + #[test] + fn odd_capacity_never_creates_slots() { + for capacity in [1, 3, 5, 7, 11] { + let authority = GlobalCapacityAuthority::new(&config(capacity)); + let runners = (0..3).map(|_| authority.register()).collect::>(); + let mut leases = Vec::new(); + for runner in &runners { + loop { + let lease = runner.with_admission(|admission| { + admission.allows(&cpu()).then(|| admission.acquire(&cpu())) + }); + let Some(lease) = lease else { break }; + leases.push(lease); + } + } + assert_eq!(authority.snapshot().0.cpu, capacity); + assert!(authority.snapshot().1.cpu <= capacity); + drop(leases); + assert_eq!(authority.snapshot().0.cpu, 0); + } + } + + #[test] + fn shared_capacity_recovers_idle_half_of_static_partition() { + let capacity = 8_usize; + let runners = 2_usize; + let static_share = capacity.div_ceil(runners); + assert_eq!(static_share, 4); + + let authority = GlobalCapacityAuthority::new(&config(capacity)); + let _idle = authority.register(); + let busy = authority.register(); + let mut leases = Vec::new(); + for _ in 0..capacity { + let lease = busy.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + leases.push(lease); + } + assert_eq!(authority.snapshot().0.cpu, capacity); + assert_eq!(static_share * 100 / capacity, 50); + assert_eq!(authority.snapshot().0.cpu * 100 / capacity, 100); + drop(leases); + assert_eq!(authority.snapshot().0, SharedCapacity::default()); + } + + #[test] + fn idle_capacity_can_be_borrowed_to_hard_limit() { + let authority = GlobalCapacityAuthority::new(&config(8)); + let _idle = authority.register(); + let busy = authority.register(); + let mut leases = Vec::new(); + for _ in 0..8 { + leases.push(busy.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + })); + } + assert_eq!(authority.snapshot().0.cpu, 8); + assert!(!busy.with_admission(|admission| admission.allows(&cpu()))); + } + + #[test] + fn waiter_reclaims_next_released_capacity_without_preemption() { + let authority = GlobalCapacityAuthority::new(&config(2)); + let borrower = authority.register(); + let waking = authority.register(); + let first = borrower.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + let second = borrower.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + assert!(!waking.with_admission(|admission| admission.allows(&cpu()))); + drop(first); + assert!(!borrower.with_admission(|admission| admission.allows(&cpu()))); + let reclaimed = waking.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + assert_eq!(authority.snapshot().0.cpu, 2); + drop((second, reclaimed)); + } + + #[test] + fn one_slot_waiters_rotate_service() { + let authority = GlobalCapacityAuthority::new(&config(1)); + let a = authority.register(); + let b = authority.register(); + let first = a.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + assert!(!b.with_admission(|admission| admission.allows(&cpu()))); + drop(first); + assert!(!a.with_admission(|admission| admission.allows(&cpu()))); + let second = b.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + drop(second); + assert!(a.with_admission(|admission| admission.allows(&cpu()))); + } + + #[test] + fn multi_resource_request_is_all_or_nothing() { + let authority = GlobalCapacityAuthority::new(&config(1)); + let a = authority.register(); + let b = authority.register(); + let extract_holder = a.with_admission(|admission| { + let request = ResourceRequest { + run: RunClass::AsyncIo, + extract: true, + ..ResourceRequest::default() + }; + assert!(admission.allows(&request)); + admission.acquire(&request) + }); + assert!(!b.with_admission(|admission| admission.allows(&cpu_extract()))); + assert_eq!(authority.snapshot().0.cpu, 0); + assert_eq!(authority.snapshot().0.extract, 1); + drop(extract_holder); + } + + #[test] + fn unrelated_resources_do_not_block_each_other() { + let authority = GlobalCapacityAuthority::new(&config(1)); + let cpu_runner = authority.register(); + let network_runner = authority.register(); + let cpu_lease = cpu_runner.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + let network_lease = network_runner.with_admission(|admission| { + assert!(admission.allows(&network())); + admission.acquire(&network()) + }); + let used = authority.snapshot().0; + assert_eq!(used.cpu, 1); + assert_eq!(used.network, 1); + drop((cpu_lease, network_lease)); + } + fn mixed_request(bits: u64) -> ResourceRequest { + ResourceRequest { + run: if bits & 1 == 0 { + RunClass::Cpu + } else { + RunClass::AsyncIo + }, + network: (bits & 2 != 0).then_some(NetworkClass::General), + extract: bits & 4 != 0, + reuse_probe: bits & 8 != 0, + ..ResourceRequest::default() + } + } + + #[test] + fn randomized_multi_runner_interleavings_never_create_or_leak_capacity() { + for runner_count in [2, 3, 8] { + for seed in [1_u64, 3, 7, 11, 29, 97, 257, 65_537] { + let authority = GlobalCapacityAuthority::new(&config(7)); + let runners = (0..runner_count) + .map(|_| authority.register()) + .collect::>(); + let mut leases = (0..runner_count) + .map(|_| Vec::::new()) + .collect::>(); + let mut state = seed; + for _ in 0..2_000 { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + let runner_index = (state as usize) % runner_count; + if state & 0x10 != 0 && !leases[runner_index].is_empty() { + drop(leases[runner_index].pop()); + } else { + let request = mixed_request(state >> 8); + if let Some(lease) = runners[runner_index].with_admission(|admission| { + admission + .allows(&request) + .then(|| admission.acquire(&request)) + }) { + leases[runner_index].push(lease); + } + } + let (used, peak) = authority.snapshot(); + for value in [ + used.cpu, + used.blocking, + used.network, + used.extract, + used.reuse_probe, + ] { + assert!(value <= 7, "runner_count={runner_count} seed={seed}"); + } + for value in [ + peak.cpu, + peak.blocking, + peak.network, + peak.extract, + peak.reuse_probe, + ] { + assert!(value <= 7, "runner_count={runner_count} seed={seed}"); + } + } + drop(leases); + assert_eq!(authority.snapshot().0, SharedCapacity::default()); + } + } + } + + #[test] + fn runner_arrival_and_departure_preserve_accounting() { + let authority = GlobalCapacityAuthority::new(&config(3)); + let a = authority.register(); + let b = authority.register(); + let a1 = a.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + let b1 = b.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + let c = authority.register(); + let c1 = c.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + assert_eq!(authority.snapshot().0.cpu, 3); + assert!(!a.with_admission(|admission| admission.allows(&cpu()))); + drop(b1); + drop(b); + assert_eq!(authority.snapshot().0.cpu, 2); + drop((a1, c1)); + assert_eq!(authority.snapshot().0, SharedCapacity::default()); + } + + #[test] + fn capacity_metrics_record_borrowing_denials_and_exact_release() { + let authority = GlobalCapacityAuthority::new(&config(2)); + let _idle = authority.register(); + let busy = authority.register(); + let first = busy.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + let second = busy.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + assert!(!busy.with_admission(|admission| admission.allows(&cpu()))); + let metrics = busy.metrics(); + assert_eq!(metrics.cpu_capacity, 2); + assert_eq!(metrics.global_cpu_peak, 2); + assert_eq!(metrics.runner_cpu_peak, 2); + assert!(metrics.borrow_events >= 1); + assert!(metrics.global_borrow_events >= metrics.borrow_events); + assert!(metrics.admission_denials >= 1); + assert!(metrics.global_admission_denials >= metrics.admission_denials); + drop((first, second)); + assert_eq!(authority.snapshot().0.cpu, 0); + } + + #[test] + #[ignore = "M2 synthetic contention probe; run explicitly with --ignored --nocapture"] + fn m2_global_capacity_contention_probe() { + use std::sync::{Arc, Barrier}; + use std::thread; + use std::time::Instant; + + const ITERATIONS: usize = 10_000; + for runner_count in [1, 2, 4, 8] { + let authority = GlobalCapacityAuthority::new(&config(runner_count)); + let runners = (0..runner_count) + .map(|_| authority.register()) + .collect::>(); + let barrier = Arc::new(Barrier::new(runner_count + 1)); + let started = Instant::now(); + thread::scope(|scope| { + for runner in runners { + let barrier = Arc::clone(&barrier); + scope.spawn(move || { + barrier.wait(); + for _ in 0..ITERATIONS { + let lease = runner.with_admission(|admission| { + assert!(admission.allows(&cpu())); + admission.acquire(&cpu()) + }); + drop(lease); + } + }); + } + barrier.wait(); + }); + let elapsed = started.elapsed(); + let operations = runner_count * ITERATIONS; + eprintln!( + "M2_GLOBAL_CAPACITY_BENCH runners={runner_count} operations={operations} elapsed_ns={} ns_per_acquire_release={} contention_events={}", + elapsed.as_nanos(), + elapsed.as_nanos() / operations as u128, + authority.contention_count(), + ); + assert_eq!(authority.snapshot().0, SharedCapacity::default()); + } + } +} diff --git a/crates/griffr-runtime/src/task_pool/scheduler/metrics.rs b/crates/griffr-runtime/src/task_pool/scheduler/metrics.rs index 885a96a..371a9d4 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/metrics.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/metrics.rs @@ -3,13 +3,13 @@ use std::sync::Mutex; use std::time::Duration; use super::routing::ResourceRequest; -use crate::task_pool::{TaskPoolMetrics, VolumeTaskMetrics}; +use crate::task_pool::{ServiceEstimate, TaskPoolMetrics, VolumeTaskMetrics}; #[derive(Debug, Clone)] struct TimingSample { queue_wait: Duration, run_time: Duration, - estimated_bytes: u64, + service_estimate: ServiceEstimate, read_volumes: Vec, write_volumes: Vec, metadata_volumes: Vec, @@ -30,7 +30,7 @@ impl SchedulerMetrics { self.samples.lock().unwrap().push(TimingSample { queue_wait, run_time, - estimated_bytes: resources.estimated_bytes, + service_estimate: resources.service_estimate, read_volumes: resources.read_volumes.clone(), write_volumes: resources.write_volumes.clone(), metadata_volumes: resources.metadata_volumes.clone(), @@ -49,15 +49,23 @@ impl SchedulerMetrics { .collect::>(); let mut volumes = BTreeMap::::new(); for sample in samples.iter() { - for volume in &sample.read_volumes { + for (index, volume) in sample.read_volumes.iter().enumerate() { let metric = volumes.entry(volume.clone()).or_default(); - metric.read_bytes = metric.read_bytes.saturating_add(sample.estimated_bytes); + metric.read_bytes = metric.read_bytes.saturating_add(distributed_bytes( + sample.service_estimate.storage_read_bytes, + index, + sample.read_volumes.len(), + )); metric.read_service_time = metric.read_service_time.saturating_add(sample.run_time); metric.read_tasks = metric.read_tasks.saturating_add(1); } - for volume in &sample.write_volumes { + for (index, volume) in sample.write_volumes.iter().enumerate() { let metric = volumes.entry(volume.clone()).or_default(); - metric.write_bytes = metric.write_bytes.saturating_add(sample.estimated_bytes); + metric.write_bytes = metric.write_bytes.saturating_add(distributed_bytes( + sample.service_estimate.storage_write_bytes, + index, + sample.write_volumes.len(), + )); metric.write_service_time = metric.write_service_time.saturating_add(sample.run_time); metric.write_tasks = metric.write_tasks.saturating_add(1); @@ -81,6 +89,16 @@ impl SchedulerMetrics { } } +fn distributed_bytes(total: u64, index: usize, lanes: usize) -> u64 { + if lanes == 0 { + return 0; + } + let lanes = u64::try_from(lanes).unwrap_or(u64::MAX); + let base = total / lanes; + let remainder = total % lanes; + base.saturating_add(u64::from((index as u64) < remainder)) +} + fn percentile(samples: &mut [Duration], percentile: usize) -> Duration { if samples.is_empty() { return Duration::ZERO; @@ -94,6 +112,7 @@ fn percentile(samples: &mut [Duration], percentile: usize) -> Duration { mod tests { use super::*; use crate::task_pool::scheduler::routing::{ResourceRequest, RunClass}; + use crate::task_pool::ServiceEstimate; #[test] fn snapshot_reports_percentiles_and_volume_service_bytes() { @@ -101,7 +120,10 @@ mod tests { let resources = ResourceRequest { run: RunClass::Cpu, read_volumes: vec!["volume-a".to_string()], - estimated_bytes: 1024, + service_estimate: ServiceEstimate { + storage_read_bytes: 1024, + ..ServiceEstimate::default() + }, ..ResourceRequest::default() }; metrics.record( @@ -121,4 +143,31 @@ mod tests { assert_eq!(snapshot.queue_wait_p95, Duration::from_millis(30)); assert_eq!(snapshot.volumes["volume-a"].read_bytes, 2048); } + + #[test] + fn multi_volume_service_bytes_are_distributed_without_double_counting() { + let metrics = SchedulerMetrics::default(); + let resources = ResourceRequest { + run: RunClass::Blocking, + read_volumes: vec!["volume-a".to_string(), "volume-b".to_string()], + write_volumes: vec!["volume-c".to_string(), "volume-d".to_string()], + service_estimate: ServiceEstimate { + storage_read_bytes: 5, + storage_write_bytes: 7, + ..ServiceEstimate::default() + }, + ..ResourceRequest::default() + }; + metrics.record(Duration::ZERO, Duration::from_millis(1), &resources); + + let snapshot = metrics.snapshot(); + let read_total = snapshot.volumes["volume-a"] + .read_bytes + .saturating_add(snapshot.volumes["volume-b"].read_bytes); + let write_total = snapshot.volumes["volume-c"] + .write_bytes + .saturating_add(snapshot.volumes["volume-d"].write_bytes); + assert_eq!(read_total, 5); + assert_eq!(write_total, 7); + } } diff --git a/crates/griffr-runtime/src/task_pool/scheduler/observatory.rs b/crates/griffr-runtime/src/task_pool/scheduler/observatory.rs new file mode 100644 index 0000000..5f9846f --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/scheduler/observatory.rs @@ -0,0 +1,781 @@ +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use super::super::graph::{DagHint, ReadyTask, TaskGraph, TaskOrigin, TaskRun}; +use super::queue::{CONTINUATION_BURST, PRIORITY_LOOKAHEAD}; +use super::routing::{NetworkClass, ResourceRequest, RunClass}; +use super::TaskPriority; +use crate::error::{Error, Result}; +use crate::task_pool::{ + AdmissionBlockReason, MachineProfile, NodeId, ResourceOccupancy, ResourceOccupancyAction, + SchedulerCompletion, SchedulerConfigProfile, SchedulerDecision, SchedulerNetworkClass, + SchedulerResourceDemand, SchedulerRunClass, SchedulerTaskPriority, SchedulerTrace, + SchedulerTraceEvent, SchedulerTraceEventKind, ServiceEstimate, StorageReservationDemand, Task, + TaskPoolConfig, TraceSink, TraceSinkFinish, VolumePolicyOverride, WorkUnitIdentity, + WorkUnitPhase, WorkloadCaptureConfig, WorkloadCaptureMode, WorkloadCompletion, WorkloadDagHint, + WorkloadDecision, WorkloadEdge, WorkloadEvent, WorkloadEventKind, WorkloadNode, WorkloadNodeId, + WorkloadOccupancyAction, WorkloadRecordPayload, WorkloadSanitizer, WorkloadTaskOrigin, + WorkloadTimeModel, WorkloadTraceHeader, WORKLOAD_TRACE_SCHEMA_VERSION, +}; + +static NEXT_TRACE_RUN_ID: AtomicU64 = AtomicU64::new(1); + +#[derive(Debug)] +pub(super) struct SchedulerTraceRecorder { + active: Option, + workload: Option, + workload_error: Option, + run_id: Option, + runner_id: u64, + started_at: Instant, +} + +#[derive(Debug)] +struct ActiveTrace { + started_at: Instant, + trace: SchedulerTrace, +} + +#[derive(Debug)] +struct ActiveWorkloadTrace { + sink: TraceSink, + sanitizer: WorkloadSanitizer, + run_id: u64, + next_event_sequence: u64, + generations: HashMap, + work_units: HashMap, + service_estimates: HashMap, +} + +impl SchedulerTraceRecorder { + #[cfg(test)] + pub(super) fn new(enabled: bool, started_at: Instant) -> Self { + Self::new_for_runner(enabled, started_at, 1) + } + + pub(super) fn new_for_runner(enabled: bool, started_at: Instant, runner_id: u64) -> Self { + let run_id = enabled.then(|| NEXT_TRACE_RUN_ID.fetch_add(1, Ordering::Relaxed)); + let active = run_id.map(|run_id| ActiveTrace { + started_at, + trace: SchedulerTrace::new(run_id, runner_id), + }); + Self { + active, + workload: None, + workload_error: None, + run_id, + runner_id, + started_at, + } + } + + pub(super) fn enable_workload_capture( + &mut self, + capture: Option<&WorkloadCaptureConfig>, + config: &TaskPoolConfig, + hdiff_decoder_slots: usize, + ) -> Result<()> { + let Some(capture) = capture else { + return Ok(()); + }; + let run_id = *self + .run_id + .get_or_insert_with(|| NEXT_TRACE_RUN_ID.fetch_add(1, Ordering::Relaxed)); + let mut sanitizer = WorkloadSanitizer::default(); + let mut volume_policy_overrides = Vec::with_capacity(config.volume_policies.len()); + let mut initial_sanitized_records = Vec::new(); + for (raw_volume, policy) in &config.volume_policies { + let (volume_id, delta) = sanitizer.intern_volume_for_capture(raw_volume); + initial_sanitized_records + .extend(delta.volumes.into_iter().map(WorkloadRecordPayload::Volume)); + initial_sanitized_records + .extend(delta.paths.into_iter().map(WorkloadRecordPayload::Path)); + volume_policy_overrides.push(VolumePolicyOverride { + volume_id, + policy: (*policy).into(), + }); + } + let wall_clock_start_unix_ns = SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|duration| u64::try_from(duration.as_nanos()).ok()); + let header = WorkloadTraceHeader { + schema_version: WORKLOAD_TRACE_SCHEMA_VERSION, + run_id, + runner_id: self.runner_id, + time_model: WorkloadTimeModel::MonotonicRelativeNanoseconds, + wall_clock_start_unix_ns, + source_tree: capture.source_tree.clone(), + workload_kind: capture.workload_kind.clone(), + capture_mode: capture.mode, + scheduler: SchedulerConfigProfile { + cpu_slots: config.cpu_slots, + hdiff_decoder_slots, + blocking_slots: config.blocking_slots, + network_slots: config.network_slots, + extract_slots: config.extract_slots, + reuse_queue_limit: config.reuse_queue_limit, + volume_write_reservation_delay_ns: duration_ns( + config.volume_write_reservation_delay, + ), + ready_frontier_limit: config.ready_frontier_limit(), + priority_lookahead: PRIORITY_LOOKAHEAD, + continuation_burst: CONTINUATION_BURST, + default_volume_policy: config.default_volume_policy.into(), + volume_policy_overrides, + }, + machine: MachineProfile { + os: std::env::consts::OS.to_owned(), + architecture: std::env::consts::ARCH.to_owned(), + available_parallelism: std::thread::available_parallelism() + .map(|value| value.get()) + .unwrap_or(1), + md5_verify_batch_capacity: super::super::verify::md5_verify_batch_capacity(), + }, + }; + let sink = match capture.mode { + WorkloadCaptureMode::Memory => TraceSink::memory(header)?, + WorkloadCaptureMode::StreamingStrict | WorkloadCaptureMode::StreamingLossAware => { + let path = unique_capture_path(&capture.path, run_id); + TraceSink::streaming(path, header, capture.channel_capacity)? + } + }; + self.workload = Some(ActiveWorkloadTrace { + sink, + sanitizer, + run_id, + next_event_sequence: 0, + generations: HashMap::new(), + work_units: HashMap::new(), + service_estimates: HashMap::new(), + }); + for record in initial_sanitized_records { + self.workload_record(record); + } + self.take_workload_error()?; + Ok(()) + } + + #[inline] + pub(super) fn enabled(&self) -> bool { + self.active.is_some() || self.workload.is_some() + } + + pub(super) fn workload_enabled(&self) -> bool { + self.workload.is_some() + } + + fn workload_record(&mut self, payload: WorkloadRecordPayload) { + if self.workload_error.is_some() { + return; + } + let result = self + .workload + .as_mut() + .map(|workload| workload.sink.record(payload)); + if let Some(Err(error)) = result { + self.workload_error = Some(error.to_string()); + } + } + + fn workload_event(&mut self, kind: WorkloadEventKind) { + if self.workload_error.is_some() { + return; + } + let elapsed_ns = duration_ns(self.started_at.elapsed()); + let Some(workload) = self.workload.as_mut() else { + return; + }; + let event_sequence = workload.next_event_sequence; + workload.next_event_sequence = workload.next_event_sequence.saturating_add(1); + if let Err(error) = workload.sink.record_event(WorkloadEvent { + event_sequence, + elapsed_ns, + kind, + }) { + self.workload_error = Some(error.to_string()); + } + } + + fn workload_sanitization_delta(&mut self, delta: crate::task_pool::SanitizationDelta) { + for volume in delta.volumes { + self.workload_record(WorkloadRecordPayload::Volume(volume)); + } + for path in delta.paths { + self.workload_record(WorkloadRecordPayload::Path(path)); + } + } + + fn take_workload_error(&mut self) -> Result<()> { + match self.workload_error.take() { + Some(detail) => Err(Error::Message { + context: "Workload trace recorder error: ", + detail, + }), + None => Ok(()), + } + } + + fn current_work_unit(&self, node_id: NodeId) -> Option { + self.workload + .as_ref() + .and_then(|workload| workload.work_units.get(&node_id.index()).cloned()) + } + + pub(super) fn capture_graph_range( + &mut self, + graph: &TaskGraph, + start: usize, + end: usize, + ready: &[ReadyTask], + expansion_parent: Option, + ) { + if !self.workload_enabled() || start >= end { + return; + } + let parent_work_unit = expansion_parent.and_then(|id| self.current_work_unit(id)); + let run_id = self.workload.as_ref().expect("workload enabled").run_id; + let mut new_nodes = Vec::with_capacity(end - start); + for index in start..end { + let Some(id) = NodeId::new(index).ok() else { + continue; + }; + let task = graph.trace_task(id).or_else(|| { + ready + .iter() + .find(|candidate| candidate.id == id) + .map(|candidate| &candidate.task) + }); + let Some(task) = task else { + self.workload_error = Some(format!( + "capture could not resolve task payload for graph node {index}" + )); + return; + }; + let Some(dag_hint) = graph.trace_dag_hint(id) else { + self.workload_error = Some(format!( + "capture could not resolve DagHint for graph node {index}" + )); + return; + }; + let node_id = WorkloadNodeId { + run_id, + node_id: index, + }; + if let Some(workload) = self.workload.as_mut() { + if let Err(error) = workload.sink.record_node(WorkloadNode { + id: node_id.clone(), + task_kind: task_kind(task).to_owned(), + dag_hint: workload_dag_hint(dag_hint), + expansion_parent: parent_work_unit.clone(), + }) { + self.workload_error = Some(error.to_string()); + return; + } + } + self.workload_event(WorkloadEventKind::Created { + node: node_id.clone(), + }); + new_nodes.push(node_id); + } + let new_edges = graph + .trace_edges_touching_range(start, end) + .into_iter() + .map(|(from, to)| WorkloadEdge { + from: WorkloadNodeId { + run_id, + node_id: from.index(), + }, + to: WorkloadNodeId { + run_id, + node_id: to.index(), + }, + }) + .collect::>(); + for edge in &new_edges { + if let Some(workload) = self.workload.as_mut() { + if let Err(error) = workload.sink.record_edge(edge.clone()) { + self.workload_error = Some(error.to_string()); + return; + } + } + } + if let Some(parent) = parent_work_unit { + self.workload_event(WorkloadEventKind::Expanded { + parent, + new_nodes, + new_edges, + }); + } + } + + pub(super) fn record(&mut self, kind: SchedulerTraceEventKind) { + let Some(active) = self.active.as_mut() else { + return; + }; + let elapsed_ns = u64::try_from(active.started_at.elapsed().as_nanos()).unwrap_or(u64::MAX); + active + .trace + .events + .push(SchedulerTraceEvent { elapsed_ns, kind }); + } + + pub(super) fn created_range(&mut self, start: usize, end: usize) { + if self.active.is_none() { + return; + } + for node_id in start..end { + self.record(SchedulerTraceEventKind::Created { node_id }); + } + } + + pub(super) fn ready_tasks(&mut self, ready: &[ReadyTask]) { + if !self.enabled() { + return; + } + for ready in ready { + self.record(SchedulerTraceEventKind::Ready { + node_id: ready.id.index(), + task_kind: task_kind(&ready.task).to_owned(), + continuation: ready.dag_hint.uses_continuation_lane(), + }); + let work_unit = self.workload.as_mut().map(|workload| { + let generation = match workload.generations.get_mut(&ready.id.index()) { + Some(generation) => { + *generation = generation.saturating_add(1); + *generation + } + None => { + workload.generations.insert(ready.id.index(), 0); + 0 + } + }; + let identity = WorkUnitIdentity { + node: WorkloadNodeId { + run_id: workload.run_id, + node_id: ready.id.index(), + }, + task_kind: task_kind(&ready.task).to_owned(), + phase: work_unit_phase(&ready.task), + attempt: 1, + continuation_generation: generation, + }; + workload + .work_units + .insert(ready.id.index(), identity.clone()); + identity + }); + if let Some(work_unit) = work_unit { + self.workload_event(WorkloadEventKind::Ready { + work_unit, + dag_hint: workload_dag_hint(ready.dag_hint), + batch_class: super::super::verify::is_md5_verify_task(&ready.task) + .then_some(crate::task_pool::WorkloadBatchClass::Md5Verify), + }); + } + } + } + + pub(super) fn routed( + &mut self, + node_id: NodeId, + priority: TaskPriority, + resources: &ResourceRequest, + ) { + if !self.enabled() { + return; + } + let demand = SchedulerResourceDemand { + cpu_on_async: resources.cpu_on_async, + hdiff_decoder_start: resources.hdiff_decoder_start, + run_class: resources.run.into(), + network_class: resources.network.map(Into::into), + read_volumes: resources.read_volumes.clone(), + write_volumes: resources.write_volumes.clone(), + metadata_volumes: resources.metadata_volumes.clone(), + archive_save_volumes: resources.archive_save_volumes.clone(), + archive_commit_volumes: resources.archive_commit_volumes.clone(), + extract: resources.extract, + mutation_paths: resources.mutation_paths.clone(), + storage_reservations: resources + .storage_reservations + .iter() + .map(|reservation| StorageReservationDemand { + volume: reservation.volume.clone(), + bytes: reservation.bytes, + }) + .collect(), + reuse_probe: resources.reuse_probe, + reuse_commit: resources.reuse_commit, + priority_cost: resources.priority_cost, + service_estimate: resources.service_estimate, + }; + if let Some(workload) = self.workload.as_mut() { + workload + .service_estimates + .insert(node_id.index(), resources.service_estimate); + } + let sanitized = self + .workload + .as_mut() + .map(|workload| workload.sanitizer.sanitize_demand(&demand)); + if let Some((demand, delta)) = sanitized { + self.workload_sanitization_delta(delta); + if let Some(work_unit) = self.current_work_unit(node_id) { + self.workload_event(WorkloadEventKind::Routed { + work_unit, + priority: priority.into(), + demand, + }); + } + } + self.record(SchedulerTraceEventKind::Routed { + node_id: node_id.index(), + priority: priority.into(), + demand, + }); + } + + pub(super) fn admitted( + &mut self, + node_id: NodeId, + service_estimate: ServiceEstimate, + occupancy: ResourceOccupancy, + ) { + if let Some(work_unit) = self.current_work_unit(node_id) { + self.workload_event(WorkloadEventKind::Admitted { + work_unit: work_unit.clone(), + service_estimate, + }); + let sanitized = self + .workload + .as_mut() + .map(|workload| workload.sanitizer.sanitize_occupancy(&occupancy)); + if let Some((occupancy, delta)) = sanitized { + self.workload_sanitization_delta(delta); + self.workload_event(WorkloadEventKind::Occupancy { + action: WorkloadOccupancyAction::Acquire, + work_unit, + occupancy, + }); + } + } + self.record(SchedulerTraceEventKind::Admitted { + node_id: node_id.index(), + service_estimate, + }); + self.record(SchedulerTraceEventKind::Occupancy { + action: ResourceOccupancyAction::Acquire, + node_id: node_id.index(), + occupancy, + }); + } + + pub(super) fn released(&mut self, node_id: NodeId, occupancy: ResourceOccupancy) { + if let Some(work_unit) = self.current_work_unit(node_id) { + let sanitized = self + .workload + .as_mut() + .map(|workload| workload.sanitizer.sanitize_occupancy(&occupancy)); + if let Some((occupancy, delta)) = sanitized { + self.workload_sanitization_delta(delta); + self.workload_event(WorkloadEventKind::Occupancy { + action: WorkloadOccupancyAction::Release, + work_unit, + occupancy, + }); + } + } + self.record(SchedulerTraceEventKind::Occupancy { + action: ResourceOccupancyAction::Release, + node_id: node_id.index(), + occupancy, + }); + } + + pub(super) fn started(&mut self, node_id: NodeId) { + if let Some(work_unit) = self.current_work_unit(node_id) { + self.workload_event(WorkloadEventKind::Started { work_unit }); + } + self.record(SchedulerTraceEventKind::Started { + node_id: node_id.index(), + }); + } + + pub(super) fn finished( + &mut self, + node_id: NodeId, + run: &TaskRun, + queue_wait: Duration, + run_time: Duration, + observed_storage_read_bytes: Option, + ) { + if let Some(work_unit) = self.current_work_unit(node_id) { + let estimate = self + .workload + .as_ref() + .and_then(|workload| workload.service_estimates.get(&node_id.index()).copied()) + .unwrap_or_default(); + let mut observed_service = + crate::task_pool::ObservedService::from_estimate(duration_ns(run_time), estimate); + if let Some(storage_read_bytes) = observed_storage_read_bytes { + observed_service.storage_read_bytes = + crate::task_pool::ServiceQuantity::observed(storage_read_bytes); + } + #[cfg(feature = "hdiff-patch")] + let hdiff_retention_released = work_unit.phase == WorkUnitPhase::HdiffDecode + && !matches!( + run, + TaskRun::Continue(Task::DecodeHdiffPatchEntry { + retained: Some(_), + .. + }) + ); + #[cfg(not(feature = "hdiff-patch"))] + let hdiff_retention_released = false; + self.workload_event(WorkloadEventKind::Finished { + work_unit, + completion: workload_completion(run), + hdiff_retention_released, + queue_wait_ns: duration_ns(queue_wait), + observed_service, + }); + } + self.record(SchedulerTraceEventKind::Finished { + node_id: node_id.index(), + completion: completion(run), + queue_wait_ns: duration_ns(queue_wait), + run_time_ns: duration_ns(run_time), + }); + } + + pub(super) fn considered( + &mut self, + node_id: NodeId, + priority: TaskPriority, + candidate_index: usize, + run_class: RunClass, + network_class: Option, + batch_member: bool, + blocked_by: Vec, + ) { + let sanitized = self + .workload + .as_mut() + .map(|workload| workload.sanitizer.sanitize_block_reasons(&blocked_by)); + if let Some((blocked_by_sanitized, delta)) = sanitized { + self.workload_sanitization_delta(delta); + if let Some(work_unit) = self.current_work_unit(node_id) { + self.workload_event(WorkloadEventKind::Considered { + work_unit, + priority: priority.into(), + candidate_index, + run_class: run_class.into(), + network_class: network_class.map(Into::into), + batch_member, + blocked_by: blocked_by_sanitized, + }); + } + } + self.record(SchedulerTraceEventKind::Considered { + node_id: node_id.index(), + priority: priority.into(), + candidate_index, + run_class: run_class.into(), + network_class: network_class.map(Into::into), + batch_member, + blocked_by, + }); + } + + pub(super) fn decision( + &mut self, + ready_frontier_len: usize, + ready_backlog_len: usize, + priority: TaskPriority, + candidate_index: usize, + run_class: RunClass, + network_class: Option, + batch_member: bool, + ) { + let decision = WorkloadDecision { + ready_frontier_len, + ready_backlog_len, + priority: priority.into(), + candidate_index, + lookahead_exhausted: !batch_member && candidate_index >= PRIORITY_LOOKAHEAD, + run_class: run_class.into(), + network_class: network_class.map(Into::into), + batch_member, + }; + self.workload_event(WorkloadEventKind::Decision(decision.clone())); + self.record(SchedulerTraceEventKind::Decision(SchedulerDecision { + ready_frontier_len, + ready_backlog_len, + priority: priority.into(), + candidate_index, + lookahead_exhausted: decision.lookahead_exhausted, + run_class: run_class.into(), + network_class: network_class.map(Into::into), + batch_member, + })); + } + + pub(super) fn finish(mut self) -> Result> { + self.take_workload_error()?; + if let Some(workload) = self.workload.take() { + let TraceSinkFinish { + footer, + footer_written, + .. + } = workload.sink.finish()?; + if footer.writer_error.is_some() || !footer_written { + return Err(Error::Message { + context: "Workload trace recorder error: ", + detail: footer + .writer_error + .unwrap_or_else(|| "trace footer was not durably written".to_owned()), + }); + } + } + self.take_workload_error()?; + Ok(self.active.map(|active| active.trace)) + } +} + +pub(super) fn unique_capture_path(base: &std::path::Path, run_id: u64) -> std::path::PathBuf { + if !base.exists() { + return base.to_path_buf(); + } + let parent = base.parent().unwrap_or_else(|| std::path::Path::new("")); + let stem = base + .file_stem() + .and_then(|value| value.to_str()) + .unwrap_or("workload"); + let extension = base.extension().and_then(|value| value.to_str()); + let file_name = match extension { + Some(extension) => format!("{stem}.run-{run_id}.{extension}"), + None => format!("{stem}.run-{run_id}"), + }; + parent.join(file_name) +} + +fn duration_ns(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) +} + +fn completion(run: &TaskRun) -> SchedulerCompletion { + match run { + TaskRun::Succeeded => SchedulerCompletion::Succeeded, + TaskRun::Failed { .. } => SchedulerCompletion::Failed, + TaskRun::Cancelled => SchedulerCompletion::Cancelled, + TaskRun::Continue(_) => SchedulerCompletion::Continued, + TaskRun::Expand(_) => SchedulerCompletion::Expanded, + TaskRun::ExpandThen { .. } => SchedulerCompletion::ExpandedThen, + } +} + +fn workload_completion(run: &TaskRun) -> WorkloadCompletion { + match run { + TaskRun::Succeeded => WorkloadCompletion::Succeeded, + TaskRun::Failed { .. } => WorkloadCompletion::Failed, + TaskRun::Cancelled => WorkloadCompletion::Cancelled, + TaskRun::Continue(_) => WorkloadCompletion::Continued, + TaskRun::Expand(_) => WorkloadCompletion::Expanded, + TaskRun::ExpandThen { .. } => WorkloadCompletion::ExpandedThen, + } +} + +fn workload_dag_hint(hint: DagHint) -> WorkloadDagHint { + WorkloadDagHint { + origin: match hint.origin { + TaskOrigin::Root => WorkloadTaskOrigin::Root, + TaskOrigin::StaticDependency => WorkloadTaskOrigin::StaticDependency, + TaskOrigin::DynamicExpansion => WorkloadTaskOrigin::DynamicExpansion, + TaskOrigin::Continuation => WorkloadTaskOrigin::Continuation, + }, + depth: hint.depth, + local_rank: hint.local_rank.map(|rank| rank.get()), + } +} + +fn work_unit_phase(task: &Task) -> WorkUnitPhase { + match task { + Task::ApplyPatchEntry { patch, entry_index } + if patch.entry(*entry_index).is_some_and(|entry| { + matches!(entry.source, crate::PlannedPatchSource::Hdiff { .. }) + }) => + { + WorkUnitPhase::HdiffPrepare + } + Task::DecodeHdiffPatchEntry { .. } => WorkUnitPhase::HdiffDecode, + Task::CommitHdiffPatchEntry { .. } => WorkUnitPhase::HdiffCommit, + _ => WorkUnitPhase::Generic, + } +} + +fn task_kind(task: &Task) -> &'static str { + match task { + Task::OpenArchive { .. } => "OpenArchive", + Task::Download { .. } => "Download", + Task::Verify { .. } => "Verify", + Task::VerifyMetadata { .. } => "VerifyMetadata", + Task::RepairFile { .. } => "RepairFile", + Task::VerifyReuseVolume { .. } => "VerifyReuseVolume", + Task::ReuseFile { .. } => "ReuseFile", + Task::FetchArchiveRepairFile { .. } => "FetchArchiveRepairFile", + Task::ExtractArchiveRepairFile { .. } => "ExtractArchiveRepairFile", + Task::FetchArchiveRange { .. } => "FetchArchiveRange", + Task::DiscoverArchiveDirectory { .. } => "DiscoverArchiveDirectory", + Task::InspectArchiveIndex { .. } => "InspectArchiveIndex", + Task::ReadArchiveControls { .. } => "ReadArchiveControls", + Task::ProbePatchArtifact { .. } => "ProbePatchArtifact", + Task::MeasurePatchRelocation { .. } => "MeasurePatchRelocation", + Task::SavePatchPlan { .. } => "SavePatchPlan", + Task::ExtractArchiveShard { .. } => "ExtractArchiveShard", + Task::RetainArchiveVolume { .. } => "RetainArchiveVolume", + Task::FinishArchive { .. } => "FinishArchive", + Task::PreparePatchApply { .. } => "PreparePatchApply", + Task::ApplyPatchEntry { .. } => "ApplyPatchEntry", + Task::DecodeHdiffPatchEntry { .. } => "DecodeHdiffPatchEntry", + Task::CommitHdiffPatchEntry { .. } => "CommitHdiffPatchEntry", + Task::ReleasePatchBase { .. } => "ReleasePatchBase", + Task::ApplyPatchDeletes { .. } => "ApplyPatchDeletes", + Task::CommitPatchDeferred { .. } => "CommitPatchDeferred", + Task::CleanPatchApply { .. } => "CleanPatchApply", + Task::CleanupArchive { .. } => "CleanupArchive", + Task::ApplyExtractedVfsPatchManifest { .. } => "ApplyExtractedVfsPatchManifest", + Task::ApplyDeleteManifest { .. } => "ApplyDeleteManifest", + } +} + +impl From for SchedulerRunClass { + fn from(value: RunClass) -> Self { + match value { + RunClass::AsyncIo => Self::AsyncIo, + RunClass::Cpu => Self::Cpu, + RunClass::Blocking => Self::Blocking, + } + } +} + +impl From for SchedulerNetworkClass { + fn from(value: NetworkClass) -> Self { + match value { + NetworkClass::General => Self::General, + NetworkClass::Vfs => Self::Vfs, + NetworkClass::Archive => Self::Archive, + NetworkClass::ArchiveBackground => Self::ArchiveBackground, + } + } +} + +impl From for SchedulerTaskPriority { + fn from(value: TaskPriority) -> Self { + match value { + TaskPriority::Continuation => Self::Continuation, + TaskPriority::Bulk => Self::Bulk, + } + } +} diff --git a/crates/griffr-runtime/src/task_pool/scheduler/queue/mod.rs b/crates/griffr-runtime/src/task_pool/scheduler/queue/mod.rs index 35b562b..74e0b38 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/queue/mod.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/queue/mod.rs @@ -5,5 +5,6 @@ mod resources; mod tests; pub(crate) use priority_queue::{ScheduledTask, SchedulerQueue}; +pub(crate) use priority_queue::{CONTINUATION_BURST, PRIORITY_LOOKAHEAD}; #[cfg(test)] pub(super) use resources::{AdmissionSnapshot, ResourceState}; diff --git a/crates/griffr-runtime/src/task_pool/scheduler/queue/priority_queue.rs b/crates/griffr-runtime/src/task_pool/scheduler/queue/priority_queue.rs index 0e0ae1d..9eb4150 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/queue/priority_queue.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/queue/priority_queue.rs @@ -5,13 +5,15 @@ use std::time::Instant; use rapidhash::{RapidHashMap as HashMap, RapidHashSet as HashSet}; +use super::super::global_capacity::{GlobalAdmission, GlobalCapacityLease, GlobalCapacityRunner}; +use super::super::observatory::SchedulerTraceRecorder; use super::super::routing::{run_class, NetworkClass, ResourceRequest, RunClass}; use super::super::TaskPriority; use super::resources::{AdmissionSnapshot, ResourceState}; -use crate::task_pool::{NodeId, Task, TaskPoolConfig}; +use crate::task_pool::{AdmissionBlockReason, NodeId, Task, TaskPoolConfig}; -const CONTINUATION_BURST: usize = 4; -const PRIORITY_LOOKAHEAD: usize = 64; +pub(crate) const CONTINUATION_BURST: usize = 4; +pub(crate) const PRIORITY_LOOKAHEAD: usize = 64; const RUN_SCHEDULE: [RunClass; 4] = [ RunClass::AsyncIo, RunClass::Cpu, @@ -29,6 +31,44 @@ const NETWORK_SCHEDULE: [NetworkClass; 8] = [ NetworkClass::ArchiveBackground, ]; +trait SharedAdmissionGate { + fn allows(&mut self, request: &ResourceRequest) -> bool; + fn explain_block(&mut self, request: &ResourceRequest) -> Vec; + fn acquire(&mut self, request: &ResourceRequest) -> Option; +} + +#[cfg(test)] +struct LocalOnlyAdmission; + +#[cfg(test)] +impl SharedAdmissionGate for LocalOnlyAdmission { + fn allows(&mut self, _request: &ResourceRequest) -> bool { + true + } + + fn explain_block(&mut self, _request: &ResourceRequest) -> Vec { + Vec::new() + } + + fn acquire(&mut self, _request: &ResourceRequest) -> Option { + None + } +} + +impl SharedAdmissionGate for GlobalAdmission<'_> { + fn allows(&mut self, request: &ResourceRequest) -> bool { + GlobalAdmission::allows(self, request) + } + + fn explain_block(&mut self, request: &ResourceRequest) -> Vec { + GlobalAdmission::explain_block(self, request) + } + + fn acquire(&mut self, request: &ResourceRequest) -> Option { + Some(GlobalAdmission::acquire(self, request)) + } +} + #[derive(Debug)] pub(super) struct QueuedTask { pub(super) node_id: NodeId, @@ -256,10 +296,11 @@ impl QueueState { } } - fn pop_next( + fn pop_next( &mut self, config: &TaskPoolConfig, blocking_dispatch_available: bool, + global: &mut G, ) -> Option { self.ensure_admission_cache(config); for offset in 0..RUN_SCHEDULE.len() { @@ -268,7 +309,7 @@ impl QueueState { if !blocking_dispatch_available && class != RunClass::AsyncIo { continue; } - if let Some(task) = self.pop_runnable(class, config) { + if let Some(task) = self.pop_runnable(class, config, global) { self.run_cursor = (index + 1) % RUN_SCHEDULE.len(); return Some(task); } @@ -276,15 +317,114 @@ impl QueueState { None } - fn pop_md5_verify_for_batch(&mut self, config: &TaskPoolConfig) -> Option { + fn pop_next_observed( + &mut self, + config: &TaskPoolConfig, + blocking_dispatch_available: bool, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + global: &mut G, + ) -> Option { + debug_assert!(trace.enabled()); + self.ensure_admission_cache(config); + let ready_frontier_len = self.continuation.len().saturating_add(self.bulk.len()); + for offset in 0..RUN_SCHEDULE.len() { + let index = (self.run_cursor + offset) % RUN_SCHEDULE.len(); + let class = RUN_SCHEDULE[index]; + if !blocking_dispatch_available && class != RunClass::AsyncIo { + continue; + } + if let Some(task) = self.pop_runnable_observed( + class, + config, + trace, + ready_frontier_len, + ready_backlog_len, + global, + ) { + self.run_cursor = (index + 1) % RUN_SCHEDULE.len(); + return Some(task); + } + } + None + } + + fn pop_md5_verify_for_batch( + &mut self, + config: &TaskPoolConfig, + global: &mut G, + ) -> Option { + self.ensure_admission_cache(config); + + let continuation_index = { + let cache = self + .admission_cache + .as_ref() + .expect("admission cache must exist while selecting MD5 verify batch"); + md5_verify_batch_index( + &self.continuation, + &self.resources, + config, + &cache.snapshot, + global, + ) + }; + if let Some(index) = continuation_index { + let queued = self + .continuation + .remove(index) + .expect("selected continuation task must exist"); + self.admission_cache + .as_mut() + .expect("admission cache must exist while selecting MD5 verify batch") + .remove_task(TaskPriority::Continuation, &queued); + return Some(queued); + } + + let bulk_index = { + let cache = self + .admission_cache + .as_ref() + .expect("admission cache must exist while selecting MD5 verify batch"); + md5_verify_batch_index(&self.bulk, &self.resources, config, &cache.snapshot, global) + }; + let index = bulk_index?; + let queued = self + .bulk + .remove(index) + .expect("selected bulk task must exist"); + self.admission_cache + .as_mut() + .expect("admission cache must exist while selecting MD5 verify batch") + .remove_task(TaskPriority::Bulk, &queued); + Some(queued) + } + + fn pop_md5_verify_for_batch_observed( + &mut self, + config: &TaskPoolConfig, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + global: &mut G, + ) -> Option { + debug_assert!(trace.enabled()); self.ensure_admission_cache(config); + let ready_frontier_len = self.continuation.len().saturating_add(self.bulk.len()); let continuation_index = { let cache = self .admission_cache .as_ref() .expect("admission cache must exist while selecting MD5 verify batch"); - md5_verify_batch_index(&self.continuation, &self.resources, config, &cache.snapshot) + md5_verify_batch_index_observed( + &self.continuation, + TaskPriority::Continuation, + &self.resources, + config, + &cache.snapshot, + trace, + global, + ) }; if let Some(index) = continuation_index { let queued = self @@ -295,6 +435,15 @@ impl QueueState { .as_mut() .expect("admission cache must exist while selecting MD5 verify batch") .remove_task(TaskPriority::Continuation, &queued); + trace.decision( + ready_frontier_len, + ready_backlog_len, + TaskPriority::Continuation, + index, + queued.resources.run, + queued.resources.network, + true, + ); return Some(queued); } @@ -303,7 +452,15 @@ impl QueueState { .admission_cache .as_ref() .expect("admission cache must exist while selecting MD5 verify batch"); - md5_verify_batch_index(&self.bulk, &self.resources, config, &cache.snapshot) + md5_verify_batch_index_observed( + &self.bulk, + TaskPriority::Bulk, + &self.resources, + config, + &cache.snapshot, + trace, + global, + ) }; let index = bulk_index?; let queued = self @@ -314,10 +471,24 @@ impl QueueState { .as_mut() .expect("admission cache must exist while selecting MD5 verify batch") .remove_task(TaskPriority::Bulk, &queued); + trace.decision( + ready_frontier_len, + ready_backlog_len, + TaskPriority::Bulk, + index, + queued.resources.run, + queued.resources.network, + true, + ); Some(queued) } - fn pop_runnable(&mut self, class: RunClass, config: &TaskPoolConfig) -> Option { + fn pop_runnable( + &mut self, + class: RunClass, + config: &TaskPoolConfig, + global: &mut G, + ) -> Option { let class_index = run_index(class); let force_bulk = self.continuation_streak[class_index] >= CONTINUATION_BURST; let preferred_network = if class == RunClass::AsyncIo { @@ -333,6 +504,7 @@ impl QueueState { class, preferred_network, config, + global, ) { self.continuation_streak[class_index] = self.continuation_streak[class_index].saturating_add(1); @@ -340,7 +512,7 @@ impl QueueState { } } if let Some(task) = - self.remove_runnable_from(TaskPriority::Bulk, class, preferred_network, config) + self.remove_runnable_from(TaskPriority::Bulk, class, preferred_network, config, global) { self.continuation_streak[class_index] = 0; return Some(task); @@ -351,6 +523,7 @@ impl QueueState { class, preferred_network, config, + global, ) { self.continuation_streak[class_index] = 1; return Some(task); @@ -359,12 +532,79 @@ impl QueueState { None } - fn remove_runnable_from( + #[allow(clippy::too_many_arguments)] + fn pop_runnable_observed( + &mut self, + class: RunClass, + config: &TaskPoolConfig, + trace: &mut SchedulerTraceRecorder, + ready_frontier_len: usize, + ready_backlog_len: usize, + global: &mut G, + ) -> Option { + let class_index = run_index(class); + let force_bulk = self.continuation_streak[class_index] >= CONTINUATION_BURST; + let preferred_network = if class == RunClass::AsyncIo { + let selected = NETWORK_SCHEDULE[self.network_cursor % NETWORK_SCHEDULE.len()]; + self.network_cursor = (self.network_cursor + 1) % NETWORK_SCHEDULE.len(); + Some(selected) + } else { + None + }; + if !force_bulk { + if let Some(task) = self.remove_runnable_from_observed( + TaskPriority::Continuation, + class, + preferred_network, + config, + trace, + ready_frontier_len, + ready_backlog_len, + global, + ) { + self.continuation_streak[class_index] = + self.continuation_streak[class_index].saturating_add(1); + return Some(task); + } + } + if let Some(task) = self.remove_runnable_from_observed( + TaskPriority::Bulk, + class, + preferred_network, + config, + trace, + ready_frontier_len, + ready_backlog_len, + global, + ) { + self.continuation_streak[class_index] = 0; + return Some(task); + } + if force_bulk { + if let Some(task) = self.remove_runnable_from_observed( + TaskPriority::Continuation, + class, + preferred_network, + config, + trace, + ready_frontier_len, + ready_backlog_len, + global, + ) { + self.continuation_streak[class_index] = 1; + return Some(task); + } + } + None + } + + fn remove_runnable_from( &mut self, priority: TaskPriority, class: RunClass, preferred_network: Option, config: &TaskPoolConfig, + global: &mut G, ) -> Option { let cache = self .admission_cache @@ -387,6 +627,7 @@ impl QueueState { config, &cache.snapshot, &queue_admission.volume_depth, + global, ); if let Some(ref queued) = selected { self.admission_cache @@ -396,9 +637,64 @@ impl QueueState { } selected } + + #[allow(clippy::too_many_arguments)] + fn remove_runnable_from_observed( + &mut self, + priority: TaskPriority, + class: RunClass, + preferred_network: Option, + config: &TaskPoolConfig, + trace: &mut SchedulerTraceRecorder, + ready_frontier_len: usize, + ready_backlog_len: usize, + global: &mut G, + ) -> Option { + let cache = self + .admission_cache + .as_ref() + .expect("admission cache must exist while selecting tasks"); + let (queue, queue_admission) = match priority { + TaskPriority::Continuation => (&mut self.continuation, &cache.continuation), + TaskPriority::Bulk => (&mut self.bulk, &cache.bulk), + }; + if !queue_admission.has_run(class) { + return None; + } + let preferred_network = + preferred_network.filter(|network| queue_admission.has_network(*network)); + let selected = remove_runnable_observed( + queue, + priority, + class, + preferred_network, + &self.resources, + config, + &cache.snapshot, + &queue_admission.volume_depth, + trace, + global, + ); + if let Some((index, ref queued)) = selected { + trace.decision( + ready_frontier_len, + ready_backlog_len, + priority, + index, + queued.resources.run, + queued.resources.network, + false, + ); + self.admission_cache + .as_mut() + .expect("admission cache must exist while selecting tasks") + .remove_task(priority, queued); + } + selected.map(|(_, queued)| queued) + } } -fn remove_runnable( +fn remove_runnable( queue: &mut VecDeque, class: RunClass, preferred_network: Option, @@ -406,6 +702,7 @@ fn remove_runnable( config: &TaskPoolConfig, admission: &AdmissionSnapshot, volume_depth: &HashMap, + global: &mut G, ) -> Option { let now = Instant::now(); let preferred = runnable_index( @@ -417,8 +714,13 @@ fn remove_runnable( admission, volume_depth, now, + global, ); - let fallback = preferred.or_else(|| { + // An unrestricted probe has already checked the entire eligible lane. + // Only retry when relaxing a real network-class restriction. + let fallback = if preferred.is_some() || preferred_network.is_none() { + preferred + } else { runnable_index( queue, class, @@ -428,13 +730,105 @@ fn remove_runnable( admission, volume_depth, now, + global, ) - }); + }; fallback.and_then(|index| queue.remove(index)) } #[allow(clippy::too_many_arguments)] -fn runnable_index( +fn remove_runnable_observed( + queue: &mut VecDeque, + priority: TaskPriority, + class: RunClass, + preferred_network: Option, + resources: &ResourceState, + config: &TaskPoolConfig, + admission: &AdmissionSnapshot, + volume_depth: &HashMap, + trace: &mut SchedulerTraceRecorder, + global: &mut G, +) -> Option<(usize, QueuedTask)> { + let now = Instant::now(); + let preferred = runnable_index_observed( + queue, + priority, + class, + preferred_network, + resources, + config, + admission, + volume_depth, + now, + trace, + global, + ); + // An unrestricted probe has already checked the entire eligible lane. + // Only retry when relaxing a real network-class restriction. + let fallback = if preferred.is_some() || preferred_network.is_none() { + preferred + } else { + runnable_index_observed( + queue, + priority, + class, + None, + resources, + config, + admission, + volume_depth, + now, + trace, + global, + ) + }; + let index = fallback?; + queue.remove(index).map(|queued| (index, queued)) +} + +fn candidate_priority_key( + index: usize, + queued: &QueuedTask, + admission: &AdmissionSnapshot, + volume_depth: &HashMap, + now: Instant, +) -> (Reverse, u8, u8, Reverse, u64, usize) { + let age_bucket = now.saturating_duration_since(queued.enqueued_at).as_secs() / 5; + let backlog = queued + .resources + .read_volumes + .iter() + .chain(&queued.resources.write_volumes) + .chain(&queued.resources.metadata_volumes) + .map(|volume| volume_depth.get(volume.as_str()).copied().unwrap_or(0)) + .sum::(); + let reserved_writer_rank = if queued + .resources + .write_volumes + .iter() + .any(|volume| admission.reserved_write_volumes.contains(volume)) + { + 0 + } else { + 1 + }; + let metadata_rank = if queued.resources.metadata_volumes.is_empty() { + 1 + } else { + 0 + }; + ( + Reverse(age_bucket), + reserved_writer_rank, + metadata_rank, + Reverse(backlog), + queued.resources.priority_cost, + index, + ) +} + +#[allow(clippy::too_many_arguments)] +fn runnable_index( queue: &VecDeque, class: RunClass, network: Option, @@ -443,81 +837,177 @@ fn runnable_index( admission: &AdmissionSnapshot, volume_depth: &HashMap, now: Instant, + global: &mut G, ) -> Option { - let runnable = |queued: &QueuedTask| { - queued.resources.run == class - && network.is_none_or(|selected| queued.resources.network == Some(selected)) - && resources.can_acquire(&queued.resources, config, admission) - }; - let priority = |index: usize, queued: &QueuedTask| { - let age_bucket = now.saturating_duration_since(queued.enqueued_at).as_secs() / 5; - let backlog = queued - .resources - .read_volumes - .iter() - .chain(&queued.resources.write_volumes) - .chain(&queued.resources.metadata_volumes) - .map(|volume| volume_depth.get(volume.as_str()).copied().unwrap_or(0)) - .sum::(); - let reserved_writer_rank = if queued - .resources - .write_volumes - .iter() - .any(|volume| admission.reserved_write_volumes.contains(volume)) + let mut selected = None; + for (index, queued) in queue.iter().enumerate().take(PRIORITY_LOOKAHEAD) { + if queued.resources.run != class + || network.is_some_and(|selected| queued.resources.network != Some(selected)) + || !resources.can_acquire(&queued.resources, config, admission) + || !global.allows(&queued.resources) { - 0 - } else { - 1 - }; - let metadata_rank = if queued.resources.metadata_volumes.is_empty() { - 1 - } else { - 0 - }; - ( - Reverse(age_bucket), - reserved_writer_rank, - metadata_rank, - Reverse(backlog), - queued.resources.estimated_bytes, + continue; + } + let key = candidate_priority_key(index, queued, admission, volume_depth, now); + if selected + .as_ref() + .is_none_or(|(best_key, _)| key < *best_key) + { + selected = Some((key, index)); + } + } + if let Some((_, index)) = selected { + return Some(index); + } + + for (index, queued) in queue.iter().enumerate().skip(PRIORITY_LOOKAHEAD) { + if queued.resources.run != class + || network.is_some_and(|selected| queued.resources.network != Some(selected)) + || !resources.can_acquire(&queued.resources, config, admission) + || !global.allows(&queued.resources) + { + continue; + } + return Some(index); + } + None +} + +#[allow(clippy::too_many_arguments)] +fn runnable_index_observed( + queue: &VecDeque, + priority: TaskPriority, + class: RunClass, + network: Option, + resources: &ResourceState, + config: &TaskPoolConfig, + admission: &AdmissionSnapshot, + volume_depth: &HashMap, + now: Instant, + trace: &mut SchedulerTraceRecorder, + global: &mut G, +) -> Option { + let mut selected = None; + for (index, queued) in queue.iter().enumerate().take(PRIORITY_LOOKAHEAD) { + if queued.resources.run != class + || network.is_some_and(|selected| queued.resources.network != Some(selected)) + { + continue; + } + let mut blocked_by = resources.explain_block(&queued.resources, config, admission); + if blocked_by.is_empty() { + blocked_by.extend(global.explain_block(&queued.resources)); + } + let runnable = blocked_by.is_empty(); + trace.considered( + queued.node_id, + priority, index, - ) - }; + queued.resources.run, + queued.resources.network, + false, + blocked_by, + ); + if runnable { + let key = candidate_priority_key(index, queued, admission, volume_depth, now); + if selected + .as_ref() + .is_none_or(|(best_key, _)| key < *best_key) + { + selected = Some((key, index)); + } + } + } + if let Some((_, index)) = selected { + return Some(index); + } - queue - .iter() - .enumerate() - .take(PRIORITY_LOOKAHEAD) - .filter(|(_, queued)| runnable(queued)) - .min_by_key(|(index, queued)| priority(*index, queued)) - .map(|(index, _)| index) - .or_else(|| { - queue - .iter() - .enumerate() - .skip(PRIORITY_LOOKAHEAD) - .find(|(_, queued)| runnable(queued)) - .map(|(index, _)| index) - }) + for (index, queued) in queue.iter().enumerate().skip(PRIORITY_LOOKAHEAD) { + if queued.resources.run != class + || network.is_some_and(|selected| queued.resources.network != Some(selected)) + { + continue; + } + let mut blocked_by = resources.explain_block(&queued.resources, config, admission); + if blocked_by.is_empty() { + blocked_by.extend(global.explain_block(&queued.resources)); + } + let runnable = blocked_by.is_empty(); + trace.considered( + queued.node_id, + priority, + index, + queued.resources.run, + queued.resources.network, + false, + blocked_by, + ); + if runnable { + return Some(index); + } + } + None } -fn md5_verify_batch_index( +fn md5_verify_batch_index( queue: &VecDeque, resources: &ResourceState, config: &TaskPoolConfig, admission: &AdmissionSnapshot, + global: &mut G, ) -> Option { - queue.iter().position(|queued| { + for (index, queued) in queue.iter().enumerate() { if !crate::task_pool::verify::is_md5_verify_task(&queued.task) { - return false; + continue; } let mut batch_resources = queued.resources.clone(); // The whole SIMD batch runs on one blocking worker. Additional streams // reserve only their I/O pressure; the first stream already owns the // batch's single CPU slot. batch_resources.run = RunClass::AsyncIo; - resources.can_acquire(&batch_resources, config, admission) - }) + if resources.can_acquire(&batch_resources, config, admission) + && global.allows(&batch_resources) + { + return Some(index); + } + } + None +} + +fn md5_verify_batch_index_observed( + queue: &VecDeque, + priority: TaskPriority, + resources: &ResourceState, + config: &TaskPoolConfig, + admission: &AdmissionSnapshot, + trace: &mut SchedulerTraceRecorder, + global: &mut G, +) -> Option { + for (index, queued) in queue.iter().enumerate() { + if !crate::task_pool::verify::is_md5_verify_task(&queued.task) { + continue; + } + let mut batch_resources = queued.resources.clone(); + batch_resources.run = RunClass::AsyncIo; + let mut blocked_by = resources.explain_block(&batch_resources, config, admission); + if blocked_by.is_empty() { + blocked_by.extend(global.explain_block(&batch_resources)); + } + let runnable = blocked_by.is_empty(); + trace.considered( + queued.node_id, + priority, + index, + batch_resources.run, + batch_resources.network, + true, + blocked_by, + ); + if runnable { + return Some(index); + } + } + None } fn run_index(class: RunClass) -> usize { @@ -556,6 +1046,7 @@ pub(crate) struct ScheduledTask { pub(crate) resources: ResourceRequest, pub(crate) enqueued_at: Instant, pub(crate) started_at: Instant, + pub(crate) global_lease: Option, } #[derive(Debug, Default)] @@ -584,8 +1075,10 @@ impl SchedulerQueue { self.state.invalidate_admission_cache(); } + #[cfg(test)] pub(crate) fn restore_front(&mut self, mut scheduled: ScheduledTask) { self.state.resources.release(&scheduled.resources); + let global_lease = scheduled.global_lease.take(); // Batched MD5 followers temporarily borrow AsyncIo admission so one SIMD // worker owns the CPU slot. If dispatch is rejected, restore the task // with its canonical run class before putting it back on the queue. @@ -597,14 +1090,29 @@ impl SchedulerQueue { enqueued_at: scheduled.enqueued_at, }); self.state.invalidate_admission_cache(); + drop(global_lease); } + #[cfg(test)] pub(crate) fn pop_next( &mut self, config: &TaskPoolConfig, blocking_dispatch_available: bool, ) -> Option { - let queued = self.state.pop_next(config, blocking_dispatch_available)?; + let mut global = LocalOnlyAdmission; + self.pop_next_with_gate(config, blocking_dispatch_available, &mut global) + } + + fn pop_next_with_gate( + &mut self, + config: &TaskPoolConfig, + blocking_dispatch_available: bool, + global: &mut G, + ) -> Option { + let queued = self + .state + .pop_next(config, blocking_dispatch_available, global)?; + let global_lease = global.acquire(&queued.resources); self.state.resources.acquire(&queued.resources); Some(ScheduledTask { node_id: queued.node_id, @@ -612,16 +1120,105 @@ impl SchedulerQueue { resources: queued.resources, enqueued_at: queued.enqueued_at, started_at: Instant::now(), + global_lease, }) } + fn pop_next_observed_with_gate( + &mut self, + config: &TaskPoolConfig, + blocking_dispatch_available: bool, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + global: &mut G, + ) -> Option { + let queued = self.state.pop_next_observed( + config, + blocking_dispatch_available, + trace, + ready_backlog_len, + global, + )?; + let global_lease = global.acquire(&queued.resources); + self.state.resources.acquire(&queued.resources); + trace.admitted( + queued.node_id, + queued.resources.service_estimate, + self.state.resources.occupancy(config), + ); + Some(ScheduledTask { + node_id: queued.node_id, + task: queued.task, + resources: queued.resources, + enqueued_at: queued.enqueued_at, + started_at: Instant::now(), + global_lease, + }) + } + + #[cfg(test)] + pub(crate) fn pop_next_observed( + &mut self, + config: &TaskPoolConfig, + blocking_dispatch_available: bool, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + ) -> Option { + if trace.enabled() { + let mut global = LocalOnlyAdmission; + self.pop_next_observed_with_gate( + config, + blocking_dispatch_available, + trace, + ready_backlog_len, + &mut global, + ) + } else { + self.pop_next(config, blocking_dispatch_available) + } + } + + pub(crate) fn pop_next_observed_global( + &mut self, + config: &TaskPoolConfig, + blocking_dispatch_available: bool, + global: &GlobalCapacityRunner, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + ) -> Option { + global.with_admission(|admission| { + if trace.enabled() { + self.pop_next_observed_with_gate( + config, + blocking_dispatch_available, + trace, + ready_backlog_len, + admission, + ) + } else { + self.pop_next_with_gate(config, blocking_dispatch_available, admission) + } + }) + } + + #[cfg(test)] pub(crate) fn pop_md5_verify_batch_member( &mut self, config: &TaskPoolConfig, ) -> Option { - let queued = self.state.pop_md5_verify_for_batch(config)?; + let mut global = LocalOnlyAdmission; + self.pop_md5_verify_batch_member_with_gate(config, &mut global) + } + + fn pop_md5_verify_batch_member_with_gate( + &mut self, + config: &TaskPoolConfig, + global: &mut G, + ) -> Option { + let queued = self.state.pop_md5_verify_for_batch(config, global)?; let mut resources = queued.resources; resources.run = RunClass::AsyncIo; + let global_lease = global.acquire(&resources); self.state.resources.acquire(&resources); Some(ScheduledTask { node_id: queued.node_id, @@ -629,14 +1226,105 @@ impl SchedulerQueue { resources, enqueued_at: queued.enqueued_at, started_at: Instant::now(), + global_lease, }) } + fn pop_md5_verify_batch_member_observed_with_gate( + &mut self, + config: &TaskPoolConfig, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + global: &mut G, + ) -> Option { + let queued = self.state.pop_md5_verify_for_batch_observed( + config, + trace, + ready_backlog_len, + global, + )?; + let mut resources = queued.resources; + resources.run = RunClass::AsyncIo; + let global_lease = global.acquire(&resources); + self.state.resources.acquire(&resources); + trace.admitted( + queued.node_id, + resources.service_estimate, + self.state.resources.occupancy(config), + ); + Some(ScheduledTask { + node_id: queued.node_id, + task: queued.task, + resources, + enqueued_at: queued.enqueued_at, + started_at: Instant::now(), + global_lease, + }) + } + + pub(crate) fn pop_md5_verify_batch_member_observed_global( + &mut self, + config: &TaskPoolConfig, + global: &GlobalCapacityRunner, + trace: &mut SchedulerTraceRecorder, + ready_backlog_len: usize, + ) -> Option { + global.with_admission(|admission| { + if trace.enabled() { + self.pop_md5_verify_batch_member_observed_with_gate( + config, + trace, + ready_backlog_len, + admission, + ) + } else { + self.pop_md5_verify_batch_member_with_gate(config, admission) + } + }) + } + + #[cfg(test)] pub(crate) fn release(&mut self, resources: &ResourceRequest) { self.state.resources.release(resources); self.state.invalidate_admission_cache(); } + pub(crate) fn release_observed( + &mut self, + node_id: NodeId, + resources: &ResourceRequest, + config: &TaskPoolConfig, + trace: &mut SchedulerTraceRecorder, + ) { + self.state.resources.release(resources); + if trace.enabled() { + trace.released(node_id, self.state.resources.occupancy(config)); + } + self.state.invalidate_admission_cache(); + } + + pub(crate) fn restore_front_observed( + &mut self, + mut scheduled: ScheduledTask, + config: &TaskPoolConfig, + trace: &mut SchedulerTraceRecorder, + ) { + self.state.resources.release(&scheduled.resources); + let global_lease = scheduled.global_lease.take(); + if trace.enabled() { + trace.released(scheduled.node_id, self.state.resources.occupancy(config)); + } + scheduled.resources.run = run_class(&scheduled.task); + self.state.continuation.push_front(QueuedTask { + node_id: scheduled.node_id, + task: scheduled.task, + resources: scheduled.resources, + enqueued_at: scheduled.enqueued_at, + }); + self.state.invalidate_admission_cache(); + drop(global_lease); + } + pub(crate) fn queued_len(&self) -> usize { self.state .continuation diff --git a/crates/griffr-runtime/src/task_pool/scheduler/queue/resources.rs b/crates/griffr-runtime/src/task_pool/scheduler/queue/resources.rs index af9397d..9149e78 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/queue/resources.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/queue/resources.rs @@ -1,7 +1,12 @@ +use std::collections::{BTreeMap, BTreeSet}; + use rapidhash::{RapidHashMap as HashMap, RapidHashSet as HashSet}; use super::super::routing::{ResourceRequest, RunClass}; -use crate::task_pool::{TaskPoolConfig, VolumeStreamingMode}; +use crate::task_pool::{ + AdmissionBlockReason, ResourceOccupancy, TaskPoolConfig, VolumeResourceOccupancy, + VolumeStreamingMode, +}; #[derive(Debug, Default)] pub(crate) struct AdmissionSnapshot { @@ -27,17 +32,68 @@ pub(crate) struct ResourceState { } impl ResourceState { + pub(crate) fn occupancy(&self, config: &TaskPoolConfig) -> ResourceOccupancy { + let mut volume_keys = BTreeSet::new(); + volume_keys.extend(self.volume_reads.keys().cloned()); + volume_keys.extend(self.volume_writes.keys().cloned()); + volume_keys.extend(self.volume_metadata.keys().cloned()); + volume_keys.extend(self.storage_reserved_bytes.keys().cloned()); + + let volumes = volume_keys + .into_iter() + .map(|volume| { + let policy = config.volume_policy(&volume); + let reads_used = self.volume_reads.get(&volume).copied().unwrap_or(0); + let writes_used = self.volume_writes.get(&volume).copied().unwrap_or(0); + let metadata_used = self.volume_metadata.get(&volume).copied().unwrap_or(0); + let streaming_pressure_used = match policy.streaming_mode { + VolumeStreamingMode::Exclusive => reads_used.max(writes_used), + VolumeStreamingMode::Mixed => reads_used.saturating_add(writes_used), + }; + VolumeResourceOccupancy { + volume, + reads_used, + reads_cap: policy.read_limit, + writes_used, + writes_cap: policy.write_limit, + metadata_used, + metadata_cap: policy.metadata_limit, + streaming_pressure_used, + streaming_pressure_cap: policy.streaming_pressure_limit, + } + }) + .collect(); + + ResourceOccupancy { + cpu_used: self.cpu_in_use, + cpu_cap: config.cpu_slots, + network_used: self.network_in_use, + network_cap: config.network_slots, + blocking_used: self.blocking_in_use, + blocking_cap: config.blocking_slots, + extract_used: self.extract_in_use, + extract_cap: config.extract_slots, + reuse_commits_used: self.reuse_commits_in_use, + mutation_paths_used: self.mutation_paths.len(), + storage_reserved_bytes: self + .storage_reserved_bytes + .iter() + .map(|(volume, bytes)| (volume.clone(), *bytes)) + .collect::>(), + volumes, + } + } + pub(crate) fn can_acquire( &self, request: &ResourceRequest, config: &TaskPoolConfig, admission: &AdmissionSnapshot, ) -> bool { - match request.run { - RunClass::AsyncIo => {} - RunClass::Cpu if self.cpu_in_use >= config.cpu_slots => return false, - RunClass::Blocking if self.blocking_in_use >= config.blocking_slots => return false, - RunClass::Cpu | RunClass::Blocking => {} + if (request.uses_cpu() && self.cpu_in_use >= config.cpu_slots) + || (request.run == RunClass::Blocking && self.blocking_in_use >= config.blocking_slots) + { + return false; } if request.network.is_some() && self.network_in_use >= config.network_slots { return false; @@ -101,6 +157,180 @@ impl ResourceState { true } + /// Return every resource constraint that currently blocks `request`. + /// + /// This is deliberately separate from `can_acquire`: the production fast + /// path stays boolean/allocation-free, while measurement builds can pay for + /// richer diagnostics only when tracing is enabled. + pub(crate) fn explain_block( + &self, + request: &ResourceRequest, + config: &TaskPoolConfig, + admission: &AdmissionSnapshot, + ) -> Vec { + let mut reasons = Vec::new(); + + if request.uses_cpu() && self.cpu_in_use >= config.cpu_slots { + reasons.push(AdmissionBlockReason::Cpu); + } + if request.run == RunClass::Blocking && self.blocking_in_use >= config.blocking_slots { + reasons.push(AdmissionBlockReason::Blocking); + } + if request.network.is_some() && self.network_in_use >= config.network_slots { + reasons.push(AdmissionBlockReason::Network); + } + if request.extract && self.extract_in_use >= config.extract_slots { + reasons.push(AdmissionBlockReason::Extract); + } + if request.reuse_probe + && self + .reuse_commits_in_use + .saturating_add(admission.queued_reuse_commits) + >= config.reuse_queue_limit.max(1) + { + reasons.push(AdmissionBlockReason::ReuseQueue); + } + for volume in &request.archive_save_volumes { + if self.archive_savers.get(volume).copied().unwrap_or(0) > 0 { + reasons.push(AdmissionBlockReason::ArchiveSave(volume.clone())); + } + } + for (volume, cross_volume) in &request.archive_commit_volumes { + let limit = if *cross_volume { 3 } else { 1 }; + if self.archive_commits.get(volume).copied().unwrap_or(0) >= limit { + reasons.push(AdmissionBlockReason::ArchiveCommit(volume.clone())); + } + } + if self.has_mutation_conflict(&request.mutation_paths) { + reasons.push(AdmissionBlockReason::MutationConflict); + } + for reservation in &request.storage_reservations { + let active = self + .storage_reserved_bytes + .get(&reservation.volume) + .copied() + .unwrap_or(0); + if active == 0 { + continue; + } + let Some(available) = admission + .storage_available_bytes + .get(&reservation.volume) + .copied() + .flatten() + else { + continue; + }; + if !storage_reservation_fits(active, reservation.bytes, available) { + reasons.push(AdmissionBlockReason::StorageReservation( + reservation.volume.clone(), + )); + } + } + + let mut explained_volumes = HashSet::default(); + for volume in request + .read_volumes + .iter() + .chain(&request.write_volumes) + .chain(&request.metadata_volumes) + { + if explained_volumes.insert(volume.clone()) { + self.explain_volume_block(request, config, admission, volume, &mut reasons); + } + } + + reasons + } + + fn explain_volume_block( + &self, + request: &ResourceRequest, + config: &TaskPoolConfig, + admission: &AdmissionSnapshot, + volume: &str, + reasons: &mut Vec, + ) { + let policy = config.volume_policy(volume); + let wants_read = request + .read_volumes + .iter() + .any(|item| item.as_str() == volume); + let wants_write = request + .write_volumes + .iter() + .any(|item| item.as_str() == volume); + let wants_metadata = request + .metadata_volumes + .iter() + .any(|item| item.as_str() == volume); + let reads = self.volume_reads.get(volume).copied().unwrap_or(0); + let writes = self.volume_writes.get(volume).copied().unwrap_or(0); + let metadata = self.volume_metadata.get(volume).copied().unwrap_or(0); + + if reads.saturating_add(usize::from(wants_read)) > policy.read_limit { + reasons.push(AdmissionBlockReason::VolumeRead(volume.to_owned())); + } + if writes.saturating_add(usize::from(wants_write)) > policy.write_limit { + reasons.push(AdmissionBlockReason::VolumeWrite(volume.to_owned())); + } + if metadata.saturating_add(usize::from(wants_metadata)) > policy.metadata_limit { + reasons.push(AdmissionBlockReason::Metadata(volume.to_owned())); + } + + let (current_pressure, requested_pressure, exclusive_conflict) = match policy.streaming_mode + { + VolumeStreamingMode::Exclusive => { + let conflict = (wants_read && writes > 0) + || (wants_write && reads > 0) + || (wants_metadata && (reads > 0 || writes > 0)) + || ((wants_read || wants_write) && metadata > 0); + ( + reads.max(writes), + usize::from(wants_read || wants_write), + conflict, + ) + } + VolumeStreamingMode::Mixed => ( + reads.saturating_add(writes), + usize::from(wants_read).saturating_add(usize::from(wants_write)), + false, + ), + }; + if exclusive_conflict { + reasons.push(AdmissionBlockReason::VolumeStreaming(volume.to_owned())); + } + + if matches!(policy.streaming_mode, VolumeStreamingMode::Exclusive) + && admission.reserved_write_volumes.contains(volume) + && !wants_write + && wants_metadata + { + reasons.push(AdmissionBlockReason::WriterReservation(volume.to_owned())); + } + + let reserve_for_waiting_writer = usize::from( + admission.reserved_write_volumes.contains(volume) + && requested_pressure > 0 + && !wants_write + && writes < policy.write_limit, + ); + if current_pressure + .saturating_add(requested_pressure) + .saturating_add(reserve_for_waiting_writer) + > policy.streaming_pressure_limit + { + if reserve_for_waiting_writer > 0 + && current_pressure.saturating_add(requested_pressure) + <= policy.streaming_pressure_limit + { + reasons.push(AdmissionBlockReason::WriterReservation(volume.to_owned())); + } else { + reasons.push(AdmissionBlockReason::VolumeStreaming(volume.to_owned())); + } + } + } + fn can_acquire_volume( &self, request: &ResourceRequest, @@ -202,10 +432,11 @@ impl ResourceState { } pub(crate) fn acquire(&mut self, request: &ResourceRequest) { - match request.run { - RunClass::AsyncIo => {} - RunClass::Cpu => self.cpu_in_use = self.cpu_in_use.saturating_add(1), - RunClass::Blocking => self.blocking_in_use = self.blocking_in_use.saturating_add(1), + if request.uses_cpu() { + self.cpu_in_use = self.cpu_in_use.saturating_add(1); + } + if request.run == RunClass::Blocking { + self.blocking_in_use = self.blocking_in_use.saturating_add(1); } if request.network.is_some() { self.network_in_use = self.network_in_use.saturating_add(1); @@ -243,10 +474,11 @@ impl ResourceState { } pub(crate) fn release(&mut self, request: &ResourceRequest) { - match request.run { - RunClass::AsyncIo => {} - RunClass::Cpu => self.cpu_in_use = self.cpu_in_use.saturating_sub(1), - RunClass::Blocking => self.blocking_in_use = self.blocking_in_use.saturating_sub(1), + if request.uses_cpu() { + self.cpu_in_use = self.cpu_in_use.saturating_sub(1); + } + if request.run == RunClass::Blocking { + self.blocking_in_use = self.blocking_in_use.saturating_sub(1); } if request.network.is_some() { self.network_in_use = self.network_in_use.saturating_sub(1); @@ -331,8 +563,12 @@ mod tests { use super::{ mutation_paths_conflict, storage_reservation_fits, AdmissionSnapshot, ResourceState, }; - use crate::task_pool::scheduler::routing::{ResourceRequest, StorageReservation}; - use crate::task_pool::TaskPoolConfig; + use crate::task_pool::scheduler::routing::{ + NetworkClass, ResourceRequest, RunClass, StorageReservation, + }; + use crate::task_pool::{ + AdmissionBlockReason, TaskPoolConfig, VolumeIoPolicy, VolumeStreamingMode, + }; use std::path::PathBuf; #[test] @@ -419,4 +655,197 @@ mod tests { )); assert!(!mutation_paths_conflict("c:/games", "c:/games-old")); } + fn assert_explanation_matches_fast_path( + state: &ResourceState, + request: &ResourceRequest, + config: &TaskPoolConfig, + admission: &AdmissionSnapshot, + ) -> Vec { + let reasons = state.explain_block(request, config, admission); + assert_eq!( + reasons.is_empty(), + state.can_acquire(request, config, admission), + "diagnostic path diverged from production admission: {reasons:?}" + ); + reasons + } + + #[test] + fn admission_explanation_matches_fast_path_for_scalar_limits() { + let config = TaskPoolConfig { + cpu_slots: 1, + blocking_slots: 1, + network_slots: 1, + extract_slots: 1, + reuse_queue_limit: 1, + ..TaskPoolConfig::default() + }; + let admission = AdmissionSnapshot { + queued_reuse_commits: 1, + ..AdmissionSnapshot::default() + }; + let mut state = ResourceState { + cpu_in_use: 1, + blocking_in_use: 1, + network_in_use: 1, + extract_in_use: 1, + ..ResourceState::default() + }; + + let cpu = ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }; + assert_eq!( + assert_explanation_matches_fast_path(&state, &cpu, &config, &admission), + vec![AdmissionBlockReason::Cpu] + ); + + let blocking = ResourceRequest { + run: RunClass::Blocking, + ..ResourceRequest::default() + }; + assert_eq!( + assert_explanation_matches_fast_path(&state, &blocking, &config, &admission), + vec![AdmissionBlockReason::Blocking] + ); + + let network = ResourceRequest { + run: RunClass::AsyncIo, + network: Some(NetworkClass::General), + ..ResourceRequest::default() + }; + assert_eq!( + assert_explanation_matches_fast_path(&state, &network, &config, &admission), + vec![AdmissionBlockReason::Network] + ); + + state.blocking_in_use = 0; + let extract = ResourceRequest { + run: RunClass::Blocking, + extract: true, + ..ResourceRequest::default() + }; + assert_eq!( + assert_explanation_matches_fast_path(&state, &extract, &config, &admission), + vec![AdmissionBlockReason::Extract] + ); + + let reuse = ResourceRequest { + run: RunClass::AsyncIo, + reuse_probe: true, + ..ResourceRequest::default() + }; + assert_eq!( + assert_explanation_matches_fast_path(&state, &reuse, &config, &admission), + vec![AdmissionBlockReason::ReuseQueue] + ); + } + + #[test] + fn admission_explanation_reports_archive_mutation_and_storage_limits() { + let config = TaskPoolConfig::default(); + let mut state = ResourceState::default(); + state.archive_savers.insert("save".to_owned(), 1); + state.archive_commits.insert("commit".to_owned(), 1); + state.mutation_paths.insert("root/active".to_owned()); + state.storage_reserved_bytes.insert("disk".to_owned(), 10); + let admission = AdmissionSnapshot { + storage_available_bytes: [("disk".to_owned(), Some(20))].into_iter().collect(), + ..AdmissionSnapshot::default() + }; + let request = ResourceRequest { + run: RunClass::AsyncIo, + archive_save_volumes: vec!["save".to_owned()], + archive_commit_volumes: vec![("commit".to_owned(), false)], + mutation_paths: vec!["root/active/file".to_owned()], + storage_reservations: vec![StorageReservation { + volume: "disk".to_owned(), + probe_path: PathBuf::from("disk"), + bytes: 11, + }], + ..ResourceRequest::default() + }; + + let reasons = assert_explanation_matches_fast_path(&state, &request, &config, &admission); + assert!(reasons.contains(&AdmissionBlockReason::ArchiveSave("save".to_owned()))); + assert!(reasons.contains(&AdmissionBlockReason::ArchiveCommit("commit".to_owned()))); + assert!(reasons.contains(&AdmissionBlockReason::MutationConflict)); + assert!(reasons.contains(&AdmissionBlockReason::StorageReservation("disk".to_owned()))); + } + + #[test] + fn admission_explanation_classifies_volume_limits_and_streaming_conflicts() { + let config = TaskPoolConfig { + default_volume_policy: VolumeIoPolicy::new(1, 1, 1, 2, VolumeStreamingMode::Exclusive), + ..TaskPoolConfig::default() + }; + let mut state = ResourceState::default(); + state.volume_reads.insert("disk".to_owned(), 1); + state.volume_writes.insert("disk".to_owned(), 1); + state.volume_metadata.insert("disk".to_owned(), 1); + let request = ResourceRequest { + run: RunClass::AsyncIo, + read_volumes: vec!["disk".to_owned()], + write_volumes: vec!["disk".to_owned()], + metadata_volumes: vec!["disk".to_owned()], + ..ResourceRequest::default() + }; + + let reasons = assert_explanation_matches_fast_path( + &state, + &request, + &config, + &AdmissionSnapshot::default(), + ); + assert!(reasons.contains(&AdmissionBlockReason::VolumeRead("disk".to_owned()))); + assert!(reasons.contains(&AdmissionBlockReason::VolumeWrite("disk".to_owned()))); + assert!(reasons.contains(&AdmissionBlockReason::Metadata("disk".to_owned()))); + assert!(reasons.contains(&AdmissionBlockReason::VolumeStreaming("disk".to_owned()))); + } + + #[test] + fn admission_explanation_identifies_waiting_writer_reservation() { + let config = TaskPoolConfig { + default_volume_policy: VolumeIoPolicy::new(4, 4, 4, 2, VolumeStreamingMode::Mixed), + ..TaskPoolConfig::default() + }; + let mut state = ResourceState::default(); + state.volume_reads.insert("disk".to_owned(), 1); + let admission = AdmissionSnapshot { + reserved_write_volumes: ["disk".to_owned()].into_iter().collect(), + ..AdmissionSnapshot::default() + }; + let request = ResourceRequest { + run: RunClass::AsyncIo, + read_volumes: vec!["disk".to_owned()], + ..ResourceRequest::default() + }; + + assert_eq!( + assert_explanation_matches_fast_path(&state, &request, &config, &admission), + vec![AdmissionBlockReason::WriterReservation("disk".to_owned())] + ); + } + + #[test] + fn admission_explanation_is_empty_when_bundle_is_feasible() { + let config = TaskPoolConfig::default(); + let request = ResourceRequest { + run: RunClass::Cpu, + network: Some(NetworkClass::Archive), + read_volumes: vec!["read".to_owned()], + write_volumes: vec!["write".to_owned()], + metadata_volumes: vec!["meta".to_owned()], + extract: true, + ..ResourceRequest::default() + }; + assert!(assert_explanation_matches_fast_path( + &ResourceState::default(), + &request, + &config, + &AdmissionSnapshot::default() + ) + .is_empty()); + } } diff --git a/crates/griffr-runtime/src/task_pool/scheduler/queue/tests.rs b/crates/griffr-runtime/src/task_pool/scheduler/queue/tests.rs index 70d6a1f..a073f71 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/queue/tests.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/queue/tests.rs @@ -1,9 +1,14 @@ use super::{AdmissionSnapshot, ResourceState, SchedulerQueue}; +use crate::task_pool::scheduler::observatory::SchedulerTraceRecorder; use crate::task_pool::scheduler::routing::{ResourceRequest, RunClass}; use crate::task_pool::scheduler::TaskPriority; -use crate::task_pool::{NodeId, Task, TaskPoolConfig, VolumeIoPolicy, VolumeStreamingMode}; +use crate::task_pool::{ + AdmissionBlockReason, NodeId, SchedulerTraceEventKind, Task, TaskPoolConfig, VolumeIoPolicy, + VolumeStreamingMode, +}; use crate::ContentHash; use std::path::PathBuf; +use std::time::Instant; fn task(name: &str) -> Task { Task::ApplyDeleteManifest { @@ -198,6 +203,109 @@ fn runnable_task_beyond_priority_lookahead_is_still_admitted() { queue.release(&selected.resources); } +#[test] +fn observed_selection_reports_priority_lookahead_exhaustion_without_changing_choice() { + let mut queue = SchedulerQueue::default(); + let config = TaskPoolConfig::default(); + for index in 0..64 { + queue.push( + NodeId::from_index(index), + task(&format!("blocking-{index}")), + ResourceRequest { + run: RunClass::Blocking, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + } + queue.push( + NodeId::from_index(64), + task("async-after-lookahead"), + ResourceRequest { + run: RunClass::AsyncIo, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + + let mut trace = SchedulerTraceRecorder::new(true, Instant::now()); + let selected = queue + .pop_next_observed(&config, false, &mut trace, 7) + .unwrap(); + assert!(matches!( + selected.task, + Task::ApplyDeleteManifest { ref install_root } + if install_root == &PathBuf::from("async-after-lookahead") + )); + queue.release(&selected.resources); + + let trace = trace + .finish() + .expect("trace finish") + .expect("trace enabled"); + let decision = trace.events.iter().find_map(|event| match &event.kind { + SchedulerTraceEventKind::Decision(decision) => Some(decision), + _ => None, + }); + let decision = decision.expect("selected task must emit a decision"); + assert_eq!(decision.ready_frontier_len, 65); + assert_eq!(decision.ready_backlog_len, 7); + assert_eq!(decision.candidate_index, 64); + assert!(decision.lookahead_exhausted); + assert!(!decision.batch_member); +} + +#[test] +fn observed_probe_reports_resource_block_without_forcing_an_admission() { + let mut queue = SchedulerQueue::default(); + let mut config = TaskPoolConfig { + cpu_slots: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + for index in 0..2 { + queue.push( + NodeId::from_index(index), + task(&format!("cpu-{index}")), + ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + } + + let first = queue.pop_next(&config, true).unwrap(); + let mut trace = SchedulerTraceRecorder::new(true, Instant::now()); + assert!(queue + .pop_next_observed(&config, true, &mut trace, 0) + .is_none()); + let trace = trace + .finish() + .expect("trace finish") + .expect("trace enabled"); + let blocked_probes = trace + .events + .iter() + .filter(|event| { + matches!( + &event.kind, + SchedulerTraceEventKind::Considered { blocked_by, .. } + if blocked_by.contains(&AdmissionBlockReason::Cpu) + ) + }) + .count(); + assert_eq!( + blocked_probes, 1, + "an unrestricted CPU probe must not scan the same lane twice" + ); + assert!(queue.pop_next(&config, true).is_none()); + queue.release(&first.resources); + let remaining = queue.pop_next(&config, true).unwrap(); + assert_eq!(remaining.node_id, NodeId::from_index(1)); + queue.release(&remaining.resources); +} + #[test] fn volume_writer_blocks_only_the_same_volume() { let mut queue = SchedulerQueue::default(); @@ -455,10 +563,10 @@ fn runnable_tasks_prefer_smaller_work_on_the_same_backlogged_volume() { let config = TaskPoolConfig::default(); let mut large = resources("volume-a"); large.run = RunClass::Blocking; - large.estimated_bytes = 1024; + large.priority_cost = 1024; let mut small = resources("volume-a"); small.run = RunClass::Blocking; - small.estimated_bytes = 1; + small.priority_cost = 1; queue.push( NodeId::from_index(0), task("large"), @@ -602,9 +710,9 @@ fn cached_admission_expires_when_writer_reservation_becomes_due() { }; let mut writer = write("volume-a"); writer.run = RunClass::AsyncIo; - writer.estimated_bytes = 100; + writer.priority_cost = 100; let mut reader = read("volume-a"); - reader.estimated_bytes = 1; + reader.priority_cost = 1; queue.push( NodeId::from_index(0), task("writer"), @@ -632,3 +740,436 @@ fn cached_admission_expires_when_writer_reservation_becomes_due() { )); assert_eq!(queue.admission_rebuilds(), 2); } + +#[test] +#[ignore = "M1 measurement probe; run explicitly with --ignored --nocapture"] +fn m1_trace_overhead_probe() { + const ITERATIONS: usize = 20_000; + + fn direct(iterations: usize) -> std::time::Duration { + let config = TaskPoolConfig::default(); + let mut queue = SchedulerQueue::default(); + queue.push( + NodeId::from_index(0), + task("m1-overhead"), + ResourceRequest { + run: RunClass::AsyncIo, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + let started = Instant::now(); + for _ in 0..iterations { + let scheduled = queue.pop_next(&config, true).unwrap(); + queue.release(&scheduled.resources); + queue.push( + scheduled.node_id, + scheduled.task, + scheduled.resources, + TaskPriority::Bulk, + ); + } + started.elapsed() + } + + fn observed(iterations: usize, enabled: bool) -> (std::time::Duration, usize) { + let config = TaskPoolConfig::default(); + let mut queue = SchedulerQueue::default(); + queue.push( + NodeId::from_index(0), + task("m1-overhead"), + ResourceRequest { + run: RunClass::AsyncIo, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + let mut trace = SchedulerTraceRecorder::new(enabled, Instant::now()); + let started = Instant::now(); + for _ in 0..iterations { + let scheduled = queue + .pop_next_observed(&config, true, &mut trace, 0) + .unwrap(); + queue.release_observed(scheduled.node_id, &scheduled.resources, &config, &mut trace); + queue.push( + scheduled.node_id, + scheduled.task, + scheduled.resources, + TaskPriority::Bulk, + ); + } + let elapsed = started.elapsed(); + let events = trace + .finish() + .expect("trace finish") + .map_or(0, |trace| trace.events.len()); + (elapsed, events) + } + + let direct = direct(ITERATIONS); + let (disabled, disabled_events) = observed(ITERATIONS, false); + let (enabled, enabled_events) = observed(ITERATIONS, true); + assert_eq!(disabled_events, 0); + assert!(enabled_events >= ITERATIONS * 4); + + let ns = |elapsed: std::time::Duration| elapsed.as_nanos() as f64 / ITERATIONS as f64; + println!( + "M1_TRACE_OVERHEAD iterations={ITERATIONS} direct_ns_per_selection={:.1} \ + disabled_ns_per_selection={:.1} enabled_ns_per_selection={:.1} \ + disabled_vs_direct={:.3} enabled_vs_direct={:.3} enabled_events={enabled_events}", + ns(direct), + ns(disabled), + ns(enabled), + disabled.as_secs_f64() / direct.as_secs_f64(), + enabled.as_secs_f64() / direct.as_secs_f64(), + ); +} + +#[test] +fn shared_global_capacity_blocks_a_second_runner_at_the_hard_limit() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + + let mut config = TaskPoolConfig { + cpu_slots: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let authority = GlobalCapacityAuthority::new(&config); + let runner_a = authority.register(); + let runner_b = authority.register(); + let mut queue_a = SchedulerQueue::default(); + let mut queue_b = SchedulerQueue::default(); + let cpu = ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }; + queue_a.push( + NodeId::from_index(0), + task("a"), + cpu.clone(), + TaskPriority::Bulk, + ); + queue_b.push(NodeId::from_index(1), task("b"), cpu, TaskPriority::Bulk); + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + + let first = queue_a + .pop_next_observed_global(&config, true, &runner_a, &mut trace, 0) + .unwrap(); + assert!(queue_b + .pop_next_observed_global(&config, true, &runner_b, &mut trace, 0) + .is_none()); + + queue_a.release(&first.resources); + drop(first); + let second = queue_b + .pop_next_observed_global(&config, true, &runner_b, &mut trace, 0) + .unwrap(); + queue_b.release(&second.resources); + drop(second); +} + +#[test] +fn idle_runner_does_not_reserve_its_nominal_global_share() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + + let mut config = TaskPoolConfig { + cpu_slots: 2, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let authority = GlobalCapacityAuthority::new(&config); + let _idle = authority.register(); + let busy = authority.register(); + let mut queue = SchedulerQueue::default(); + for index in 0..3 { + queue.push( + NodeId::from_index(index), + task(&format!("busy-{index}")), + ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + } + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + + let first = queue + .pop_next_observed_global(&config, true, &busy, &mut trace, 0) + .unwrap(); + let second = queue + .pop_next_observed_global(&config, true, &busy, &mut trace, 0) + .unwrap(); + assert!(queue + .pop_next_observed_global(&config, true, &busy, &mut trace, 0) + .is_none()); + + queue.release(&first.resources); + drop(first); + queue.release(&second.resources); + drop(second); +} + +#[test] +fn waking_runner_reclaims_released_capacity_before_borrower_can_reborrow() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + + let mut config = TaskPoolConfig { + cpu_slots: 2, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let authority = GlobalCapacityAuthority::new(&config); + let waking = authority.register(); + let borrower = authority.register(); + let mut waking_queue = SchedulerQueue::default(); + let mut borrower_queue = SchedulerQueue::default(); + let cpu = ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }; + waking_queue.push( + NodeId::from_index(0), + task("waking"), + cpu.clone(), + TaskPriority::Bulk, + ); + for index in 1..=3 { + borrower_queue.push( + NodeId::from_index(index), + task(&format!("borrower-{index}")), + cpu.clone(), + TaskPriority::Bulk, + ); + } + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + + let first = borrower_queue + .pop_next_observed_global(&config, true, &borrower, &mut trace, 0) + .unwrap(); + let second = borrower_queue + .pop_next_observed_global(&config, true, &borrower, &mut trace, 0) + .unwrap(); + // The borrower is already at its local/global hard limit, so its extra + // queued task cannot establish a speculative waiter ahead of real demand. + assert!(borrower_queue + .pop_next_observed_global(&config, true, &borrower, &mut trace, 0) + .is_none()); + assert!(waking_queue + .pop_next_observed_global(&config, true, &waking, &mut trace, 0) + .is_none()); + + borrower_queue.release(&first.resources); + drop(first); + // The first released slot is reserved for the waking runner; the borrower + // cannot immediately turn the released credit back into another borrow. + assert!(borrower_queue + .pop_next_observed_global(&config, true, &borrower, &mut trace, 0) + .is_none()); + let reclaimed = waking_queue + .pop_next_observed_global(&config, true, &waking, &mut trace, 0) + .unwrap(); + + borrower_queue.release(&second.resources); + drop(second); + waking_queue.release(&reclaimed.resources); + drop(reclaimed); +} + +#[test] +fn observed_global_denial_is_visible_in_m1_trace() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + + let mut config = TaskPoolConfig { + cpu_slots: 1, + scheduler_trace: true, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let authority = GlobalCapacityAuthority::new(&config); + let holder = authority.register(); + let waiter = authority.register(); + let mut holder_queue = SchedulerQueue::default(); + let mut waiter_queue = SchedulerQueue::default(); + let cpu = ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }; + holder_queue.push( + NodeId::from_index(0), + task("holder"), + cpu.clone(), + TaskPriority::Bulk, + ); + waiter_queue.push( + NodeId::from_index(1), + task("waiter"), + cpu, + TaskPriority::Bulk, + ); + let mut trace = SchedulerTraceRecorder::new(true, Instant::now()); + + let held = holder_queue + .pop_next_observed_global(&config, true, &holder, &mut trace, 0) + .unwrap(); + assert!(waiter_queue + .pop_next_observed_global(&config, true, &waiter, &mut trace, 0) + .is_none()); + let finished = trace.finish().unwrap().unwrap(); + assert!(finished.events.iter().any(|event| matches!( + &event.kind, + SchedulerTraceEventKind::Considered { blocked_by, .. } + if blocked_by.contains(&AdmissionBlockReason::GlobalCpu) + ))); + + holder_queue.release(&held.resources); + drop(held); +} + +#[test] +fn abandoned_admitted_task_releases_global_capacity_by_ownership() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + + let mut config = TaskPoolConfig { + cpu_slots: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let authority = GlobalCapacityAuthority::new(&config); + let runner = authority.register(); + let mut queue = SchedulerQueue::default(); + queue.push( + NodeId::from_index(0), + task("abandoned"), + ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + let scheduled = queue + .pop_next_observed_global(&config, true, &runner, &mut trace, 0) + .unwrap(); + assert_eq!(authority.snapshot().0.cpu, 1); + + // A runner-level error/shutdown drops its local queue state. The admitted + // task still owns the global lease, so abandoning that task returns the + // command-wide credit without a separate rollback protocol. + drop(queue); + drop(scheduled); + assert_eq!(authority.snapshot().0.cpu, 0); +} + +#[test] +fn restore_front_returns_global_capacity_before_retry() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + + let mut config = TaskPoolConfig { + blocking_slots: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let authority = GlobalCapacityAuthority::new(&config); + let runner = authority.register(); + let mut queue = SchedulerQueue::default(); + queue.push( + NodeId::from_index(0), + task("retry"), + ResourceRequest { + run: RunClass::Blocking, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + let scheduled = queue + .pop_next_observed_global(&config, true, &runner, &mut trace, 0) + .unwrap(); + assert_eq!(authority.snapshot().0.blocking, 1); + queue.restore_front(scheduled); + assert_eq!(authority.snapshot().0.blocking, 0); + + let scheduled = queue + .pop_next_observed_global(&config, true, &runner, &mut trace, 0) + .unwrap(); + queue.release(&scheduled.resources); + drop(scheduled); + assert_eq!(authority.snapshot().0.blocking, 0); +} + +#[test] +#[ignore = "M2 synthetic scheduler-accounting overhead probe; run explicitly with --ignored --nocapture"] +fn m2_shared_accounting_overhead_probe() { + use crate::task_pool::scheduler::global_capacity::GlobalCapacityAuthority; + use std::time::Duration; + + const ITERATIONS: usize = 20_000; + fn run_local(config: &TaskPoolConfig) -> Duration { + let mut queue = SchedulerQueue::default(); + queue.push( + NodeId::from_index(0), + task("local"), + ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + let started = Instant::now(); + for _ in 0..ITERATIONS { + let scheduled = queue.pop_next(config, true).unwrap(); + let node_id = scheduled.node_id; + let task = scheduled.task.clone(); + let resources = scheduled.resources.clone(); + queue.release(&scheduled.resources); + drop(scheduled); + queue.push(node_id, task, resources, TaskPriority::Bulk); + } + started.elapsed() + } + + fn run_global(config: &TaskPoolConfig) -> Duration { + let authority = GlobalCapacityAuthority::new(config); + let runner = authority.register(); + let mut queue = SchedulerQueue::default(); + queue.push( + NodeId::from_index(0), + task("global"), + ResourceRequest { + run: RunClass::Cpu, + ..ResourceRequest::default() + }, + TaskPriority::Bulk, + ); + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + let started = Instant::now(); + for _ in 0..ITERATIONS { + let scheduled = queue + .pop_next_observed_global(config, true, &runner, &mut trace, 0) + .unwrap(); + let node_id = scheduled.node_id; + let task = scheduled.task.clone(); + let resources = scheduled.resources.clone(); + queue.release(&scheduled.resources); + drop(scheduled); + queue.push(node_id, task, resources, TaskPriority::Bulk); + } + assert_eq!(authority.snapshot().0.cpu, 0); + started.elapsed() + } + + let mut config = TaskPoolConfig { + cpu_slots: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let local = run_local(&config); + let global = run_global(&config); + println!( + "M2_ACCOUNTING_OVERHEAD iterations={ITERATIONS} local_ns_per_cycle={:.1} global_ns_per_cycle={:.1} global_vs_local={:.3}", + local.as_nanos() as f64 / ITERATIONS as f64, + global.as_nanos() as f64 / ITERATIONS as f64, + global.as_secs_f64() / local.as_secs_f64(), + ); +} diff --git a/crates/griffr-runtime/src/task_pool/scheduler/routing.rs b/crates/griffr-runtime/src/task_pool/scheduler/routing.rs index fb0ad10..54ceb7d 100644 --- a/crates/griffr-runtime/src/task_pool/scheduler/routing.rs +++ b/crates/griffr-runtime/src/task_pool/scheduler/routing.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; use rapidhash::RapidHashMap as HashMap; use crate::download::extractor::safe_relative_archive_path; -use crate::task_pool::{ArchiveRangePriority, ArchiveSource, Task, TransferClass}; +use crate::task_pool::{ArchiveRangePriority, ArchiveSource, ServiceEstimate, Task, TransferClass}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum RunClass { @@ -31,6 +31,8 @@ pub(super) struct StorageReservation { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct ResourceRequest { pub(super) run: RunClass, + pub(super) cpu_on_async: bool, + pub(super) hdiff_decoder_start: bool, pub(super) network: Option, pub(super) read_volumes: Vec, pub(super) write_volumes: Vec, @@ -40,7 +42,8 @@ pub(super) struct ResourceRequest { pub(super) extract: bool, pub(super) mutation_paths: Vec, pub(super) storage_reservations: Vec, - pub(super) estimated_bytes: u64, + pub(super) service_estimate: ServiceEstimate, + pub(super) priority_cost: u64, pub(super) reuse_probe: bool, pub(super) reuse_commit: bool, } @@ -86,6 +89,8 @@ impl Default for ResourceRequest { fn default() -> Self { Self { run: RunClass::Blocking, + cpu_on_async: false, + hdiff_decoder_start: false, network: None, read_volumes: Vec::new(), write_volumes: Vec::new(), @@ -95,7 +100,8 @@ impl Default for ResourceRequest { extract: false, mutation_paths: Vec::new(), storage_reservations: Vec::new(), - estimated_bytes: 0, + service_estimate: ServiceEstimate::default(), + priority_cost: 0, reuse_probe: false, reuse_commit: false, } @@ -107,11 +113,18 @@ pub(super) fn task_resources(task: &Task) -> ResourceRequest { task_resources_cached(task, &mut VolumeKeyCache::default()) } +impl ResourceRequest { + pub(super) fn uses_cpu(&self) -> bool { + self.run == RunClass::Cpu || self.cpu_on_async + } +} + pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) -> ResourceRequest { let mut request = ResourceRequest { run: run_class(task), ..ResourceRequest::default() }; + request.service_estimate = task_service_estimate(task); match task { Task::FetchArchiveRange { request: range, @@ -467,52 +480,106 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - } crate::PlannedPatchSource::Local { payload } => { let source = patch.plan().stage_root.join(payload); - let source_volume = volume_key(volumes, &source); - let destination_volume = volume_key(volumes, &entry.destination); - request.read_volumes.push(source_volume.clone()); - request.write_volumes.push(destination_volume.clone()); - request.mutation_paths.push(path_key(&source)); - if source_volume != destination_volume { - reserve_storage( - &mut request, - &entry.destination, - entry.expected_size, - volumes, - ); - } + request.read_volumes.push(volume_key(volumes, &source)); + request + .write_volumes + .push(volume_key(volumes, &entry.destination)); + reserve_storage( + &mut request, + &entry.destination, + entry.expected_size, + volumes, + ); } - crate::PlannedPatchSource::Hdiff { base, payload, .. } => { - let payload_path = patch.plan().stage_root.join(payload); + crate::PlannedPatchSource::Hdiff { base, .. } => { request.read_volumes.push(volume_key(volumes, base)); request .read_volumes - .push(volume_key(volumes, &payload_path)); - request.mutation_paths.push(path_key(&payload_path)); - request - .write_volumes .push(volume_key(volumes, &entry.destination)); - if let Some(work_dir) = patch.plan().work_dir.as_deref() { - request.write_volumes.push(volume_key(volumes, work_dir)); - reserve_storage(&mut request, work_dir, entry.expected_size, volumes); - reserve_storage( - &mut request, - &entry.destination, - entry.expected_size, - volumes, - ); - } else { - reserve_storage( - &mut request, - &entry.destination, - entry.expected_size, - volumes, - ); - } + let temp_root = patch + .plan() + .work_dir + .as_deref() + .unwrap_or(&entry.destination); + request + .metadata_volumes + .push(volume_key(volumes, temp_root)); } } request.mutation_paths.push(path_key(&entry.destination)); } } + Task::DecodeHdiffPatchEntry { + patch, + entry_index, + prepared, + #[cfg(feature = "hdiff-patch")] + checkpoint, + .. + } => { + request.cpu_on_async = true; + #[cfg(feature = "hdiff-patch")] + { + request.hdiff_decoder_start = checkpoint.is_initial(); + } + if let Some(entry) = patch.entry(*entry_index) { + if let crate::PlannedPatchSource::Hdiff { base, payload, .. } = &entry.source { + request.read_volumes.push(volume_key(volumes, base)); + request + .read_volumes + .push(volume_key(volumes, &patch.plan().stage_root.join(payload))); + } + request + .write_volumes + .push(volume_key(volumes, prepared.path())); + request.mutation_paths.push(path_key(prepared.path())); + // The initial allocation needs the whole output. Confirmed + // allocation is already reflected in physical free space. + // Subsequent writes still acquire volume write pressure. + #[cfg(feature = "hdiff-patch")] + let preallocated = checkpoint.has_preallocated_output(); + #[cfg(not(feature = "hdiff-patch"))] + let preallocated = false; + let bytes = if request.hdiff_decoder_start { + entry.expected_size + } else if preallocated { + 0 + } else { + request.service_estimate.storage_write_bytes + }; + reserve_storage(&mut request, prepared.path(), bytes, volumes); + } + } + Task::CommitHdiffPatchEntry { + patch, + entry_index, + prepared, + } => { + if let Some(entry) = patch.entry(*entry_index) { + let prepared_volume = volume_key(volumes, prepared.path()); + request.read_volumes.push(prepared_volume.clone()); + // The continuation owner removes the prepared temporary before + // the WorkUnit returns, so phase B needs metadata authority on + // the prepared volume as well as read authority. + request.metadata_volumes.push(prepared_volume); + if prepared.copy_to_destination_temp() { + request + .write_volumes + .push(volume_key(volumes, &entry.destination)); + reserve_storage( + &mut request, + &entry.destination, + entry.expected_size, + volumes, + ); + } else { + request + .metadata_volumes + .push(volume_key(volumes, &entry.destination)); + } + request.mutation_paths.push(path_key(&entry.destination)); + } + } Task::ReleasePatchBase { base, .. } => { request.metadata_volumes.push(volume_key(volumes, base)); request.mutation_paths.push(path_key(base)); @@ -526,6 +593,10 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - } Task::CommitPatchDeferred { patch } => { let plan = patch.plan(); + request + .metadata_volumes + .push(volume_key(volumes, &plan.stage_root)); + request.mutation_paths.push(path_key(&plan.stage_root)); let mut destination_totals = BTreeMap::::new(); let deferred_root = crate::griffr_patch_path(&plan.install_root).join(crate::PATCH_DEFERRED_DIR); @@ -551,17 +622,23 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - reserve_storage(&mut request, &path, bytes, volumes); } } - Task::CleanPatchApply { patch, archive: _ } => { + Task::CleanPatchApply { patch, .. } => { let plan = patch.plan(); let patch_root = crate::griffr_patch_path(&plan.install_root); - request - .metadata_volumes - .push(volume_key(volumes, &plan.stage_root)); request .metadata_volumes .push(volume_key(volumes, &patch_root)); - request.mutation_paths.push(path_key(&plan.stage_root)); request.mutation_paths.push(path_key(&patch_root)); + if plan.is_extracted_manifest() { + for name in [ + crate::PATCH_MANIFEST_NAME, + crate::DELETE_FILES_MANIFEST_NAME, + ] { + request + .mutation_paths + .push(path_key(&plan.install_root.join(name))); + } + } } Task::CleanupArchive { work } => { request.metadata_volumes.extend( @@ -572,7 +649,7 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - ); } Task::ApplyExtractedVfsPatchManifest { install_root } => { - route_extracted_vfs_patch_manifest(&mut request, install_root, volumes); + request.read_volumes.push(volume_key(volumes, install_root)); } Task::ApplyDeleteManifest { install_root } => { request @@ -582,7 +659,7 @@ pub(super) fn task_resources_cached(task: &Task, volumes: &mut VolumeKeyCache) - } Task::RepairFile { .. } => {} } - request.estimated_bytes = task_estimated_bytes(task); + request.priority_cost = task_priority_cost(task); normalize_volumes(&mut request); request } @@ -612,6 +689,9 @@ fn route_prepare_patch_apply( request .read_volumes .push(volume_key(volumes, &plan.stage_root)); + request + .read_volumes + .push(volume_key(volumes, &plan.vfs_destination)); request .write_volumes .push(volume_key(volumes, &plan.install_root)); @@ -648,6 +728,9 @@ fn route_prepare_patch_apply( } fn patch_prepare_commit_files(plan: &crate::PatchPlan) -> Vec<(PathBuf, PathBuf, u64)> { + if plan.is_extracted_manifest() { + return Vec::new(); + } let deferred = plan.deferred_paths.iter().cloned().collect::>(); let mut files = Vec::new(); let mut pending = vec![plan.stage_root.clone()]; @@ -695,55 +778,6 @@ fn is_patch_control_path(relative: &Path) -> bool { || relative.starts_with(crate::PATCH_STAGE_DIR) } -fn route_extracted_vfs_patch_manifest( - request: &mut ResourceRequest, - install_root: &Path, - volumes: &mut VolumeKeyCache, -) { - let manifest_path = install_root.join(crate::PATCH_MANIFEST_NAME); - let stage_root = install_root.join(crate::PATCH_STAGE_DIR); - request - .read_volumes - .push(volume_key(volumes, &manifest_path)); - let manifest = std::fs::read(&manifest_path).ok().and_then(|bytes| { - serde_json::from_slice::(&bytes).ok() - }); - let Some(manifest) = manifest else { - let volume = volume_key(volumes, install_root); - request.read_volumes.push(volume.clone()); - request.write_volumes.push(volume); - request.mutation_paths.push(path_key(install_root)); - return; - }; - let Ok(vfs_base_path) = crate::task_pool::fs_ops::path_safety::parse_safe_relative_path( - "patch.json vfs_base_path", - manifest.vfs_base_path.trim(), - ) else { - request.mutation_paths.push(path_key(install_root)); - return; - }; - request.read_volumes.push(volume_key(volumes, &stage_root)); - let destination_root = install_root.join(vfs_base_path); - let mut destination_totals = BTreeMap::::new(); - for entry in manifest.files { - let Ok(relative) = crate::task_pool::fs_ops::path_safety::parse_safe_relative_path( - "patch.json file name", - &entry.name, - ) else { - continue; - }; - let destination = destination_root.join(relative); - let volume = volume_key(volumes, &destination); - request.read_volumes.push(volume.clone()); - request.write_volumes.push(volume); - request.mutation_paths.push(path_key(&destination)); - accumulate_storage(&mut destination_totals, &destination, entry.size, volumes); - } - for (_, (path, bytes)) in destination_totals { - reserve_storage(request, &path, bytes, volumes); - } -} - fn reserve_storage( request: &mut ResourceRequest, path: &Path, @@ -798,7 +832,241 @@ fn existing_file_len(path: &Path) -> u64 { .unwrap_or(0) } -fn task_estimated_bytes(task: &Task) -> u64 { +fn task_service_estimate(task: &Task) -> ServiceEstimate { + use crate::download::extractor::MultiVolumeExtractor; + + let mut estimate = ServiceEstimate::default(); + match task { + Task::FetchArchiveRange { request, .. } => { + let bytes = request + .local_range + .end + .saturating_sub(request.local_range.start); + estimate.network_bytes = bytes; + estimate.storage_write_bytes = bytes; + } + Task::FetchArchiveRepairFile { repair } => { + estimate.network_bytes = repair.source_bytes; + estimate.storage_write_bytes = repair.source_bytes; + } + Task::ExtractArchiveRepairFile { repair } => { + estimate.cpu_cost = repair.expected_size; + estimate.storage_read_bytes = repair.source_bytes; + estimate.storage_write_bytes = repair.expected_size; + } + Task::Download { + expected_size, + resume, + .. + } => { + if let Some(resume) = resume { + let bytes = expected_size + .map(|size| resume.remaining_bytes(size)) + .unwrap_or(0); + estimate.network_bytes = bytes; + estimate.storage_write_bytes = bytes; + } else if let Some(bytes) = expected_size { + // Preparation may hash a partial file before the network phase. + // Until the partial length is materialized in the task payload, + // expected_size is a conservative physical-read upper bound. + estimate.cpu_cost = *bytes; + estimate.storage_read_bytes = *bytes; + } + } + Task::Verify { expected_size, .. } => { + let bytes = expected_size.unwrap_or(0); + estimate.cpu_cost = bytes; + estimate.storage_read_bytes = bytes; + } + Task::VerifyMetadata { .. } => estimate.metadata_ops = 1, + Task::RepairFile { .. } => { + // RepairFile is a planning/continuation task; payload work is done + // by the child task selected at runtime. + estimate.cpu_cost = 1; + } + Task::VerifyReuseVolume { expected_size, .. } => { + estimate.cpu_cost = *expected_size; + estimate.storage_read_bytes = *expected_size; + } + Task::ReuseFile { + copy_only, + expected_size, + .. + } => { + estimate.storage_read_bytes = *expected_size; + if *copy_only { + estimate.storage_write_bytes = *expected_size; + } else { + estimate.cpu_cost = *expected_size; + estimate.metadata_ops = 1; + } + } + Task::OpenArchive { .. } => { + // Opening discovers metadata; full archive size is deliberately not + // reported as physical I/O because the task does not read it all. + estimate.metadata_ops = 1; + } + Task::DiscoverArchiveDirectory { + work, + required_range, + } => { + let tail = work.layout.tail_probe_range(); + estimate.storage_read_bytes = tail.end.saturating_sub(tail.start); + if let Some(range) = required_range { + estimate.storage_read_bytes = estimate + .storage_read_bytes + .saturating_add(range.end.saturating_sub(range.start)); + } + } + Task::InspectArchiveIndex { directory, .. } => { + estimate.storage_read_bytes = directory + .central_directory + .end + .saturating_sub(directory.central_directory.start) + .saturating_add( + directory + .end_records + .end + .saturating_sub(directory.end_records.start), + ); + estimate.cpu_cost = estimate.storage_read_bytes; + } + Task::ReadArchiveControls { archive_index, .. } => { + let indices = MultiVolumeExtractor::control_volume_indices(archive_index); + estimate.storage_read_bytes = + MultiVolumeExtractor::source_ranges_for_indices(archive_index, &indices) + .into_iter() + .fold(0u64, |total, range| { + total.saturating_add(range.end.saturating_sub(range.start)) + }); + estimate.cpu_cost = estimate.storage_read_bytes; + } + Task::ProbePatchArtifact { + patch_check, + probe_index, + } => { + let bytes = patch_check.probe_size(*probe_index).unwrap_or(0); + estimate.cpu_cost = bytes; + estimate.storage_read_bytes = bytes; + } + Task::MeasurePatchRelocation { .. } => estimate.metadata_ops = 1, + Task::SavePatchPlan { .. } => estimate.metadata_ops = 1, + Task::ExtractArchiveShard { shard } => { + estimate.cpu_cost = shard.estimated_cost; + estimate.storage_read_bytes = MultiVolumeExtractor::source_ranges_for_indices( + &shard.archive_index, + &shard.entries, + ) + .into_iter() + .fold(0u64, |total, range| { + total.saturating_add(range.end.saturating_sub(range.start)) + }); + estimate.storage_write_bytes = shard.entries.iter().fold(0u64, |total, index| { + total.saturating_add(shard.archive_index.entry_sizes[*index]) + }); + } + Task::RetainArchiveVolume { work, volume_index } => { + if work + .layout + .volume_range(*volume_index) + .is_some_and(|range| work.layout.range_is_available(&range)) + { + let bytes = work + .parts + .get(*volume_index) + .map(|part| part.expected_size) + .unwrap_or(0); + estimate.storage_read_bytes = bytes; + estimate.storage_write_bytes = bytes; + } else { + estimate.metadata_ops = 1; + } + } + Task::FinishArchive { .. } => { + // Deferred cross-volume commit bytes depend on files materialized by + // earlier extraction. Routing records the resource vector, but M1 + // leaves this service estimate unknown instead of inventing bytes. + estimate.metadata_ops = 1; + } + Task::PreparePatchApply { .. } => estimate.metadata_ops = 1, + Task::ApplyPatchEntry { patch, entry_index } => { + if let Some(entry) = patch.entry(*entry_index) { + let base_bytes = match &entry.source { + crate::PlannedPatchSource::Hdiff { base_size, .. } => *base_size, + _ => 0, + }; + estimate.storage_read_bytes = entry.expected_size.saturating_add(base_bytes); + estimate.cpu_cost = estimate.storage_read_bytes; + if matches!(entry.source, crate::PlannedPatchSource::Local { .. }) { + estimate.storage_write_bytes = entry.expected_size; + } + } + } + Task::DecodeHdiffPatchEntry { + patch, + entry_index, + #[cfg(feature = "hdiff-patch")] + checkpoint, + .. + } => { + #[cfg(feature = "hdiff-patch")] + let written = checkpoint.written(); + #[cfg(not(feature = "hdiff-patch"))] + let written = 0; + if let Some(entry) = patch.entry(*entry_index) { + let bytes = entry + .expected_size + .saturating_sub(written) + .min(patch.hdiff_budget() as u64); + estimate.storage_read_bytes = bytes; + estimate.storage_write_bytes = bytes; + estimate.cpu_cost = bytes; + estimate.metadata_ops = 3; + } + } + Task::CommitHdiffPatchEntry { + patch, + entry_index, + prepared, + } => { + if let Some(entry) = patch.entry(*entry_index) { + estimate.storage_read_bytes = entry.expected_size; + estimate.cpu_cost = entry.expected_size; + estimate.metadata_ops = 3; + if prepared.copy_to_destination_temp() { + estimate.storage_write_bytes = entry.expected_size; + } + } + } + Task::ReleasePatchBase { .. } => estimate.metadata_ops = 1, + Task::ApplyPatchDeletes { patch } => { + estimate.metadata_ops = + u32::try_from(patch.plan().delete_paths.len()).unwrap_or(u32::MAX); + } + Task::CommitPatchDeferred { patch } => { + let plan = patch.plan(); + let deferred_root = + crate::griffr_patch_path(&plan.install_root).join(crate::PATCH_DEFERRED_DIR); + let bytes = plan.deferred_paths.iter().fold(0u64, |total, relative| { + total.saturating_add(existing_file_len(&deferred_root.join(relative))) + }); + estimate.storage_read_bytes = bytes; + estimate.storage_write_bytes = bytes; + } + Task::CleanPatchApply { .. } | Task::CleanupArchive { .. } => { + estimate.metadata_ops = 1; + } + Task::ApplyExtractedVfsPatchManifest { .. } => { + // Exact file bytes depend on an on-disk manifest read during the + // task. Keep bytes unknown; routing still exposes volume lanes. + estimate.metadata_ops = 1; + } + Task::ApplyDeleteManifest { .. } => estimate.metadata_ops = 1, + } + estimate +} + +fn task_priority_cost(task: &Task) -> u64 { match task { Task::FetchArchiveRange { request, .. } => { request.local_range.end - request.local_range.start @@ -817,7 +1085,13 @@ fn task_estimated_bytes(task: &Task) -> u64 { probe_index, } => patch_check.probe_size(*probe_index).unwrap_or(0), Task::ExtractArchiveShard { shard } => shard.estimated_cost, - Task::ApplyPatchEntry { patch, entry_index } => patch + Task::ApplyPatchEntry { patch, entry_index } + | Task::DecodeHdiffPatchEntry { + patch, entry_index, .. + } + | Task::CommitHdiffPatchEntry { + patch, entry_index, .. + } => patch .entry(*entry_index) .map(|entry| entry.expected_size) .unwrap_or(0), @@ -871,22 +1145,25 @@ pub(super) fn run_class(task: &Task) -> RunClass { | Task::ReuseFile { copy_only: true, .. } - | Task::ApplyDeleteManifest { .. } => RunClass::AsyncIo, + | Task::ApplyDeleteManifest { .. } + | Task::DecodeHdiffPatchEntry { .. } => RunClass::AsyncIo, Task::Verify { .. } | Task::ReuseFile { copy_only: false, .. } | Task::RepairFile { .. } | Task::VerifyReuseVolume { .. } - | Task::ProbePatchArtifact { .. } => RunClass::Cpu, + | Task::ProbePatchArtifact { .. } + | Task::ApplyExtractedVfsPatchManifest { .. } => RunClass::Cpu, Task::ApplyPatchEntry { patch, entry_index } => patch .entry(*entry_index) .map(|entry| match &entry.source { - crate::PlannedPatchSource::Local { .. } => RunClass::Blocking, + crate::PlannedPatchSource::Local { .. } => RunClass::Cpu, crate::PlannedPatchSource::AlreadyPresent | crate::PlannedPatchSource::Hdiff { .. } => RunClass::Cpu, }) .unwrap_or(RunClass::Blocking), + Task::CommitHdiffPatchEntry { .. } => RunClass::Cpu, Task::VerifyMetadata { .. } | Task::ExtractArchiveRepairFile { .. } | Task::OpenArchive { .. } @@ -903,8 +1180,7 @@ pub(super) fn run_class(task: &Task) -> RunClass { | Task::ApplyPatchDeletes { .. } | Task::CommitPatchDeferred { .. } | Task::CleanPatchApply { .. } - | Task::CleanupArchive { .. } - | Task::ApplyExtractedVfsPatchManifest { .. } => RunClass::Blocking, + | Task::CleanupArchive { .. } => RunClass::Blocking, } } @@ -1006,7 +1282,13 @@ pub(super) fn task_path(task: &Task) -> String { Task::PreparePatchApply { patch } | Task::ApplyPatchDeletes { patch } | Task::CommitPatchDeferred { patch } => patch.plan().install_root.display().to_string(), - Task::ApplyPatchEntry { patch, entry_index } => patch + Task::ApplyPatchEntry { patch, entry_index } + | Task::DecodeHdiffPatchEntry { + patch, entry_index, .. + } + | Task::CommitHdiffPatchEntry { + patch, entry_index, .. + } => patch .entry(*entry_index) .map(|entry| entry.destination.display().to_string()) .unwrap_or_else(|| format!("patch-entry-{entry_index}")), @@ -1025,9 +1307,14 @@ mod tests { VolumeKeyCache, }; use crate::download::extractor::ArchiveRangeRequest; - use crate::task_pool::types::{ArchiveRepairSession, DownloadResumeState}; + use crate::task_pool::types::{ + ArchiveRepairSession, DownloadResumeState, PatchApplyWork, PreparedHdiffPatchOutput, + }; use crate::task_pool::{Task, TransferClass}; - use crate::{griffr_patch_path, PatchPlan, PATCH_DEFERRED_DIR, PATCH_STAGE_DIR}; + use crate::{ + griffr_patch_path, PatchPlan, PlannedPatchEntry, PlannedPatchSource, PATCH_DEFERRED_DIR, + PATCH_STAGE_DIR, + }; use std::collections::BTreeMap; use std::path::PathBuf; @@ -1060,6 +1347,174 @@ mod tests { } } + fn hdiff_patch_work(root: &std::path::Path, work_dir: Option) -> Arc { + let install_root = root.join("install"); + let stage_root = root.join("stage"); + let vfs_base_path = PathBuf::from("Game_Data/StreamingAssets/VFS"); + let vfs_destination = install_root.join(&vfs_base_path); + let entry = PlannedPatchEntry { + name: "output.bin".to_string(), + destination: vfs_destination.join("output.bin"), + expected_md5: "00".repeat(16), + expected_size: 64, + source: PlannedPatchSource::Hdiff { + base: vfs_destination.join("base.bin"), + payload: PathBuf::from("patch/output.hdiff"), + base_md5: "11".repeat(16), + base_size: 32, + }, + }; + PatchApplyWork::new(PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root, + stage_root, + vfs_base_path, + vfs_destination, + work_dir, + entries: vec![entry], + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + }) + } + + #[test] + fn hdiff_prepare_workunit_does_not_hold_destination_write_with_external_work_dir() { + let temp = tempfile::tempdir().unwrap(); + let work_dir = temp.path().join("work"); + let patch = hdiff_patch_work(temp.path(), Some(work_dir.clone())); + let resources = task_resources(&Task::ApplyPatchEntry { + patch: patch.clone(), + entry_index: 0, + }); + + assert_eq!(resources.run, RunClass::Cpu); + assert!(resources.storage_reservations.is_empty()); + assert!(resources.write_volumes.is_empty()); + assert_eq!(resources.service_estimate.storage_write_bytes, 0); + #[cfg(feature = "hdiff-patch")] + { + let output = work_dir.join("prepared.tmp"); + let resources = task_resources(&Task::DecodeHdiffPatchEntry { + patch: patch.clone(), + entry_index: 0, + prepared: PreparedHdiffPatchOutput::new(output.clone(), true), + checkpoint: Default::default(), + retained: None, + }); + assert_eq!(resources.run, RunClass::AsyncIo); + assert!(resources.uses_cpu()); + assert!(resources.hdiff_decoder_start); + assert_eq!(resources.storage_reservations[0].probe_path, output); + assert_eq!(resources.storage_reservations[0].bytes, 64); + assert_eq!(resources.service_estimate.storage_write_bytes, 64); + } + } + + #[test] + fn hdiff_commit_workunit_describes_work_read_and_destination_copy() { + let temp = tempfile::tempdir().unwrap(); + let work_dir = temp.path().join("work"); + std::fs::create_dir_all(&work_dir).unwrap(); + let prepared_path = work_dir.join("prepared.tmp"); + std::fs::write(&prepared_path, [0u8; 64]).unwrap(); + let patch = hdiff_patch_work(temp.path(), Some(work_dir)); + let destination = patch.entry(0).unwrap().destination.clone(); + let resources = task_resources(&Task::CommitHdiffPatchEntry { + patch, + entry_index: 0, + prepared: PreparedHdiffPatchOutput::new(prepared_path.clone(), true), + }); + + assert_eq!(resources.run, RunClass::Cpu); + assert!(resources + .read_volumes + .contains(&crate::task_pool::storage_volume_key(&prepared_path))); + assert_eq!(resources.storage_reservations.len(), 1); + assert_eq!(resources.storage_reservations[0].probe_path, destination); + assert_eq!(resources.service_estimate.storage_read_bytes, 64); + assert_eq!(resources.service_estimate.storage_write_bytes, 64); + } + + #[test] + fn hdiff_commit_cleans_candidate_and_keeps_staging_for_the_graph_barrier() { + let temp = tempfile::tempdir().unwrap(); + let work_dir = temp.path().join("work"); + std::fs::create_dir_all(&work_dir).unwrap(); + let prepared_path = work_dir.join("prepared.tmp"); + std::fs::write(&prepared_path, [0u8; 64]).unwrap(); + let patch = hdiff_patch_work(temp.path(), Some(work_dir)); + let entry = patch.entry(0).unwrap(); + let payload_path = match &entry.source { + PlannedPatchSource::Hdiff { payload, .. } => patch.plan().stage_root.join(payload), + other => panic!("expected HDiff source, got {other:?}"), + }; + let destination = entry.destination.clone(); + let mut volumes = VolumeKeyCache::default(); + volumes + .entries + .insert(prepared_path.clone(), "prepared-volume".to_string()); + volumes + .entries + .insert(payload_path.clone(), "payload-volume".to_string()); + volumes + .entries + .insert(destination.clone(), "destination-volume".to_string()); + + let resources = task_resources_cached( + &Task::CommitHdiffPatchEntry { + patch: patch.clone(), + entry_index: 0, + prepared: PreparedHdiffPatchOutput::new(prepared_path, true), + }, + &mut volumes, + ); + + assert!(resources + .read_volumes + .contains(&"prepared-volume".to_string())); + assert!(resources + .metadata_volumes + .contains(&"prepared-volume".to_string())); + assert!(!resources + .metadata_volumes + .contains(&"payload-volume".to_string())); + volumes.entries.insert( + patch.plan().stage_root.clone(), + "payload-volume".to_string(), + ); + let finish = task_resources_cached(&Task::CommitPatchDeferred { patch }, &mut volumes); + assert!(finish + .metadata_volumes + .contains(&"payload-volume".to_string())); + assert!(resources + .write_volumes + .contains(&"destination-volume".to_string())); + assert_eq!(resources.service_estimate.metadata_ops, 3); + } + + #[test] + fn hdiff_same_volume_commit_uses_read_plus_metadata_without_second_write_reservation() { + let temp = tempfile::tempdir().unwrap(); + let patch = hdiff_patch_work(temp.path(), None); + let destination = patch.entry(0).unwrap().destination.clone(); + std::fs::create_dir_all(destination.parent().unwrap()).unwrap(); + let prepared_path = destination.parent().unwrap().join("prepared.tmp"); + std::fs::write(&prepared_path, [0u8; 64]).unwrap(); + let resources = task_resources(&Task::CommitHdiffPatchEntry { + patch, + entry_index: 0, + prepared: PreparedHdiffPatchOutput::new(prepared_path, false), + }); + + assert_eq!(resources.run, RunClass::Cpu); + assert!(resources.write_volumes.is_empty()); + assert_eq!(resources.metadata_volumes.len(), 1); + assert!(resources.storage_reservations.is_empty()); + assert_eq!(resources.service_estimate.storage_read_bytes, 64); + assert_eq!(resources.service_estimate.storage_write_bytes, 0); + assert_eq!(resources.service_estimate.metadata_ops, 3); + } + #[test] fn verify_routing_reuses_parent_directory_volume_key() { let temp = tempfile::tempdir().unwrap(); @@ -1109,7 +1564,11 @@ mod tests { assert!(resources.write_volumes.is_empty()); assert_eq!(resources.metadata_volumes.len(), 1); assert!(resources.reuse_commit); - assert_eq!(resources.estimated_bytes, 1); + assert_eq!(resources.priority_cost, 1); + assert_eq!(resources.service_estimate.cpu_cost, 1); + assert_eq!(resources.service_estimate.storage_read_bytes, 1); + assert_eq!(resources.service_estimate.storage_write_bytes, 0); + assert_eq!(resources.service_estimate.metadata_ops, 1); assert_eq!(resources.run, RunClass::Cpu); } @@ -1123,6 +1582,8 @@ mod tests { assert_eq!(resources.storage_reservations.len(), 1); assert_eq!(resources.storage_reservations[0].bytes, 1); assert!(!resources.reuse_commit); + assert_eq!(resources.service_estimate.storage_read_bytes, 1); + assert_eq!(resources.service_estimate.storage_write_bytes, 1); assert_eq!(resources.run, RunClass::AsyncIo); } @@ -1163,7 +1624,9 @@ mod tests { assert_eq!(resources.run, RunClass::AsyncIo); assert_eq!(resources.network, Some(NetworkClass::General)); - assert_eq!(resources.estimated_bytes, 4); + assert_eq!(resources.priority_cost, 4); + assert_eq!(resources.service_estimate.network_bytes, 4); + assert_eq!(resources.service_estimate.storage_write_bytes, 4); assert_eq!(resources.storage_reservations.len(), 1); assert_eq!(resources.storage_reservations[0].bytes, 4); } @@ -1280,26 +1743,12 @@ mod tests { } #[test] - fn legacy_vfs_patch_reserves_all_outputs_created_by_one_task() { - let temp = tempfile::tempdir().unwrap(); - let install_root = temp.path().join("install"); - std::fs::create_dir_all(&install_root).unwrap(); - std::fs::write( - install_root.join(crate::PATCH_MANIFEST_NAME), - r#"{ - "version": "1", - "vfs_base_path": "Data/VFS", - "files": [ - {"name":"a.bin","md5":"00","size":4,"diffType":0,"patch":[]}, - {"name":"b.bin","md5":"00","size":9,"diffType":0,"patch":[]} - ] -}"#, - ) - .unwrap(); - + fn extracted_vfs_root_routes_only_plan_loading() { + let install_root = PathBuf::from("install"); let resources = task_resources(&Task::ApplyExtractedVfsPatchManifest { install_root }); - - assert_eq!(resources.storage_reservations.len(), 1); - assert_eq!(resources.storage_reservations[0].bytes, 13); + assert_eq!(resources.run, RunClass::Cpu); + assert!(resources.storage_reservations.is_empty()); + assert!(resources.write_volumes.is_empty()); + assert_eq!(resources.read_volumes.len(), 1); } } diff --git a/crates/griffr-runtime/src/task_pool/scheduler/tests/retention.rs b/crates/griffr-runtime/src/task_pool/scheduler/tests/retention.rs new file mode 100644 index 0000000..5cb0b45 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/scheduler/tests/retention.rs @@ -0,0 +1,781 @@ +use super::*; +use crate::patch_apply::hdiff_sf20::HdiffCheckpoint; +use crate::task_pool::types::{PatchApplyWork, PreparedHdiffPatchOutput}; +use crate::{PatchPlan, PlannedPatchEntry, PlannedPatchSource}; +use md5::Digest; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const CHILD: &str = "GRIFFR_RETENTION_TEST_CHILD"; +const FIXTURE_ROOT: &str = "GRIFFR_RETENTION_TEST_ROOT"; +const TEST_NAME: &str = "task_pool::scheduler::retention_tests::runner_group_retention_liveness"; + +struct Fixture { + patch: Arc, + base: PathBuf, + payload: PathBuf, + target: PathBuf, + temporary: PathBuf, + expected: Vec, +} + +impl Fixture { + fn new(root: &Path) -> Self { + let vfs = root.join("VFS"); + let stage = root.join("stage"); + std::fs::create_dir_all(&vfs).unwrap(); + std::fs::create_dir_all(&stage).unwrap(); + let base = vfs.join("base.bin"); + let payload = stage.join("delta.patch"); + let target = vfs.join("target.bin"); + let old = (0..8192) + .map(|n| ((n * 47 + 13) % 256) as u8) + .collect::>(); + let mut expected = old.clone(); + for (i, value) in expected[2550..2850].iter_mut().enumerate() { + *value = ((i * 17) % 256) as u8; + } + std::fs::write(&base, &old).unwrap(); + std::fs::write( + &payload, + include_bytes!("../../../patch_apply/hdiff_sf20_reference_zstd.patch"), + ) + .unwrap(); + let patch = PatchApplyWork::with_hdiff_budget( + PatchPlan { + schema_version: PatchPlan::SCHEMA_VERSION, + install_root: root.to_path_buf(), + stage_root: stage, + vfs_base_path: "VFS".into(), + vfs_destination: vfs.clone(), + work_dir: None, + entries: vec![PlannedPatchEntry { + name: "target.bin".into(), + destination: target.clone(), + expected_md5: griffr_core::to_hex(&md5::Md5::digest(&expected)), + expected_size: expected.len() as u64, + source: PlannedPatchSource::Hdiff { + base: base.clone(), + payload: "delta.patch".into(), + base_md5: griffr_core::to_hex(&md5::Md5::digest(&old)), + base_size: old.len() as u64, + }, + }], + delete_paths: Vec::new(), + deferred_paths: Vec::new(), + }, + 1024, + ); + Self { + patch, + base, + payload, + target, + temporary: vfs.join("retained"), + expected, + } + } + + fn task(&self, checkpoint: HdiffCheckpoint, retained: Option) -> Task { + Task::DecodeHdiffPatchEntry { + patch: self.patch.clone(), + entry_index: 0, + prepared: PreparedHdiffPatchOutput::create(self.temporary.clone(), false).unwrap(), + checkpoint, + retained, + } + } + + fn paused_decode(&self, runner: &TaskPoolRunner) -> Task { + let request = ResourceRequest { + run: RunClass::AsyncIo, + cpu_on_async: true, + hdiff_decoder_start: true, + ..ResourceRequest::default() + }; + let mut lease = runner.global_capacity.with_admission(|admission| { + assert!(admission.allows(&request)); + admission.acquire(&request) + }); + let checkpoint = HdiffCheckpoint::default(); + let prepared = PreparedHdiffPatchOutput::create(self.temporary.clone(), false).unwrap(); + let rt = compio::runtime::Runtime::new().unwrap(); + let checkpoint = rt + .block_on(checkpoint.advance( + &self.base, + &self.payload, + prepared.path(), + self.expected.len() as u64, + 1024, + )) + .unwrap() + .expect("fixture must pause after the first slice"); + let retained = lease.take_hdiff_memory().unwrap(); + drop(lease); + let confirmed = checkpoint.has_preallocated_output(); + let task = Task::DecodeHdiffPatchEntry { + patch: self.patch.clone(), + entry_index: 0, + prepared, + checkpoint, + retained: Some(retained), + }; + let demand = super::routing::task_resources(&task); + assert!(!demand.hdiff_decoder_start); + assert!(!demand.write_volumes.is_empty()); + assert!(demand.service_estimate.storage_write_bytes > 0); + assert_eq!(demand.storage_reservations.is_empty(), confirmed); + #[cfg(windows)] + assert!( + confirmed, + "Windows fixture must retain its physical allocation" + ); + task + } +} + +// A regression in either admission path can deadlock the coordinators. Only +// this fixture subprocess can be terminated by the test's deadline. +#[test] +fn runner_group_retention_liveness() { + if let Some(case) = std::env::var_os(CHILD) { + let root = PathBuf::from(std::env::var_os(FIXTURE_ROOT).unwrap()); + let case = case.to_str().unwrap(); + let (slots, tracing) = match case { + "untraced" => (1, false), + "traced" => (1, true), + "two-slots" => (2, true), + _ => panic!("unknown retention test case"), + }; + run_case(&root, slots, tracing); + return; + } + + for case in ["untraced", "traced", "two-slots"] { + let temp = tempfile::tempdir().unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST_NAME, "--nocapture"]) + .env(CHILD, case) + .env(FIXTURE_ROOT, temp.path()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(12); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success(), "{case}: fixture failed with {status}"); + break; + } + if Instant::now() >= deadline { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("{case}: retained decoder and waiter did not make progress"); + } + std::thread::sleep(Duration::from_millis(10)); + } + } +} + +fn run_case(root: &Path, slots: usize, tracing: bool) { + let mut config = TaskPoolConfig { + cpu_slots: slots, + scheduler_trace: tracing, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool_for_runners(slots + 1); + let group = TaskPoolRunnerGroup::new(config.clone()).unwrap(); + let mut owners = (0..slots) + .map(|index| { + let runner = group.runner(config.clone()).unwrap(); + let fixture = Fixture::new(&root.join(format!("owner-{index}"))); + let continuation = fixture.paused_decode(&runner); + assert_eq!(group.global_capacity.snapshot().0.cpu, 0); + (runner, fixture, continuation) + }) + .collect::>(); + let mut contender = group.runner(config).unwrap(); + let fixture = Fixture::new(&root.join("contender")); + let mut tasks = vec![fixture.task(HdiffCheckpoint::default(), None)]; + let mixed = slots > 1; + let server = mixed.then(|| { + use crate::task_pool::TransferClass; + use std::io::{Read, Write}; + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let download = fixture.base.with_file_name("download.bin"); + tasks.push(Task::Download { + url: format!("http://{address}/fixture"), + dest: download.clone(), + logical_path: "download.bin".to_owned(), + expected_hash: griffr_core::to_hex(&md5::Md5::digest(b"fixture")).into(), + expected_size: Some(7), + retry_count: 0, + transfer_class: TransferClass::General, + archive_repair: None, + resume: None, + }); + tasks.push(Task::VerifyMetadata { + path: fixture.base.clone(), + logical_path: "base.bin".to_owned(), + expected_hash: "0".repeat(32).into(), + expected_size: 8192, + on_fail: None, + }); + let handle = std::thread::spawn(move || { + // The parent bounds the entire isolated test, including a faulty + // admission that never makes the loopback request. + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") && request.len() < 8192 { + let mut byte = [0]; + stream.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + assert!(request.starts_with(b"GET /fixture HTTP/")); + stream + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nfixture", + ) + .unwrap(); + }); + (handle, download) + }); + let (done_tx, done_rx) = flume::bounded(1); + std::thread::spawn(move || { + let result = contender.run_batch(tasks, TaskProgress::disabled()); + done_tx.send(result).unwrap(); + }); + + // Wait until B probes while all decoder slots are held and CPU is free. + // Before the fix untraced B exits here, while traced B registers a CPU + // waiter that prevents A from running its real decoder continuation. + let deadline = Instant::now() + Duration::from_secs(4); + let observer = &owners[0].0.global_capacity; + while observer.metrics().global_admission_denials == 0 { + if let Ok(result) = done_rx.try_recv() { + panic!("retention waiter exited early: {result:?}"); + } + assert!( + Instant::now() < deadline, + "contender never reached admission" + ); + std::thread::sleep(Duration::from_millis(1)); + } + + let (mut owner, owner_fixture, continuation) = owners.pop().unwrap(); + let result = owner + .run_batch(vec![continuation], TaskProgress::disabled()) + .unwrap(); + verify_success(&owner_fixture, result); + let result = done_rx + .recv_timeout(Duration::from_secs(4)) + .unwrap() + .unwrap(); + if let Some((server, download)) = server { + // Download includes preparation/verification continuations on the + // same node, and the metadata check consumes the blocking lane. + assert_eq!( + result.metrics.graph.succeeded_nodes, 3, + "{:?}", + result.outcomes + ); + assert!(result.metrics.global_capacity.runner_network_peak >= 1); + assert!(result.metrics.global_capacity.runner_blocking_peak >= 1); + server.join().unwrap(); + assert_eq!(std::fs::read(download).unwrap(), b"fixture"); + assert_eq!(std::fs::read(&fixture.target).unwrap(), fixture.expected); + assert!(!fixture.temporary.exists()); + } else { + verify_success(&fixture, result); + } + + // A malformed decoder still releases both leases and leaves the + // pre-existing target untouched when the shared Dispatcher reports it. + let failed = Fixture::new(&root.join("failed")); + std::fs::write(&failed.payload, b"invalid payload").unwrap(); + std::fs::write(&failed.target, b"previous").unwrap(); + let result = owner + .run_batch( + vec![failed.task(HdiffCheckpoint::default(), None)], + TaskProgress::disabled(), + ) + .unwrap(); + assert_eq!(result.metrics.graph.failed_nodes, 1); + assert_eq!(std::fs::read(&failed.target).unwrap(), b"previous"); + assert!(!failed.temporary.exists()); + + // Inject a panic after consuming a real retained cursor on a worker. + // The partial output and allocation handle must be dropped before retry. + let panicked = Fixture::new(&root.join("panicked")); + std::fs::write(&panicked.target, b"previous").unwrap(); + let mut continuation = panicked.paused_decode(&owner); + let Task::DecodeHdiffPatchEntry { checkpoint, .. } = &mut continuation else { + unreachable!(); + }; + checkpoint.inject_panic_after_take(); + let result = owner + .run_batch(vec![continuation], TaskProgress::disabled()) + .unwrap(); + assert_eq!(result.metrics.graph.failed_nodes, 1, "{result:?}"); + assert!(format!("{:?}", result.outcomes).contains("task run panicked")); + assert_eq!(std::fs::read(&panicked.target).unwrap(), b"previous"); + assert!(panicked.base.is_file() && panicked.payload.is_file()); + assert!(!panicked.temporary.exists()); + verify_success( + &panicked, + owner + .run_batch( + vec![panicked.task(HdiffCheckpoint::default(), None)], + TaskProgress::disabled(), + ) + .unwrap(), + ); + + // A retained continuation discarded before dispatch releases its slot + // and private temporary directory with the task's final owner. + for (runner, fixture, continuation) in owners { + drop(continuation); + assert!(!fixture.temporary.exists()); + drop(runner); + } + assert_eq!(group.global_capacity.snapshot().0, Default::default()); + let request = ResourceRequest { + hdiff_decoder_start: true, + ..ResourceRequest::default() + }; + let leases = (0..slots) + .map(|_| { + owner.global_capacity.with_admission(|admission| { + assert!(admission.allows(&request), "decoder lease leaked"); + admission.acquire(&request) + }) + }) + .collect::>(); + drop(leases); +} + +fn verify_success(fixture: &Fixture, result: TaskPoolResult) { + assert_eq!( + result.metrics.graph.failed_nodes, 0, + "{:?}", + result.outcomes + ); + assert_eq!(result.metrics.graph.succeeded_nodes, 1); + assert_eq!(std::fs::read(&fixture.target).unwrap(), fixture.expected); + assert!(!fixture.temporary.exists()); +} + +#[test] +fn captured_retention_has_node_ownership_and_explicit_release() { + use crate::task_pool::workload::{ + replay_workload, validate_workload_trace, CompactWorkload, ReplayPolicy, WorkUnitPhase, + WorkloadCaptureConfig, WorkloadEventKind, WorkloadOccupancyAction, WorkloadRecordPayload, + WorkloadTrace, + }; + + let temp = tempfile::tempdir().unwrap(); + let fixture = Fixture::new(&temp.path().join("install")); + let path = temp.path().join("trace.ndjson"); + let mut config = TaskPoolConfig { + cpu_slots: 1, + workload_capture: Some(WorkloadCaptureConfig::streaming_strict(&path, "test")), + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let mut runner = TaskPoolRunner::new(config).unwrap(); + verify_success( + &fixture, + runner + .run_batch( + vec![fixture.task(HdiffCheckpoint::default(), None)], + TaskProgress::disabled(), + ) + .unwrap(), + ); + + let trace = WorkloadTrace::from_path(path).unwrap(); + assert!(validate_workload_trace(&trace).unwrap().replay_authority); + let compact = CompactWorkload::from_trace(&trace).unwrap(); + assert_eq!(compact.scheduler.hdiff_decoder_slots, 1); + assert_eq!( + compact + .work_units + .iter() + .filter(|unit| unit.demand.hdiff_decoder_start) + .count(), + 1 + ); + let release = compact + .work_units + .iter() + .position(|unit| unit.hdiff_retention_released) + .unwrap(); + assert_eq!( + compact.work_units[release].identity.phase, + WorkUnitPhase::HdiffDecode + ); + assert_eq!( + compact.work_units[release + 1].identity.phase, + WorkUnitPhase::HdiffCommit + ); + let result = replay_workload(&compact, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!( + result.summary.completed_work_units, + compact.work_units.len() + ); + + // Model the admission/acquire/release emitted by a real rejected + // dispatch (covered by the saturated-pool test) before successful retry. + // Use the complete captured decode-to-commit lineage rather than a + // synthetic commit root with no preceding decoder ownership. + let commit = &compact.work_units[release + 1].identity; + let mut retried = trace.clone(); + let mut revoked = Vec::new(); + let mut insert_at = None; + for (i, record) in trace.records.iter().enumerate() { + if let WorkloadRecordPayload::Event(event) = &record.payload { + match &event.kind { + WorkloadEventKind::Admitted { work_unit, .. } if work_unit == commit => { + insert_at = Some(i); + revoked.push(record.clone()); + } + WorkloadEventKind::Occupancy { work_unit, .. } if work_unit == commit => { + revoked.push(record.clone()); + } + _ => {} + } + } + } + assert_eq!(revoked.len(), 3); + assert!( + matches!(&revoked[2].payload, WorkloadRecordPayload::Event(event) if matches!(event.kind, WorkloadEventKind::Occupancy { action: WorkloadOccupancyAction::Release, .. })) + ); + let index = insert_at.unwrap(); + let elapsed = match &revoked[0].payload { + WorkloadRecordPayload::Event(event) => event.elapsed_ns, + _ => unreachable!(), + }; + for record in &mut revoked { + if let WorkloadRecordPayload::Event(event) = &mut record.payload { + event.elapsed_ns = elapsed; + } + } + retried.records.splice(index..index, revoked); + fn resequence(trace: &mut WorkloadTrace) { + let count = trace.records.len() as u64; + let mut events = 0; + for (index, record) in trace.records.iter_mut().enumerate() { + record.sequence = index as u64; + match &mut record.payload { + WorkloadRecordPayload::Event(event) => { + event.event_sequence = events; + events += 1; + } + WorkloadRecordPayload::Footer(footer) => { + footer.record_count = count; + footer.event_count = events; + } + _ => {} + } + } + } + resequence(&mut retried); + assert!(validate_workload_trace(&retried).unwrap().replay_authority); + let retried_compact = CompactWorkload::from_trace(&retried).unwrap(); + assert_eq!( + retried_compact, compact, + "rejected admission is not a service sample or MD5 batch" + ); + let mut duplicate = retried; + duplicate.records.remove(index + 2); + resequence(&mut duplicate); + assert!(validate_workload_trace(&duplicate) + .unwrap_err() + .to_string() + .contains("duplicate/out-of-order admission")); + + for (generation, starts_decoder, reason) in [ + (0, false, "no retained decoder"), + (1, true, "duplicate decoder retention acquire"), + ] { + let mut invalid = trace.clone(); + for record in &mut invalid.records { + if let WorkloadRecordPayload::Event(event) = &mut record.payload { + if let WorkloadEventKind::Routed { + work_unit, demand, .. + } = &mut event.kind + { + if work_unit.phase == WorkUnitPhase::HdiffDecode + && work_unit.continuation_generation == generation + { + demand.hdiff_decoder_start = starts_decoder; + } + } + } + } + let error = validate_workload_trace(&invalid).unwrap_err(); + assert!(error.to_string().contains(reason), "{error}"); + } + + let mut invalid = compact.clone(); + invalid.work_units[release].hdiff_retention_released = false; + let error = replay_workload(&invalid, ReplayPolicy::CurrentProduction).unwrap_err(); + assert!(error + .to_string() + .contains("non-decode work while decoder retention is held")); + + let mut invalid = compact; + invalid.work_units[release + 1].hdiff_retention_released = true; + let error = replay_workload(&invalid, ReplayPolicy::CurrentProduction).unwrap_err(); + assert!(error.to_string().contains("released without ownership")); +} + +#[test] +fn actual_blocking_dispatch_rejection_preserves_commit_candidate() { + let temp = tempfile::tempdir().unwrap(); + let fixture = Fixture::new(temp.path()); + let mut config = TaskPoolConfig { + cpu_slots: 1, + blocking_slots: 1, + dispatcher_threads: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let group = TaskPoolRunnerGroup::new(config.clone()).unwrap(); + let runner = group.runner(config.clone()).unwrap(); + let prepared = PreparedHdiffPatchOutput::create(fixture.temporary.clone(), false).unwrap(); + std::fs::write(prepared.path(), &fixture.expected).unwrap(); + std::fs::write(&fixture.target, b"previous").unwrap(); + let task = Task::CommitHdiffPatchEntry { + patch: fixture.patch.clone(), + entry_index: 0, + prepared, + }; + let resources = routing::task_resources(&task); + let mut queue = SchedulerQueue::default(); + queue.push( + crate::task_pool::NodeId::from_index(0), + task, + resources, + TaskPriority::Continuation, + ); + let mut trace = SchedulerTraceRecorder::new(false, Instant::now()); + let (finish_tx, finish_rx) = flume::unbounded(); + let (event_tx, _event_rx) = flume::unbounded(); + let (release_tx, done_rx) = occupy_blocking_pool(&runner, &config); + let scheduled = queue + .pop_next_observed_global(&config, true, &runner.global_capacity, &mut trace, 0) + .unwrap(); + assert_eq!(scheduled.resources.run, RunClass::Cpu); + assert_eq!(runner.global_capacity.metrics().global_cpu_peak, 1); + let attempt = runner + .dispatch_scheduled(scheduled, finish_tx.clone(), &event_tx) + .unwrap(); + let DispatchAttempt::BlockingPoolBusy(mut returned) = attempt else { + panic!("saturated compio pool did not reject commit submission"); + }; + assert_eq!(returned.len(), 1); + queue.restore_front_observed(returned.pop().unwrap(), &config, &mut trace); + assert_eq!(group.global_capacity.snapshot().0, Default::default()); + assert!(fixture.temporary.exists()); + assert_eq!(std::fs::read(&fixture.target).unwrap(), b"previous"); + // The same global CPU credit is immediately available again. + let scheduled = queue + .pop_next_observed_global(&config, true, &runner.global_capacity, &mut trace, 0) + .unwrap(); + queue.restore_front_observed(scheduled, &config, &mut trace); + drop(release_tx); + for _ in 0..config.blocking_pool_limit { + done_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + } + let deadline = Instant::now() + Duration::from_secs(2); + loop { + let scheduled = queue + .pop_next_observed_global(&config, true, &runner.global_capacity, &mut trace, 0) + .unwrap(); + match runner + .dispatch_scheduled(scheduled, finish_tx.clone(), &event_tx) + .unwrap() + { + DispatchAttempt::Submitted => break, + DispatchAttempt::BlockingPoolBusy(mut returned) => { + queue.restore_front_observed(returned.pop().unwrap(), &config, &mut trace); + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(1)); + } + } + } + let finish = finish_rx.recv_timeout(Duration::from_secs(3)).unwrap(); + assert!(matches!(finish.run, TaskRun::Succeeded)); + queue.release(&finish.resources); + drop(finish); + assert_eq!(group.global_capacity.snapshot().0, Default::default()); + assert_eq!(std::fs::read(&fixture.target).unwrap(), fixture.expected); + assert!(!fixture.temporary.exists()); +} + +/// Hold every real compio blocking worker until the caller drops the sender. +/// All fixture waits are bounded, including unwinding on a failed assertion. +fn occupy_blocking_pool( + runner: &TaskPoolRunner, + config: &TaskPoolConfig, +) -> (flume::Sender<()>, flume::Receiver<()>) { + let (release_tx, release_rx) = flume::bounded::<()>(0); + let (entered_tx, entered_rx) = flume::bounded(config.blocking_pool_limit); + let (done_tx, done_rx) = flume::bounded(config.blocking_pool_limit); + // Occupy the actual compio pool, not a mocked dispatch result. Dropping + // release_tx on unwind also releases all of these fixture workers. + for _ in 0..config.blocking_pool_limit { + let release = release_rx.clone(); + let entered = entered_tx.clone(); + let done = done_tx.clone(); + let submitted = runner.dispatcher.dispatch_blocking(move || { + entered.send(()).unwrap(); + let _ = release.recv_timeout(Duration::from_secs(12)); + let _ = done.send(()); + }); + assert!(submitted.is_ok()); + entered_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + } + (release_tx, done_rx) +} + +#[test] +fn full_runner_capture_survives_actual_dispatch_rejection() { + use crate::task_pool::workload::{ + replay_workload, validate_workload_trace, CompactWorkload, ReplayPolicy, + WorkloadCaptureConfig, WorkloadEventKind, WorkloadRecordPayload, WorkloadTrace, + }; + let temp = tempfile::tempdir().unwrap(); + let fixture = Fixture::new(&temp.path().join("install")); + std::fs::write(&fixture.target, b"previous").unwrap(); + let capture = temp.path().join("saturated.ndjson"); + let mut config = TaskPoolConfig { + cpu_slots: 1, + blocking_slots: 1, + dispatcher_threads: 1, + workload_capture: Some(WorkloadCaptureConfig::streaming_strict( + &capture, + "saturated-dispatch", + )), + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let group = TaskPoolRunnerGroup::new(config.clone()).unwrap(); + let mut runner = group.runner(config.clone()).unwrap(); + let (release_tx, done_rx) = occupy_blocking_pool(&runner, &config); + let patch = fixture.patch.clone(); + let (tx, rx) = flume::bounded(1); + let coordinator = std::thread::spawn(move || { + let result = runner.run_batch( + vec![Task::ApplyPatchEntry { + patch, + entry_index: 0, + }], + TaskProgress::disabled(), + ); + let _ = tx.send(result); + }); + // The sole CPU task has been admitted and returned its lease, although + // every blocking worker remains held. Only a real rejection can do this. + let deadline = Instant::now() + Duration::from_secs(3); + loop { + let (used, peak) = group.global_capacity.snapshot(); + if peak.cpu == 1 && used.cpu == 0 { + break; + } + assert!( + Instant::now() < deadline, + "coordinator did not restore rejected admission" + ); + std::thread::sleep(Duration::from_millis(1)); + } + assert_eq!(std::fs::read(&fixture.target).unwrap(), b"previous"); + drop(release_tx); + for _ in 0..config.blocking_pool_limit { + done_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + } + let result = rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); + coordinator.join().unwrap(); + verify_success(&fixture, result); + assert_eq!(group.global_capacity.snapshot().0, Default::default()); + let trace = WorkloadTrace::from_path(capture).unwrap(); + assert!(validate_workload_trace(&trace).unwrap().replay_authority); + let mut admits = 0; + let mut starts = 0; + for record in &trace.records { + if let WorkloadRecordPayload::Event(event) = &record.payload { + match &event.kind { + WorkloadEventKind::Admitted { work_unit, .. } + if work_unit.continuation_generation == 0 => + { + admits += 1 + } + WorkloadEventKind::Started { work_unit } + if work_unit.continuation_generation == 0 => + { + starts += 1 + } + _ => {} + } + } + } + assert!(admits >= 2, "trace must contain actual rejected admission"); + assert_eq!(starts, 1); + let compact = CompactWorkload::from_trace(&trace).unwrap(); + assert!(compact.observed_batch_services.is_empty()); + assert_eq!( + compact + .work_units + .iter() + .filter(|unit| unit.identity.continuation_generation == 0) + .count(), + 1 + ); + let replay = replay_workload(&compact, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!( + replay.summary.completed_work_units, + compact.work_units.len() + ); +} + +#[test] +fn storage_full_at_allocation_preserves_retry_sources() { + let temp = tempfile::tempdir().unwrap(); + let fixture = Fixture::new(temp.path()); + std::fs::write(&fixture.target, b"previous").unwrap(); + let mut config = TaskPoolConfig { + cpu_slots: 1, + ..TaskPoolConfig::default() + }; + config.fit_blocking_pool(); + let group = TaskPoolRunnerGroup::new(config.clone()).unwrap(); + let mut runner = group.runner(config).unwrap(); + let mut checkpoint = HdiffCheckpoint::default(); + checkpoint.inject_storage_full_on_allocate(); + let result = runner + .run_batch( + vec![fixture.task(checkpoint, None)], + TaskProgress::disabled(), + ) + .unwrap(); + assert_eq!(result.metrics.graph.failed_nodes, 1); + assert!(format!("{:?}", result.outcomes).contains("injected allocation storage full")); + assert_eq!(std::fs::read(&fixture.target).unwrap(), b"previous"); + assert!(fixture.base.is_file() && fixture.payload.is_file()); + assert!(!fixture.temporary.exists()); + assert_eq!(group.global_capacity.snapshot().0, Default::default()); + verify_success( + &fixture, + runner + .run_batch( + vec![fixture.task(HdiffCheckpoint::default(), None)], + TaskProgress::disabled(), + ) + .unwrap(), + ); + assert_eq!(group.global_capacity.snapshot().0, Default::default()); +} diff --git a/crates/griffr-runtime/src/task_pool/test/archive.rs b/crates/griffr-runtime/src/task_pool/test/archive.rs index f0bc23e..2019968 100644 --- a/crates/griffr-runtime/src/task_pool/test/archive.rs +++ b/crates/griffr-runtime/src/task_pool/test/archive.rs @@ -418,3 +418,109 @@ fn patch_archive_extracts_only_selected_payloads_and_direct_entries() { b"owned by task" ); } + +#[cfg(feature = "hdiff-patch")] +#[test] +fn source_directed_hdiff_archive_applies_and_finishes_marker() { + source_directed_hdiff_archive_case(false); +} + +#[cfg(feature = "hdiff-patch")] +#[test] +fn unsupported_hdiff_archive_preserves_install_before_direct_commit() { + source_directed_hdiff_archive_case(true); +} + +#[cfg(feature = "hdiff-patch")] +fn source_directed_hdiff_archive_case(unsupported: bool) { + let temp = tempdir().unwrap(); + let install = temp.path().join("install"); + let vfs = install.join("VFS"); + std::fs::create_dir_all(&vfs).unwrap(); + let base = (0..8192) + .map(|i| ((i * 47 + 13) % 256) as u8) + .collect::>(); + let mut expected = base.clone(); + expected.extend((0..901).map(|i| ((i * 13 + 3) % 256) as u8)); + std::fs::write(vfs.join("base.bin"), &base).unwrap(); + std::fs::write(install.join("config.ini"), b"version=1").unwrap(); + + let archive = temp.path().join("patch.zip"); + let diff: &[u8] = if unsupported { + b"HDIFF13&\0" + } else { + include_bytes!("../../patch_apply/hdiff_sf20_reference_tail.patch") + }; + std::fs::write(install.join("ordinary.bin"), b"old ordinary").unwrap(); + std::fs::write(install.join("obsolete.bin"), b"old obsolete").unwrap(); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap()); + let controls = serde_json::json!({ + "version": "2", "vfs_base_path": "VFS", "files": [{ + "name": "output.bin", "md5": griffr_core::to_hex(&Md5::digest(&expected)), + "size": expected.len(), "diffType": 1, "patch": [{ + "base_file": "base.bin", "base_md5": griffr_core::to_hex(&Md5::digest(&base)), + "base_size": base.len(), "patch": "output.patch", "patch_size": diff.len() + }] + }] + }); + for (name, bytes) in [ + ("patch.json", serde_json::to_vec(&controls).unwrap()), + ("vfs_files/vfs_patch/output.patch", diff.to_vec()), + ("delete_files.txt", b"VFS/base.bin\nobsolete.bin\n".to_vec()), + ("ordinary.bin", b"new ordinary".to_vec()), + ("config.ini", b"version=2".to_vec()), + ] { + zip.start_file(name, FileOptions::<()>::default()).unwrap(); + zip.write_all(&bytes).unwrap(); + } + zip.finish().unwrap(); + let result = run_tasks( + vec![Task::OpenArchive { + base_name: "source-directed-patch".to_string(), + source: ArchiveSource::Local(vec![archive]), + dest: install.clone(), + retention: ArchiveRetention::Ephemeral, + password: None, + patch_options: crate::PatchApplyOptions::default(), + expected_files: archive_expected_files(Vec::new()), + excluded_commit_paths: Default::default(), + }], + TaskPoolConfig::default(), + ) + .unwrap(); + if unsupported { + assert!( + result.metrics.graph.failed_nodes > 0, + "{:?}", + result.outcomes + ); + assert!(format!("{:?}", result.outcomes).contains("unsupported HDiff format")); + assert_eq!( + std::fs::read(install.join("ordinary.bin")).unwrap(), + b"old ordinary" + ); + assert_eq!( + std::fs::read(install.join("obsolete.bin")).unwrap(), + b"old obsolete" + ); + assert_eq!( + std::fs::read(install.join("config.ini")).unwrap(), + b"version=1" + ); + assert_eq!(std::fs::read(vfs.join("base.bin")).unwrap(), base); + assert!(!vfs.join("output.bin").exists()); + return; + } + assert_eq!( + result.metrics.graph.failed_nodes, 0, + "{:?}", + result.outcomes + ); + assert_eq!(std::fs::read(vfs.join("output.bin")).unwrap(), expected); + assert_eq!( + std::fs::read(install.join("config.ini")).unwrap(), + b"version=2" + ); + assert!(!vfs.join("base.bin").exists()); + assert!(!crate::griffr_patch_path(&install).exists()); +} diff --git a/crates/griffr-runtime/src/task_pool/types.rs b/crates/griffr-runtime/src/task_pool/types.rs index 482f150..ca6b397 100644 --- a/crates/griffr-runtime/src/task_pool/types.rs +++ b/crates/griffr-runtime/src/task_pool/types.rs @@ -1,6 +1,7 @@ mod archive; mod config; mod events; +mod measurement; mod progress; mod tasks; @@ -14,8 +15,16 @@ pub use config::{ }; pub(crate) use events::WorkerEvent; pub use events::{ - TaskOutcome, TaskPoolMetrics, TaskPoolResult, TaskPoolRunner, TaskPoolRunnerGroup, - VolumeTaskMetrics, + GlobalCapacityMetrics, TaskOutcome, TaskPoolMetrics, TaskPoolResult, TaskPoolRunner, + TaskPoolRunnerGroup, VolumeTaskMetrics, +}; +pub use measurement::{ + AdmissionBlockReason, ResourceOccupancy, ResourceOccupancyAction, ResourceOccupancyPeaks, + SchedulerCompletion, SchedulerDecision, SchedulerNetworkClass, SchedulerResourceDemand, + SchedulerRunClass, SchedulerServiceSample, SchedulerTaskPriority, SchedulerTrace, + SchedulerTraceAggregate, SchedulerTraceEvent, SchedulerTraceEventKind, ServiceEstimate, + StorageReservationDemand, VolumeResourceOccupancy, VolumeResourceOccupancyPeak, + SCHEDULER_TRACE_SCHEMA_VERSION, }; pub use progress::TaskProgress; pub use tasks::*; diff --git a/crates/griffr-runtime/src/task_pool/types/archive.rs b/crates/griffr-runtime/src/task_pool/types/archive.rs index 6ba3460..9850b65 100644 --- a/crates/griffr-runtime/src/task_pool/types/archive.rs +++ b/crates/griffr-runtime/src/task_pool/types/archive.rs @@ -27,6 +27,7 @@ pub(crate) fn should_report_item_progress(finished: usize, total: usize) -> bool pub struct PatchApplyWork { plan: Arc, finished_entries: AtomicUsize, + hdiff_budget: usize, verification_cache: VerifiedArtifactCache, } @@ -35,10 +36,22 @@ impl PatchApplyWork { Arc::new(Self { plan: Arc::new(plan), finished_entries: AtomicUsize::new(0), + hdiff_budget: usize::MAX, verification_cache: VerifiedArtifactCache::default(), }) } + pub(crate) fn hdiff_budget(&self) -> usize { + self.hdiff_budget + } + + #[cfg(all(test, feature = "hdiff-patch"))] + pub(crate) fn with_hdiff_budget(plan: PatchPlan, hdiff_budget: usize) -> Arc { + let mut work = Self::new(plan); + Arc::get_mut(&mut work).unwrap().hdiff_budget = hdiff_budget; + work + } + pub(crate) fn plan(&self) -> &PatchPlan { &self.plan } diff --git a/crates/griffr-runtime/src/task_pool/types/config.rs b/crates/griffr-runtime/src/task_pool/types/config.rs index 9991a78..ca4dfa0 100644 --- a/crates/griffr-runtime/src/task_pool/types/config.rs +++ b/crates/griffr-runtime/src/task_pool/types/config.rs @@ -95,7 +95,7 @@ pub struct TaskPoolConfig { pub dispatcher_threads: usize, /// Shared network capacity across general, archive, and VFS transfers. pub network_slots: usize, - /// Maximum CPU-heavy tasks admitted to Dispatcher::dispatch_blocking(). + /// Maximum CPU-heavy WorkUnits admitted across both dispatcher lanes. pub cpu_slots: usize, /// Maximum non-CPU blocking tasks admitted to Dispatcher::dispatch_blocking(). pub blocking_slots: usize, @@ -121,6 +121,12 @@ pub struct TaskPoolConfig { pub user_agent: String, pub extraction_progress_buffer_bytes: usize, pub download_progress_buffer_bytes: usize, + /// Capture the detailed scheduler measurement trace in `TaskPoolResult`. + /// Disabled by default so the production hot path does not allocate trace events. + pub scheduler_trace: bool, + /// Optional M5 content-free workload capture. This is separate from the + /// in-memory M1 trace so long-running capture does not retain every event. + pub workload_capture: Option, } impl TaskPoolConfig { @@ -142,6 +148,11 @@ impl TaskPoolConfig { } } + pub fn with_scheduler_trace(mut self, enabled: bool) -> Self { + self.scheduler_trace = enabled; + self + } + pub fn with_extract_slots(extract_slots: usize) -> Self { let extract_slots = extract_slots.clamp(MIN_EXTRACT_SLOTS, MAX_EXTRACT_SLOTS); Self { @@ -240,6 +251,8 @@ impl Default for TaskPoolConfig { user_agent: MIN_USER_AGENT.to_owned(), extraction_progress_buffer_bytes: DEFAULT_PROGRESS_BUFFER_BYTES, download_progress_buffer_bytes: DEFAULT_PROGRESS_BUFFER_BYTES, + scheduler_trace: false, + workload_capture: None, } } } diff --git a/crates/griffr-runtime/src/task_pool/types/events.rs b/crates/griffr-runtime/src/task_pool/types/events.rs index 6083bdb..1f5fc26 100644 --- a/crates/griffr-runtime/src/task_pool/types/events.rs +++ b/crates/griffr-runtime/src/task_pool/types/events.rs @@ -114,6 +114,30 @@ impl VolumeTaskMetrics { } } +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GlobalCapacityMetrics { + pub runner_id: u64, + pub cpu_capacity: usize, + pub blocking_capacity: usize, + pub network_capacity: usize, + pub extract_capacity: usize, + pub reuse_probe_capacity: usize, + pub global_cpu_peak: usize, + pub global_blocking_peak: usize, + pub global_network_peak: usize, + pub global_extract_peak: usize, + pub global_reuse_probe_peak: usize, + pub runner_cpu_peak: usize, + pub runner_blocking_peak: usize, + pub runner_network_peak: usize, + pub runner_extract_peak: usize, + pub runner_reuse_probe_peak: usize, + pub global_borrow_events: u64, + pub global_admission_denials: u64, + pub borrow_events: u64, + pub admission_denials: u64, +} + #[derive(Debug, Clone, Default)] pub struct TaskPoolMetrics { pub finished_tasks: usize, @@ -129,6 +153,7 @@ pub struct TaskPoolMetrics { pub ready_backlog_peak: usize, pub volume_cache_hits: usize, pub volume_cache_misses: usize, + pub global_capacity: GlobalCapacityMetrics, pub volumes: BTreeMap, } @@ -145,6 +170,7 @@ fn bytes_per_second(bytes: u64, duration: Duration) -> f64 { pub struct TaskPoolResult { pub outcomes: Vec, pub metrics: TaskPoolMetrics, + pub scheduler_trace: Option, } #[derive(Clone)] @@ -152,11 +178,12 @@ pub struct TaskPoolRunnerGroup { pub(crate) dispatcher: std::sync::Arc, pub(crate) dispatcher_threads: usize, pub(crate) blocking_pool_limit: usize, + pub(crate) global_capacity: + std::sync::Arc, } pub struct TaskPoolRunner { pub(crate) config: super::TaskPoolConfig, pub(crate) dispatcher: std::sync::Arc, - pub(crate) event_tx: flume::Sender, - pub(crate) event_rx: flume::Receiver, + pub(crate) global_capacity: crate::task_pool::scheduler::GlobalCapacityRunner, } diff --git a/crates/griffr-runtime/src/task_pool/types/measurement.rs b/crates/griffr-runtime/src/task_pool/types/measurement.rs new file mode 100644 index 0000000..4ea2cf3 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/types/measurement.rs @@ -0,0 +1,569 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +pub const SCHEDULER_TRACE_SCHEMA_VERSION: u32 = 3; + +/// Routed, per-task service estimate used only for measurement in M1. +/// +/// `cpu_cost` is an intentionally unitless relative cost. The byte fields are +/// physical byte estimates and must not be populated with abstract CPU work. +/// `metadata_ops` is a coarse operation count when a task has a meaningful +/// metadata-only phase; zero means unknown/not estimated rather than free. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServiceEstimate { + pub cpu_cost: u64, + pub network_bytes: u64, + pub storage_read_bytes: u64, + pub storage_write_bytes: u64, + pub metadata_ops: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StorageReservationDemand { + pub volume: String, + pub bytes: u64, +} + +/// Serializable resource vector materialized when a dependency-ready task is +/// routed into the bounded scheduler frontier. It is trace evidence, not a +/// second admission authority. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerResourceDemand { + pub cpu_on_async: bool, + pub hdiff_decoder_start: bool, + pub run_class: SchedulerRunClass, + pub network_class: Option, + pub read_volumes: Vec, + pub write_volumes: Vec, + pub metadata_volumes: Vec, + pub archive_save_volumes: Vec, + pub archive_commit_volumes: Vec<(String, bool)>, + pub extract: bool, + pub mutation_paths: Vec, + pub storage_reservations: Vec, + pub reuse_probe: bool, + pub reuse_commit: bool, + /// Scalar cost used by the current scheduler ordering. This + /// is deliberately not named or interpreted as bytes. + pub priority_cost: u64, + pub service_estimate: ServiceEstimate, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum SchedulerRunClass { + AsyncIo, + Cpu, + Blocking, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum SchedulerNetworkClass { + General, + Vfs, + Archive, + ArchiveBackground, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum SchedulerTaskPriority { + Continuation, + Bulk, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum SchedulerCompletion { + Succeeded, + Failed, + Cancelled, + Continued, + Expanded, + ExpandedThen, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum ResourceOccupancyAction { + Acquire, + Release, +} + +/// Why a dependency-ready task could not be admitted at one scheduler probe. +/// +/// Volume-bearing variants preserve the physical-volume authority already used +/// by `ResourceState`; they do not create a second resource identity model. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum AdmissionBlockReason { + Cpu, + Blocking, + Network, + Extract, + GlobalCpu, + GlobalBlocking, + GlobalNetwork, + GlobalExtract, + GlobalReuseQueue, + HdiffDecoderMemory, + GlobalFairness, + VolumeRead(String), + VolumeWrite(String), + Metadata(String), + VolumeStreaming(String), + WriterReservation(String), + MutationConflict, + StorageReservation(String), + ReuseQueue, + ArchiveSave(String), + ArchiveCommit(String), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct VolumeResourceOccupancy { + pub volume: String, + pub reads_used: usize, + pub reads_cap: usize, + pub writes_used: usize, + pub writes_cap: usize, + pub metadata_used: usize, + pub metadata_cap: usize, + pub streaming_pressure_used: usize, + pub streaming_pressure_cap: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceOccupancy { + pub cpu_used: usize, + pub cpu_cap: usize, + pub network_used: usize, + pub network_cap: usize, + pub blocking_used: usize, + pub blocking_cap: usize, + pub extract_used: usize, + pub extract_cap: usize, + pub reuse_commits_used: usize, + pub mutation_paths_used: usize, + pub storage_reserved_bytes: BTreeMap, + pub volumes: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct VolumeResourceOccupancyPeak { + pub reads_used: usize, + pub writes_used: usize, + pub metadata_used: usize, + pub streaming_pressure_used: usize, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceOccupancyPeaks { + pub cpu_used: usize, + pub network_used: usize, + pub blocking_used: usize, + pub extract_used: usize, + pub reuse_commits_used: usize, + pub mutation_paths_used: usize, + pub storage_reserved_bytes: BTreeMap, + pub volumes: BTreeMap, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerTraceAggregate { + pub created: u64, + pub ready: u64, + pub routed: u64, + pub considered: u64, + pub admitted: u64, + pub started: u64, + pub finished: u64, + pub decisions: u64, + pub lookahead_exhausted: u64, + pub max_ready_frontier_len: usize, + pub max_ready_backlog_len: usize, + pub selected_candidate_indices: BTreeMap, + pub admission_blocks: BTreeMap, + pub occupancy_peaks: ResourceOccupancyPeaks, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerServiceSample { + pub node_id: usize, + pub service_estimate: ServiceEstimate, + pub completion: SchedulerCompletion, + pub queue_wait_ns: u64, + pub run_time_ns: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerDecision { + pub ready_frontier_len: usize, + pub ready_backlog_len: usize, + pub priority: SchedulerTaskPriority, + pub candidate_index: usize, + pub lookahead_exhausted: bool, + pub run_class: SchedulerRunClass, + pub network_class: Option, + /// True for a SIMD MD5 follower selected by the batch-member path rather + /// than the normal priority-lookahead policy. + pub batch_member: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum SchedulerTraceEventKind { + Created { + node_id: usize, + }, + Ready { + node_id: usize, + task_kind: String, + continuation: bool, + }, + Routed { + node_id: usize, + priority: SchedulerTaskPriority, + demand: SchedulerResourceDemand, + }, + Considered { + node_id: usize, + priority: SchedulerTaskPriority, + candidate_index: usize, + run_class: SchedulerRunClass, + network_class: Option, + batch_member: bool, + blocked_by: Vec, + }, + Admitted { + node_id: usize, + service_estimate: ServiceEstimate, + }, + Started { + node_id: usize, + }, + Finished { + node_id: usize, + completion: SchedulerCompletion, + queue_wait_ns: u64, + run_time_ns: u64, + }, + Decision(SchedulerDecision), + Occupancy { + action: ResourceOccupancyAction, + node_id: usize, + occupancy: ResourceOccupancy, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerTraceEvent { + /// Nanoseconds elapsed since the scheduler run began. This is a monotonic + /// relative timestamp; wall-clock time is intentionally not part of replay. + pub elapsed_ns: u64, + pub kind: SchedulerTraceEventKind, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerTrace { + pub schema_version: u32, + pub run_id: u64, + pub runner_id: u64, + pub events: Vec, +} + +impl SchedulerTrace { + pub fn new(run_id: u64, runner_id: u64) -> Self { + Self { + schema_version: SCHEDULER_TRACE_SCHEMA_VERSION, + run_id, + runner_id, + events: Vec::new(), + } + } + + /// Serialize the versioned M1 measurement authority. The event timestamps + /// remain monotonic offsets, so the payload contains no wall-clock data. + pub fn to_json(&self) -> crate::error::Result { + Ok(serde_json::to_string(self)?) + } + + /// Parse a durable trace produced by [`SchedulerTrace::to_json`]. + /// Unknown schema versions fail closed instead of being silently replayed + /// under changed measurement semantics. + pub fn from_json(payload: &str) -> crate::error::Result { + let trace: Self = serde_json::from_str(payload)?; + if trace.schema_version != SCHEDULER_TRACE_SCHEMA_VERSION { + return Err(crate::error::Error::Message { + context: "Scheduler trace error: ", + detail: format!( + "unsupported schema version {} (expected {})", + trace.schema_version, SCHEDULER_TRACE_SCHEMA_VERSION + ), + }); + } + Ok(trace) + } + + /// Re-aggregate scheduler decisions, blockers, and occupancy from the trace + /// alone. This intentionally replays measurement state only; M1 does not + /// simulate or substitute a scheduling policy. + pub fn aggregate(&self) -> SchedulerTraceAggregate { + let mut aggregate = SchedulerTraceAggregate::default(); + for event in &self.events { + match &event.kind { + SchedulerTraceEventKind::Created { .. } => aggregate.created += 1, + SchedulerTraceEventKind::Ready { .. } => aggregate.ready += 1, + SchedulerTraceEventKind::Routed { .. } => aggregate.routed += 1, + SchedulerTraceEventKind::Considered { blocked_by, .. } => { + aggregate.considered += 1; + for reason in blocked_by { + *aggregate + .admission_blocks + .entry(admission_block_key(reason)) + .or_default() += 1; + } + } + SchedulerTraceEventKind::Admitted { .. } => aggregate.admitted += 1, + SchedulerTraceEventKind::Started { .. } => aggregate.started += 1, + SchedulerTraceEventKind::Finished { .. } => aggregate.finished += 1, + SchedulerTraceEventKind::Decision(decision) => { + aggregate.decisions += 1; + aggregate.max_ready_frontier_len = aggregate + .max_ready_frontier_len + .max(decision.ready_frontier_len); + aggregate.max_ready_backlog_len = aggregate + .max_ready_backlog_len + .max(decision.ready_backlog_len); + *aggregate + .selected_candidate_indices + .entry(decision.candidate_index) + .or_default() += 1; + if decision.lookahead_exhausted { + aggregate.lookahead_exhausted += 1; + } + } + SchedulerTraceEventKind::Occupancy { occupancy, .. } => { + aggregate.occupancy_peaks.observe(occupancy); + } + } + } + aggregate + } + + /// Pair routed/admitted estimates with the actual scheduler wait/runtime + /// observed by each completed task attempt. Re-admission after a dispatcher + /// rejection simply replaces the pending estimate for that node. + pub fn service_samples(&self) -> Vec { + let mut pending = BTreeMap::::new(); + let mut samples = Vec::new(); + for event in &self.events { + match &event.kind { + SchedulerTraceEventKind::Admitted { + node_id, + service_estimate, + } => { + pending.insert(*node_id, *service_estimate); + } + SchedulerTraceEventKind::Finished { + node_id, + completion, + queue_wait_ns, + run_time_ns, + } => { + if let Some(service_estimate) = pending.remove(node_id) { + samples.push(SchedulerServiceSample { + node_id: *node_id, + service_estimate, + completion: *completion, + queue_wait_ns: *queue_wait_ns, + run_time_ns: *run_time_ns, + }); + } + } + _ => {} + } + } + samples + } +} + +impl ResourceOccupancyPeaks { + fn observe(&mut self, occupancy: &ResourceOccupancy) { + self.cpu_used = self.cpu_used.max(occupancy.cpu_used); + self.network_used = self.network_used.max(occupancy.network_used); + self.blocking_used = self.blocking_used.max(occupancy.blocking_used); + self.extract_used = self.extract_used.max(occupancy.extract_used); + self.reuse_commits_used = self.reuse_commits_used.max(occupancy.reuse_commits_used); + self.mutation_paths_used = self.mutation_paths_used.max(occupancy.mutation_paths_used); + for (volume, bytes) in &occupancy.storage_reserved_bytes { + self.storage_reserved_bytes + .entry(volume.clone()) + .and_modify(|peak| *peak = (*peak).max(*bytes)) + .or_insert(*bytes); + } + for volume in &occupancy.volumes { + let peak = self.volumes.entry(volume.volume.clone()).or_default(); + peak.reads_used = peak.reads_used.max(volume.reads_used); + peak.writes_used = peak.writes_used.max(volume.writes_used); + peak.metadata_used = peak.metadata_used.max(volume.metadata_used); + peak.streaming_pressure_used = peak + .streaming_pressure_used + .max(volume.streaming_pressure_used); + } + } +} + +fn admission_block_key(reason: &AdmissionBlockReason) -> String { + match reason { + AdmissionBlockReason::Cpu => "CPU".to_owned(), + AdmissionBlockReason::Blocking => "Blocking".to_owned(), + AdmissionBlockReason::Network => "Network".to_owned(), + AdmissionBlockReason::Extract => "Extract".to_owned(), + AdmissionBlockReason::GlobalCpu => "GlobalCpu".to_owned(), + AdmissionBlockReason::GlobalBlocking => "GlobalBlocking".to_owned(), + AdmissionBlockReason::GlobalNetwork => "GlobalNetwork".to_owned(), + AdmissionBlockReason::GlobalExtract => "GlobalExtract".to_owned(), + AdmissionBlockReason::GlobalReuseQueue => "GlobalReuseQueue".to_owned(), + AdmissionBlockReason::HdiffDecoderMemory => "HdiffDecoderMemory".to_owned(), + AdmissionBlockReason::GlobalFairness => "GlobalFairness".to_owned(), + AdmissionBlockReason::VolumeRead(volume) => format!("VolumeRead:{volume}"), + AdmissionBlockReason::VolumeWrite(volume) => format!("VolumeWrite:{volume}"), + AdmissionBlockReason::Metadata(volume) => format!("Metadata:{volume}"), + AdmissionBlockReason::VolumeStreaming(volume) => format!("VolumeStreaming:{volume}"), + AdmissionBlockReason::WriterReservation(volume) => format!("WriterReservation:{volume}"), + AdmissionBlockReason::MutationConflict => "MutationConflict".to_owned(), + AdmissionBlockReason::StorageReservation(volume) => { + format!("StorageReservation:{volume}") + } + AdmissionBlockReason::ReuseQueue => "ReuseQueue".to_owned(), + AdmissionBlockReason::ArchiveSave(volume) => format!("ArchiveSave:{volume}"), + AdmissionBlockReason::ArchiveCommit(volume) => format!("ArchiveCommit:{volume}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn durable_trace_round_trip_reaggregates_measurement_state() { + let mut trace = SchedulerTrace::new(7, 1); + trace.events.push(SchedulerTraceEvent { + elapsed_ns: 1, + kind: SchedulerTraceEventKind::Admitted { + node_id: 3, + service_estimate: ServiceEstimate { + cpu_cost: 4, + network_bytes: 8, + storage_read_bytes: 16, + storage_write_bytes: 32, + metadata_ops: 1, + }, + }, + }); + trace.events.push(SchedulerTraceEvent { + elapsed_ns: 2, + kind: SchedulerTraceEventKind::Considered { + node_id: 4, + priority: SchedulerTaskPriority::Bulk, + candidate_index: 64, + run_class: SchedulerRunClass::Cpu, + network_class: None, + batch_member: false, + blocked_by: vec![AdmissionBlockReason::Cpu], + }, + }); + trace.events.push(SchedulerTraceEvent { + elapsed_ns: 3, + kind: SchedulerTraceEventKind::Decision(SchedulerDecision { + ready_frontier_len: 100, + ready_backlog_len: 20, + priority: SchedulerTaskPriority::Bulk, + candidate_index: 64, + lookahead_exhausted: true, + run_class: SchedulerRunClass::Cpu, + network_class: None, + batch_member: false, + }), + }); + trace.events.push(SchedulerTraceEvent { + elapsed_ns: 4, + kind: SchedulerTraceEventKind::Occupancy { + action: ResourceOccupancyAction::Acquire, + node_id: 3, + occupancy: ResourceOccupancy { + cpu_used: 2, + cpu_cap: 4, + network_used: 1, + network_cap: 4, + blocking_used: 0, + blocking_cap: 4, + extract_used: 0, + extract_cap: 2, + reuse_commits_used: 0, + mutation_paths_used: 1, + storage_reserved_bytes: [("disk".to_owned(), 64)].into_iter().collect(), + volumes: vec![VolumeResourceOccupancy { + volume: "disk".to_owned(), + reads_used: 1, + reads_cap: 4, + writes_used: 1, + writes_cap: 4, + metadata_used: 0, + metadata_cap: 4, + streaming_pressure_used: 2, + streaming_pressure_cap: 4, + }], + }, + }, + }); + trace.events.push(SchedulerTraceEvent { + elapsed_ns: 5, + kind: SchedulerTraceEventKind::Finished { + node_id: 3, + completion: SchedulerCompletion::Succeeded, + queue_wait_ns: 10, + run_time_ns: 20, + }, + }); + + let payload = trace.to_json().unwrap(); + let parsed = SchedulerTrace::from_json(&payload).unwrap(); + assert_eq!(parsed, trace); + let aggregate = parsed.aggregate(); + assert_eq!(aggregate.considered, 1); + assert_eq!(aggregate.decisions, 1); + assert_eq!(aggregate.lookahead_exhausted, 1); + assert_eq!(aggregate.selected_candidate_indices.get(&64), Some(&1)); + assert_eq!(aggregate.admission_blocks.get("CPU"), Some(&1)); + assert_eq!(aggregate.occupancy_peaks.cpu_used, 2); + assert_eq!(aggregate.occupancy_peaks.storage_reserved_bytes["disk"], 64); + assert_eq!(parsed.service_samples().len(), 1); + assert_eq!(parsed.service_samples()[0].run_time_ns, 20); + } + + #[test] + fn durable_trace_requires_runner_identity() { + let trace = SchedulerTrace::new(9, 17); + let payload = trace.to_json().unwrap(); + let parsed = SchedulerTrace::from_json(&payload).unwrap(); + assert_eq!(parsed.run_id, 9); + assert_eq!(parsed.runner_id, 17); + + let missing_runner = format!( + r#"{{"schema_version":{},"run_id":3,"events":[]}}"#, + SCHEDULER_TRACE_SCHEMA_VERSION + ); + assert!(SchedulerTrace::from_json(&missing_runner).is_err()); + } + + #[test] + fn durable_trace_rejects_unknown_schema_version() { + let payload = SchedulerTrace { + schema_version: SCHEDULER_TRACE_SCHEMA_VERSION + 1, + run_id: 1, + runner_id: 1, + events: Vec::new(), + } + .to_json() + .unwrap(); + let error = SchedulerTrace::from_json(&payload).unwrap_err().to_string(); + assert!(error.contains("unsupported schema version")); + } +} diff --git a/crates/griffr-runtime/src/task_pool/types/tasks.rs b/crates/griffr-runtime/src/task_pool/types/tasks.rs index 7183b3c..8971631 100644 --- a/crates/griffr-runtime/src/task_pool/types/tasks.rs +++ b/crates/griffr-runtime/src/task_pool/types/tasks.rs @@ -65,6 +65,204 @@ impl std::fmt::Debug for DownloadResumeState { } } +/// Owns a generated HDiff temporary across a same-node scheduler continuation. +/// Dropping the last clone removes the temporary, which makes queued +/// cancellation and runner teardown release the intermediate without retaining +/// a scheduler resource lease across WorkUnits. +#[doc(hidden)] +#[derive(Clone)] +pub struct PreparedHdiffPatchOutput { + inner: Arc, +} + +#[derive(Debug)] +struct PreparedHdiffPatchOutputInner { + path: PathBuf, + directory: Option, + owner: Option, + copy_to_destination_temp: bool, +} + +impl PreparedHdiffPatchOutputInner { + const OWNER_NAME: &str = "owner"; +} + +impl Drop for PreparedHdiffPatchOutputInner { + fn drop(&mut self) { + if let Err(error) = std::fs::remove_file(&self.path) { + if error.kind() != std::io::ErrorKind::NotFound { + return; // Keep the recovery marker so a later run can reclaim the output. + } + } + if let Some(directory) = &self.directory { + if let Some(owner) = self.owner.take() { + drop(owner); + let _ = std::fs::remove_file(directory.join(Self::OWNER_NAME)); + } + let _ = std::fs::remove_dir(directory); + } + } +} + +impl PreparedHdiffPatchOutput { + #[cfg(test)] + pub(crate) fn create( + directory: PathBuf, + copy_to_destination_temp: bool, + ) -> std::io::Result { + Self::create_owned(directory, copy_to_destination_temp, None) + } + + #[cfg(feature = "hdiff-patch")] + pub(crate) fn create_recoverable( + directory: PathBuf, + copy_to_destination_temp: bool, + scope: &[u8], + ) -> std::io::Result { + Self::create_owned(directory, copy_to_destination_temp, Some(scope)) + } + + pub(crate) fn create_local(directory: PathBuf) -> std::io::Result { + Self::create_owned(directory, false, None) + } + + fn create_owned( + directory: PathBuf, + copy_to_destination_temp: bool, + scope: Option<&[u8]>, + ) -> std::io::Result { + std::fs::create_dir(&directory)?; + let mut inner = PreparedHdiffPatchOutputInner { + path: directory.join("output"), + directory: Some(directory), + owner: None, + copy_to_destination_temp, + }; + if let Some(scope) = scope { + use std::io::Write; + let marker = inner + .directory + .as_ref() + .unwrap() + .join(PreparedHdiffPatchOutputInner::OWNER_NAME); + inner.owner = Some( + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(marker)?, + ); + let owner = inner.owner.as_mut().unwrap(); + owner.lock()?; + owner.write_all(scope)?; + owner.sync_all()?; + } + Ok(Self { + inner: Arc::new(inner), + }) + } + + /// Remove only a Griffr-owned output whose process no longer holds the + /// marker's exclusive lock. The caller supplies the exact install scope. + #[cfg(feature = "hdiff-patch")] + pub(crate) fn reclaim_orphan(directory: &Path, scope: &[u8]) -> std::io::Result<()> { + use std::fs::{OpenOptions, TryLockError}; + use std::io::{ErrorKind, Read}; + let marker = directory.join(PreparedHdiffPatchOutputInner::OWNER_NAME); + let metadata = match std::fs::symlink_metadata(&marker) { + Ok(metadata) => metadata, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + if !metadata.is_file() || metadata.len() != scope.len() as u64 { + return Ok(()); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT; + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Ok(()); + } + } + let mut owner = match OpenOptions::new().read(true).write(true).open(&marker) { + Ok(file) => file, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + let mut token = vec![0; scope.len()]; + // The length check skips an empty marker while its creator is + // acquiring the lock. The scope bytes are written only after locking. + // Windows can reject reads of active locked bytes with a lock violation. + match owner.try_lock() { + Ok(()) => {} + Err(TryLockError::WouldBlock) => return Ok(()), + Err(TryLockError::Error(error)) => return Err(error), + } + owner.read_exact(&mut token)?; + if token != scope { + return Ok(()); + } + let output = directory.join("output"); + match std::fs::remove_file(output) { + Ok(()) => {} + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + drop(owner); + match std::fs::remove_file(marker) { + Ok(()) => {} + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + match std::fs::remove_dir(directory) { + Ok(()) => Ok(()), + Err(error) + if matches!( + error.kind(), + ErrorKind::NotFound | ErrorKind::DirectoryNotEmpty + ) => + { + Ok(()) + } + Err(error) => Err(error), + } + } + + #[cfg(test)] + pub(crate) fn new(path: PathBuf, copy_to_destination_temp: bool) -> Self { + Self { + inner: Arc::new(PreparedHdiffPatchOutputInner { + path, + directory: None, + owner: None, + copy_to_destination_temp, + }), + } + } + + pub(crate) fn path(&self) -> &Path { + &self.inner.path + } + + pub(crate) fn copy_to_destination_temp(&self) -> bool { + self.inner.copy_to_destination_temp + } +} + +impl std::fmt::Debug for PreparedHdiffPatchOutput { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("PreparedHdiffPatchOutput") + .field("path", &self.inner.path) + .field( + "copy_to_destination_temp", + &self.inner.copy_to_destination_temp, + ) + .finish() + } +} + /// Borrowed canonical view of a task that reads or writes one final file. /// Source-specific task variants keep their scheduler data, while integrity, /// ownership, and frontend code use this shared view. @@ -493,6 +691,27 @@ pub enum Task { patch: Arc, entry_index: usize, }, + /// Decode a prevalidated HDiff patch through compio. The temporary is + /// carried by RAII ownership across the same-node WorkUnit continuation. + #[doc(hidden)] + DecodeHdiffPatchEntry { + patch: Arc, + entry_index: usize, + #[cfg(feature = "hdiff-patch")] + checkpoint: crate::patch_apply::hdiff_sf20::HdiffCheckpoint, + #[cfg(feature = "hdiff-patch")] + retained: Option, + prepared: PreparedHdiffPatchOutput, + }, + /// Third scheduling WorkUnit for an HDiff entry. `TaskRun::Continue` + /// replaces the payload of the same graph node, so this is not a new DAG + /// dependency/correctness node. + #[doc(hidden)] + CommitHdiffPatchEntry { + patch: Arc, + entry_index: usize, + prepared: PreparedHdiffPatchOutput, + }, #[doc(hidden)] ReleasePatchBase { patch: Arc, @@ -509,7 +728,7 @@ pub enum Task { #[doc(hidden)] CleanPatchApply { patch: Arc, - archive: Arc, + archive: Option>, }, #[doc(hidden)] CleanupArchive { diff --git a/crates/griffr-runtime/src/task_pool/types/tests.rs b/crates/griffr-runtime/src/task_pool/types/tests.rs index a1274ef..0ac3b44 100644 --- a/crates/griffr-runtime/src/task_pool/types/tests.rs +++ b/crates/griffr-runtime/src/task_pool/types/tests.rs @@ -1,7 +1,7 @@ use super::{ destination_or_repair_tasks, should_report_item_progress, ArchiveDirectCommitState, - ArchiveRepairSession, ArchiveRetention, ArchiveWork, FileEnsureTask, PreparedArchive, Task, - TaskOutcome, TaskPoolConfig, TransferClass, WorkerEvent, + ArchiveRepairSession, ArchiveRetention, ArchiveWork, FileEnsureTask, PreparedArchive, + PreparedHdiffPatchOutput, Task, TaskOutcome, TaskPoolConfig, TransferClass, WorkerEvent, }; use crate::download::extractor::MultiVolumeLayout; use crate::ContentHash; @@ -9,6 +9,20 @@ use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Arc; +#[test] +fn prepared_hdiff_output_cleans_up_when_last_continuation_owner_drops() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("prepared-hdiff.tmp"); + std::fs::write(&path, b"prepared").unwrap(); + + let prepared = PreparedHdiffPatchOutput::new(path.clone(), true); + let clone = prepared.clone(); + drop(prepared); + assert!(path.exists()); + drop(clone); + assert!(!path.exists()); +} + #[test] fn transient_worker_progress_is_not_a_durable_outcome() { assert!(matches!( @@ -398,3 +412,15 @@ fn extract_slot_override_keeps_two_ready_shards_per_slot() { assert_eq!(two_slots.extract_slots, 2); assert_eq!(two_slots.extract_shards, 4); } + +#[test] +fn patch_output_owner_rejects_collision_without_removing_foreign_path() { + let temp = tempfile::tempdir().unwrap(); + let directory = temp.path().join("occupied"); + std::fs::create_dir(&directory).unwrap(); + let foreign = directory.join("output"); + std::fs::write(&foreign, b"foreign").unwrap(); + let error = PreparedHdiffPatchOutput::create(directory, false).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(foreign).unwrap(), b"foreign"); +} diff --git a/crates/griffr-runtime/src/task_pool/verify.rs b/crates/griffr-runtime/src/task_pool/verify.rs index 28182b7..d41260f 100644 --- a/crates/griffr-runtime/src/task_pool/verify.rs +++ b/crates/griffr-runtime/src/task_pool/verify.rs @@ -53,12 +53,19 @@ pub(crate) fn run_verify( expected_size: Option, on_fail: Option>, event_tx: &flume::Sender, -) -> super::graph::TaskRun { - finish_verify( +) -> (super::graph::TaskRun, u64) { + let mut read_bytes = 0; + let issue = build_issue_impl( + None, + path, logical_path, - build_issue(path, logical_path, expected_hash, expected_size), - on_fail, - event_tx, + expected_hash, + expected_size, + &mut read_bytes, + ); + ( + finish_verify(logical_path, issue, on_fail, event_tx), + read_bytes, ) } @@ -97,6 +104,7 @@ fn finish_verify( struct Md5VerifyEntry { file: Option, + read_bytes: u64, logical_path: String, expected_hash: ContentHash, expected_size: Option, @@ -121,6 +129,7 @@ impl Md5VerifyEntry { let mut entry = Self { file: None, + read_bytes: 0, logical_path: logical_path.clone(), expected_hash: expected_hash.clone(), expected_size: *expected_size, @@ -174,10 +183,15 @@ impl Md5VerifyEntry { } } +pub(crate) struct Md5VerifyBatchResult { + pub(crate) run: super::graph::TaskRun, + pub(crate) storage_read_bytes: u64, +} + pub(crate) fn run_md5_verify_batch( tasks: &mut [&mut Task], event_tx: &flume::Sender, -) -> Vec { +) -> Vec { debug_assert!(tasks.len() >= 2); debug_assert!(tasks.iter().all(|task| is_md5_verify_task(task))); @@ -215,6 +229,8 @@ pub(crate) fn run_md5_verify_batch( Ok(0) => entries[index].file = None, Ok(read) => { lengths[index] = read; + entries[index].read_bytes = + entries[index].read_bytes.saturating_add(read as u64); any_read = true; } Err(_) => { @@ -246,7 +262,11 @@ pub(crate) fn run_md5_verify_batch( entry.issue = Some(entry.hash_failure(Some(actual_hash))); } } - finish_verify(&entry.logical_path, entry.issue, entry.on_fail, event_tx) + let run = finish_verify(&entry.logical_path, entry.issue, entry.on_fail, event_tx); + Md5VerifyBatchResult { + run, + storage_read_bytes: entry.read_bytes, + } }) .collect() } @@ -376,6 +396,7 @@ impl VerifiedArtifactCache { logical_path, &expected_hash, expected_size, + &mut 0, ) } } @@ -387,7 +408,14 @@ pub(crate) fn build_issue( expected_size: Option, ) -> Option { let expected_hash = expected_hash.into(); - build_issue_impl(None, path, logical_path, &expected_hash, expected_size) + build_issue_impl( + None, + path, + logical_path, + &expected_hash, + expected_size, + &mut 0, + ) } fn build_issue_impl( @@ -396,6 +424,7 @@ fn build_issue_impl( logical_path: &str, expected_hash: &ContentHash, expected_size: Option, + read_bytes: &mut u64, ) -> Option { let metadata = match std::fs::metadata(path) { Ok(metadata) => metadata, @@ -447,7 +476,7 @@ fn build_issue_impl( kind: FileIssueKind::SizeMismatch, }) } else { - match file_hash(path, expected_hash) { + match file_hash_counted(path, expected_hash, read_bytes) { Ok(actual_hash) if actual_hash == *expected_hash => None, Ok(actual_hash) => Some(FileIssue { path: logical_path.to_string(), @@ -530,6 +559,14 @@ pub(crate) fn verify_candidate_cancellable( } pub(crate) fn file_hash(path: &Path, expected_hash: &ContentHash) -> Result { + file_hash_counted(path, expected_hash, &mut 0) +} + +fn file_hash_counted( + path: &Path, + expected_hash: &ContentHash, + read_bytes: &mut u64, +) -> Result { let mut file = open_sequential_read(path).map_err(|e| Error::IoAt { action: "open file", path: path.to_path_buf(), @@ -542,6 +579,7 @@ pub(crate) fn file_hash(path: &Path, expected_hash: &ContentHash) -> Result>(); + let (event_tx, _event_rx) = flume::unbounded(); + + let results = super::run_md5_verify_batch(&mut task_refs, &event_tx); + + assert_eq!(results.len(), 2); + assert_eq!(results[0].storage_read_bytes, 0); + assert!(results[0].run.failure_details().is_some()); + assert_eq!(results[1].storage_read_bytes, payload.len() as u64); + assert!(results[1].run.failure_details().is_none()); + } + #[test] fn cached_mismatch_is_invalidated_when_file_metadata_changes() { let temp = tempfile::tempdir().unwrap(); @@ -673,3 +753,79 @@ mod tests { assert!(super::build_issue(&path, "artifact.bin", &expected, Some(9)).is_none()); } } + +#[cfg(test)] +mod capture_tests { + use crate::task_pool::{Task, TaskPoolConfig}; + + #[test] + fn scalar_verify_reports_actual_bytes_including_early_failure() { + use crate::task_pool::run_tasks; + use crate::task_pool::workload::{CompactWorkload, QuantitySource, WorkloadCaptureConfig}; + use md5::Digest; + let temp = tempfile::tempdir().unwrap(); + let data = b"scalar verify bytes"; + let hash = crate::ContentHash::md5(griffr_core::to_hex(&md5::Md5::digest(data))).unwrap(); + let path = temp.path().join("file"); + std::fs::write(&path, data).unwrap(); + for (name, expected_size, expected_bytes, should_fail, present) in [ + ("match", data.len() as u64, data.len() as u64, false, true), + ("size-mismatch", 1, 0, true, true), + ("missing", data.len() as u64, 0, true, false), + ] { + let trace = temp.path().join(format!("{name}.ndjson")); + let config = TaskPoolConfig { + workload_capture: Some(WorkloadCaptureConfig::streaming_strict( + &trace, + "scalar-verify", + )), + ..TaskPoolConfig::default() + }; + let result = run_tasks( + vec![Task::Verify { + path: if present { + path.clone() + } else { + temp.path().join("missing") + }, + logical_path: name.to_string(), + expected_hash: hash.clone(), + expected_size: Some(expected_size), + on_fail: None, + }], + config, + ) + .unwrap(); + assert_eq!(result.metrics.graph.failed_nodes, usize::from(should_fail)); + // A failed workload may be ineligible for counterfactual replay; + // inspect its actual Finished sample directly. + let trace = crate::task_pool::workload::WorkloadTrace::from_path(trace).unwrap(); + use crate::task_pool::workload::{WorkloadEventKind, WorkloadRecordPayload}; + let samples = trace + .records + .iter() + .filter_map(|r| match &r.payload { + WorkloadRecordPayload::Event(e) => match &e.kind { + WorkloadEventKind::Finished { + observed_service, .. + } => Some(observed_service.storage_read_bytes), + _ => None, + }, + _ => None, + }) + .collect::>(); + assert_eq!(samples.len(), 1); + assert_eq!(samples[0].source, QuantitySource::Observed); + assert_eq!(samples[0].value, expected_bytes); + if !should_fail { + assert_eq!( + CompactWorkload::from_trace(&trace) + .unwrap() + .work_units + .len(), + 1 + ); + } + } + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/compact.rs b/crates/griffr-runtime/src/task_pool/workload/compact.rs new file mode 100644 index 0000000..935adc3 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/compact.rs @@ -0,0 +1,761 @@ +use std::collections::BTreeMap; +use std::io::{BufRead, Read, Write}; +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use super::schema::visit_workload_records; +use super::validate::WorkloadTraceValidator; +use super::{ + MachineProfile, ObservedService, SanitizedPath, SanitizedVolume, SchedulerConfigProfile, + ValidationReport, WorkUnitIdentity, WorkloadBatchClass, WorkloadCompletion, WorkloadEdge, + WorkloadEventKind, WorkloadNode, WorkloadNodeId, WorkloadOccupancyAction, WorkloadRecord, + WorkloadRecordPayload, WorkloadResourceDemand, WorkloadTrace, WorkloadTraceHeader, +}; +use crate::error::{Error, Result}; +use crate::task_pool::SchedulerTaskPriority; + +pub const COMPACT_WORKLOAD_SCHEMA_VERSION: u32 = 5; + +/// Content-free scheduler replay model reduced from a validated raw workload trace. +/// +/// Raw observation-only records such as candidate probes, occupancy snapshots, wall-clock +/// timestamps, and writer statistics intentionally do not survive this reduction. Replay is +/// driven by DAG/expansion structure, resource demand, and observed service rather than by the +/// captured start timeline. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompactWorkload { + pub schema_version: u32, + pub source_tree: String, + pub scheduler: SchedulerConfigProfile, + pub machine: MachineProfile, + pub nodes: Vec, + pub edges: Vec, + pub paths: Vec, + pub volumes: Vec, + pub work_units: Vec, + pub expansions: Vec, + /// Empirical coalesced-service samples retained for policies that may form different legal + /// execution batches. These samples describe service shape, not captured admission timing. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub observed_batch_services: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompactNode { + pub node: WorkloadNode, + pub dependencies: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompactWorkUnit { + pub identity: WorkUnitIdentity, + pub priority: SchedulerTaskPriority, + pub demand: WorkloadResourceDemand, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub batch_class: Option, + /// Relative capture time at which the runtime first reported this WorkUnit dependency-ready. + /// Structural replay does not force admission at this timestamp; it is retained as an + /// observation/calibration constraint for future live analysis. + pub observed_ready_ns: u64, + pub observed_queue_wait_ns: u64, + pub observed_service: ObservedService, + pub completion: WorkloadCompletion, + pub hdiff_retention_released: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObservedBatchService { + pub batch_class: WorkloadBatchClass, + pub member_count: usize, + pub total_storage_read_bytes: u64, + pub max_storage_read_bytes: u64, + pub run_time_ns: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompactExpansion { + pub parent: WorkUnitIdentity, + pub new_nodes: Vec, + pub new_edges: Vec, +} + +#[derive(Debug, Default)] +struct WorkUnitBuilder { + ready_ns: Option, + priority: Option, + demand: Option, + queue_wait_ns: Option, + service: Option, + completion: Option, + hdiff_retention_released: bool, + ready_order: Option, + batch_class: Option, +} + +#[derive(Debug, Default)] +struct CompactWorkloadBuilder { + header: Option, + nodes: BTreeMap, + edges: Vec, + dependencies: BTreeMap>, + paths: Vec, + volumes: Vec, + units: BTreeMap, + expansions: Vec, + ready_order: u64, + pending_admissions: Vec, + observed_batch_groups: Vec>, +} + +impl CompactWorkloadBuilder { + fn push(&mut self, record: &WorkloadRecord) { + match &record.payload { + WorkloadRecordPayload::Header(header) => self.header = Some(header.clone()), + WorkloadRecordPayload::Node(node) => { + self.nodes.insert(node.id.clone(), node.clone()); + } + WorkloadRecordPayload::Edge(edge) => { + self.dependencies + .entry(edge.to.clone()) + .or_default() + .push(edge.from.clone()); + self.edges.push(edge.clone()); + } + WorkloadRecordPayload::Path(path) => self.paths.push(path.clone()), + WorkloadRecordPayload::Volume(volume) => self.volumes.push(volume.clone()), + WorkloadRecordPayload::Event(event) => match &event.kind { + WorkloadEventKind::Ready { + work_unit, + batch_class, + .. + } => { + let builder = self.units.entry(work_unit.clone()).or_default(); + builder.ready_ns = Some(event.elapsed_ns); + builder.ready_order = Some(self.ready_order); + builder.batch_class = *batch_class; + self.ready_order = self.ready_order.saturating_add(1); + } + WorkloadEventKind::Routed { + work_unit, + priority, + demand, + } => { + let builder = self.units.entry(work_unit.clone()).or_default(); + builder.priority = Some(*priority); + builder.demand = Some(demand.clone()); + } + WorkloadEventKind::Finished { + work_unit, + completion, + hdiff_retention_released, + queue_wait_ns, + observed_service, + } => { + let builder = self.units.entry(work_unit.clone()).or_default(); + builder.queue_wait_ns = Some(*queue_wait_ns); + builder.service = Some(*observed_service); + builder.completion = Some(*completion); + builder.hdiff_retention_released = *hdiff_retention_released; + } + WorkloadEventKind::Expanded { + parent, + new_nodes, + new_edges, + } => self.expansions.push(CompactExpansion { + parent: parent.clone(), + new_nodes: new_nodes.clone(), + new_edges: new_edges.clone(), + }), + WorkloadEventKind::Admitted { work_unit, .. } => { + self.pending_admissions.push(work_unit.clone()); + } + WorkloadEventKind::Started { .. } => { + if !self.pending_admissions.is_empty() { + if self.pending_admissions.len() > 1 { + self.observed_batch_groups + .push(self.pending_admissions.clone()); + } + self.pending_admissions.clear(); + } + } + WorkloadEventKind::Occupancy { + action: WorkloadOccupancyAction::Release, + work_unit, + .. + } => { + // A released admission that never started is not a batch member. + self.pending_admissions + .retain(|pending| pending != work_unit); + } + WorkloadEventKind::Created { .. } + | WorkloadEventKind::Considered { .. } + | WorkloadEventKind::Decision(_) + | WorkloadEventKind::Occupancy { .. } => {} + }, + WorkloadRecordPayload::Footer(_) => {} + } + } + + fn finish(mut self, report: ValidationReport) -> Result { + require_replay_authority(&report)?; + let header = self.header.take().ok_or_else(|| Error::Message { + context: "Compact workload error: ", + detail: "validated trace has no header".to_owned(), + })?; + + for deps in self.dependencies.values_mut() { + deps.sort(); + deps.dedup(); + } + self.edges + .sort_by(|left, right| (&left.to, &left.from).cmp(&(&right.to, &right.from))); + self.paths + .sort_by(|left, right| left.path_id.cmp(&right.path_id)); + self.volumes + .sort_by(|left, right| left.volume_id.cmp(&right.volume_id)); + + let mut compact_nodes = self + .nodes + .into_values() + .map(|node| CompactNode { + dependencies: self.dependencies.remove(&node.id).unwrap_or_default(), + node, + }) + .collect::>(); + compact_nodes.sort_by(|left, right| left.node.id.cmp(&right.node.id)); + + let mut observed_batch_services = Vec::new(); + for group in &self.observed_batch_groups { + let mut run_time_ns = None; + let mut total_storage_read_bytes = 0u64; + let mut max_storage_read_bytes = 0u64; + let mut complete_success = true; + for identity in group { + let Some(builder) = self.units.get(identity) else { + complete_success = false; + break; + }; + if builder.completion != Some(WorkloadCompletion::Succeeded) { + complete_success = false; + break; + } + let Some(service) = builder.service else { + complete_success = false; + break; + }; + let member_run = service.run_time_ns.value; + if let Some(expected) = run_time_ns { + if expected != member_run { + complete_success = false; + break; + } + } else { + run_time_ns = Some(member_run); + } + let read_bytes = service.storage_read_bytes.value; + total_storage_read_bytes = total_storage_read_bytes.saturating_add(read_bytes); + max_storage_read_bytes = max_storage_read_bytes.max(read_bytes); + } + if complete_success + && total_storage_read_bytes > 0 + && run_time_ns.is_some_and(|value| value > 0) + { + observed_batch_services.push(ObservedBatchService { + batch_class: WorkloadBatchClass::Md5Verify, + member_count: group.len(), + total_storage_read_bytes, + max_storage_read_bytes, + run_time_ns: run_time_ns.unwrap_or(1), + }); + } + } + observed_batch_services.sort_by_key(|sample| { + ( + sample.member_count, + sample.total_storage_read_bytes, + sample.max_storage_read_bytes, + sample.run_time_ns, + ) + }); + + let mut compact_units = self + .units + .into_iter() + .map(|(identity, builder)| build_work_unit(identity, builder)) + .collect::>>()?; + compact_units.sort_by_key(|unit| unit.1); + let compact_units = compact_units.into_iter().map(|(unit, _)| unit).collect(); + + self.expansions + .sort_by(|left, right| left.parent.cmp(&right.parent)); + + Ok(CompactWorkload { + schema_version: COMPACT_WORKLOAD_SCHEMA_VERSION, + source_tree: header.source_tree, + scheduler: header.scheduler, + machine: header.machine, + nodes: compact_nodes, + edges: self.edges, + paths: self.paths, + volumes: self.volumes, + work_units: compact_units, + expansions: self.expansions, + observed_batch_services, + }) + } +} + +impl CompactWorkload { + fn reduce_records<'a>(records: impl IntoIterator) -> Result { + let mut validator = WorkloadTraceValidator::default(); + let mut builder = CompactWorkloadBuilder::default(); + for record in records { + validator.push(record)?; + builder.push(record); + } + let report = validator.finish()?; + builder.finish(report) + } + + pub fn from_trace(trace: &WorkloadTrace) -> Result { + Self::reduce_records(&trace.records) + } + + /// Validate and reduce a raw NDJSON workload trace in one pass. + /// + /// Memory use is proportional to scheduler-semantic topology/WorkUnits, not to the number of + /// observation records. This is the preferred M5E path for workstation traces. + pub fn from_trace_reader(reader: impl BufRead) -> Result { + let mut validator = WorkloadTraceValidator::default(); + let mut builder = CompactWorkloadBuilder::default(); + visit_workload_records(reader, |record| { + validator.push(&record)?; + builder.push(&record); + Ok(()) + })?; + let report = validator.finish()?; + builder.finish(report) + } + + pub fn from_trace_path(path: impl AsRef) -> Result { + let file = std::fs::File::open(path)?; + Self::from_trace_reader(std::io::BufReader::new(file)) + } + + pub fn from_reader(reader: impl Read) -> Result { + let workload = serde_json::from_reader::<_, Self>(reader)?; + if workload.schema_version != COMPACT_WORKLOAD_SCHEMA_VERSION { + return Err(Error::Message { + context: "Compact workload error: ", + detail: format!( + "unsupported compact schema version {}; supported version is {}", + workload.schema_version, COMPACT_WORKLOAD_SCHEMA_VERSION + ), + }); + } + Ok(workload) + } + + pub fn write_json(&self, writer: impl Write) -> Result<()> { + serde_json::to_writer(writer, self)?; + Ok(()) + } +} + +fn require_replay_authority(report: &ValidationReport) -> Result<()> { + if report.replay_authority { + return Ok(()); + } + Err(Error::Message { + context: "Compact workload error: ", + detail: format!( + "raw trace is not replay authority: {}", + report.disqualifications.join(", ") + ), + }) +} + +fn build_work_unit( + identity: WorkUnitIdentity, + builder: WorkUnitBuilder, +) -> Result<(CompactWorkUnit, u64)> { + let identity_label = format!("{identity:?}"); + let missing = |field: &'static str| Error::Message { + context: "Compact workload error: ", + detail: format!("work unit {identity_label} is missing {field}"), + }; + let order = builder.ready_order.ok_or_else(|| missing("ready event"))?; + Ok(( + CompactWorkUnit { + identity, + priority: builder.priority.ok_or_else(|| missing("routed event"))?, + demand: builder.demand.ok_or_else(|| missing("resource demand"))?, + batch_class: builder.batch_class, + observed_ready_ns: builder.ready_ns.ok_or_else(|| missing("ready time"))?, + observed_queue_wait_ns: builder + .queue_wait_ns + .ok_or_else(|| missing("queue wait observation"))?, + observed_service: builder.service.ok_or_else(|| missing("observed service"))?, + completion: builder.completion.ok_or_else(|| missing("completion"))?, + hdiff_retention_released: builder.hdiff_retention_released, + }, + order, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::task_pool::workload::{ + MachineProfile, QuantitySource, SchedulerConfigProfile, ServiceQuantity, TraceFooter, + WorkUnitPhase, WorkloadCaptureMode, WorkloadDagHint, WorkloadEvent, WorkloadNodeId, + WorkloadRecord, WorkloadTaskOrigin, WorkloadTimeModel, WorkloadTraceHeader, + WorkloadVolumePolicy, WorkloadVolumeStreamingMode, WORKLOAD_TRACE_SCHEMA_VERSION, + }; + use crate::task_pool::{SchedulerRunClass, ServiceEstimate}; + + fn header() -> WorkloadTraceHeader { + WorkloadTraceHeader { + schema_version: WORKLOAD_TRACE_SCHEMA_VERSION, + run_id: 1, + runner_id: 1, + time_model: WorkloadTimeModel::MonotonicRelativeNanoseconds, + wall_clock_start_unix_ns: Some(123), + source_tree: "tree".to_owned(), + workload_kind: Some("verify".to_owned()), + capture_mode: WorkloadCaptureMode::Memory, + scheduler: SchedulerConfigProfile { + cpu_slots: 1, + hdiff_decoder_slots: 2, + blocking_slots: 1, + network_slots: 1, + extract_slots: 1, + reuse_queue_limit: 1, + volume_write_reservation_delay_ns: 15_000_000, + ready_frontier_limit: 256, + priority_lookahead: 64, + continuation_burst: 4, + default_volume_policy: WorkloadVolumePolicy { + read_limit: 1, + write_limit: 1, + metadata_limit: 1, + streaming_pressure_limit: 1, + streaming_mode: WorkloadVolumeStreamingMode::Mixed, + }, + volume_policy_overrides: vec![], + }, + machine: MachineProfile { + os: "test".to_owned(), + architecture: "test".to_owned(), + available_parallelism: 1, + md5_verify_batch_capacity: 1, + }, + } + } + + fn trace() -> WorkloadTrace { + let node = WorkloadNodeId { + run_id: 1, + node_id: 0, + }; + let unit = WorkUnitIdentity { + node: node.clone(), + task_kind: "Verify".to_owned(), + phase: WorkUnitPhase::Generic, + attempt: 1, + continuation_generation: 0, + }; + let demand = WorkloadResourceDemand { + cpu_on_async: false, + hdiff_decoder_start: false, + run_class: SchedulerRunClass::Cpu, + network_class: None, + read_volumes: vec!["volume#01".to_owned()], + write_volumes: vec![], + metadata_volumes: vec![], + archive_save_volumes: vec![], + archive_commit_volumes: vec![], + extract: false, + mutation_paths: vec!["path#000001".to_owned()], + storage_reservations: vec![], + reuse_probe: false, + reuse_commit: false, + priority_cost: 10, + service_estimate: ServiceEstimate { + cpu_cost: 10, + ..ServiceEstimate::default() + }, + }; + let service = ObservedService { + run_time_ns: ServiceQuantity::observed(50), + cpu_cost: ServiceQuantity { + value: 10, + source: QuantitySource::Estimated, + }, + network_bytes: ServiceQuantity::unknown(), + storage_read_bytes: ServiceQuantity::unknown(), + storage_write_bytes: ServiceQuantity::unknown(), + metadata_ops: ServiceQuantity::unknown(), + }; + let payloads = vec![ + WorkloadRecordPayload::Header(header()), + WorkloadRecordPayload::Node(WorkloadNode { + id: node.clone(), + task_kind: "Verify".to_owned(), + dag_hint: WorkloadDagHint { + origin: WorkloadTaskOrigin::Root, + depth: 0, + local_rank: None, + }, + expansion_parent: None, + }), + WorkloadRecordPayload::Path(SanitizedPath { + path_id: "path#000001".to_owned(), + parent_id: None, + volume_id: "volume#01".to_owned(), + }), + WorkloadRecordPayload::Volume(SanitizedVolume { + volume_id: "volume#01".to_owned(), + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 0, + elapsed_ns: 0, + kind: WorkloadEventKind::Created { node: node.clone() }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 1, + elapsed_ns: 1, + kind: WorkloadEventKind::Ready { + work_unit: unit.clone(), + dag_hint: WorkloadDagHint { + origin: WorkloadTaskOrigin::Root, + depth: 0, + local_rank: None, + }, + batch_class: None, + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 2, + elapsed_ns: 2, + kind: WorkloadEventKind::Routed { + work_unit: unit.clone(), + priority: SchedulerTaskPriority::Bulk, + demand, + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 3, + elapsed_ns: 3, + kind: WorkloadEventKind::Admitted { + work_unit: unit.clone(), + service_estimate: ServiceEstimate::default(), + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 4, + elapsed_ns: 4, + kind: WorkloadEventKind::Started { + work_unit: unit.clone(), + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 5, + elapsed_ns: 54, + kind: WorkloadEventKind::Finished { + work_unit: unit, + hdiff_retention_released: false, + completion: WorkloadCompletion::Succeeded, + queue_wait_ns: 2, + observed_service: service, + }, + }), + ]; + let mut records = payloads + .into_iter() + .enumerate() + .map(|(sequence, payload)| WorkloadRecord { + sequence: sequence as u64, + payload, + }) + .collect::>(); + records.push(WorkloadRecord { + sequence: records.len() as u64, + payload: WorkloadRecordPayload::Footer(TraceFooter { + record_count: records.len() as u64 + 1, + event_count: 6, + node_count: 1, + edge_count: 0, + dropped_event_count: 0, + peak_queued_events: 0, + capture_complete: true, + complete_for_replay: true, + writer_error: None, + }), + }); + WorkloadTrace { records } + } + + #[test] + fn compact_reduction_keeps_scheduler_semantics_and_drops_wall_clock() { + let compact = CompactWorkload::from_trace(&trace()).unwrap(); + assert_eq!(compact.nodes.len(), 1); + assert_eq!(compact.work_units.len(), 1); + assert_eq!(compact.work_units[0].observed_service.run_time_ns.value, 50); + let json = serde_json::to_string(&compact).unwrap(); + assert!(!json.contains("wall_clock_start")); + assert!(!json.contains("candidate_index")); + assert!(!json.contains("123")); + } + + #[test] + fn compact_round_trip_is_stable() { + let compact = CompactWorkload::from_trace(&trace()).unwrap(); + let mut bytes = Vec::new(); + compact.write_json(&mut bytes).unwrap(); + let parsed = CompactWorkload::from_reader(bytes.as_slice()).unwrap(); + assert_eq!(parsed, compact); + } + + #[test] + fn observed_md5_batch_service_keeps_actual_bytes_and_shared_runtime() { + let identity = |node_id| WorkUnitIdentity { + node: WorkloadNodeId { run_id: 1, node_id }, + task_kind: "Verify".to_owned(), + phase: WorkUnitPhase::Generic, + attempt: 1, + continuation_generation: 0, + }; + let leader = identity(0); + let follower = identity(1); + let mut builder = CompactWorkloadBuilder::default(); + let mut capture_header = header(); + capture_header.machine.md5_verify_batch_capacity = 3; + builder.push(&WorkloadRecord { + sequence: 0, + payload: WorkloadRecordPayload::Header(capture_header), + }); + let demand = WorkloadResourceDemand { + cpu_on_async: false, + hdiff_decoder_start: false, + run_class: SchedulerRunClass::Cpu, + network_class: None, + read_volumes: vec!["volume#01".to_owned()], + write_volumes: vec![], + metadata_volumes: vec![], + archive_save_volumes: vec![], + archive_commit_volumes: vec![], + extract: false, + mutation_paths: vec![], + storage_reservations: vec![], + reuse_probe: false, + reuse_commit: false, + priority_cost: 0, + service_estimate: ServiceEstimate::default(), + }; + let event = |event_sequence, kind| WorkloadRecord { + sequence: event_sequence + 1, + payload: WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence, + elapsed_ns: event_sequence, + kind, + }), + }; + for unit in [&leader, &follower] { + builder.push(&event( + unit.node.node_id as u64 * 3, + WorkloadEventKind::Ready { + work_unit: unit.clone(), + dag_hint: WorkloadDagHint { + origin: WorkloadTaskOrigin::Root, + depth: 0, + local_rank: None, + }, + batch_class: Some(WorkloadBatchClass::Md5Verify), + }, + )); + builder.push(&event( + unit.node.node_id as u64 * 3 + 1, + WorkloadEventKind::Routed { + work_unit: unit.clone(), + priority: SchedulerTaskPriority::Bulk, + demand: demand.clone(), + }, + )); + } + builder.push(&event( + 6, + WorkloadEventKind::Admitted { + work_unit: leader.clone(), + service_estimate: ServiceEstimate::default(), + }, + )); + builder.push(&event( + 7, + WorkloadEventKind::Admitted { + work_unit: follower.clone(), + service_estimate: ServiceEstimate::default(), + }, + )); + builder.push(&event( + 8, + WorkloadEventKind::Started { + work_unit: leader.clone(), + }, + )); + for (offset, unit, read_bytes) in [(9, leader, 10_u64), (10, follower, 30_u64)] { + builder.push(&event( + offset, + WorkloadEventKind::Finished { + work_unit: unit, + hdiff_retention_released: false, + completion: WorkloadCompletion::Succeeded, + queue_wait_ns: 0, + observed_service: ObservedService { + run_time_ns: ServiceQuantity::observed(50), + cpu_cost: ServiceQuantity::unknown(), + network_bytes: ServiceQuantity::unknown(), + storage_read_bytes: ServiceQuantity::observed(read_bytes), + storage_write_bytes: ServiceQuantity::unknown(), + metadata_ops: ServiceQuantity::unknown(), + }, + }, + )); + } + + let compact = builder + .finish(ValidationReport { + replay_authority: true, + disqualifications: vec![], + record_count: 0, + event_count: 0, + node_count: 0, + edge_count: 0, + }) + .unwrap(); + assert_eq!(compact.machine.md5_verify_batch_capacity, 3); + assert_eq!(compact.observed_batch_services.len(), 1); + assert_eq!( + compact.observed_batch_services[0], + ObservedBatchService { + batch_class: WorkloadBatchClass::Md5Verify, + member_count: 2, + total_storage_read_bytes: 40, + max_storage_read_bytes: 30, + run_time_ns: 50, + } + ); + } + + #[test] + fn raw_trace_streaming_reduction_matches_in_memory_reduction() { + let trace = trace(); + let expected = CompactWorkload::from_trace(&trace).unwrap(); + let mut bytes = Vec::new(); + trace.write_ndjson(&mut bytes).unwrap(); + let actual = + CompactWorkload::from_trace_reader(std::io::BufReader::new(bytes.as_slice())).unwrap(); + assert_eq!(actual, expected); + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/mod.rs b/crates/griffr-runtime/src/task_pool/workload/mod.rs new file mode 100644 index 0000000..6c91c75 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/mod.rs @@ -0,0 +1,14 @@ +mod compact; +mod recorder; +mod replay; +mod retention; +mod sanitize; +mod schema; +mod validate; + +pub use compact::*; +pub use recorder::*; +pub use replay::*; +pub use sanitize::*; +pub use schema::*; +pub use validate::*; diff --git a/crates/griffr-runtime/src/task_pool/workload/recorder.rs b/crates/griffr-runtime/src/task_pool/workload/recorder.rs new file mode 100644 index 0000000..2a53571 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/recorder.rs @@ -0,0 +1,607 @@ +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; + +use super::{ + TraceFooter, WorkloadCaptureMode, WorkloadRecord, WorkloadRecordPayload, WorkloadTrace, + WorkloadTraceHeader, +}; +use crate::error::{Error, Result}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RecordDisposition { + Stored, + Dropped, + Disabled, +} + +#[derive(Debug)] +pub struct TraceSink { + inner: TraceSinkInner, + next_sequence: u64, + event_count: u64, + node_count: u64, + edge_count: u64, + dropped_event_count: Arc, + peak_queued_events: Arc, +} + +#[derive(Debug)] +enum TraceSinkInner { + Disabled, + Memory(Vec), + Streaming(StreamingSink), +} + +#[derive(Debug)] +struct StreamingSink { + mode: WorkloadCaptureMode, + tx: flume::Sender, + worker: Option>, +} + +// Keep the record inline: boxing every hot-path event would add one heap allocation per +// trace record solely to shrink this channel enum. The bounded queue already caps memory. +#[allow(clippy::large_enum_variant)] +#[derive(Debug)] +enum WriterMessage { + Record(WorkloadRecord), + Finish(TraceFooter), +} + +#[derive(Debug, Default)] +struct WriterOutcome { + writer_error: Option, + footer_written: bool, +} + +#[derive(Debug)] +pub struct TraceSinkFinish { + pub trace: Option, + pub footer: TraceFooter, + pub footer_written: bool, +} + +impl TraceSink { + pub fn disabled() -> Self { + Self { + inner: TraceSinkInner::Disabled, + next_sequence: 0, + event_count: 0, + node_count: 0, + edge_count: 0, + dropped_event_count: Arc::new(AtomicU64::new(0)), + peak_queued_events: Arc::new(AtomicUsize::new(0)), + } + } + + pub fn memory(header: WorkloadTraceHeader) -> Result { + let mut sink = Self { + inner: TraceSinkInner::Memory(Vec::new()), + next_sequence: 0, + event_count: 0, + node_count: 0, + edge_count: 0, + dropped_event_count: Arc::new(AtomicU64::new(0)), + peak_queued_events: Arc::new(AtomicUsize::new(0)), + }; + sink.store_required(WorkloadRecordPayload::Header(header))?; + Ok(sink) + } + + pub fn streaming( + path: impl AsRef, + header: WorkloadTraceHeader, + channel_capacity: usize, + ) -> Result { + if !matches!( + header.capture_mode, + WorkloadCaptureMode::StreamingStrict | WorkloadCaptureMode::StreamingLossAware + ) { + return Err(Error::Message { + context: "Workload trace configuration error: ", + detail: "streaming sink requires a streaming capture mode".to_owned(), + }); + } + let path = path.as_ref(); + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent)?; + } + let file = File::create(path)?; + let (tx, rx) = flume::bounded(channel_capacity.max(1)); + let worker = thread::Builder::new() + .name("griffr-workload-trace-writer".to_owned()) + .spawn(move || writer_main(file, rx)) + .map_err(Error::Io)?; + let mode = header.capture_mode; + let mut sink = Self { + inner: TraceSinkInner::Streaming(StreamingSink { + mode, + tx, + worker: Some(worker), + }), + next_sequence: 0, + event_count: 0, + node_count: 0, + edge_count: 0, + dropped_event_count: Arc::new(AtomicU64::new(0)), + peak_queued_events: Arc::new(AtomicUsize::new(0)), + }; + sink.store_required(WorkloadRecordPayload::Header(header))?; + Ok(sink) + } + + #[inline] + pub fn enabled(&self) -> bool { + !matches!(self.inner, TraceSinkInner::Disabled) + } + + pub fn record(&mut self, payload: WorkloadRecordPayload) -> Result { + match self.inner { + TraceSinkInner::Disabled => Ok(RecordDisposition::Disabled), + TraceSinkInner::Memory(_) => self.store_required(payload), + TraceSinkInner::Streaming(StreamingSink { + mode: WorkloadCaptureMode::StreamingStrict, + .. + }) => self.store_required(payload), + TraceSinkInner::Streaming(StreamingSink { + mode: WorkloadCaptureMode::StreamingLossAware, + .. + }) => self.try_store(payload), + TraceSinkInner::Streaming(StreamingSink { + mode: WorkloadCaptureMode::Memory, + .. + }) => unreachable!("streaming constructor rejects memory mode"), + } + } + + pub fn dropped_event_count(&self) -> u64 { + self.dropped_event_count.load(Ordering::Relaxed) + } + + pub fn peak_queued_events(&self) -> usize { + self.peak_queued_events.load(Ordering::Relaxed) + } + + pub fn finish(mut self) -> Result { + if matches!(self.inner, TraceSinkInner::Disabled) { + let footer = self.build_footer(true, None); + return Ok(TraceSinkFinish { + trace: None, + footer, + footer_written: false, + }); + } + + let mut footer = self.build_footer(true, None); + footer.record_count = self.next_sequence.saturating_add(1); + let footer_record = WorkloadRecord { + sequence: self.next_sequence, + payload: WorkloadRecordPayload::Footer(footer.clone()), + }; + + match &mut self.inner { + TraceSinkInner::Memory(records) => { + records.push(footer_record); + self.next_sequence = self.next_sequence.saturating_add(1); + let trace = WorkloadTrace { + records: std::mem::take(records), + }; + Ok(TraceSinkFinish { + trace: Some(trace), + footer, + footer_written: true, + }) + } + TraceSinkInner::Streaming(streaming) => { + // Footer is a control record: even loss-aware capture blocks here so the writer + // gets an explicit shutdown boundary and a durable incompleteness count. + streaming + .tx + .send(WriterMessage::Finish(footer.clone())) + .map_err(|_| writer_disconnected())?; + update_peak(&self.peak_queued_events, streaming.tx.len()); + let worker = streaming.worker.take().ok_or_else(|| Error::Message { + context: "Workload trace writer error: ", + detail: "writer worker already joined".to_owned(), + })?; + let outcome = worker.join().map_err(|_| Error::Message { + context: "Workload trace writer error: ", + detail: "writer worker panicked".to_owned(), + })?; + if let Some(writer_error) = outcome.writer_error { + footer.capture_complete = false; + footer.writer_error = Some(writer_error); + } + Ok(TraceSinkFinish { + trace: None, + footer, + footer_written: outcome.footer_written, + }) + } + TraceSinkInner::Disabled => unreachable!(), + } + } + + fn store_required(&mut self, payload: WorkloadRecordPayload) -> Result { + let record = WorkloadRecord { + sequence: self.next_sequence, + payload, + }; + match &mut self.inner { + TraceSinkInner::Disabled => return Ok(RecordDisposition::Disabled), + TraceSinkInner::Memory(records) => records.push(record), + TraceSinkInner::Streaming(streaming) => { + streaming + .tx + .send(WriterMessage::Record(record)) + .map_err(|_| writer_disconnected())?; + update_peak(&self.peak_queued_events, streaming.tx.len()); + } + } + self.account_stored_payload(); + self.next_sequence = self.next_sequence.saturating_add(1); + Ok(RecordDisposition::Stored) + } + + fn try_store(&mut self, payload: WorkloadRecordPayload) -> Result { + let record = WorkloadRecord { + sequence: self.next_sequence, + payload, + }; + let TraceSinkInner::Streaming(streaming) = &mut self.inner else { + return self.store_required(record.payload); + }; + match streaming.tx.try_send(WriterMessage::Record(record)) { + Ok(()) => { + update_peak(&self.peak_queued_events, streaming.tx.len()); + self.account_stored_payload(); + self.next_sequence = self.next_sequence.saturating_add(1); + Ok(RecordDisposition::Stored) + } + Err(flume::TrySendError::Full(_)) => { + self.dropped_event_count.fetch_add(1, Ordering::Relaxed); + Ok(RecordDisposition::Dropped) + } + Err(flume::TrySendError::Disconnected(_)) => Err(writer_disconnected()), + } + } + + fn account_stored_payload(&mut self) { + // The just-stored payload is at next_sequence. Inspecting the record again would require + // cloning it; counts are instead incremented by the public typed helpers below. + } + + pub fn record_node(&mut self, node: super::WorkloadNode) -> Result { + let result = self.record(WorkloadRecordPayload::Node(node))?; + if result == RecordDisposition::Stored { + self.node_count = self.node_count.saturating_add(1); + } + Ok(result) + } + + pub fn record_edge(&mut self, edge: super::WorkloadEdge) -> Result { + let result = self.record(WorkloadRecordPayload::Edge(edge))?; + if result == RecordDisposition::Stored { + self.edge_count = self.edge_count.saturating_add(1); + } + Ok(result) + } + + pub fn record_event(&mut self, event: super::WorkloadEvent) -> Result { + let result = self.record(WorkloadRecordPayload::Event(event))?; + if result == RecordDisposition::Stored { + self.event_count = self.event_count.saturating_add(1); + } + Ok(result) + } + + fn build_footer(&self, capture_complete: bool, writer_error: Option) -> TraceFooter { + let dropped_event_count = self.dropped_event_count(); + TraceFooter { + record_count: self.next_sequence, + event_count: self.event_count, + node_count: self.node_count, + edge_count: self.edge_count, + dropped_event_count, + peak_queued_events: self.peak_queued_events(), + capture_complete, + complete_for_replay: capture_complete && dropped_event_count == 0, + writer_error, + } + } +} + +impl Drop for TraceSink { + fn drop(&mut self) { + let TraceSinkInner::Streaming(streaming) = &mut self.inner else { + return; + }; + if streaming.worker.is_none() { + return; + } + + let dropped_event_count = self.dropped_event_count.load(Ordering::Relaxed); + let footer = TraceFooter { + record_count: self.next_sequence.saturating_add(1), + event_count: self.event_count, + node_count: self.node_count, + edge_count: self.edge_count, + dropped_event_count, + peak_queued_events: self.peak_queued_events.load(Ordering::Relaxed), + capture_complete: false, + complete_for_replay: false, + writer_error: Some("capture_aborted".to_owned()), + }; + let _ = streaming.tx.send(WriterMessage::Finish(footer)); + if let Some(worker) = streaming.worker.take() { + let _ = worker.join(); + } + } +} + +fn update_peak(peak: &AtomicUsize, queued: usize) { + peak.fetch_max(queued, Ordering::Relaxed); +} + +fn writer_main(file: File, rx: flume::Receiver) -> WriterOutcome { + let mut writer = BufWriter::new(file); + let mut outcome = WriterOutcome::default(); + while let Ok(message) = rx.recv() { + match message { + WriterMessage::Record(record) => { + if outcome.writer_error.is_none() { + if let Err(error) = write_record(&mut writer, &record) { + outcome.writer_error = Some(io_error_code(&error)); + } + } + } + WriterMessage::Finish(mut footer) => { + if outcome.writer_error.is_some() { + break; + } + footer.record_count = footer.record_count.max(1); + let record = WorkloadRecord { + sequence: footer.record_count.saturating_sub(1), + payload: WorkloadRecordPayload::Footer(footer), + }; + match write_record(&mut writer, &record).and_then(|()| writer.flush()) { + Ok(()) => outcome.footer_written = true, + Err(error) => outcome.writer_error = Some(io_error_code(&error)), + } + break; + } + } + } + outcome +} + +fn write_record(writer: &mut BufWriter, record: &WorkloadRecord) -> std::io::Result<()> { + serde_json::to_writer(&mut *writer, record).map_err(std::io::Error::other)?; + writer.write_all(b"\n") +} + +fn writer_disconnected() -> Error { + Error::Message { + context: "Workload trace writer error: ", + detail: "writer channel disconnected".to_owned(), + } +} + +fn io_error_code(error: &std::io::Error) -> String { + match error.raw_os_error() { + Some(code) => format!("io_os_error:{code}"), + None => format!("io_kind:{:?}", error.kind()), + } +} + +#[cfg(test)] +mod tests { + use std::time::{SystemTime, UNIX_EPOCH}; + + use super::*; + use crate::task_pool::workload::{ + MachineProfile, SchedulerConfigProfile, WorkloadTimeModel, WorkloadVolumePolicy, + WorkloadVolumeStreamingMode, WORKLOAD_TRACE_SCHEMA_VERSION, + }; + + fn header(mode: WorkloadCaptureMode) -> WorkloadTraceHeader { + WorkloadTraceHeader { + schema_version: WORKLOAD_TRACE_SCHEMA_VERSION, + run_id: 1, + runner_id: 1, + time_model: WorkloadTimeModel::MonotonicRelativeNanoseconds, + wall_clock_start_unix_ns: None, + source_tree: "tree".to_owned(), + workload_kind: Some("test".to_owned()), + capture_mode: mode, + scheduler: SchedulerConfigProfile { + cpu_slots: 1, + hdiff_decoder_slots: 2, + blocking_slots: 1, + network_slots: 1, + extract_slots: 1, + reuse_queue_limit: 1, + volume_write_reservation_delay_ns: 15_000_000, + ready_frontier_limit: 256, + priority_lookahead: 64, + continuation_burst: 4, + default_volume_policy: WorkloadVolumePolicy { + read_limit: 1, + write_limit: 1, + metadata_limit: 1, + streaming_pressure_limit: 1, + streaming_mode: WorkloadVolumeStreamingMode::Mixed, + }, + volume_policy_overrides: Vec::new(), + }, + machine: MachineProfile { + os: "test".to_owned(), + architecture: "test".to_owned(), + available_parallelism: 1, + md5_verify_batch_capacity: 1, + }, + } + } + + fn temp_trace(name: &str) -> std::path::PathBuf { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + std::env::temp_dir().join(format!( + "griffr-{name}-{}-{unique}.ndjson", + std::process::id() + )) + } + + #[test] + fn memory_sink_finishes_with_footer() { + let sink = TraceSink::memory(header(WorkloadCaptureMode::Memory)).unwrap(); + let finished = sink.finish().unwrap(); + let trace = finished.trace.unwrap(); + assert!(finished.footer_written); + assert_eq!(trace.records.len(), 2); + assert_eq!(trace.footer().unwrap().record_count, 2); + assert!(trace.footer().unwrap().complete_for_replay); + } + + #[test] + fn strict_streaming_sink_flushes_footer() { + let path = temp_trace("strict"); + let sink = + TraceSink::streaming(&path, header(WorkloadCaptureMode::StreamingStrict), 1).unwrap(); + let finished = sink.finish().unwrap(); + assert!(finished.footer_written); + let trace = WorkloadTrace::from_path(&path).unwrap(); + assert!(trace.footer().unwrap().complete_for_replay); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn dropped_streaming_sink_writes_incomplete_footer() { + let path = temp_trace("drop-footer"); + { + let mut sink = + TraceSink::streaming(&path, header(WorkloadCaptureMode::StreamingStrict), 4) + .unwrap(); + sink.record(WorkloadRecordPayload::Volume( + super::super::SanitizedVolume { + volume_id: "volume#01".to_owned(), + }, + )) + .unwrap(); + } + + let trace = WorkloadTrace::from_path(&path).unwrap(); + let footer = trace.footer().expect("drop must emit footer"); + assert!(!footer.capture_complete); + assert!(!footer.complete_for_replay); + assert_eq!(footer.writer_error.as_deref(), Some("capture_aborted")); + std::fs::remove_file(path).ok(); + } + + #[test] + fn synthetic_recorder_performance_guard_reports_metrics() { + use std::time::Instant; + + use super::super::{WorkloadEvent, WorkloadEventKind, WorkloadNodeId}; + + const EVENTS: u64 = 20_000; + fn event(sequence: u64) -> WorkloadEvent { + WorkloadEvent { + event_sequence: sequence, + elapsed_ns: sequence, + kind: WorkloadEventKind::Created { + node: WorkloadNodeId { + run_id: 1, + node_id: 0, + }, + }, + } + } + + let started = Instant::now(); + let mut disabled = TraceSink::disabled(); + for sequence in 0..EVENTS { + disabled.record_event(event(sequence)).unwrap(); + } + let disabled_ns = started.elapsed().as_nanos() / u128::from(EVENTS); + + let started = Instant::now(); + let mut memory = TraceSink::memory(header(WorkloadCaptureMode::Memory)).unwrap(); + for sequence in 0..EVENTS { + memory.record_event(event(sequence)).unwrap(); + } + let memory_finished = memory.finish().unwrap(); + let memory_ns = started.elapsed().as_nanos() / u128::from(EVENTS); + let mut memory_bytes = Vec::new(); + memory_finished + .trace + .as_ref() + .unwrap() + .write_ndjson(&mut memory_bytes) + .unwrap(); + + let path = temp_trace("perf-guard"); + let started = Instant::now(); + let mut streaming = + TraceSink::streaming(&path, header(WorkloadCaptureMode::StreamingStrict), 4096) + .unwrap(); + for sequence in 0..EVENTS { + streaming.record_event(event(sequence)).unwrap(); + } + let streaming_finished = streaming.finish().unwrap(); + let streaming_ns = started.elapsed().as_nanos() / u128::from(EVENTS); + let streaming_bytes = std::fs::metadata(&path).unwrap().len(); + std::fs::remove_file(path).unwrap(); + + let memory_bytes_per_event = memory_bytes.len() as f64 / EVENTS as f64; + let streaming_bytes_per_event = streaming_bytes as f64 / EVENTS as f64; + eprintln!( + "M5_RECORDER_PERF disabled_ns_per_event={disabled_ns} memory_ns_per_event={memory_ns} streaming_ns_per_event={streaming_ns} memory_events_per_sec={:.0} streaming_events_per_sec={:.0} peak_queued_events={} memory_bytes_per_event={memory_bytes_per_event:.2} streaming_bytes_per_event={streaming_bytes_per_event:.2}", + 1_000_000_000_f64 / memory_ns.max(1) as f64, + 1_000_000_000_f64 / streaming_ns.max(1) as f64, + streaming_finished.footer.peak_queued_events, + ); + assert_eq!(memory_finished.footer.event_count, EVENTS); + assert_eq!(streaming_finished.footer.event_count, EVENTS); + assert!(streaming_finished.footer.complete_for_replay); + } + + #[test] + fn loss_aware_mode_marks_drops_and_never_claims_replay_authority() { + let path = temp_trace("loss-aware"); + let mut sink = + TraceSink::streaming(&path, header(WorkloadCaptureMode::StreamingLossAware), 1) + .unwrap(); + + // The writer can drain concurrently, so produce enough records to force a bounded-channel + // full condition without relying on exact scheduling. + let payload = super::super::SanitizedVolume { + volume_id: "volume#01".to_owned(), + }; + for _ in 0..100_000 { + let _ = sink + .record(WorkloadRecordPayload::Volume(payload.clone())) + .unwrap(); + if sink.dropped_event_count() > 0 { + break; + } + } + assert!(sink.dropped_event_count() > 0); + assert!(sink.peak_queued_events() <= 1); + let finished = sink.finish().unwrap(); + assert!(!finished.footer.complete_for_replay); + assert!(finished.footer.dropped_event_count > 0); + let trace = WorkloadTrace::from_path(&path).unwrap(); + assert!(!trace.footer().unwrap().complete_for_replay); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/replay.rs b/crates/griffr-runtime/src/task_pool/workload/replay.rs new file mode 100644 index 0000000..bc3cb90 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/replay.rs @@ -0,0 +1,1958 @@ +use super::retention::DecoderRetention; +use std::cmp::Reverse; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap, VecDeque}; + +use serde::{Deserialize, Serialize}; + +use super::{ + CompactExpansion, CompactNode, CompactWorkUnit, CompactWorkload, WorkUnitIdentity, + WorkUnitPhase, WorkloadAdmissionBlockReason, WorkloadBatchClass, WorkloadCompletion, + WorkloadNodeId, WorkloadResourceDemand, WorkloadVolumePolicy, WorkloadVolumeStreamingMode, +}; +use crate::error::{Error, Result}; +use crate::task_pool::{SchedulerNetworkClass, SchedulerRunClass, SchedulerTaskPriority}; + +const RUN_SCHEDULE: [SchedulerRunClass; 4] = [ + SchedulerRunClass::AsyncIo, + SchedulerRunClass::Cpu, + SchedulerRunClass::Blocking, + SchedulerRunClass::AsyncIo, +]; +const NETWORK_SCHEDULE: [SchedulerNetworkClass; 8] = [ + SchedulerNetworkClass::General, + SchedulerNetworkClass::General, + SchedulerNetworkClass::General, + SchedulerNetworkClass::General, + SchedulerNetworkClass::Archive, + SchedulerNetworkClass::Archive, + SchedulerNetworkClass::Vfs, + SchedulerNetworkClass::ArchiveBackground, +]; +const AGE_BUCKET_NS: u64 = 5_000_000_000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReplayPolicy { + CurrentProduction, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayResourceUtilization { + pub cpu_basis_points: u64, + pub blocking_basis_points: u64, + pub network_basis_points: u64, + pub extract_basis_points: u64, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplayQueueSummary { + pub p50_ns: u64, + pub p95_ns: u64, + pub p99_ns: u64, + pub max_ns: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplaySummary { + pub policy: ReplayPolicy, + pub makespan_ns: u64, + pub longest_chain_service_ns: u64, + pub queue_wait: ReplayQueueSummary, + pub resource_utilization: ReplayResourceUtilization, + pub candidate_index_histogram: BTreeMap, + pub lookahead_exhaustion_count: u64, + pub admission_block_breakdown: BTreeMap, + pub max_concurrently_running_work: usize, + pub completed_work_units: usize, + /// Stable non-cryptographic fingerprint over the deterministic summary fields. + pub determinism_fingerprint: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReplayResult { + pub summary: ReplaySummary, + pub completion_times_ns: BTreeMap, +} + +#[derive(Debug)] +struct ReplayGraph { + deps: Vec>, + dependents: Vec>, +} + +impl ReplayGraph { + fn build(workload: &CompactWorkload) -> Result { + let unit_index = workload + .work_units + .iter() + .enumerate() + .map(|(index, unit)| (unit.identity.clone(), index)) + .collect::>(); + let units_by_node = units_by_node(workload); + let nodes = workload + .nodes + .iter() + .map(|node| (node.node.id.clone(), node)) + .collect::>(); + let expansions = workload + .expansions + .iter() + .map(|expansion| (expansion.parent.clone(), expansion)) + .collect::>(); + let mut barrier_cache = BTreeMap::>::new(); + let mut visiting = BTreeSet::new(); + let mut deps = vec![Vec::new(); workload.work_units.len()]; + + for (node_id, unit_indices) in &units_by_node { + let node = nodes.get(node_id).ok_or_else(|| { + replay_error(format!( + "work units reference node {node_id:?} absent from compact topology" + )) + })?; + let mut retention = DecoderRetention::default(); + for (position, &index) in unit_indices.iter().enumerate() { + let unit = &workload.work_units[index]; + if usize::try_from(unit.identity.continuation_generation).ok() != Some(position) { + return Err(replay_error(format!( + "invalid continuation generation for {:?}", + unit.identity + ))); + } + retention + .admit(unit.identity.phase, unit.demand.hdiff_decoder_start) + .and_then(|()| { + retention.finish( + unit.identity.phase, + unit.completion, + unit.hdiff_retention_released, + ) + }) + .map_err(|reason| replay_error(format!("{reason} for {:?}", unit.identity)))?; + } + if retention.is_held() { + return Err(replay_error(format!( + "dangling decoder retention for {node_id:?}" + ))); + } + for (position, &unit_idx) in unit_indices.iter().enumerate() { + let mut required = BTreeSet::new(); + if position == 0 { + if let Some(parent) = &node.node.expansion_parent { + required.insert(*unit_index.get(parent).ok_or_else(|| { + replay_error(format!( + "dynamic node {node_id:?} references missing expansion parent {parent:?}" + )) + })?); + } + for dependency in &node.dependencies { + for barrier in node_completion_barrier( + dependency, + workload, + &units_by_node, + &nodes, + &expansions, + &unit_index, + &mut barrier_cache, + &mut visiting, + )? { + required.insert(barrier); + } + } + } else { + let previous = unit_indices[position - 1]; + let previous_unit = &workload.work_units[previous]; + if matches!( + previous_unit.completion, + WorkloadCompletion::Expanded | WorkloadCompletion::ExpandedThen + ) { + if let Some(expansion) = expansions.get(&previous_unit.identity) { + let terminals = expansion_terminal_nodes(expansion); + if terminals.is_empty() { + required.insert(previous); + } else { + for terminal in terminals { + for barrier in node_completion_barrier( + &terminal, + workload, + &units_by_node, + &nodes, + &expansions, + &unit_index, + &mut barrier_cache, + &mut visiting, + )? { + required.insert(barrier); + } + } + } + } else { + required.insert(previous); + } + } else { + required.insert(previous); + } + } + deps[unit_idx] = required.into_iter().collect(); + } + } + + let mut dependents = vec![Vec::new(); deps.len()]; + for (unit, dependencies) in deps.iter().enumerate() { + for &dependency in dependencies { + if dependency == unit { + return Err(replay_error(format!( + "work unit {} has a replay self-dependency", + unit + ))); + } + dependents[dependency].push(unit); + } + } + for dependents in &mut dependents { + dependents.sort_unstable(); + dependents.dedup(); + } + Ok(Self { deps, dependents }) + } +} + +#[allow(clippy::too_many_arguments)] +fn node_completion_barrier( + node_id: &WorkloadNodeId, + workload: &CompactWorkload, + units_by_node: &BTreeMap>, + nodes: &BTreeMap, + expansions: &BTreeMap, + unit_index: &BTreeMap, + cache: &mut BTreeMap>, + visiting: &mut BTreeSet, +) -> Result> { + if let Some(cached) = cache.get(node_id) { + return Ok(cached.clone()); + } + if !visiting.insert(node_id.clone()) { + return Err(replay_error(format!( + "cycle detected while resolving completion barrier for {node_id:?}" + ))); + } + let _node = nodes + .get(node_id) + .ok_or_else(|| replay_error(format!("missing compact node {node_id:?}")))?; + let unit_indices = units_by_node.get(node_id).ok_or_else(|| { + replay_error(format!( + "node {node_id:?} has no captured WorkUnit and cannot satisfy a dependency" + )) + })?; + let &last = unit_indices + .last() + .ok_or_else(|| replay_error(format!("node {node_id:?} has no WorkUnit")))?; + let last_unit = &workload.work_units[last]; + let barriers = if matches!( + last_unit.completion, + WorkloadCompletion::Expanded | WorkloadCompletion::ExpandedThen + ) { + if let Some(expansion) = expansions.get(&last_unit.identity) { + let terminals = expansion_terminal_nodes(expansion); + if terminals.is_empty() { + vec![last] + } else { + let mut resolved = BTreeSet::new(); + for terminal in terminals { + for barrier in node_completion_barrier( + &terminal, + workload, + units_by_node, + nodes, + expansions, + unit_index, + cache, + visiting, + )? { + resolved.insert(barrier); + } + } + resolved.into_iter().collect() + } + } else { + vec![last] + } + } else { + vec![*unit_index.get(&last_unit.identity).unwrap_or(&last)] + }; + visiting.remove(node_id); + cache.insert(node_id.clone(), barriers.clone()); + Ok(barriers) +} + +fn expansion_terminal_nodes(expansion: &CompactExpansion) -> Vec { + let members = expansion + .new_nodes + .iter() + .cloned() + .collect::>(); + let has_local_dependent = expansion + .new_edges + .iter() + .filter(|edge| members.contains(&edge.from) && members.contains(&edge.to)) + .map(|edge| edge.from.clone()) + .collect::>(); + expansion + .new_nodes + .iter() + .filter(|node| !has_local_dependent.contains(*node)) + .cloned() + .collect() +} + +fn units_by_node(workload: &CompactWorkload) -> BTreeMap> { + let mut map = BTreeMap::>::new(); + for (index, unit) in workload.work_units.iter().enumerate() { + map.entry(unit.identity.node.clone()) + .or_default() + .push(index); + } + map +} + +#[derive(Debug, Default)] +struct ReplayBacklog { + continuation: [VecDeque; 3], + bulk: [VecDeque; 3], + continuation_cursor: usize, + bulk_cursor: usize, + len: usize, +} + +impl ReplayBacklog { + fn push(&mut self, unit: usize, work: &CompactWorkUnit) { + let class = run_index(work.demand.run_class); + match work.priority { + SchedulerTaskPriority::Continuation => self.continuation[class].push_back(unit), + SchedulerTaskPriority::Bulk => self.bulk[class].push_back(unit), + } + self.len = self.len.saturating_add(1); + } + + fn pop(&mut self) -> Option { + let unit = pop_ready_class(&mut self.continuation, &mut self.continuation_cursor) + .or_else(|| pop_ready_class(&mut self.bulk, &mut self.bulk_cursor)); + if unit.is_some() { + self.len = self.len.saturating_sub(1); + } + unit + } +} + +fn pop_ready_class(queues: &mut [VecDeque; 3], cursor: &mut usize) -> Option { + for offset in 0..queues.len() { + let index = (*cursor + offset) % queues.len(); + if let Some(unit) = queues[index].pop_front() { + *cursor = (index + 1) % queues.len(); + return Some(unit); + } + } + None +} + +#[derive(Debug, Default)] +struct ReplayLane { + units: VecDeque, + volume_depth: BTreeMap, + run_counts: [usize; 3], + network_counts: [usize; 4], +} + +impl ReplayLane { + fn push(&mut self, unit: usize, work: &CompactWorkUnit) { + self.units.push_back(unit); + self.run_counts[run_index(work.demand.run_class)] = + self.run_counts[run_index(work.demand.run_class)].saturating_add(1); + if let Some(network) = work.demand.network_class { + self.network_counts[network_index(network)] = + self.network_counts[network_index(network)].saturating_add(1); + } + for volume in work + .demand + .read_volumes + .iter() + .chain(&work.demand.write_volumes) + .chain(&work.demand.metadata_volumes) + { + *self.volume_depth.entry(volume.clone()).or_default() += 1; + } + } + + fn remove(&mut self, index: usize, workload: &CompactWorkload) -> Option { + let unit = self.units.remove(index)?; + let work = &workload.work_units[unit]; + let run = run_index(work.demand.run_class); + self.run_counts[run] = self.run_counts[run].saturating_sub(1); + if let Some(network) = work.demand.network_class { + let network = network_index(network); + self.network_counts[network] = self.network_counts[network].saturating_sub(1); + } + for volume in work + .demand + .read_volumes + .iter() + .chain(&work.demand.write_volumes) + .chain(&work.demand.metadata_volumes) + { + decrement(&mut self.volume_depth, volume); + } + Some(unit) + } + + fn has_network(&self, network: SchedulerNetworkClass) -> bool { + self.network_counts[network_index(network)] > 0 + } +} + +#[derive(Debug, Default)] +struct ReplayQueue { + continuation: ReplayLane, + bulk: ReplayLane, + continuation_streak: [usize; 3], + run_cursor: usize, + network_cursor: usize, + queued_reuse_commits: usize, + queued_write_units: BTreeSet, +} + +impl ReplayQueue { + fn len(&self) -> usize { + self.continuation + .units + .len() + .saturating_add(self.bulk.units.len()) + } + + fn push(&mut self, unit: usize, work: &CompactWorkUnit) { + if work.demand.reuse_commit { + self.queued_reuse_commits = self.queued_reuse_commits.saturating_add(1); + } + if !work.demand.write_volumes.is_empty() { + self.queued_write_units.insert(unit); + } + match work.priority { + SchedulerTaskPriority::Continuation => self.continuation.push(unit, work), + SchedulerTaskPriority::Bulk => self.bulk.push(unit, work), + } + } + + fn remove( + &mut self, + priority: SchedulerTaskPriority, + index: usize, + workload: &CompactWorkload, + ) -> Option { + let unit = match priority { + SchedulerTaskPriority::Continuation => self.continuation.remove(index, workload), + SchedulerTaskPriority::Bulk => self.bulk.remove(index, workload), + }?; + let work = &workload.work_units[unit]; + if work.demand.reuse_commit { + self.queued_reuse_commits = self.queued_reuse_commits.saturating_sub(1); + } + self.queued_write_units.remove(&unit); + Some(unit) + } +} + +#[derive(Debug, Clone, Default)] +struct ResourceState { + cpu: usize, + hdiff_decoders: BTreeSet, + blocking: usize, + network: usize, + extract: usize, + reuse_commits: usize, + reads: BTreeMap, + writes: BTreeMap, + metadata: BTreeMap, + archive_savers: BTreeMap, + archive_commits: BTreeMap, + mutations: BTreeMap, +} + +impl ResourceState { + fn acquire(&mut self, demand: &WorkloadResourceDemand) { + if demand.run_class == SchedulerRunClass::Cpu || demand.cpu_on_async { + self.cpu = self.cpu.saturating_add(1); + } + if demand.run_class == SchedulerRunClass::Blocking { + self.blocking = self.blocking.saturating_add(1); + } + if demand.network_class.is_some() { + self.network = self.network.saturating_add(1); + } + if demand.extract { + self.extract = self.extract.saturating_add(1); + } + if demand.reuse_commit { + self.reuse_commits = self.reuse_commits.saturating_add(1); + } + increment_all(&mut self.reads, &demand.read_volumes); + increment_all(&mut self.writes, &demand.write_volumes); + increment_all(&mut self.metadata, &demand.metadata_volumes); + increment_all(&mut self.archive_savers, &demand.archive_save_volumes); + for (volume, _) in &demand.archive_commit_volumes { + increment(&mut self.archive_commits, volume); + } + increment_all(&mut self.mutations, &demand.mutation_paths); + } + + fn release(&mut self, demand: &WorkloadResourceDemand) { + if demand.run_class == SchedulerRunClass::Cpu || demand.cpu_on_async { + self.cpu = self.cpu.saturating_sub(1); + } + if demand.run_class == SchedulerRunClass::Blocking { + self.blocking = self.blocking.saturating_sub(1); + } + if demand.network_class.is_some() { + self.network = self.network.saturating_sub(1); + } + if demand.extract { + self.extract = self.extract.saturating_sub(1); + } + if demand.reuse_commit { + self.reuse_commits = self.reuse_commits.saturating_sub(1); + } + decrement_all(&mut self.reads, &demand.read_volumes); + decrement_all(&mut self.writes, &demand.write_volumes); + decrement_all(&mut self.metadata, &demand.metadata_volumes); + decrement_all(&mut self.archive_savers, &demand.archive_save_volumes); + for (volume, _) in &demand.archive_commit_volumes { + decrement(&mut self.archive_commits, volume); + } + decrement_all(&mut self.mutations, &demand.mutation_paths); + } + + fn blockers( + &self, + demand: &WorkloadResourceDemand, + workload: &CompactWorkload, + queued_reuse_commits: usize, + reserved_write_volumes: &BTreeSet, + path_parents: &BTreeMap>, + ) -> Vec { + let config = &workload.scheduler; + let mut reasons = Vec::new(); + if demand.hdiff_decoder_start && self.hdiff_decoders.len() >= config.hdiff_decoder_slots { + reasons.push(WorkloadAdmissionBlockReason::HdiffDecoderMemory); + } + if (demand.run_class == SchedulerRunClass::Cpu || demand.cpu_on_async) + && self.cpu >= config.cpu_slots + { + reasons.push(WorkloadAdmissionBlockReason::Cpu); + } + if demand.run_class == SchedulerRunClass::Blocking && self.blocking >= config.blocking_slots + { + reasons.push(WorkloadAdmissionBlockReason::Blocking); + } + if demand.network_class.is_some() && self.network >= config.network_slots { + reasons.push(WorkloadAdmissionBlockReason::Network); + } + if demand.extract && self.extract >= config.extract_slots { + reasons.push(WorkloadAdmissionBlockReason::Extract); + } + if demand.reuse_probe + && self.reuse_commits.saturating_add(queued_reuse_commits) + >= config.reuse_queue_limit.max(1) + { + reasons.push(WorkloadAdmissionBlockReason::ReuseQueue); + } + for volume in &demand.archive_save_volumes { + if self.archive_savers.get(volume).copied().unwrap_or(0) > 0 { + reasons.push(WorkloadAdmissionBlockReason::ArchiveSave(volume.clone())); + } + } + for (volume, cross_volume) in &demand.archive_commit_volumes { + let limit = if *cross_volume { 3 } else { 1 }; + if self.archive_commits.get(volume).copied().unwrap_or(0) >= limit { + reasons.push(WorkloadAdmissionBlockReason::ArchiveCommit(volume.clone())); + } + } + if demand.mutation_paths.iter().any(|requested| { + self.mutations + .keys() + .any(|active| paths_conflict(requested, active, path_parents)) + }) { + reasons.push(WorkloadAdmissionBlockReason::MutationConflict); + } + + let mut seen = BTreeSet::new(); + for volume in demand + .read_volumes + .iter() + .chain(&demand.write_volumes) + .chain(&demand.metadata_volumes) + { + if seen.insert(volume.clone()) { + self.volume_blockers( + demand, + workload, + volume, + reserved_write_volumes, + &mut reasons, + ); + } + } + reasons + } + + fn volume_blockers( + &self, + demand: &WorkloadResourceDemand, + workload: &CompactWorkload, + volume: &str, + reserved_write_volumes: &BTreeSet, + reasons: &mut Vec, + ) { + let policy = volume_policy(workload, volume); + let wants_read = demand.read_volumes.iter().any(|item| item == volume); + let wants_write = demand.write_volumes.iter().any(|item| item == volume); + let wants_metadata = demand.metadata_volumes.iter().any(|item| item == volume); + let reads = self.reads.get(volume).copied().unwrap_or(0); + let writes = self.writes.get(volume).copied().unwrap_or(0); + let metadata = self.metadata.get(volume).copied().unwrap_or(0); + if reads.saturating_add(usize::from(wants_read)) > policy.read_limit { + reasons.push(WorkloadAdmissionBlockReason::VolumeRead(volume.to_owned())); + } + if writes.saturating_add(usize::from(wants_write)) > policy.write_limit { + reasons.push(WorkloadAdmissionBlockReason::VolumeWrite(volume.to_owned())); + } + if metadata.saturating_add(usize::from(wants_metadata)) > policy.metadata_limit { + reasons.push(WorkloadAdmissionBlockReason::Metadata(volume.to_owned())); + } + + let (current_pressure, requested_pressure, exclusive_conflict) = match policy.streaming_mode + { + WorkloadVolumeStreamingMode::Exclusive => { + let conflict = (wants_read && writes > 0) + || (wants_write && reads > 0) + || (wants_metadata && (reads > 0 || writes > 0)) + || ((wants_read || wants_write) && metadata > 0); + ( + reads.max(writes), + usize::from(wants_read || wants_write), + conflict, + ) + } + WorkloadVolumeStreamingMode::Mixed => ( + reads.saturating_add(writes), + usize::from(wants_read).saturating_add(usize::from(wants_write)), + false, + ), + }; + if exclusive_conflict { + reasons.push(WorkloadAdmissionBlockReason::VolumeStreaming( + volume.to_owned(), + )); + } + if matches!( + policy.streaming_mode, + WorkloadVolumeStreamingMode::Exclusive + ) && reserved_write_volumes.contains(volume) + && !wants_write + && wants_metadata + { + reasons.push(WorkloadAdmissionBlockReason::WriterReservation( + volume.to_owned(), + )); + } + let reserve_for_waiting_writer = usize::from( + reserved_write_volumes.contains(volume) + && requested_pressure > 0 + && !wants_write + && writes < policy.write_limit, + ); + if current_pressure + .saturating_add(requested_pressure) + .saturating_add(reserve_for_waiting_writer) + > policy.streaming_pressure_limit + { + if reserve_for_waiting_writer > 0 + && current_pressure.saturating_add(requested_pressure) + <= policy.streaming_pressure_limit + { + reasons.push(WorkloadAdmissionBlockReason::WriterReservation( + volume.to_owned(), + )); + } else { + reasons.push(WorkloadAdmissionBlockReason::VolumeStreaming( + volume.to_owned(), + )); + } + } + } +} + +#[derive(Debug, Default)] +struct BusyArea { + cpu: u128, + blocking: u128, + network: u128, + extract: u128, + last_ns: u64, +} + +impl BusyArea { + fn account_to(&mut self, now: u64, resources: &ResourceState) { + let delta = now.saturating_sub(self.last_ns) as u128; + self.cpu = self + .cpu + .saturating_add((resources.cpu as u128).saturating_mul(delta)); + self.blocking = self + .blocking + .saturating_add((resources.blocking as u128).saturating_mul(delta)); + self.network = self + .network + .saturating_add((resources.network as u128).saturating_mul(delta)); + self.extract = self + .extract + .saturating_add((resources.extract as u128).saturating_mul(delta)); + self.last_ns = now; + } +} + +#[derive(Debug)] +struct ReplayState<'a> { + workload: &'a CompactWorkload, + graph: ReplayGraph, + remaining_deps: Vec, + completed: Vec, + ready_since: Vec>, + queued_since: Vec>, + backlog: ReplayBacklog, + queue: ReplayQueue, + resources: ResourceState, + running: BinaryHeap>, + acquired_demands: Vec>, + queue_waits: Vec, + completion_times: Vec, + candidate_histogram: BTreeMap, + lookahead_exhaustion: u64, + admission_blocks: BTreeMap, + max_running: usize, + busy_area: BusyArea, + path_parents: BTreeMap>, + now: u64, +} + +impl<'a> ReplayState<'a> { + fn new(workload: &'a CompactWorkload) -> Result { + if workload.work_units.is_empty() { + return Err(replay_error("compact workload contains no WorkUnits")); + } + let graph = ReplayGraph::build(workload)?; + let remaining_deps = graph.deps.iter().map(Vec::len).collect::>(); + let path_parents = workload + .paths + .iter() + .map(|path| (path.path_id.clone(), path.parent_id.clone())) + .collect(); + let mut state = Self { + workload, + graph, + remaining_deps, + completed: vec![false; workload.work_units.len()], + ready_since: vec![None; workload.work_units.len()], + queued_since: vec![None; workload.work_units.len()], + backlog: ReplayBacklog::default(), + queue: ReplayQueue::default(), + resources: ResourceState::default(), + running: BinaryHeap::new(), + acquired_demands: vec![None; workload.work_units.len()], + queue_waits: Vec::new(), + completion_times: vec![0; workload.work_units.len()], + candidate_histogram: BTreeMap::new(), + lookahead_exhaustion: 0, + admission_blocks: BTreeMap::new(), + max_running: 0, + busy_area: BusyArea::default(), + path_parents, + now: 0, + }; + for index in 0..state.remaining_deps.len() { + if state.remaining_deps[index] == 0 { + state.mark_ready(index); + } + } + state.refill_frontier(); + Ok(state) + } + + fn mark_ready(&mut self, unit: usize) { + if self.ready_since[unit].is_some() || self.completed[unit] { + return; + } + self.ready_since[unit] = Some(self.now); + self.backlog.push(unit, &self.workload.work_units[unit]); + } + + fn refill_frontier(&mut self) { + let limit = self.workload.scheduler.ready_frontier_limit.max(1); + let routed = self.queue.len().saturating_add(self.running.len()); + let mut remaining = limit.saturating_sub(routed); + while remaining > 0 { + let Some(unit) = self.backlog.pop() else { + break; + }; + self.queued_since[unit] = Some(self.now); + self.queue.push(unit, &self.workload.work_units[unit]); + remaining -= 1; + } + } + + fn run(mut self) -> Result { + let total = self.workload.work_units.len(); + let mut completed_count = 0usize; + while completed_count < total { + while let Some(group) = self.select_next_group() { + self.start_group(group)?; + } + if completed_count >= total { + break; + } + if self.running.is_empty() { + if self.queue.len() == 0 && self.backlog.len > 0 { + self.refill_frontier(); + continue; + } + return Err(replay_error(format!( + "virtual admission deadlock at {} ns: {} queued, {} backlog, {} of {} complete", + self.now, + self.queue.len(), + self.backlog.len, + completed_count, + total + ))); + } + let next_end = self.running.peek().map(|item| item.0 .0).unwrap(); + self.busy_area.account_to(next_end, &self.resources); + self.now = next_end; + let mut finished = Vec::new(); + while self + .running + .peek() + .is_some_and(|item| item.0 .0 == self.now) + { + let Reverse((_, unit)) = self.running.pop().unwrap(); + finished.push(unit); + } + finished.sort_unstable(); + for unit in finished { + let demand = self.acquired_demands[unit] + .take() + .expect("running replay unit must retain acquired demand"); + self.resources.release(&demand); + self.completed[unit] = true; + self.completion_times[unit] = self.now; + completed_count = completed_count.saturating_add(1); + let dependents = self.graph.dependents[unit].clone(); + let work = &self.workload.work_units[unit]; + if work.hdiff_retention_released + && !self.resources.hdiff_decoders.remove(&work.identity.node) + { + return Err(replay_error(format!( + "decoder retention released without ownership for {:?}", + work.identity + ))); + } + for dependent in dependents { + self.remaining_deps[dependent] = + self.remaining_deps[dependent].saturating_sub(1); + if self.remaining_deps[dependent] == 0 { + self.mark_ready(dependent); + } + } + } + self.refill_frontier(); + // A turn may legitimately admit nothing while existing work finishes and unlocks + // later DAG/continuation work. The next loop iteration owns admission/deadlock + // detection after those completions have been applied. + } + self.busy_area.account_to(self.now, &self.resources); + self.finish_result() + } + + fn select_next_group(&mut self) -> Option> { + let leader = self.select_next()?; + let leader_demand = self.workload.work_units[leader].demand.clone(); + // Match production: reserve each member when it is selected, so + // every subsequent follower sees the complete admitted vector. + self.resources.acquire(&leader_demand); + let mut group = vec![(leader, leader_demand)]; + if self.workload.work_units[leader].batch_class != Some(WorkloadBatchClass::Md5Verify) { + return Some(group); + } + + let capacity = self.workload.machine.md5_verify_batch_capacity.max(1); + while group.len() < capacity { + let Some(follower) = self.select_md5_batch_follower() else { + break; + }; + let mut demand = self.workload.work_units[follower].demand.clone(); + // Production reserves one CPU slot for the whole SIMD MD5 batch. Followers still + // own their independent volume/network pressure but borrow AsyncIo admission. + demand.run_class = SchedulerRunClass::AsyncIo; + self.resources.acquire(&demand); + group.push((follower, demand)); + } + Some(group) + } + + fn select_md5_batch_follower(&mut self) -> Option { + let reserved = self.reserved_write_volumes(); + let queued_reuse_commits = self.queue.queued_reuse_commits; + for priority in [ + SchedulerTaskPriority::Continuation, + SchedulerTaskPriority::Bulk, + ] { + let len = self.lane(priority).units.len(); + for index in 0..len { + let unit = self.lane(priority).units[index]; + let work = &self.workload.work_units[unit]; + if work.batch_class != Some(WorkloadBatchClass::Md5Verify) { + continue; + } + let mut demand = work.demand.clone(); + demand.run_class = SchedulerRunClass::AsyncIo; + let blockers = self.resources.blockers( + &demand, + self.workload, + queued_reuse_commits, + &reserved, + &self.path_parents, + ); + self.record_blockers(&blockers); + if !blockers.is_empty() { + continue; + } + let unit = self + .queue + .remove(priority, index, self.workload) + .expect("selected MD5 replay follower must exist"); + *self.candidate_histogram.entry(index).or_default() += 1; + return Some(unit); + } + } + None + } + + fn select_next(&mut self) -> Option { + let reserved = self.reserved_write_volumes(); + let queued_reuse_commits = self.queue.queued_reuse_commits; + for offset in 0..RUN_SCHEDULE.len() { + let schedule_index = (self.queue.run_cursor + offset) % RUN_SCHEDULE.len(); + let class = RUN_SCHEDULE[schedule_index]; + if let Some(unit) = self.select_for_class(class, &reserved, queued_reuse_commits) { + self.queue.run_cursor = (schedule_index + 1) % RUN_SCHEDULE.len(); + return Some(unit); + } + } + None + } + + fn select_for_class( + &mut self, + class: SchedulerRunClass, + reserved: &BTreeSet, + queued_reuse_commits: usize, + ) -> Option { + let class_index = run_index(class); + let force_bulk = self.queue.continuation_streak[class_index] + >= self.workload.scheduler.continuation_burst.max(1); + let preferred_network = if class == SchedulerRunClass::AsyncIo { + let selected = NETWORK_SCHEDULE[self.queue.network_cursor % NETWORK_SCHEDULE.len()]; + self.queue.network_cursor = (self.queue.network_cursor + 1) % NETWORK_SCHEDULE.len(); + Some(selected) + } else { + None + }; + + if !force_bulk { + if let Some(unit) = self.select_from_priority( + SchedulerTaskPriority::Continuation, + class, + preferred_network, + reserved, + queued_reuse_commits, + ) { + self.queue.continuation_streak[class_index] = + self.queue.continuation_streak[class_index].saturating_add(1); + return Some(unit); + } + } + if let Some(unit) = self.select_from_priority( + SchedulerTaskPriority::Bulk, + class, + preferred_network, + reserved, + queued_reuse_commits, + ) { + self.queue.continuation_streak[class_index] = 0; + return Some(unit); + } + if force_bulk { + if let Some(unit) = self.select_from_priority( + SchedulerTaskPriority::Continuation, + class, + preferred_network, + reserved, + queued_reuse_commits, + ) { + self.queue.continuation_streak[class_index] = 1; + return Some(unit); + } + } + None + } + + fn select_from_priority( + &mut self, + priority: SchedulerTaskPriority, + class: SchedulerRunClass, + preferred_network: Option, + reserved: &BTreeSet, + queued_reuse_commits: usize, + ) -> Option { + let has_preferred = { + let lane = self.lane(priority); + preferred_network.is_some_and(|network| lane.has_network(network)) + }; + let preferred = preferred_network.filter(|_| has_preferred); + let selected = + self.select_lane_index(priority, class, preferred, reserved, queued_reuse_commits); + let selected = selected.or_else(|| { + preferred.and_then(|_| { + self.select_lane_index(priority, class, None, reserved, queued_reuse_commits) + }) + })?; + let unit = self.queue.remove(priority, selected, self.workload)?; + *self.candidate_histogram.entry(selected).or_default() += 1; + if selected >= self.workload.scheduler.priority_lookahead.max(1) { + self.lookahead_exhaustion = self.lookahead_exhaustion.saturating_add(1); + } + Some(unit) + } + + fn select_lane_index( + &mut self, + priority: SchedulerTaskPriority, + class: SchedulerRunClass, + network: Option, + reserved: &BTreeSet, + queued_reuse_commits: usize, + ) -> Option { + let lookahead = self.workload.scheduler.priority_lookahead.max(1); + let mut best: Option<((Reverse, u8, u8, Reverse, u64, usize), usize)> = None; + let lane_len = self.lane(priority).units.len(); + for index in 0..lane_len.min(lookahead) { + let unit = self.lane(priority).units[index]; + let work = &self.workload.work_units[unit]; + if work.demand.run_class != class + || network.is_some_and(|selected| work.demand.network_class != Some(selected)) + { + continue; + } + let blockers = self.resources.blockers( + &work.demand, + self.workload, + queued_reuse_commits, + reserved, + &self.path_parents, + ); + self.record_blockers(&blockers); + if !blockers.is_empty() { + continue; + } + let key = self.candidate_key(index, unit, reserved, &self.lane(priority).volume_depth); + if best.as_ref().is_none_or(|(best_key, _)| key < *best_key) { + best = Some((key, index)); + } + } + if let Some((_, index)) = best { + return Some(index); + } + for index in lookahead.min(lane_len)..lane_len { + let unit = self.lane(priority).units[index]; + let work = &self.workload.work_units[unit]; + if work.demand.run_class != class + || network.is_some_and(|selected| work.demand.network_class != Some(selected)) + { + continue; + } + let blockers = self.resources.blockers( + &work.demand, + self.workload, + queued_reuse_commits, + reserved, + &self.path_parents, + ); + self.record_blockers(&blockers); + if blockers.is_empty() { + return Some(index); + } + } + None + } + + fn candidate_key( + &self, + index: usize, + unit: usize, + reserved: &BTreeSet, + volume_depth: &BTreeMap, + ) -> (Reverse, u8, u8, Reverse, u64, usize) { + let work = &self.workload.work_units[unit]; + let ready = self.ready_since[unit].unwrap_or(self.now); + let age_bucket = self.now.saturating_sub(ready) / AGE_BUCKET_NS; + let backlog = work + .demand + .read_volumes + .iter() + .chain(&work.demand.write_volumes) + .chain(&work.demand.metadata_volumes) + .map(|volume| volume_depth.get(volume).copied().unwrap_or(0)) + .sum::(); + let reserved_writer_rank = if work + .demand + .write_volumes + .iter() + .any(|volume| reserved.contains(volume)) + { + 0 + } else { + 1 + }; + let metadata_rank = if work.demand.metadata_volumes.is_empty() { + 1 + } else { + 0 + }; + ( + Reverse(age_bucket), + reserved_writer_rank, + metadata_rank, + Reverse(backlog), + work.demand.priority_cost, + index, + ) + } + + fn reserved_write_volumes(&self) -> BTreeSet { + let delay = self.workload.scheduler.volume_write_reservation_delay_ns; + let mut reserved = BTreeSet::new(); + for &unit in &self.queue.queued_write_units { + let work = &self.workload.work_units[unit]; + let locally_saturated = match work.demand.run_class { + SchedulerRunClass::AsyncIo => { + work.demand.cpu_on_async + && self.resources.cpu >= self.workload.scheduler.cpu_slots + } + SchedulerRunClass::Cpu => self.resources.cpu >= self.workload.scheduler.cpu_slots, + SchedulerRunClass::Blocking => { + self.resources.blocking >= self.workload.scheduler.blocking_slots + } + } || (work.demand.extract + && self.resources.extract >= self.workload.scheduler.extract_slots) + || work.demand.mutation_paths.iter().any(|requested| { + self.resources + .mutations + .keys() + .any(|active| paths_conflict(requested, active, &self.path_parents)) + }); + if locally_saturated { + continue; + } + let ready = self.ready_since[unit].unwrap_or(self.now); + if self.now.saturating_sub(ready) >= delay { + reserved.extend(work.demand.write_volumes.iter().cloned()); + } + } + reserved + } + + fn start_group(&mut self, group: Vec<(usize, WorkloadResourceDemand)>) -> Result<()> { + // Coalesced MD5 service is not separable into per-member intrinsic durations. Until a + // validated batch-service predictor exists, retain the conservative M5 behavior here; + // observed_batch_services are calibration evidence, not an implicit timing oracle. + let duration = group + .iter() + .map(|(unit, _)| { + self.workload.work_units[*unit] + .observed_service + .run_time_ns + .value + .max(1) + }) + .max() + .unwrap_or(1); + let end = self.now.saturating_add(duration); + for (unit, demand) in group { + let queued = self.queued_since[unit].unwrap_or(self.now); + self.queue_waits.push(self.now.saturating_sub(queued)); + let identity = &self.workload.work_units[unit].identity; + if demand.hdiff_decoder_start + && !self.resources.hdiff_decoders.insert(identity.node.clone()) + { + return Err(replay_error(format!( + "duplicate decoder retention acquire for {identity:?}" + ))); + } + if identity.phase == WorkUnitPhase::HdiffDecode + && !self.resources.hdiff_decoders.contains(&identity.node) + { + return Err(replay_error(format!( + "decode continuation has no retained decoder for {identity:?}" + ))); + } + // The group already owns its scalar/volume demand from selection. + self.acquired_demands[unit] = Some(demand); + self.running.push(Reverse((end, unit))); + } + self.max_running = self.max_running.max(self.running.len()); + Ok(()) + } + + fn record_blockers(&mut self, blockers: &[WorkloadAdmissionBlockReason]) { + for blocker in blockers { + let key = format!("{blocker:?}"); + *self.admission_blocks.entry(key).or_default() += 1; + } + } + + fn lane(&self, priority: SchedulerTaskPriority) -> &ReplayLane { + match priority { + SchedulerTaskPriority::Continuation => &self.queue.continuation, + SchedulerTaskPriority::Bulk => &self.queue.bulk, + } + } + + fn finish_result(self) -> Result { + let makespan = self.now; + let queue_wait = queue_summary(&self.queue_waits); + let longest_chain_service_ns = longest_chain_service(self.workload, &self.graph)?; + let utilization = ReplayResourceUtilization { + cpu_basis_points: utilization_bp( + self.busy_area.cpu, + makespan, + self.workload.scheduler.cpu_slots, + ), + blocking_basis_points: utilization_bp( + self.busy_area.blocking, + makespan, + self.workload.scheduler.blocking_slots, + ), + network_basis_points: utilization_bp( + self.busy_area.network, + makespan, + self.workload.scheduler.network_slots, + ), + extract_basis_points: utilization_bp( + self.busy_area.extract, + makespan, + self.workload.scheduler.extract_slots, + ), + }; + let mut summary = ReplaySummary { + policy: ReplayPolicy::CurrentProduction, + makespan_ns: makespan, + longest_chain_service_ns, + queue_wait, + resource_utilization: utilization, + candidate_index_histogram: self.candidate_histogram, + lookahead_exhaustion_count: self.lookahead_exhaustion, + admission_block_breakdown: self.admission_blocks, + max_concurrently_running_work: self.max_running, + completed_work_units: self.workload.work_units.len(), + determinism_fingerprint: String::new(), + }; + summary.determinism_fingerprint = summary_fingerprint(&summary)?; + let completion_times_ns = self + .workload + .work_units + .iter() + .zip(self.completion_times) + .map(|(unit, completion)| (unit.identity.clone(), completion)) + .collect(); + Ok(ReplayResult { + summary, + completion_times_ns, + }) + } +} + +pub fn replay_workload(workload: &CompactWorkload, policy: ReplayPolicy) -> Result { + match policy { + ReplayPolicy::CurrentProduction => ReplayState::new(workload)?.run(), + } +} + +fn volume_policy(workload: &CompactWorkload, volume: &str) -> WorkloadVolumePolicy { + workload + .scheduler + .volume_policy_overrides + .iter() + .find(|override_| override_.volume_id == volume) + .map(|override_| override_.policy) + .unwrap_or(workload.scheduler.default_volume_policy) +} + +fn paths_conflict(left: &str, right: &str, parents: &BTreeMap>) -> bool { + left == right || is_ancestor(left, right, parents) || is_ancestor(right, left, parents) +} + +fn is_ancestor(ancestor: &str, child: &str, parents: &BTreeMap>) -> bool { + let mut current = parents.get(child).and_then(Clone::clone); + while let Some(path) = current { + if path == ancestor { + return true; + } + current = parents.get(&path).and_then(Clone::clone); + } + false +} + +fn increment_all(map: &mut BTreeMap, values: &[String]) { + for value in values { + increment(map, value); + } +} + +fn decrement_all(map: &mut BTreeMap, values: &[String]) { + for value in values { + decrement(map, value); + } +} + +fn increment(map: &mut BTreeMap, key: &str) { + *map.entry(key.to_owned()).or_default() += 1; +} + +fn decrement(map: &mut BTreeMap, key: &str) { + let remove = if let Some(value) = map.get_mut(key) { + *value = value.saturating_sub(1); + *value == 0 + } else { + false + }; + if remove { + map.remove(key); + } +} + +fn run_index(class: SchedulerRunClass) -> usize { + match class { + SchedulerRunClass::AsyncIo => 0, + SchedulerRunClass::Cpu => 1, + SchedulerRunClass::Blocking => 2, + } +} + +fn network_index(class: SchedulerNetworkClass) -> usize { + match class { + SchedulerNetworkClass::General => 0, + SchedulerNetworkClass::Vfs => 1, + SchedulerNetworkClass::Archive => 2, + SchedulerNetworkClass::ArchiveBackground => 3, + } +} + +fn queue_summary(values: &[u64]) -> ReplayQueueSummary { + if values.is_empty() { + return ReplayQueueSummary::default(); + } + let mut sorted = values.to_vec(); + sorted.sort_unstable(); + ReplayQueueSummary { + p50_ns: percentile(&sorted, 50), + p95_ns: percentile(&sorted, 95), + p99_ns: percentile(&sorted, 99), + max_ns: *sorted.last().unwrap_or(&0), + } +} + +fn percentile(sorted: &[u64], percentile: usize) -> u64 { + let rank = sorted.len().saturating_mul(percentile).saturating_add(99) / 100; + sorted[rank.saturating_sub(1).min(sorted.len().saturating_sub(1))] +} + +fn utilization_bp(area: u128, makespan_ns: u64, capacity: usize) -> u64 { + if makespan_ns == 0 || capacity == 0 { + return 0; + } + let denominator = (makespan_ns as u128).saturating_mul(capacity as u128); + u64::try_from(area.saturating_mul(10_000) / denominator).unwrap_or(u64::MAX) +} + +fn longest_chain_service(workload: &CompactWorkload, graph: &ReplayGraph) -> Result { + let mut memo = vec![None; workload.work_units.len()]; + let mut visiting = vec![false; workload.work_units.len()]; + fn visit( + index: usize, + workload: &CompactWorkload, + graph: &ReplayGraph, + memo: &mut [Option], + visiting: &mut [bool], + ) -> Result { + if let Some(value) = memo[index] { + return Ok(value); + } + if visiting[index] { + return Err(replay_error("cycle detected in WorkUnit replay graph")); + } + visiting[index] = true; + let dependency = graph.deps[index] + .iter() + .map(|&dep| visit(dep, workload, graph, memo, visiting)) + .collect::>>()? + .into_iter() + .max() + .unwrap_or(0); + let value = dependency.saturating_add( + workload.work_units[index] + .observed_service + .run_time_ns + .value + .max(1), + ); + visiting[index] = false; + memo[index] = Some(value); + Ok(value) + } + (0..workload.work_units.len()) + .map(|index| visit(index, workload, graph, &mut memo, &mut visiting)) + .collect::>>() + .map(|values| values.into_iter().max().unwrap_or(0)) +} + +fn summary_fingerprint(summary: &ReplaySummary) -> Result { + let mut canonical = summary.clone(); + canonical.determinism_fingerprint.clear(); + let bytes = serde_json::to_vec(&canonical)?; + let mut hash = 0xcbf29ce484222325_u64; + for byte in bytes { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x100000001b3); + } + Ok(format!("fnv1a64:{hash:016x}")) +} + +fn replay_error(detail: impl Into) -> Error { + Error::Message { + context: "Workload replay error: ", + detail: detail.into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::task_pool::workload::{ + MachineProfile, ObservedService, QuantitySource, SanitizedVolume, SchedulerConfigProfile, + ServiceQuantity, VolumePolicyOverride, WorkUnitPhase, WorkloadDagHint, WorkloadEdge, + WorkloadNode, WorkloadStorageReservation, WorkloadTaskOrigin, WorkloadVolumePolicy, + WorkloadVolumeStreamingMode, COMPACT_WORKLOAD_SCHEMA_VERSION, + }; + use crate::task_pool::{SchedulerNetworkClass, ServiceEstimate}; + + fn config( + cpu: usize, + blocking: usize, + network: usize, + extract: usize, + ) -> SchedulerConfigProfile { + SchedulerConfigProfile { + cpu_slots: cpu, + hdiff_decoder_slots: cpu.clamp(1, 2), + blocking_slots: blocking, + network_slots: network, + extract_slots: extract, + reuse_queue_limit: 64, + volume_write_reservation_delay_ns: 15_000_000, + ready_frontier_limit: 256, + priority_lookahead: 64, + continuation_burst: 4, + default_volume_policy: WorkloadVolumePolicy { + read_limit: 16, + write_limit: 16, + metadata_limit: 128, + streaming_pressure_limit: 32, + streaming_mode: WorkloadVolumeStreamingMode::Mixed, + }, + volume_policy_overrides: Vec::::new(), + } + } + + fn node(index: usize, deps: Vec, origin: WorkloadTaskOrigin) -> CompactNode { + CompactNode { + node: WorkloadNode { + id: WorkloadNodeId { + run_id: 1, + node_id: index, + }, + task_kind: "Test".to_owned(), + dag_hint: WorkloadDagHint { + origin, + depth: deps.len() as u32, + local_rank: None, + }, + expansion_parent: None, + }, + dependencies: deps + .into_iter() + .map(|node_id| WorkloadNodeId { run_id: 1, node_id }) + .collect(), + } + } + + fn unit( + node_id: usize, + generation: u32, + phase: WorkUnitPhase, + priority: SchedulerTaskPriority, + run: SchedulerRunClass, + duration: u64, + ) -> CompactWorkUnit { + CompactWorkUnit { + identity: WorkUnitIdentity { + node: WorkloadNodeId { run_id: 1, node_id }, + task_kind: "Test".to_owned(), + phase, + attempt: 1, + continuation_generation: generation, + }, + priority, + demand: WorkloadResourceDemand { + cpu_on_async: false, + hdiff_decoder_start: false, + run_class: run, + network_class: None, + read_volumes: vec![], + write_volumes: vec![], + metadata_volumes: vec![], + archive_save_volumes: vec![], + archive_commit_volumes: vec![], + extract: false, + mutation_paths: vec![], + storage_reservations: Vec::::new(), + reuse_probe: false, + reuse_commit: false, + priority_cost: duration, + service_estimate: ServiceEstimate::default(), + }, + batch_class: None, + observed_ready_ns: 999_999, + observed_queue_wait_ns: 0, + observed_service: ObservedService { + run_time_ns: ServiceQuantity::observed(duration), + cpu_cost: ServiceQuantity { + value: duration, + source: QuantitySource::Estimated, + }, + network_bytes: ServiceQuantity::unknown(), + storage_read_bytes: ServiceQuantity::unknown(), + storage_write_bytes: ServiceQuantity::unknown(), + metadata_ops: ServiceQuantity::unknown(), + }, + completion: WorkloadCompletion::Succeeded, + hdiff_retention_released: false, + } + } + + fn workload(nodes: Vec, units: Vec) -> CompactWorkload { + let edges = nodes + .iter() + .flat_map(|node| { + node.dependencies.iter().map(|dependency| WorkloadEdge { + from: dependency.clone(), + to: node.node.id.clone(), + }) + }) + .collect(); + CompactWorkload { + schema_version: COMPACT_WORKLOAD_SCHEMA_VERSION, + source_tree: "tree".to_owned(), + scheduler: config(1, 1, 1, 1), + machine: MachineProfile { + os: "test".to_owned(), + architecture: "test".to_owned(), + available_parallelism: 1, + md5_verify_batch_capacity: 1, + }, + nodes, + edges, + paths: vec![], + volumes: Vec::::new(), + work_units: units, + expansions: vec![], + observed_batch_services: vec![], + } + } + + #[test] + fn chain_replays_dependency_readiness_not_observed_ready_timestamp() { + let input = workload( + vec![ + node(0, vec![], WorkloadTaskOrigin::Root), + node(1, vec![0], WorkloadTaskOrigin::StaticDependency), + node(2, vec![1], WorkloadTaskOrigin::StaticDependency), + ], + vec![ + unit( + 0, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ), + unit( + 1, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 20, + ), + unit( + 2, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 30, + ), + ], + ); + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.makespan_ns, 60); + assert_eq!(result.summary.longest_chain_service_ns, 60); + } + + #[test] + fn fanout_uses_available_cpu_capacity() { + let mut input = workload( + vec![ + node(0, vec![], WorkloadTaskOrigin::Root), + node(1, vec![], WorkloadTaskOrigin::Root), + node(2, vec![], WorkloadTaskOrigin::Root), + ], + vec![ + unit( + 0, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ), + unit( + 1, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ), + unit( + 2, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ), + ], + ); + input.scheduler.cpu_slots = 2; + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.makespan_ns, 20); + assert_eq!(result.summary.max_concurrently_running_work, 2); + } + + #[test] + fn md5_verify_batch_shares_one_cpu_slot_and_keeps_read_pressure() { + let mut units = (0..3) + .map(|node_id| { + unit( + node_id, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ) + }) + .collect::>(); + for work in &mut units { + work.identity.task_kind = "Verify".to_owned(); + work.batch_class = Some(WorkloadBatchClass::Md5Verify); + work.demand.read_volumes = vec!["volume#01".to_owned()]; + } + let mut input = workload( + vec![ + node(0, vec![], WorkloadTaskOrigin::Root), + node(1, vec![], WorkloadTaskOrigin::Root), + node(2, vec![], WorkloadTaskOrigin::Root), + ], + units, + ); + input.machine.md5_verify_batch_capacity = 3; + input.scheduler.cpu_slots = 1; + input.scheduler.default_volume_policy.read_limit = 3; + input + .scheduler + .default_volume_policy + .streaming_pressure_limit = 3; + + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.makespan_ns, 10); + assert_eq!(result.summary.max_concurrently_running_work, 3); + assert_eq!(result.summary.resource_utilization.cpu_basis_points, 10_000); + assert_eq!(result.summary.queue_wait.max_ns, 0); + + // Batch capacity is not authority to overcommit a volume. Each + // follower must be feasible against all already-selected members. + for (read_limit, pressure_limit, expected_parallelism, expected_makespan) in + [(1, 3, 1, 30), (2, 3, 2, 20), (3, 1, 1, 30), (3, 2, 2, 20)] + { + input.scheduler.default_volume_policy.read_limit = read_limit; + input + .scheduler + .default_volume_policy + .streaming_pressure_limit = pressure_limit; + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!( + result.summary.max_concurrently_running_work, expected_parallelism, + "read_limit={read_limit}, pressure_limit={pressure_limit}" + ); + assert_eq!(result.summary.makespan_ns, expected_makespan); + } + } + + #[test] + fn mixed_resource_vector_is_admitted_atomically() { + let mut first = unit( + 0, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 20, + ); + first.demand.network_class = Some(SchedulerNetworkClass::General); + let second = unit( + 1, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ); + let mut input = workload( + vec![ + node(0, vec![], WorkloadTaskOrigin::Root), + node(1, vec![], WorkloadTaskOrigin::Root), + ], + vec![first, second], + ); + input.scheduler.cpu_slots = 1; + input.scheduler.network_slots = 1; + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.makespan_ns, 30); + assert!(result + .summary + .admission_block_breakdown + .keys() + .any(|key| key == "Cpu")); + } + + #[test] + fn completion_can_unlock_a_previously_blocked_ready_unit_without_false_deadlock() { + let mut first = unit( + 0, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ); + let mut blocker = unit( + 1, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 20, + ); + let mut waiting = unit( + 2, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 5, + ); + for work in [&mut first, &mut blocker, &mut waiting] { + work.demand.priority_cost = 1; + } + blocker.demand.mutation_paths = vec!["path#01".to_owned()]; + waiting.demand.mutation_paths = vec!["path#01".to_owned()]; + + let mut input = workload( + vec![ + node(0, vec![], WorkloadTaskOrigin::Root), + node(1, vec![], WorkloadTaskOrigin::Root), + node(2, vec![], WorkloadTaskOrigin::Root), + ], + vec![first, blocker, waiting], + ); + input.scheduler.cpu_slots = 2; + + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.completed_work_units, 3); + assert_eq!(result.summary.makespan_ns, 25); + assert!(result + .summary + .admission_block_breakdown + .keys() + .any(|key| key == "MutationConflict")); + } + + #[test] + fn hdiff_replay_keeps_same_node_order_across_decode_slices() { + let mut prepare = unit( + 0, + 0, + WorkUnitPhase::HdiffPrepare, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 15, + ); + prepare.completion = WorkloadCompletion::Continued; + let mut first = unit( + 0, + 1, + WorkUnitPhase::HdiffDecode, + SchedulerTaskPriority::Continuation, + SchedulerRunClass::AsyncIo, + 10, + ); + first.demand.cpu_on_async = true; + first.demand.hdiff_decoder_start = true; + first.completion = WorkloadCompletion::Continued; + let mut second = unit( + 0, + 2, + WorkUnitPhase::HdiffDecode, + SchedulerTaskPriority::Continuation, + SchedulerRunClass::AsyncIo, + 5, + ); + second.demand.cpu_on_async = true; + second.hdiff_retention_released = true; + second.completion = WorkloadCompletion::Continued; + let commit = unit( + 0, + 3, + WorkUnitPhase::HdiffCommit, + SchedulerTaskPriority::Continuation, + SchedulerRunClass::Cpu, + 25, + ); + let input = workload( + vec![node(0, vec![], WorkloadTaskOrigin::Root)], + vec![prepare, first, second, commit], + ); + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.makespan_ns, 55); + let completion = input + .work_units + .iter() + .map(|work| result.completion_times_ns[&work.identity]) + .collect::>(); + assert_eq!(completion, [15, 25, 30, 55]); + } + + #[test] + fn dynamic_expansion_children_are_revealed_by_parent_workunit() { + let parent = node(0, vec![], WorkloadTaskOrigin::Root); + let parent_unit = WorkUnitIdentity { + node: parent.node.id.clone(), + task_kind: "Test".to_owned(), + phase: WorkUnitPhase::Generic, + attempt: 1, + continuation_generation: 0, + }; + let mut child = node(1, vec![], WorkloadTaskOrigin::DynamicExpansion); + child.node.expansion_parent = Some(parent_unit.clone()); + let mut parent_work = unit( + 0, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ); + parent_work.completion = WorkloadCompletion::Expanded; + let child_work = unit( + 1, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Continuation, + SchedulerRunClass::Cpu, + 20, + ); + let mut input = workload(vec![parent, child], vec![parent_work, child_work]); + input.expansions.push(CompactExpansion { + parent: parent_unit, + new_nodes: vec![WorkloadNodeId { + run_id: 1, + node_id: 1, + }], + new_edges: vec![], + }); + let result = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(result.summary.makespan_ns, 30); + } + + #[test] + fn repeated_replay_is_byte_stable_at_summary_level() { + let input = workload( + vec![ + node(0, vec![], WorkloadTaskOrigin::Root), + node(1, vec![], WorkloadTaskOrigin::Root), + ], + vec![ + unit( + 0, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 10, + ), + unit( + 1, + 0, + WorkUnitPhase::Generic, + SchedulerTaskPriority::Bulk, + SchedulerRunClass::Cpu, + 20, + ), + ], + ); + let first = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + let second = replay_workload(&input, ReplayPolicy::CurrentProduction).unwrap(); + assert_eq!(first.summary, second.summary); + assert_eq!(first.completion_times_ns, second.completion_times_ns); + assert!(first + .summary + .determinism_fingerprint + .starts_with("fnv1a64:")); + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/retention.rs b/crates/griffr-runtime/src/task_pool/workload/retention.rs new file mode 100644 index 0000000..90c8de1 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/retention.rs @@ -0,0 +1,66 @@ +use super::{WorkUnitPhase, WorkloadCompletion}; + +#[derive(Debug, Default, Clone, Copy)] +pub(super) enum DecoderRetention { + #[default] + Unused, + Held, + Decoded, + Terminal, +} + +impl DecoderRetention { + pub(super) fn is_held(&self) -> bool { + matches!(self, Self::Held) + } + + pub(super) fn admit( + &mut self, + phase: WorkUnitPhase, + starts_decoder: bool, + ) -> Result<(), &'static str> { + match (phase, starts_decoder, &*self) { + (WorkUnitPhase::HdiffDecode, true, Self::Unused) => *self = Self::Held, + (WorkUnitPhase::HdiffDecode, true, _) => { + return Err("duplicate decoder retention acquire") + } + (WorkUnitPhase::HdiffDecode, false, Self::Held) => {} + (WorkUnitPhase::HdiffDecode, false, _) => { + return Err("decode continuation has no retained decoder") + } + (_, true, _) => return Err("non-decode work requested decoder retention"), + (_, false, Self::Held) => { + return Err("non-decode work while decoder retention is held") + } + (WorkUnitPhase::HdiffCommit, false, Self::Decoded) => *self = Self::Terminal, + (_, false, Self::Decoded) => return Err("invalid HDiff commit continuation"), + (WorkUnitPhase::HdiffCommit, false, _) => { + return Err("HDiff commit without completed decoder ownership") + } + _ => {} + } + Ok(()) + } + + pub(super) fn finish( + &mut self, + phase: WorkUnitPhase, + completion: WorkloadCompletion, + releases_decoder: bool, + ) -> Result<(), &'static str> { + if releases_decoder { + if phase != WorkUnitPhase::HdiffDecode || !self.is_held() { + return Err("decoder retention released without ownership"); + } + *self = match completion { + WorkloadCompletion::Continued => Self::Decoded, + WorkloadCompletion::Failed | WorkloadCompletion::Cancelled => Self::Terminal, + _ => return Err("invalid terminal completion for HDiff decode"), + }; + } else if phase == WorkUnitPhase::HdiffDecode && completion != WorkloadCompletion::Continued + { + return Err("terminal decode must release decoder retention"); + } + Ok(()) + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/sanitize.rs b/crates/griffr-runtime/src/task_pool/workload/sanitize.rs new file mode 100644 index 0000000..72d25aa --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/sanitize.rs @@ -0,0 +1,377 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use super::{ + SanitizedPath, SanitizedVolume, WorkloadAdmissionBlockReason, WorkloadResourceDemand, + WorkloadResourceOccupancy, WorkloadStorageReservation, WorkloadVolumeOccupancy, +}; +use crate::task_pool::{ + storage_volume_key, AdmissionBlockReason, ResourceOccupancy, SchedulerResourceDemand, +}; + +/// Deterministic, run-local content sanitizer for scheduler-visible path and volume identities. +/// +/// The output IDs intentionally carry no cryptographic meaning. A trace only needs stable +/// equality/ancestry/volume relationships, so first-seen interning is sufficient and avoids +/// preserving user paths or pretending that anonymization requires a content fingerprint. +#[derive(Debug, Default)] +pub struct WorkloadSanitizer { + volumes: BTreeMap, + paths: BTreeMap, + emitted_volumes: BTreeSet, + emitted_paths: BTreeSet, + next_volume: u64, + next_path: u64, +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub struct SanitizationDelta { + pub volumes: Vec, + pub paths: Vec, +} + +impl WorkloadSanitizer { + pub fn sanitize_demand( + &mut self, + demand: &SchedulerResourceDemand, + ) -> (WorkloadResourceDemand, SanitizationDelta) { + let mut delta = SanitizationDelta::default(); + let read_volumes = self.sanitize_volumes(&demand.read_volumes, &mut delta); + let write_volumes = self.sanitize_volumes(&demand.write_volumes, &mut delta); + let metadata_volumes = self.sanitize_volumes(&demand.metadata_volumes, &mut delta); + let archive_save_volumes = self.sanitize_volumes(&demand.archive_save_volumes, &mut delta); + let archive_commit_volumes = demand + .archive_commit_volumes + .iter() + .map(|(volume, exclusive)| (self.intern_volume(volume, &mut delta), *exclusive)) + .collect(); + let mutation_paths = demand + .mutation_paths + .iter() + .map(|path| self.intern_path(path, &mut delta)) + .collect(); + let storage_reservations = demand + .storage_reservations + .iter() + .map(|reservation| WorkloadStorageReservation { + volume_id: self.intern_volume(&reservation.volume, &mut delta), + bytes: reservation.bytes, + }) + .collect(); + + ( + WorkloadResourceDemand { + cpu_on_async: demand.cpu_on_async, + hdiff_decoder_start: demand.hdiff_decoder_start, + run_class: demand.run_class, + network_class: demand.network_class, + read_volumes, + write_volumes, + metadata_volumes, + archive_save_volumes, + archive_commit_volumes, + extract: demand.extract, + mutation_paths, + storage_reservations, + reuse_probe: demand.reuse_probe, + reuse_commit: demand.reuse_commit, + priority_cost: demand.priority_cost, + service_estimate: demand.service_estimate, + }, + delta, + ) + } + + pub fn sanitize_occupancy( + &mut self, + occupancy: &ResourceOccupancy, + ) -> (WorkloadResourceOccupancy, SanitizationDelta) { + let mut delta = SanitizationDelta::default(); + let storage_reserved_bytes = occupancy + .storage_reserved_bytes + .iter() + .map(|(volume, bytes)| (self.intern_volume(volume, &mut delta), *bytes)) + .collect(); + let volumes = occupancy + .volumes + .iter() + .map(|volume| WorkloadVolumeOccupancy { + volume_id: self.intern_volume(&volume.volume, &mut delta), + reads_used: volume.reads_used, + reads_cap: volume.reads_cap, + writes_used: volume.writes_used, + writes_cap: volume.writes_cap, + metadata_used: volume.metadata_used, + metadata_cap: volume.metadata_cap, + streaming_pressure_used: volume.streaming_pressure_used, + streaming_pressure_cap: volume.streaming_pressure_cap, + }) + .collect(); + + ( + WorkloadResourceOccupancy { + cpu_used: occupancy.cpu_used, + cpu_cap: occupancy.cpu_cap, + network_used: occupancy.network_used, + network_cap: occupancy.network_cap, + blocking_used: occupancy.blocking_used, + blocking_cap: occupancy.blocking_cap, + extract_used: occupancy.extract_used, + extract_cap: occupancy.extract_cap, + reuse_commits_used: occupancy.reuse_commits_used, + mutation_paths_used: occupancy.mutation_paths_used, + storage_reserved_bytes, + volumes, + }, + delta, + ) + } + + pub fn sanitize_block_reasons( + &mut self, + reasons: &[AdmissionBlockReason], + ) -> (Vec, SanitizationDelta) { + let mut delta = SanitizationDelta::default(); + let reasons = reasons + .iter() + .map(|reason| match reason { + AdmissionBlockReason::Cpu => WorkloadAdmissionBlockReason::Cpu, + AdmissionBlockReason::Blocking => WorkloadAdmissionBlockReason::Blocking, + AdmissionBlockReason::Network => WorkloadAdmissionBlockReason::Network, + AdmissionBlockReason::Extract => WorkloadAdmissionBlockReason::Extract, + AdmissionBlockReason::GlobalCpu => WorkloadAdmissionBlockReason::GlobalCpu, + AdmissionBlockReason::GlobalBlocking => { + WorkloadAdmissionBlockReason::GlobalBlocking + } + AdmissionBlockReason::GlobalNetwork => WorkloadAdmissionBlockReason::GlobalNetwork, + AdmissionBlockReason::GlobalExtract => WorkloadAdmissionBlockReason::GlobalExtract, + AdmissionBlockReason::HdiffDecoderMemory => { + WorkloadAdmissionBlockReason::HdiffDecoderMemory + } + AdmissionBlockReason::GlobalReuseQueue => { + WorkloadAdmissionBlockReason::GlobalReuseQueue + } + AdmissionBlockReason::GlobalFairness => { + WorkloadAdmissionBlockReason::GlobalFairness + } + AdmissionBlockReason::VolumeRead(volume) => { + WorkloadAdmissionBlockReason::VolumeRead(self.intern_volume(volume, &mut delta)) + } + AdmissionBlockReason::VolumeWrite(volume) => { + WorkloadAdmissionBlockReason::VolumeWrite( + self.intern_volume(volume, &mut delta), + ) + } + AdmissionBlockReason::Metadata(volume) => { + WorkloadAdmissionBlockReason::Metadata(self.intern_volume(volume, &mut delta)) + } + AdmissionBlockReason::VolumeStreaming(volume) => { + WorkloadAdmissionBlockReason::VolumeStreaming( + self.intern_volume(volume, &mut delta), + ) + } + AdmissionBlockReason::WriterReservation(volume) => { + WorkloadAdmissionBlockReason::WriterReservation( + self.intern_volume(volume, &mut delta), + ) + } + AdmissionBlockReason::MutationConflict => { + WorkloadAdmissionBlockReason::MutationConflict + } + AdmissionBlockReason::StorageReservation(volume) => { + WorkloadAdmissionBlockReason::StorageReservation( + self.intern_volume(volume, &mut delta), + ) + } + AdmissionBlockReason::ReuseQueue => WorkloadAdmissionBlockReason::ReuseQueue, + AdmissionBlockReason::ArchiveSave(volume) => { + WorkloadAdmissionBlockReason::ArchiveSave( + self.intern_volume(volume, &mut delta), + ) + } + AdmissionBlockReason::ArchiveCommit(volume) => { + WorkloadAdmissionBlockReason::ArchiveCommit( + self.intern_volume(volume, &mut delta), + ) + } + }) + .collect(); + (reasons, delta) + } + + pub(crate) fn intern_volume_for_capture( + &mut self, + volume: &str, + ) -> (String, SanitizationDelta) { + let mut delta = SanitizationDelta::default(); + let id = self.intern_volume(volume, &mut delta); + (id, delta) + } + + pub fn intern_path_for_test(&mut self, path: &str) -> (String, SanitizationDelta) { + let mut delta = SanitizationDelta::default(); + let id = self.intern_path(path, &mut delta); + (id, delta) + } + + fn sanitize_volumes( + &mut self, + values: &[String], + delta: &mut SanitizationDelta, + ) -> Vec { + values + .iter() + .map(|volume| self.intern_volume(volume, delta)) + .collect() + } + + fn intern_volume(&mut self, raw: &str, delta: &mut SanitizationDelta) -> String { + let id = match self.volumes.get(raw) { + Some(id) => id.clone(), + None => { + self.next_volume += 1; + let id = format!("volume#{:02}", self.next_volume); + self.volumes.insert(raw.to_owned(), id.clone()); + id + } + }; + if self.emitted_volumes.insert(id.clone()) { + delta.volumes.push(SanitizedVolume { + volume_id: id.clone(), + }); + } + id + } + + fn intern_path(&mut self, raw: &str, delta: &mut SanitizationDelta) -> String { + let volume_raw = storage_volume_key(Path::new(raw)); + let volume_id = self.intern_volume(&volume_raw, delta); + let normalized = normalize_path(raw); + let prefixes = path_prefixes(&normalized); + let mut parent_id = None; + let mut leaf_id = None; + + for prefix in prefixes { + let id = match self.paths.get(&prefix) { + Some(id) => id.clone(), + None => { + self.next_path += 1; + let id = format!("path#{:06}", self.next_path); + self.paths.insert(prefix, id.clone()); + id + } + }; + if self.emitted_paths.insert(id.clone()) { + delta.paths.push(SanitizedPath { + path_id: id.clone(), + parent_id: parent_id.clone(), + volume_id: volume_id.clone(), + }); + } + parent_id = Some(id.clone()); + leaf_id = Some(id); + } + + leaf_id.unwrap_or_else(|| { + let synthetic = format!("@{volume_raw}"); + if let Some(id) = self.paths.get(&synthetic) { + return id.clone(); + } + self.next_path += 1; + let id = format!("path#{:06}", self.next_path); + self.paths.insert(synthetic, id.clone()); + if self.emitted_paths.insert(id.clone()) { + delta.paths.push(SanitizedPath { + path_id: id.clone(), + parent_id: None, + volume_id, + }); + } + id + }) + } +} + +fn normalize_path(raw: &str) -> String { + let replaced = raw.replace('\\', "/"); + let absolute = replaced.starts_with('/'); + let mut components = Vec::new(); + for component in replaced.split('/') { + match component { + "" | "." => {} + ".." => { + components.pop(); + } + value => components.push(value), + } + } + let joined = components.join("/"); + if absolute { + format!("/{joined}") + } else { + joined + } +} + +fn path_prefixes(normalized: &str) -> Vec { + let absolute = normalized.starts_with('/'); + let components: Vec<_> = normalized + .split('/') + .filter(|part| !part.is_empty()) + .collect(); + let mut prefixes = Vec::with_capacity(components.len()); + let mut current = String::new(); + for component in components { + if current.is_empty() { + if absolute { + current.push('/'); + } + current.push_str(component); + } else { + current.push('/'); + current.push_str(component); + } + prefixes.push(current.clone()); + } + prefixes +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deterministic_path_ids_preserve_parent_relationship_without_leakage() { + let raw_parent = "/home/alice/Games/example/data"; + let raw_child = "/home/alice/Games/example/data/chunk.bin"; + + let mut first = WorkloadSanitizer::default(); + let (parent_id, parent_delta) = first.intern_path_for_test(raw_parent); + let (child_id, child_delta) = first.intern_path_for_test(raw_child); + let mut second = WorkloadSanitizer::default(); + let (parent_id_again, _) = second.intern_path_for_test(raw_parent); + let (child_id_again, _) = second.intern_path_for_test(raw_child); + + assert_eq!(parent_id, parent_id_again); + assert_eq!(child_id, child_id_again); + assert_ne!(parent_id, child_id); + let child = child_delta.paths.last().unwrap(); + assert_eq!(child.parent_id.as_deref(), Some(parent_id.as_str())); + + let json = serde_json::to_string(&(parent_delta.paths, child_delta.paths)).unwrap(); + assert!(!json.contains("alice")); + assert!(!json.contains("Games")); + assert!(!json.contains("chunk.bin")); + } + + #[test] + fn paths_on_same_volume_keep_same_sanitized_volume() { + let mut sanitizer = WorkloadSanitizer::default(); + let (_, first) = sanitizer.intern_path_for_test("/tmp/game/a.bin"); + let (_, second) = sanitizer.intern_path_for_test("/tmp/other/b.bin"); + + let first_volume = first.paths.last().unwrap().volume_id.clone(); + let second_volume = second.paths.last().unwrap().volume_id.clone(); + assert_eq!(first_volume, second_volume); + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/schema.rs b/crates/griffr-runtime/src/task_pool/workload/schema.rs new file mode 100644 index 0000000..7eb5833 --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/schema.rs @@ -0,0 +1,686 @@ +use std::collections::BTreeMap; +use std::io::{BufRead, Write}; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use super::super::{ + SchedulerNetworkClass, SchedulerRunClass, SchedulerTaskPriority, ServiceEstimate, + VolumeIoPolicy, VolumeStreamingMode, +}; +use crate::error::{Error, Result}; + +pub const WORKLOAD_TRACE_SCHEMA_VERSION: u32 = 4; +pub const DEFAULT_WORKLOAD_TRACE_CHANNEL_CAPACITY: usize = 4096; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkloadCaptureConfig { + pub path: PathBuf, + pub mode: WorkloadCaptureMode, + pub channel_capacity: usize, + pub source_tree: String, + pub workload_kind: Option, +} + +impl WorkloadCaptureConfig { + pub fn streaming_strict(path: impl Into, source_tree: impl Into) -> Self { + Self { + path: path.into(), + mode: WorkloadCaptureMode::StreamingStrict, + channel_capacity: DEFAULT_WORKLOAD_TRACE_CHANNEL_CAPACITY, + source_tree: source_tree.into(), + workload_kind: None, + } + } + + pub fn streaming_loss_aware(path: impl Into, source_tree: impl Into) -> Self { + Self { + path: path.into(), + mode: WorkloadCaptureMode::StreamingLossAware, + channel_capacity: DEFAULT_WORKLOAD_TRACE_CHANNEL_CAPACITY, + source_tree: source_tree.into(), + workload_kind: None, + } + } + + pub fn with_workload_kind(mut self, workload_kind: impl Into) -> Self { + self.workload_kind = Some(workload_kind.into()); + self + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadCaptureMode { + Memory, + StreamingStrict, + StreamingLossAware, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadTimeModel { + MonotonicRelativeNanoseconds, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadTraceHeader { + pub schema_version: u32, + pub run_id: u64, + pub runner_id: u64, + pub time_model: WorkloadTimeModel, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wall_clock_start_unix_ns: Option, + pub source_tree: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workload_kind: Option, + pub capture_mode: WorkloadCaptureMode, + pub scheduler: SchedulerConfigProfile, + pub machine: MachineProfile, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SchedulerConfigProfile { + pub cpu_slots: usize, + pub hdiff_decoder_slots: usize, + pub blocking_slots: usize, + pub network_slots: usize, + pub extract_slots: usize, + pub reuse_queue_limit: usize, + pub volume_write_reservation_delay_ns: u64, + pub ready_frontier_limit: usize, + pub priority_lookahead: usize, + pub continuation_burst: usize, + pub default_volume_policy: WorkloadVolumePolicy, + pub volume_policy_overrides: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadVolumePolicy { + pub read_limit: usize, + pub write_limit: usize, + pub metadata_limit: usize, + pub streaming_pressure_limit: usize, + pub streaming_mode: WorkloadVolumeStreamingMode, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadVolumeStreamingMode { + Exclusive, + Mixed, +} + +impl From for WorkloadVolumePolicy { + fn from(value: VolumeIoPolicy) -> Self { + Self { + read_limit: value.read_limit, + write_limit: value.write_limit, + metadata_limit: value.metadata_limit, + streaming_pressure_limit: value.streaming_pressure_limit, + streaming_mode: value.streaming_mode.into(), + } + } +} + +impl From for WorkloadVolumeStreamingMode { + fn from(value: VolumeStreamingMode) -> Self { + match value { + VolumeStreamingMode::Exclusive => Self::Exclusive, + VolumeStreamingMode::Mixed => Self::Mixed, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct VolumePolicyOverride { + pub volume_id: String, + pub policy: WorkloadVolumePolicy, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MachineProfile { + pub os: String, + pub architecture: String, + pub available_parallelism: usize, + /// Number of Verify work items that the runtime may coalesce into one MD5 SIMD dispatch. + pub md5_verify_batch_capacity: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct WorkloadNodeId { + pub run_id: u64, + pub node_id: usize, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadTaskOrigin { + Root, + StaticDependency, + DynamicExpansion, + Continuation, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadDagHint { + pub origin: WorkloadTaskOrigin, + pub depth: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local_rank: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadBatchClass { + Md5Verify, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadNode { + pub id: WorkloadNodeId, + pub task_kind: String, + pub dag_hint: WorkloadDagHint, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expansion_parent: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadEdge { + pub from: WorkloadNodeId, + pub to: WorkloadNodeId, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkUnitPhase { + Generic, + HdiffPrepare, + HdiffDecode, + HdiffCommit, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct WorkUnitIdentity { + pub node: WorkloadNodeId, + pub task_kind: String, + pub phase: WorkUnitPhase, + pub attempt: u32, + pub continuation_generation: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum QuantitySource { + Observed, + Estimated, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServiceQuantity { + pub value: u64, + pub source: QuantitySource, +} + +impl ServiceQuantity { + pub const fn observed(value: u64) -> Self { + Self { + value, + source: QuantitySource::Observed, + } + } + + pub const fn estimated(value: u64) -> Self { + Self { + value, + source: QuantitySource::Estimated, + } + } + + pub const fn unknown() -> Self { + Self { + value: 0, + source: QuantitySource::Unknown, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObservedService { + pub run_time_ns: ServiceQuantity, + pub cpu_cost: ServiceQuantity, + pub network_bytes: ServiceQuantity, + pub storage_read_bytes: ServiceQuantity, + pub storage_write_bytes: ServiceQuantity, + pub metadata_ops: ServiceQuantity, +} + +impl ObservedService { + pub fn from_estimate(run_time_ns: u64, estimate: ServiceEstimate) -> Self { + Self { + run_time_ns: ServiceQuantity::observed(run_time_ns), + cpu_cost: if estimate.cpu_cost == 0 { + ServiceQuantity::unknown() + } else { + ServiceQuantity::estimated(estimate.cpu_cost) + }, + network_bytes: if estimate.network_bytes == 0 { + ServiceQuantity::unknown() + } else { + ServiceQuantity::estimated(estimate.network_bytes) + }, + storage_read_bytes: if estimate.storage_read_bytes == 0 { + ServiceQuantity::unknown() + } else { + ServiceQuantity::estimated(estimate.storage_read_bytes) + }, + storage_write_bytes: if estimate.storage_write_bytes == 0 { + ServiceQuantity::unknown() + } else { + ServiceQuantity::estimated(estimate.storage_write_bytes) + }, + metadata_ops: if estimate.metadata_ops == 0 { + ServiceQuantity::unknown() + } else { + ServiceQuantity::estimated(u64::from(estimate.metadata_ops)) + }, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadStorageReservation { + pub volume_id: String, + pub bytes: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadResourceDemand { + pub cpu_on_async: bool, + pub hdiff_decoder_start: bool, + pub run_class: SchedulerRunClass, + pub network_class: Option, + pub read_volumes: Vec, + pub write_volumes: Vec, + pub metadata_volumes: Vec, + pub archive_save_volumes: Vec, + pub archive_commit_volumes: Vec<(String, bool)>, + pub extract: bool, + pub mutation_paths: Vec, + pub storage_reservations: Vec, + pub reuse_probe: bool, + pub reuse_commit: bool, + pub priority_cost: u64, + pub service_estimate: ServiceEstimate, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadVolumeOccupancy { + pub volume_id: String, + pub reads_used: usize, + pub reads_cap: usize, + pub writes_used: usize, + pub writes_cap: usize, + pub metadata_used: usize, + pub metadata_cap: usize, + pub streaming_pressure_used: usize, + pub streaming_pressure_cap: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadResourceOccupancy { + pub cpu_used: usize, + pub cpu_cap: usize, + pub network_used: usize, + pub network_cap: usize, + pub blocking_used: usize, + pub blocking_cap: usize, + pub extract_used: usize, + pub extract_cap: usize, + pub reuse_commits_used: usize, + pub mutation_paths_used: usize, + pub storage_reserved_bytes: BTreeMap, + pub volumes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SanitizedPath { + pub path_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + pub volume_id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SanitizedVolume { + pub volume_id: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadCompletion { + Succeeded, + Failed, + Cancelled, + Continued, + Expanded, + ExpandedThen, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadOccupancyAction { + Acquire, + Release, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkloadAdmissionBlockReason { + Cpu, + Blocking, + Network, + Extract, + GlobalCpu, + GlobalBlocking, + GlobalNetwork, + GlobalExtract, + GlobalReuseQueue, + HdiffDecoderMemory, + GlobalFairness, + VolumeRead(String), + VolumeWrite(String), + Metadata(String), + VolumeStreaming(String), + WriterReservation(String), + MutationConflict, + StorageReservation(String), + ReuseQueue, + ArchiveSave(String), + ArchiveCommit(String), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadDecision { + pub ready_frontier_len: usize, + pub ready_backlog_len: usize, + pub priority: SchedulerTaskPriority, + pub candidate_index: usize, + pub lookahead_exhausted: bool, + pub run_class: SchedulerRunClass, + pub network_class: Option, + pub batch_member: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum WorkloadEventKind { + Created { + node: WorkloadNodeId, + }, + Ready { + work_unit: WorkUnitIdentity, + dag_hint: WorkloadDagHint, + /// Execution coalescing capability intrinsic to this WorkUnit. This is deliberately + /// separate from captured scheduling decisions so replay may form a different legal + /// batch instead of replaying the original admission timeline. + #[serde(default, skip_serializing_if = "Option::is_none")] + batch_class: Option, + }, + Routed { + work_unit: WorkUnitIdentity, + priority: SchedulerTaskPriority, + demand: WorkloadResourceDemand, + }, + Considered { + work_unit: WorkUnitIdentity, + priority: SchedulerTaskPriority, + candidate_index: usize, + run_class: SchedulerRunClass, + network_class: Option, + batch_member: bool, + blocked_by: Vec, + }, + Admitted { + work_unit: WorkUnitIdentity, + service_estimate: ServiceEstimate, + }, + Started { + work_unit: WorkUnitIdentity, + }, + Finished { + work_unit: WorkUnitIdentity, + completion: WorkloadCompletion, + hdiff_retention_released: bool, + queue_wait_ns: u64, + observed_service: ObservedService, + }, + Decision(WorkloadDecision), + Occupancy { + action: WorkloadOccupancyAction, + work_unit: WorkUnitIdentity, + occupancy: WorkloadResourceOccupancy, + }, + Expanded { + parent: WorkUnitIdentity, + new_nodes: Vec, + new_edges: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadEvent { + pub event_sequence: u64, + pub elapsed_ns: u64, + #[serde(flatten)] + pub kind: WorkloadEventKind, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceFooter { + pub record_count: u64, + pub event_count: u64, + pub node_count: u64, + pub edge_count: u64, + pub dropped_event_count: u64, + pub peak_queued_events: usize, + pub capture_complete: bool, + pub complete_for_replay: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub writer_error: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "record", rename_all = "snake_case")] +pub enum WorkloadRecordPayload { + Header(WorkloadTraceHeader), + Node(WorkloadNode), + Edge(WorkloadEdge), + Path(SanitizedPath), + Volume(SanitizedVolume), + Event(WorkloadEvent), + Footer(TraceFooter), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkloadRecord { + pub sequence: u64, + #[serde(flatten)] + pub payload: WorkloadRecordPayload, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct WorkloadTrace { + pub records: Vec, +} + +pub(super) fn visit_workload_records( + mut reader: impl BufRead, + mut visitor: impl FnMut(WorkloadRecord) -> Result<()>, +) -> Result<()> { + let mut line = Vec::new(); + let mut line_index = 0usize; + loop { + line.clear(); + let bytes = reader.read_until(b'\n', &mut line).map_err(Error::Io)?; + if bytes == 0 { + break; + } + line_index = line_index.saturating_add(1); + if line.iter().all(u8::is_ascii_whitespace) { + continue; + } + let record = + serde_json::from_slice::(&line).map_err(|source| Error::Message { + context: "Workload trace parse error: ", + detail: format!("line {line_index}: {source}"), + })?; + visitor(record)?; + } + Ok(()) +} + +impl WorkloadTrace { + pub fn from_reader(reader: impl BufRead) -> Result { + let mut records = Vec::new(); + visit_workload_records(reader, |record| { + records.push(record); + Ok(()) + })?; + Ok(Self { records }) + } + + pub fn from_path(path: impl AsRef) -> Result { + let file = std::fs::File::open(path)?; + Self::from_reader(std::io::BufReader::new(file)) + } + + pub fn write_ndjson(&self, mut writer: impl Write) -> Result<()> { + for record in &self.records { + serde_json::to_writer(&mut writer, record)?; + writer.write_all(b"\n")?; + } + Ok(()) + } + + pub fn header(&self) -> Option<&WorkloadTraceHeader> { + self.records + .iter() + .find_map(|record| match &record.payload { + WorkloadRecordPayload::Header(header) => Some(header), + _ => None, + }) + } + + pub fn footer(&self) -> Option<&TraceFooter> { + self.records + .iter() + .rev() + .find_map(|record| match &record.payload { + WorkloadRecordPayload::Footer(footer) => Some(footer), + _ => None, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_header() -> WorkloadTraceHeader { + WorkloadTraceHeader { + schema_version: WORKLOAD_TRACE_SCHEMA_VERSION, + run_id: 1, + runner_id: 2, + time_model: WorkloadTimeModel::MonotonicRelativeNanoseconds, + wall_clock_start_unix_ns: Some(3), + source_tree: "tree".to_owned(), + workload_kind: Some("verify".to_owned()), + capture_mode: WorkloadCaptureMode::Memory, + scheduler: SchedulerConfigProfile { + cpu_slots: 1, + hdiff_decoder_slots: 2, + blocking_slots: 1, + network_slots: 1, + extract_slots: 1, + reuse_queue_limit: 1, + volume_write_reservation_delay_ns: 15_000_000, + ready_frontier_limit: 256, + priority_lookahead: 64, + continuation_burst: 4, + default_volume_policy: WorkloadVolumePolicy { + read_limit: 1, + write_limit: 1, + metadata_limit: 1, + streaming_pressure_limit: 1, + streaming_mode: WorkloadVolumeStreamingMode::Mixed, + }, + volume_policy_overrides: Vec::new(), + }, + machine: MachineProfile { + os: "test".to_owned(), + architecture: "test".to_owned(), + available_parallelism: 1, + md5_verify_batch_capacity: 1, + }, + } + } + + #[test] + fn current_header_requires_runner_and_batch_capacity() { + let header = serde_json::to_value(test_header()).unwrap(); + let mut missing_runner = header.clone(); + missing_runner.as_object_mut().unwrap().remove("runner_id"); + assert!(serde_json::from_value::(missing_runner).is_err()); + let mut missing_capacity = header; + missing_capacity["machine"] + .as_object_mut() + .unwrap() + .remove("md5_verify_batch_capacity"); + assert!(serde_json::from_value::(missing_capacity).is_err()); + } + + #[test] + fn workload_ndjson_round_trip_ignores_same_version_unknown_fields() { + let trace = WorkloadTrace { + records: vec![ + WorkloadRecord { + sequence: 0, + payload: WorkloadRecordPayload::Header(test_header()), + }, + WorkloadRecord { + sequence: 1, + payload: WorkloadRecordPayload::Footer(TraceFooter { + record_count: 2, + event_count: 0, + node_count: 0, + edge_count: 0, + dropped_event_count: 0, + peak_queued_events: 0, + capture_complete: true, + complete_for_replay: true, + writer_error: None, + }), + }, + ], + }; + let mut payload = Vec::new(); + trace.write_ndjson(&mut payload).unwrap(); + let payload = String::from_utf8(payload).unwrap(); + let mut lines = payload.lines(); + let first = lines.next().unwrap(); + let mut first_json: serde_json::Value = serde_json::from_str(first).unwrap(); + first_json["future_additive_field"] = serde_json::json!(true); + let modified = format!("{}\n{}\n", first_json, lines.next().unwrap()); + let parsed = WorkloadTrace::from_reader(std::io::Cursor::new(modified)).unwrap(); + assert_eq!(parsed, trace); + } + + #[test] + fn truncated_ndjson_is_rejected() { + let payload = br#"{"sequence":0,"record":"header"\n"#; + let error = WorkloadTrace::from_reader(std::io::Cursor::new(payload)).unwrap_err(); + assert!(error.to_string().contains("line 1")); + } +} diff --git a/crates/griffr-runtime/src/task_pool/workload/validate.rs b/crates/griffr-runtime/src/task_pool/workload/validate.rs new file mode 100644 index 0000000..49ed5bc --- /dev/null +++ b/crates/griffr-runtime/src/task_pool/workload/validate.rs @@ -0,0 +1,740 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use super::retention::DecoderRetention; +use super::{ + TraceFooter, WorkUnitIdentity, WorkUnitPhase, WorkloadCompletion, WorkloadEventKind, + WorkloadNodeId, WorkloadOccupancyAction, WorkloadRecord, WorkloadRecordPayload, WorkloadTrace, + WORKLOAD_TRACE_SCHEMA_VERSION, +}; +use crate::error::{Error, Result}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ValidationReport { + pub replay_authority: bool, + pub disqualifications: Vec, + pub record_count: u64, + pub event_count: u64, + pub node_count: u64, + pub edge_count: u64, +} + +#[derive(Debug, Default)] +struct LifecycleState { + ready: bool, + admitted: bool, + started: bool, + finished: bool, + decoder_start: Option, + retention_before_admission: Option, +} + +#[derive(Debug, Default)] +struct NodeLifecycle { + next_generation: Option, + retention: DecoderRetention, +} + +/// Incremental validator for a workload trace. +/// +/// The recorder emits topology records before any event that references them, so validation can +/// remain bounded by scheduler-semantic state (nodes, edges, WorkUnits) instead of retaining every +/// observation event. This is important for live traces where candidate probes can number in the +/// millions. +#[derive(Debug, Default)] +pub(super) struct WorkloadTraceValidator { + header_seen: bool, + footer: Option, + decoder_slots: usize, + retained_decoders: usize, + record_count: u64, + event_count: u64, + expected_event_sequence: u64, + last_event_elapsed_ns: Option, + nodes: BTreeSet, + edges: BTreeSet<(WorkloadNodeId, WorkloadNodeId)>, + created: BTreeMap, + lifecycle: BTreeMap, +} + +impl WorkloadTraceValidator { + pub(super) fn push(&mut self, record: &WorkloadRecord) -> Result<()> { + if self.footer.is_some() { + return validation_error("record appears after terminal footer"); + } + + let expected_sequence = self.record_count; + if record.sequence != expected_sequence { + return validation_error(format!( + "record sequence is not contiguous at index {expected_sequence}: found {}", + record.sequence + )); + } + if expected_sequence == 0 && !matches!(record.payload, WorkloadRecordPayload::Header(_)) { + return validation_error("first record is not a header"); + } + self.record_count = self.record_count.saturating_add(1); + + match &record.payload { + WorkloadRecordPayload::Header(header) => { + if self.header_seen || expected_sequence != 0 { + return validation_error("trace contains more than one header"); + } + if header.schema_version != WORKLOAD_TRACE_SCHEMA_VERSION { + return validation_error(format!( + "unsupported schema version {}; supported version is {}", + header.schema_version, WORKLOAD_TRACE_SCHEMA_VERSION + )); + } + self.decoder_slots = header.scheduler.hdiff_decoder_slots; + self.header_seen = true; + } + WorkloadRecordPayload::Node(node) => { + if !self.nodes.insert(node.id.clone()) { + return validation_error(format!( + "node {:?} appears more than once in topology", + node.id + )); + } + if let Some(parent) = &node.expansion_parent { + require_work_unit_node(&self.nodes, parent)?; + } + } + WorkloadRecordPayload::Edge(edge) => { + if !self.nodes.contains(&edge.from) { + return validation_error(format!( + "edge references missing dependency node {:?}", + edge.from + )); + } + if !self.nodes.contains(&edge.to) { + return validation_error(format!( + "edge references missing dependent node {:?}", + edge.to + )); + } + if edge.from == edge.to { + return validation_error(format!("self-dependency on node {:?}", edge.from)); + } + self.edges.insert((edge.from.clone(), edge.to.clone())); + } + WorkloadRecordPayload::Event(event) => { + self.validate_event(event)?; + } + WorkloadRecordPayload::Footer(footer) => { + self.footer = Some(footer.clone()); + } + WorkloadRecordPayload::Path(_) | WorkloadRecordPayload::Volume(_) => {} + } + Ok(()) + } + + fn validate_event(&mut self, event: &super::WorkloadEvent) -> Result<()> { + self.event_count = self.event_count.saturating_add(1); + if event.event_sequence != self.expected_event_sequence { + return validation_error(format!( + "event sequence is not contiguous: expected {}, found {}", + self.expected_event_sequence, event.event_sequence + )); + } + self.expected_event_sequence = self.expected_event_sequence.saturating_add(1); + if let Some(previous) = self.last_event_elapsed_ns { + if event.elapsed_ns < previous { + return validation_error(format!( + "event monotonic time moved backwards: previous {previous}, found {}", + event.elapsed_ns + )); + } + } + self.last_event_elapsed_ns = Some(event.elapsed_ns); + + match &event.kind { + WorkloadEventKind::Created { node } => { + require_node(&self.nodes, node)?; + let initial = NodeLifecycle { + next_generation: Some(0), + ..Default::default() + }; + if self.created.insert(node.clone(), initial).is_some() { + return validation_error(format!("node {:?} was created more than once", node)); + } + } + WorkloadEventKind::Ready { work_unit, .. } => { + require_work_unit_node(&self.nodes, work_unit)?; + let Some(node) = self.created.get_mut(&work_unit.node) else { + return validation_error(format!( + "work unit {work_unit:?} became ready before creation" + )); + }; + if node.next_generation.take() != Some(work_unit.continuation_generation) { + return validation_error(format!( + "invalid continuation generation for {work_unit:?}" + )); + } + let state = self.lifecycle.entry(work_unit.clone()).or_default(); + if state.ready { + return validation_error(format!( + "work unit {:?} became ready twice", + work_unit + )); + } + state.ready = true; + } + WorkloadEventKind::Routed { + work_unit, demand, .. + } => { + require_ready(&self.lifecycle, work_unit, "routed")?; + if demand.hdiff_decoder_start && work_unit.phase != WorkUnitPhase::HdiffDecode { + return validation_error(format!( + "non-decode resource demand for {work_unit:?}" + )); + } + self.lifecycle.get_mut(work_unit).unwrap().decoder_start = + Some(demand.hdiff_decoder_start); + } + WorkloadEventKind::Considered { work_unit, .. } => { + require_ready(&self.lifecycle, work_unit, "considered")?; + } + WorkloadEventKind::Admitted { work_unit, .. } => { + require_ready(&self.lifecycle, work_unit, "admitted")?; + let state = self.lifecycle.get_mut(work_unit).unwrap(); + if state.admitted || state.started || state.finished { + return validation_error(format!( + "invalid duplicate/out-of-order admission for {:?}", + work_unit + )); + } + if work_unit.phase == WorkUnitPhase::HdiffDecode && state.decoder_start.is_none() { + return validation_error(format!( + "missing routed decoder demand for {work_unit:?}" + )); + } + let node = self.created.get_mut(&work_unit.node).unwrap(); + let before = node.retention; + if let Err(reason) = node + .retention + .admit(work_unit.phase, state.decoder_start.unwrap_or(false)) + { + return validation_error(format!("{reason} for {work_unit:?}")); + } + if state.decoder_start == Some(true) { + if self.retained_decoders >= self.decoder_slots { + return validation_error(format!( + "decoder retention exceeds recorded capacity for {work_unit:?}" + )); + } + self.retained_decoders += 1; + } + state.admitted = true; + state.retention_before_admission = Some(before); + } + WorkloadEventKind::Started { work_unit } => { + let Some(state) = self.lifecycle.get_mut(work_unit) else { + return validation_error(format!("start before ready for {:?}", work_unit)); + }; + if !state.admitted { + return validation_error(format!("start before admission for {:?}", work_unit)); + } + if state.started || state.finished { + return validation_error(format!( + "duplicate/out-of-order start for {:?}", + work_unit + )); + } + state.started = true; + state.retention_before_admission = None; + } + WorkloadEventKind::Finished { + work_unit, + completion, + hdiff_retention_released, + .. + } => { + let Some(state) = self.lifecycle.get_mut(work_unit) else { + return validation_error(format!("finish before ready for {:?}", work_unit)); + }; + if !state.started { + return validation_error(format!("finish before start for {:?}", work_unit)); + } + if state.finished { + return validation_error(format!("duplicate finish for {:?}", work_unit)); + } + state.finished = true; + let node = self.created.get_mut(&work_unit.node).unwrap(); + if let Err(reason) = + node.retention + .finish(work_unit.phase, *completion, *hdiff_retention_released) + { + return validation_error(format!("{reason} for {work_unit:?}")); + } + if *hdiff_retention_released { + self.retained_decoders -= 1; + } + if matches!( + completion, + WorkloadCompletion::Continued | WorkloadCompletion::ExpandedThen + ) { + node.next_generation = Some( + work_unit + .continuation_generation + .checked_add(1) + .ok_or_else(|| Error::Message { + context: "Workload trace validation error: ", + detail: format!( + "continuation generation overflow for {work_unit:?}" + ), + })?, + ); + } + } + WorkloadEventKind::Decision(_) => {} + WorkloadEventKind::Occupancy { + work_unit, action, .. + } => { + require_work_unit_node(&self.nodes, work_unit)?; + if *action == WorkloadOccupancyAction::Release { + if let Some(state) = self.lifecycle.get_mut(work_unit) { + if !state.started { + // Dispatch can reject an admitted blocking job before + // it starts. The coordinator restores the same WorkUnit + // to the queue, rather than advancing its generation. + let Some(before) = state.retention_before_admission.take() else { + return validation_error(format!( + "release before admission for {work_unit:?}" + )); + }; + let node = self.created.get_mut(&work_unit.node).unwrap(); + node.retention = before; + if state.decoder_start == Some(true) { + self.retained_decoders -= 1; + } + state.admitted = false; + } + } + } + } + WorkloadEventKind::Expanded { + parent, + new_nodes, + new_edges, + } => { + require_work_unit_node(&self.nodes, parent)?; + for node in new_nodes { + require_node(&self.nodes, node)?; + } + for edge in new_edges { + require_node(&self.nodes, &edge.from)?; + require_node(&self.nodes, &edge.to)?; + if !self.edges.contains(&(edge.from.clone(), edge.to.clone())) { + return validation_error(format!( + "expansion event references edge {:?}->{:?} absent from topology", + edge.from, edge.to + )); + } + } + } + } + Ok(()) + } + + pub(super) fn finish(self) -> Result { + if self.record_count == 0 { + return validation_error("trace is empty"); + } + if !self.header_seen { + return validation_error("first record is not a header"); + } + let Some(footer) = self.footer else { + return validation_error("trace is missing a terminal footer"); + }; + + if footer.capture_complete && footer.dropped_event_count == 0 { + for (work_unit, state) in &self.lifecycle { + if (state.admitted || work_unit.phase == WorkUnitPhase::HdiffCommit) + && !state.finished + { + return validation_error(format!( + "work unit {work_unit:?} was admitted but has no finish event" + )); + } + } + for (id, node) in &self.created { + if node.retention.is_held() { + return validation_error(format!("dangling decoder retention for {id:?}")); + } + if node + .next_generation + .is_some_and(|generation| generation > 0) + { + return validation_error(format!("missing promised continuation for {id:?}")); + } + } + } + + let actual_node_count = u64::try_from(self.nodes.len()).unwrap_or(u64::MAX); + let actual_edge_count = u64::try_from(self.edges.len()).unwrap_or(u64::MAX); + if footer.record_count != self.record_count { + return validation_error(format!( + "footer record_count {} does not match {}", + footer.record_count, self.record_count + )); + } + if footer.event_count != self.event_count { + return validation_error(format!( + "footer event_count {} does not match {}", + footer.event_count, self.event_count + )); + } + if footer.node_count != actual_node_count { + return validation_error(format!( + "footer node_count {} does not match {actual_node_count}", + footer.node_count + )); + } + if footer.edge_count != actual_edge_count { + return validation_error(format!( + "footer edge_count {} does not match {actual_edge_count}", + footer.edge_count + )); + } + + let mut disqualifications = Vec::new(); + if !footer.capture_complete { + disqualifications.push("capture_complete=false".to_owned()); + } + if footer.dropped_event_count != 0 { + disqualifications.push(format!( + "dropped_event_count={}", + footer.dropped_event_count + )); + } + if footer.writer_error.is_some() { + disqualifications.push("writer_error present".to_owned()); + } + if !footer.complete_for_replay { + disqualifications.push("complete_for_replay=false".to_owned()); + } + + Ok(ValidationReport { + replay_authority: disqualifications.is_empty(), + disqualifications, + record_count: self.record_count, + event_count: self.event_count, + node_count: actual_node_count, + edge_count: actual_edge_count, + }) + } +} + +pub fn validate_workload_trace(trace: &WorkloadTrace) -> Result { + let mut validator = WorkloadTraceValidator::default(); + for record in &trace.records { + validator.push(record)?; + } + validator.finish() +} + +fn require_node(nodes: &BTreeSet, node: &WorkloadNodeId) -> Result<()> { + if nodes.contains(node) { + Ok(()) + } else { + validation_error(format!("event references missing node {node:?}")) + } +} + +fn require_work_unit_node( + nodes: &BTreeSet, + work_unit: &WorkUnitIdentity, +) -> Result<()> { + require_node(nodes, &work_unit.node) +} + +fn require_ready( + lifecycle: &BTreeMap, + work_unit: &WorkUnitIdentity, + action: &str, +) -> Result<()> { + if lifecycle.get(work_unit).is_some_and(|state| state.ready) { + Ok(()) + } else { + validation_error(format!("{action} before ready for {work_unit:?}")) + } +} + +fn validation_error(detail: impl Into) -> Result { + Err(Error::Message { + context: "Workload trace validation error: ", + detail: detail.into(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::task_pool::workload::{ + MachineProfile, SchedulerConfigProfile, TraceFooter, WorkUnitPhase, WorkloadCaptureMode, + WorkloadDagHint, WorkloadEvent, WorkloadNode, WorkloadRecord, WorkloadTaskOrigin, + WorkloadTimeModel, WorkloadTraceHeader, WorkloadVolumePolicy, WorkloadVolumeStreamingMode, + }; + + fn header(version: u32) -> WorkloadTraceHeader { + WorkloadTraceHeader { + schema_version: version, + run_id: 1, + runner_id: 1, + time_model: WorkloadTimeModel::MonotonicRelativeNanoseconds, + wall_clock_start_unix_ns: None, + source_tree: "tree".to_owned(), + workload_kind: Some("test".to_owned()), + capture_mode: WorkloadCaptureMode::Memory, + scheduler: SchedulerConfigProfile { + cpu_slots: 1, + hdiff_decoder_slots: 2, + blocking_slots: 1, + network_slots: 1, + extract_slots: 1, + reuse_queue_limit: 1, + volume_write_reservation_delay_ns: 15_000_000, + ready_frontier_limit: 256, + priority_lookahead: 64, + continuation_burst: 4, + default_volume_policy: WorkloadVolumePolicy { + read_limit: 1, + write_limit: 1, + metadata_limit: 1, + streaming_pressure_limit: 1, + streaming_mode: WorkloadVolumeStreamingMode::Mixed, + }, + volume_policy_overrides: vec![], + }, + machine: MachineProfile { + os: "test".to_owned(), + architecture: "test".to_owned(), + available_parallelism: 1, + md5_verify_batch_capacity: 1, + }, + } + } + + fn node() -> WorkloadNodeId { + WorkloadNodeId { + run_id: 1, + node_id: 0, + } + } + + fn unit() -> WorkUnitIdentity { + WorkUnitIdentity { + node: node(), + task_kind: "Verify".to_owned(), + phase: WorkUnitPhase::Generic, + attempt: 1, + continuation_generation: 0, + } + } + + fn valid_trace() -> WorkloadTrace { + let node_id = node(); + let unit = unit(); + let payloads = vec![ + WorkloadRecordPayload::Header(header(WORKLOAD_TRACE_SCHEMA_VERSION)), + WorkloadRecordPayload::Node(WorkloadNode { + id: node_id.clone(), + task_kind: "Verify".to_owned(), + dag_hint: WorkloadDagHint { + origin: WorkloadTaskOrigin::Root, + depth: 0, + local_rank: None, + }, + expansion_parent: None, + }), + WorkloadRecordPayload::Event(super::super::WorkloadEvent { + event_sequence: 0, + elapsed_ns: 0, + kind: WorkloadEventKind::Created { node: node_id }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 1, + elapsed_ns: 1, + kind: WorkloadEventKind::Ready { + work_unit: unit.clone(), + dag_hint: WorkloadDagHint { + origin: WorkloadTaskOrigin::Root, + depth: 0, + local_rank: None, + }, + batch_class: None, + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 2, + elapsed_ns: 2, + kind: WorkloadEventKind::Admitted { + work_unit: unit.clone(), + service_estimate: Default::default(), + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 3, + elapsed_ns: 3, + kind: WorkloadEventKind::Started { + work_unit: unit.clone(), + }, + }), + WorkloadRecordPayload::Event(WorkloadEvent { + event_sequence: 4, + elapsed_ns: 4, + kind: WorkloadEventKind::Finished { + work_unit: unit, + hdiff_retention_released: false, + completion: WorkloadCompletion::Succeeded, + queue_wait_ns: 1, + observed_service: super::super::ObservedService::from_estimate( + 1, + Default::default(), + ), + }, + }), + ]; + let mut records: Vec<_> = payloads + .into_iter() + .enumerate() + .map(|(sequence, payload)| WorkloadRecord { + sequence: sequence as u64, + payload, + }) + .collect(); + records.push(WorkloadRecord { + sequence: records.len() as u64, + payload: WorkloadRecordPayload::Footer(TraceFooter { + record_count: records.len() as u64 + 1, + event_count: 5, + node_count: 1, + edge_count: 0, + dropped_event_count: 0, + peak_queued_events: 0, + capture_complete: true, + complete_for_replay: true, + writer_error: None, + }), + }); + WorkloadTrace { records } + } + + #[test] + fn valid_trace_has_replay_authority() { + let report = validate_workload_trace(&valid_trace()).unwrap(); + assert!(report.replay_authority); + } + + #[test] + fn unsupported_version_is_rejected() { + let mut trace = valid_trace(); + if let WorkloadRecordPayload::Header(header) = &mut trace.records[0].payload { + header.schema_version = WORKLOAD_TRACE_SCHEMA_VERSION + 1; + } + assert!(validate_workload_trace(&trace) + .unwrap_err() + .to_string() + .contains("unsupported schema version")); + } + + #[test] + fn invalid_node_reference_is_rejected() { + let mut trace = valid_trace(); + if let WorkloadRecordPayload::Event(event) = &mut trace.records[2].payload { + event.kind = WorkloadEventKind::Created { + node: WorkloadNodeId { + run_id: 1, + node_id: 999, + }, + }; + } + assert!(validate_workload_trace(&trace) + .unwrap_err() + .to_string() + .contains("missing node")); + } + + #[test] + fn invalid_dependency_reference_is_rejected() { + let mut trace = valid_trace(); + trace.records.insert( + 2, + WorkloadRecord { + sequence: 2, + payload: WorkloadRecordPayload::Edge(super::super::WorkloadEdge { + from: WorkloadNodeId { + run_id: 1, + node_id: 999, + }, + to: node(), + }), + }, + ); + for (sequence, record) in trace.records.iter_mut().enumerate() { + record.sequence = sequence as u64; + } + let record_count = trace.records.len() as u64; + if let WorkloadRecordPayload::Footer(footer) = + &mut trace.records.last_mut().unwrap().payload + { + footer.record_count = record_count; + footer.edge_count = 1; + } + assert!(validate_workload_trace(&trace) + .unwrap_err() + .to_string() + .contains("missing dependency node")); + } + + #[test] + fn invalid_lifecycle_is_rejected() { + let mut trace = valid_trace(); + if let WorkloadRecordPayload::Event(event) = &mut trace.records[4].payload { + event.kind = WorkloadEventKind::Started { work_unit: unit() }; + } + assert!(validate_workload_trace(&trace) + .unwrap_err() + .to_string() + .contains("start before admission")); + } + + #[test] + fn missing_footer_is_rejected() { + let mut trace = valid_trace(); + trace.records.pop(); + assert!(validate_workload_trace(&trace) + .unwrap_err() + .to_string() + .contains("missing a terminal footer")); + } + + #[test] + fn non_monotonic_event_time_is_rejected() { + let mut trace = valid_trace(); + if let WorkloadRecordPayload::Event(event) = &mut trace.records[4].payload { + event.elapsed_ns = 0; + } + assert!(validate_workload_trace(&trace) + .unwrap_err() + .to_string() + .contains("monotonic time moved backwards")); + } + + #[test] + fn dropped_events_disqualify_replay_authority() { + let mut trace = valid_trace(); + if let WorkloadRecordPayload::Footer(footer) = + &mut trace.records.last_mut().unwrap().payload + { + footer.dropped_event_count = 2; + footer.complete_for_replay = false; + } + let report = validate_workload_trace(&trace).unwrap(); + assert!(!report.replay_authority); + assert!(report + .disqualifications + .iter() + .any(|reason| reason.contains("dropped_event_count=2"))); + } +} diff --git a/docs/DESIGN_patch_steps.md b/docs/DESIGN_patch_steps.md index 9e60144..d480699 100644 --- a/docs/DESIGN_patch_steps.md +++ b/docs/DESIGN_patch_steps.md @@ -31,7 +31,7 @@ Before mutating the installation: 5. Saves the selected sources to `.griffr/patch/plan.json` before any archive entry changes the installation. 6. Fails early if free space on the destination volume is insufficient. -Apply and resume phases consume `plan.json` directly to avoid re-calculating sources after mutation has begun. The command-level `.griffr/state.json` marker wraps this patch plan and keeps the target version visible if the process stops before final integrity and metadata sync. +Archive updates and recovery use the persisted plan. An extracted manifest uses the same source selector against on-disk payloads and persists its plan before mutation. The command-level `.griffr/state.json` marker wraps this patch plan and keeps the target version visible if the process stops before final integrity and metadata sync. --- @@ -40,14 +40,14 @@ Apply and resume phases consume `plan.json` directly to avoid re-calculating sou Rollbacks are not supported. The patch runs forward: 1. Write `.griffr/patch/plan.json`. -2. Extract only selected patch payloads to private staging. Unused alternate diffs and payloads for already-valid outputs are skipped entirely. +2. Extract only selected patch payloads to private staging. Validate selected HDiff headers and their old/new sizes before direct archive commits. Unused alternate diffs and payloads for already-valid outputs are skipped entirely. 3. Extract ordinary top-level files to private temporary paths, verify them, and commit each file immediately. Deferred markers such as `config.ini` remain private. 4. Prepare VFS folder/links and move deferred markers to `.griffr/patch/deferred`. 5. Remove files marked for deletion unless they remain active patch bases. 6. Apply each patch entry as a DAG node. Local payloads are verified before destination replacement; HDiff outputs are generated to temporary paths, verified, and atomically renamed. Each entry returns an `ArtifactProof`; an already-correct output returns an `Existing` proof without reporting a mutation. 7. Delete a base file after all of its consumer nodes finish. -8. Commit deferred markers. -9. Clean up staging directories and plan files. +8. Apply remaining deletes and clean the payload staging tree. +9. Atomically commit deferred markers and remove the private patch plan and deferred data. --- @@ -66,21 +66,25 @@ PreparePatchApply `-> CleanPatchApply ``` -* A writer depends only on the consumers of the path it replaces; unrelated entries do not share a wave-wide join. +* A writer depends on consumers of its physical or logical aliases; unrelated entries do not share a wave-wide join. * Each entry declares its base and payload reads, output/work writes, and destination mutation path to the scheduler. * Path mutation locks reject equal, ancestor, and descendant conflicts while allowing unrelated files to run together. * If a dependency cycle is detected, the patch fails before step work begins. * A command-local `VerifiedArtifactCache` prevents redundant base checks across entry nodes. -* Dependency waves remain as a derived view for peak-space simulation and the serial recovery fallback; they no longer control normal archive commit runs. +* Dependency waves remain a derived view for peak-space simulation. All three entry points use exact DAG dependencies. --- ## 6. Staging, Work Directory, and Asset Links * **Source-Directed Staging:** Patch archives do not extract the full `vfs_files/` tree. The selected plan determines the exact local and HDiff payload paths needed by the run; all alternatives remain compressed and unfetched when range delivery is used. -* **Work Directory:** When using `--work-dir`, selected payload staging and HDiff temporary files are created outside the install root. Outputs are verified in the work directory, copied local to the install volume, verified again, and committed. +* **Work Directory:** When using `--work-dir`, selected payload staging and HDiff temporary files are created outside the install root. A copy into a destination-local candidate computes its integrity digest before atomic replacement. * **External Asset Root:** `--external-asset-root` moves the patch-managed asset tree to an external target and links it into the install. Details are stored in `.griffr-storage.json`. Verification and repair resolve the same physical target. -* **Codecs:** Patches use `HDIFFSF20` format, applied via `hdiffpatch-rs`. +* **Codecs:** The supported input is HDIFFSF20 with an empty compression identifier or zstd. Unsupported headers are rejected before ordinary archive commits or recovery preparation mutates installed files. Already-verified outputs need no old payload. All three entry points use the same native decoder; the complete output is verified before commit. No legacy decoder fallback is retained. +* **Extracted manifests:** The manifest task loads or builds the plan on the CPU lane. HDiff decode slices run on the compio I/O lane with CPU admission. Local payloads stay available to every consumer until staging cleanup. +* **Decoder ownership:** Each queued decode checkpoint can be consumed once. On reopen the decoder checks the opened base and payload identity, size and modification time, and checks that the private output is the same file at the expected length. An interrupted or failed WorkUnit consumes its in-memory checkpoint. The next recovery run regenerates any entry that has yet to commit from the selected plan. The final decode WorkUnit synchronizes and closes its output before the commit WorkUnit can verify and publish it. +* **Output space:** The first decode asks the scheduler for the full planned output allocation. On Windows the decoder retains an unregistered handle to keep the allocation across slice closes. When the first eligible writer cannot allocate, it returns the filesystem error and drops the private candidate. A successful allocation query permits later slices to reuse those bytes without a second storage reservation; volume write pressure is still acquired. If allocation cannot be confirmed, later growth remains conservatively reserved. The decode CPU lease covers the blocking allocation call, with shared pool capacity sized for CPU and non-CPU blocking tasks plus fallback headroom. Fresh archive plans also check the expected allocation peaks for each dependency wave. +* **Interrupted output cleanup:** Each HDiff output directory carries a synchronized owner marker for its canonical install root. The worker holds an exclusive lock on the marker through decode and commit. Recovery and discard with a saved plan inspect the known destination parents and configured work directory, skip active locks and foreign markers, and remove only the abandoned candidate and its own marker. --- diff --git a/docs/DESIGN_resources.md b/docs/DESIGN_resources.md index 697d913..a91ea36 100644 --- a/docs/DESIGN_resources.md +++ b/docs/DESIGN_resources.md @@ -15,7 +15,7 @@ The `auto` resource policy calls `get_latest_resources` without hard-coded param The `package-only` policy skips `get_latest_resources`. Package archives and `game_files` manage resource files. -`--resources package-only` selects package-only handling on install and update. The hidden legacy `--skip-vfs` alias remains for compatibility; it does not filter resource entries inside packages or `game_files`. +`--resources package-only` selects package-only handling on install and update. This policy does not filter resource entries inside packages or `game_files`. --- @@ -65,7 +65,7 @@ Install and update run a final closure pass against the command-scoped `ContentP Verification supports three scopes: - `all`: core game files and launcher resource baseline -- `core`: core files only; direct alias for `verify --skip-vfs` +- `core`: core files only - `resources`: launcher resource baseline only During repair, launcher metadata is excluded from generic file repair. `game_files` and `package_files` commit after payload closure; `config.ini` commits last. diff --git a/docs/DESIGN_task_pool.md b/docs/DESIGN_task_pool.md index 6ec1aab..729a74e 100644 --- a/docs/DESIGN_task_pool.md +++ b/docs/DESIGN_task_pool.md @@ -108,7 +108,8 @@ struct ResourceRequest { extract: bool, mutation_paths: Vec, storage_reservations: Vec<(VolumeId, Path, Bytes)>, - estimated_bytes: u64, + service_estimate: ServiceEstimate, + priority_cost: u64, reuse_probe: bool, reuse_commit: bool, } @@ -126,7 +127,9 @@ HTTP transfers use a bounded receive/write pipeline. Small body chunks are coale Root nodes enter a bounded ready frontier before the admission queue. The frontier scales with command capacity and remains between 256 and 1,024 routed nodes, so a large manifest starts workers without first resolving every path. Unrouted nodes retain graph-ready state in a lightweight backlog. The backlog samples async I/O, CPU, and blocking classes round-robin, preventing one large root class from hiding otherwise usable capacity. -Requeued nodes and nodes created by dynamic expansion enter the continuation side of the backlog. Continuations route before bulk roots; once routed, the scheduler admits up to three continuations before forcing a bulk admission when bulk work is runnable. This keeps retries and dependency-unblocking work near the critical path without starving a large first scan. +Requeued nodes and nodes created by dynamic expansion enter the continuation side of the backlog. Continuations route before bulk roots; once routed, the scheduler admits up to four continuations before forcing a bulk admission when bulk work is runnable. This keeps retries and dependency-unblocking work near the critical path without starving a large first scan. + +`DagHint` distinguishes root, static dependency, dynamic expansion, and continuation origins. Depth and local rank are descriptive graph facts; they do not override feasibility or the existing queue ordering. Dynamic expansions and continuations use the continuation lane, while roots and static dependencies use the bulk lane. Within one priority class, selection considers: @@ -134,10 +137,14 @@ Within one priority class, selection considers: 2. physical-volume backlog; 3. waiting-writer reservation; 4. metadata rank; -5. estimated byte cost; +5. the priority cost scalar used by the scheduler; 6. original queue order. -General, archive, and VFS network tasks receive weighted opportunities in a `4:2:1` cycle, while unused capacity remains borrowable. +`ServiceEstimate` is measurement data, not a scheduling key in M1. Its CPU field is an abstract relative cost; network/read/write fields are physical bytes; metadata is a coarse operation count. The separate `priority_cost` preserves current ordering semantics without pretending the scalar is always a byte quantity. + +General, archive, VFS, and archive-background network tasks receive weighted opportunities in a `4:2:1:1` cycle, while unused capacity remains borrowable. + +A new HDiff decoder requires a retained decoder slot in the same global admission transaction as its execution resources. A continuation that already owns a slot requests only its execution resources. The global authority registers a denied bundle for wakeup and counts it for FIFO fairness only while the whole bundle fits. Both traced and untraced probes use this decision, and releasing the final retention owner advances the global wakeup generation. --- @@ -157,6 +164,15 @@ Reservations cover download remainders, range-cache files, reuse copies, extract The graph does not encode these capacity constraints as edges. Doing so would make the graph machine-specific and would serialize work unnecessarily. The graph expresses correctness ordering; admission expresses current hardware capacity. +The native HDiff path claims the full output at its first decode admission and +asks the filesystem to allocate it before writing. Windows keeps that +allocation with a separate unregistered handle while slices reopen their +compio handles. The runner-local snapshot still governs scheduling pressure, +and independent runner groups see the allocation through the filesystem. +When a coordinator abandons a batch, it clears its waiter claims. Workers +still own their execution leases until they finish or are dropped, and late +worker events remain isolated to the departed batch. + --- ## 6. Download, Verify, Repair, and Reuse DAGs @@ -218,8 +234,8 @@ Archive repair is deliberately simple in this phase: it uses the archive only wh ### Batch Execution and Peer Reuse - **Batch Execution**: `update` and `verify` build a dependency graph over target and reuse-source physical volumes. Targets that share any volume retain input-order serialization; unrelated targets start as soon as their own predecessors finish instead of waiting for a wave-wide barrier. -- **Shared Runtime**: Concurrent targets use independent schedulers and event channels over one command-scoped compio `Dispatcher` and one correctly sized blocking pool. This prevents `--jobs` from multiplying runtime threads and validates every runner against the real shared capacity. -- **Resource Partitioning**: Network, CPU, blocking, extraction, and reuse lanes are divided by the graph's achievable target parallelism, not the requested `--jobs` value. Per-volume limits remain intact because the outer graph already prevents conflicting targets from running together. +- **Shared Runtime**: Concurrent targets use independent schedulers and event channels over one command-scoped compio `Dispatcher` and one correctly sized blocking pool. This prevents `--jobs` from multiplying runtime threads. +- **Shared Scalar Capacity**: `TaskPoolRunnerGroup` owns one command-wide global capacity authority for CPU, blocking, network, extraction, and reuse-probe admission. Runner-local scalar limits are not statically divided by target count: an idle runner strands no scalar capacity, while aggregate admission can never exceed the command-wide hard limit. Per-volume limits remain runner-local because the outer volume-dependency graph serializes targets that name the same physical volume. Global waiter ordering only protects an older overlapping request once its complete scalar demand is feasible; it does not reserve partial resources for a multi-resource request. - **Reuse Provenance**: Selected same-game targets act as automatic peer sources for later batch targets. Explicit `--reuse-from` enables manifest-driven updates without archive extraction. Automatic peers bypass archives only when target-version matched; otherwise, they serve as VFS/repair sources. - **Candidate Validation**: Reused files are verified against the target manifest's size and MD5 before commit. Cross-game reuse is rejected. - **Hardlink Safety**: Hardlink reuse uses atomic replacement to maintain copy-on-write isolation for Griffr mutations. `--force-copy` forces copy fallback. @@ -397,7 +413,9 @@ Terminal facts are defined only in `TaskOutcome`; they are not mirrored as separ - task-duration p50 and p95; - initial graph activation, initial routing, and first-task-start latency; - ready-frontier limit, peak unrouted backlog, and volume-key cache hit/miss counts; -- per-volume read/write/metadata counts, estimated bytes, and service time. +- per-volume read/write/metadata counts, typed estimated read/write service bytes, and service time. + +When `TaskPoolConfig::scheduler_trace` is enabled, the same run also returns a versioned `SchedulerTrace`. The default remains disabled. Trace events cover node creation/readiness/routing/admission/start/finish, every observed candidate probe and blocker set, selected candidate index/lookahead state, and snapshots of the existing `ResourceState` after acquire/release. Routed events serialize the resource vector materialized at the bounded ready frontier; no trace-heavy state is stored permanently in DAG nodes. The trace can be serialized as versioned JSON, parsed with schema validation, re-aggregated into scheduler metrics, and paired into per-attempt service-estimate/runtime samples. `run_tasks*` remains a convenience wrapper that turns a vector into independent root nodes. Callers that need explicit ordering use `TaskGraphBuilder` and `run_task_graph*` or `TaskPoolRunner::run_graph`. @@ -415,3 +433,13 @@ DAG nodes represent meaningful restartable work: Network chunks, read buffers, and individual hashing blocks are intentionally not nodes. Fine-grained byte processing stays inside one runner to avoid millions of scheduler entries. Patch apply ordering and recovery are documented in [`DESIGN_patch_steps.md`](DESIGN_patch_steps.md). File allocation and Windows storage strategy are documented in [`DESIGN_optimizations.md`](DESIGN_optimizations.md). + +## Durable workload capture and replay + +The optional scheduler trace output records schema-versioned NDJSON with run and node identities, explicit dependency edges, WorkUnit phases and continuation generations, resource demand, admission and completion events, and service quantities with observed, estimated, or unknown provenance. Scalar and batched verification record actual storage bytes read. Path and volume identities are interned into opaque identifiers before records reach the bounded writer queue; payload bytes and original path components are not included. + +Strict capture waits for space in the bounded queue; loss-aware capture records dropped events and cannot provide replay authority if records were lost. Incomplete captures, invalid dependency or lifecycle references, and dangling decoder retention are rejected for replay. A rejected dispatch is not a started attempt: admission and decoder retention are restored before retry. Compact schema 5 retains the validated workload semantics, including decoder slot acquisition and release and observed batch service evidence. + +Replay advances virtual time through readiness, current-policy selection, complete feasibility, atomic admission and observed service durations. Batch selection reserves resource demand as each member is selected. Replay summaries are deterministic for the same compact input and configuration. Replay is structural evidence, not a calibrated prediction of throughput under different capacity, devices, caching, or concurrent runners. It does not implement adaptive capacity or change the production ordering policy. + +Use `--scheduler-trace-out ` on a normal install, update, or verify command to request strict capture. Update and verify capture are restricted to one target and one job. Capture records the resolved Git source tree; subsequent scheduler runs use separate sibling trace files. diff --git a/docs/TESTING.md b/docs/TESTING.md index 6a069a2..e1e35ad 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -33,7 +33,7 @@ Hardlink assertions are physical identity checks rather than content checks: keeps the E2E suite compatible with the repository's Rust 1.97.1 stable CI. `CI` compiles this suite once per platform with the `ci` Cargo profile, archives the -result with cargo-nextest, and fans the archive out across four deterministic hash shards on +result with cargo-nextest, and runs the complete archive once per platform on Ubuntu 24.04 and Windows Server 2025. The test runners do not rebuild the workspace. The equivalent local Windows entry point is: @@ -54,8 +54,9 @@ compiled test payload: 2. Linux and Windows each compile the workspace test graph once with `[profile.ci]` and `cargo nextest archive`. The archive contains test executables, required dynamic libraries, Cargo metadata, and non-test binaries needed by integration tests. -3. Four `hash:m/4` nextest jobs per platform download that archive and run independent - deterministic shards. The real-process CLI E2E is part of this archive. +3. One nextest job per platform downloads the archive and runs every non-ignored test with + nextest's native parallel execution. The real-process CLI E2E is part of this archive. + This avoids redundant runner startup, archive transfers and extraction for short test suites. 4. Platform `cargo check`, release-profile check, all-features check, and `clippy -D warnings` fan out in parallel with the archive builds after the cheap repository-policy/rustfmt gates. They still reuse sccache entries from prior jobs/runs when compiler flags match, without putting @@ -74,9 +75,8 @@ check, clippy, and the non-ignored workspace tests with current Rust nightly. St For branch protection, require the single **`CI / Required`** check rather than every matrix expansion. That aggregate job runs with `always()` and fails unless repository policy, rustfmt, -feature boundaries, both platform build archives, both quality jobs, and both platform test matrices -all finished successfully. This keeps the protected check name stable if shard counts or internal job -names change. +feature boundaries, both platform build archives, both quality jobs, and both platform test jobs +all finished successfully. This keeps the protected check name stable if internal job names or test execution topology change. `.github/workflows/extended-platform.yml` is a separate weekly/manual host-integration lane. Its Ubuntu job installs Wine, clang, and lld, builds a tiny generated Windows PE fixture, launches diff --git a/scripts/README.md b/scripts/README.md index 9677ced..0638c2d 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -66,12 +66,12 @@ floor before production payload I/O. The retained lifecycle adds a package-aware preflight; if a full game cannot fit, use the bounded streaming lane or the local lifecycle harness on a roomier volume instead of maintaining a default self-hosted Actions runner. The classifier has regression coverage in `scripts/tests/test_live_e2e_policy.py`. -`test_ci_workflows.py` additionally locks the intended build-once/shard topology, the aggregate +`test_ci_workflows.py` additionally locks the intended build-once/run-all topology, the aggregate required gate, sccache setup, hosted-first live execution, build-space reclamation, and smoke/disk gates for destructive lanes. Normal CI compiles a cargo-nextest archive once per operating system with Cargo `profile.ci` and -runs four hash-partitioned shards from the archive. Cargo registry/Git source downloads are cached +runs all non-ignored tests once per platform from the archive. Cargo registry/Git source downloads are cached separately; `sccache` caches compiler outputs. Neither is a replacement for the archive, and the workflow does not persist the complete `target/` tree. diff --git a/scripts/check_repo.py b/scripts/check_repo.py index e1d28ff..193ad1f 100755 --- a/scripts/check_repo.py +++ b/scripts/check_repo.py @@ -197,7 +197,6 @@ def _check_crate_boundaries(self, rust_files: list[RustSource]) -> None: "compio", "cyper", "zip", - "hdiffpatch-rs", "windows-sys", "libc", "griffr-hypergryph-api", diff --git a/scripts/tests/test_ci_workflows.py b/scripts/tests/test_ci_workflows.py index d1e361f..2b20768 100644 --- a/scripts/tests/test_ci_workflows.py +++ b/scripts/tests/test_ci_workflows.py @@ -121,14 +121,25 @@ def test_feature_boundaries_wait_for_static_gates(self) -> None: feature = job_block(workflow, "feature-boundaries") self.assertIn("needs: [repository-policy, formatting]", feature) - def test_ci_builds_one_nextest_archive_per_platform_then_shards(self) -> None: + def test_ci_builds_one_nextest_archive_and_runs_all_tests_per_platform(self) -> None: workflow = read(".github/workflows/ci.yml") self.assertEqual(workflow.count("cargo nextest archive --workspace"), 2) - self.assertIn("nextest-linux.tar.zst", workflow) - self.assertIn("nextest-windows.tar.zst", workflow) - self.assertIn('shard: [1, 2, 3, 4]', workflow) - self.assertEqual(workflow.count("--partition \"hash:${{ matrix.shard }}/4\""), 2) - self.assertEqual(workflow.count('--workspace-remap "${{ github.workspace }}"'), 2) + for os_name in ("linux", "windows"): + build = job_block(workflow, f"build-tests-{os_name}") + tests = job_block(workflow, f"test-{os_name}") + self.assertIn(f"nextest-{os_name}.tar.zst", build) + self.assertIn(f"needs: build-tests-{os_name}", tests) + self.assertIn( + f"cargo-nextest nextest run -P ci --archive-file nextest-{os_name}.tar.zst " + '--workspace-remap "${{ github.workspace }}"', + tests, + ) + self.assertNotIn("--partition", tests) + self.assertNotIn("matrix:", tests) + self.assertNotIn("--filterset", tests) + self.assertNotIn("--run-ignored", tests) + self.assertIn("if: always()", tests) + self.assertIn(f"junit-{os_name}-", tests) def test_archive_test_runners_do_not_recompile_workspace(self) -> None: workflow = read(".github/workflows/ci.yml")