qubit-fs-testkit 0.9.2

Reusable provider contract checks for qubit-fs implementations
Documentation
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Stage-aware cancellation of owning asynchronous writes.

use std::future::Future;
use std::future::poll_fn;
use std::task::Poll;

use qubit_fs::error::FsErrorKind;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::write::AsyncWriteAllOperation;
use qubit_fs::write::AsyncWriteAllOperationState;
use qubit_fs::write::AsyncWriterRecovery;
use qubit_fs::write::WriteAbortOutcome;
use qubit_fs::write::WriteFailureState;
use qubit_fs::write::WriterState;

use crate::AsyncFileSystemContractSuite;
use crate::AsyncWriteCancellationStage;
use crate::ContractCheckId;
use crate::ContractCheckOutcome;
use crate::ContractFailure;
use crate::FixtureSupport;
use crate::WriteCancellationProbe;
use crate::internal::probe_disarm_guard::ProbeDisarmGuard;
use crate::internal::verify_condition;

impl AsyncFileSystemContractSuite<'_> {
    /// Executes only the selected stage, including its own probe preparation.
    ///
    /// # Parameters
    ///
    /// - `id`: Write-cancellation check identity selecting the lifecycle stage.
    ///
    /// # Errors
    ///
    /// Returns a failure when the selected stage cannot be prepared or
    /// verified.
    pub(super) async fn check_write_cancellation_item(&mut self, id: ContractCheckId) -> Result<(), ContractFailure> {
        let stage = match id {
            ContractCheckId::WriteCancelOpen => AsyncWriteCancellationStage::Open,
            ContractCheckId::WriteCancelWrite => AsyncWriteCancellationStage::Write,
            ContractCheckId::WriteCancelFlush => AsyncWriteCancellationStage::Flush,
            ContractCheckId::WriteCancelCommit => AsyncWriteCancellationStage::Commit,
            _ => {
                return Err(ContractFailure::message_only("selected entry is not write cancellation").at(id));
            }
        };
        if !self.capable(FileSystemCapability::Write) {
            self.context.record_check(
                id,
                Some(FileSystemCapability::Write),
                ContractCheckOutcome::NotApplicable {
                    reason: "Write capability is unavailable".to_owned(),
                },
            );
            return Ok(());
        }
        let relative = self.context.relative_name(&format!("write-cancel-{stage:?}"));
        let prepared = self
            .fixture
            .prepare_write_cancellation(stage, &relative)
            .await
            .map_err(|error| ContractFailure::with_source("write cancellation preparation failed", error).at(id))?;
        match prepared {
            FixtureSupport::Supported(probe) => self.run_write_cancellation_probe(stage, id, probe).await?,
            FixtureSupport::Unsupported => self.context.record_check(
                id,
                Some(FileSystemCapability::Write),
                ContractCheckOutcome::SkippedOptional {
                    reason: "fixture has no stage acknowledgement probe".to_owned(),
                },
            ),
        }
        Ok(())
    }

    /// Drives a stage-aware probe and preserves its disarm obligation across
    /// every asynchronous suspension point.
    ///
    /// # Parameters
    ///
    /// - `stage`: Lifecycle stage at which the operation is cancelled.
    /// - `id`: Check identity associated with the probe result.
    /// - `probe`: Fixture probe that arms, observes, and disarms the stage.
    ///
    /// # Errors
    ///
    /// Returns a failure when the probe or post-cancellation checks fail.
    async fn run_write_cancellation_probe(
        &mut self,
        stage: AsyncWriteCancellationStage,
        id: ContractCheckId,
        probe: Box<dyn WriteCancellationProbe>,
    ) -> Result<(), ContractFailure> {
        let (path, bytes, options) = probe.case().clone().into_parts();
        self.context.record_created(path.clone());
        // The observation can suspend too: own the disarm obligation before it.
        // Later locals drop first, so execution always stops before disarming.
        let mut guard = ProbeDisarmGuard::new(|| probe.disarm(), &mut self.context.run.cleanup.failures);
        let before = probe.observe_target().await.map_err(|error| {
            ContractFailure::with_source("write cancellation initial observation failed", error).at(id)
        })?;
        let mut operation = self
            .fixture
            .file_system()
            .begin_write_all(path, bytes.clone(), options)
            .map_err(|error| {
                ContractFailure::with_owned_source(
                    "write cancellation request admission failed",
                    crate::ContractAsyncWriteFailure::new(error, None),
                )
                .at(id)
            })?;
        drop(operation.execute());
        verify_condition(
            operation.state() == AsyncWriteAllOperationState::Ready,
            id,
            "unpolled execution changed state",
        )?;
        let mut execution_failure = None;
        let mut execution = Box::pin(operation.execute());
        let reached = poll_fn(|context| match execution.as_mut().poll(context) {
            Poll::Pending => probe.poll_reached(context).map(|result| {
                result.map_err(|error| {
                    ContractFailure::with_source("write cancellation stage acknowledgement failed", error).at(id)
                })
            }),
            Poll::Ready(Ok(_)) => Poll::Ready(Err(ContractFailure::message_only(
                "write completed before requested stage acknowledgement",
            )
            .at(id))),
            Poll::Ready(Err(error)) => {
                execution_failure = Some(error);
                Poll::Ready(Err(ContractFailure::message_only(
                    "write failed before requested stage acknowledgement",
                )
                .at(id)))
            }
        })
        .await;
        drop(execution);
        let disarmed = guard.disarm();
        drop(guard);
        if let Some(error) = execution_failure {
            return Err(ContractFailure::with_owned_source(
                "write failed before requested stage acknowledgement",
                crate::ContractAsyncWriteFailure::new(error, Some(operation)),
            )
            .at(id));
        }
        if let Err(error) = reached {
            return Err(retain_write_operation(error, operation, id));
        }
        if let Err(error) = verify_condition(
            disarmed,
            id,
            "probe disarm failed; original cause is retained in cleanup",
        ) {
            return Err(retain_write_operation(error, operation, id));
        }
        let expected_bytes = match probe.accepted_bytes() {
            Ok(bytes) => bytes,
            Err(error) => {
                return Err(retain_write_operation(
                    ContractFailure::with_source("write cancellation byte observation failed", error).at(id),
                    operation,
                    id,
                ));
            }
        };
        if let Err(error) = verify_condition(
            expected_bytes <= bytes.len() as u64,
            id,
            "observed accepted bytes exceed the request",
        ) {
            return Err(retain_write_operation(error, operation, id));
        }
        if let Err(error) = verify_condition(
            operation.state() == AsyncWriteAllOperationState::Failed(WriteFailureState::Indeterminate),
            id,
            "cancellation state mismatch",
        ) {
            return Err(retain_write_operation(error, operation, id));
        }
        if let Err(error) = verify_condition(
            operation.written_bytes() == expected_bytes,
            id,
            "accepted byte count mismatch",
        ) {
            return Err(retain_write_operation(error, operation, id));
        }
        if let Err(error) = verify_condition(
            operation.has_recovery() == (stage != AsyncWriteCancellationStage::Open),
            id,
            "writer recovery responsibility mismatch",
        ) {
            return Err(retain_write_operation(error, operation, id));
        }
        let failure = match operation.execute().await {
            Err(failure) => failure,
            Ok(_) => {
                return Err(retain_write_operation(
                    ContractFailure::message_only("cancelled write ran twice").at(id),
                    operation,
                    id,
                ));
            }
        };
        if failure.error().kind() != FsErrorKind::InvalidState
            || failure.state() != WriteFailureState::Indeterminate
            || failure.written_bytes() != expected_bytes
        {
            return Err(ContractFailure::with_owned_source(
                "repeated cancelled write lost its recovery facts",
                crate::ContractAsyncWriteFailure::new(failure, Some(operation)),
            )
            .at(id));
        }
        if let Err(error) = verify_condition(
            operation.has_recovery() == (stage != AsyncWriteCancellationStage::Open),
            id,
            "repeated execution lost writer",
        ) {
            return Err(retain_write_operation(error, operation, id));
        }
        self.verify_write_cancellation_recovery(id, probe.as_ref(), operation, before)
            .await
    }

    /// Aborts a retained writer and checks the resulting publication evidence.
    ///
    /// # Parameters
    ///
    /// - `id`: Check identity associated with recovery failures.
    /// - `probe`: Probe that prepared the cancelled writer operation.
    /// - `operation`: Retained whole-file write operation to recover.
    /// - `before`: Optional target bytes observed before the operation.
    ///
    /// # Errors
    ///
    /// Returns a failure when abort or publication-state evidence is invalid.
    async fn verify_write_cancellation_recovery(
        &mut self,
        id: ContractCheckId,
        probe: &dyn WriteCancellationProbe,
        mut operation: AsyncWriteAllOperation,
        before: Option<Vec<u8>>,
    ) -> Result<(), ContractFailure> {
        if let Some(recovery) = operation.take_recovery() {
            let mut writer = match recovery {
                AsyncWriterRecovery::Opened(writer) => *writer,
                AsyncWriterRecovery::Rejected(recovery) => {
                    return Err(ContractFailure::with_owned_source(
                        "cancellation probe retained a rejected provider identity",
                        crate::ContractWriterFailure::new(
                            ContractFailure::message_only("validated writer required by this stage probe"),
                            recovery,
                        ),
                    )
                    .at(id));
                }
            };
            let outcome = match writer.abort_async().await {
                Ok(outcome) => outcome,
                Err(error) => {
                    return Err(ContractFailure::with_owned_source(
                        "write cancellation recovery abort failed",
                        crate::ContractWriterFailure::new(error, writer),
                    )
                    .at(id));
                }
            };
            let expected = match outcome {
                WriteAbortOutcome::NotPublished => WriterState::Aborted,
                WriteAbortOutcome::Published => WriterState::Published,
                WriteAbortOutcome::Indeterminate => WriterState::Indeterminate,
            };
            verify_condition(writer.state() == expected, id, "recovery state mismatch")?;
            if outcome != WriteAbortOutcome::Indeterminate {
                let after = probe.observe_target().await.map_err(|error| {
                    ContractFailure::with_source("write cancellation recovery observation failed", error).at(id)
                })?;
                match outcome {
                    WriteAbortOutcome::NotPublished => {
                        verify_condition(after == before, id, "NotPublished recovery changed the target")?
                    }
                    WriteAbortOutcome::Published => verify_condition(
                        after.is_some(),
                        id,
                        "Published recovery target is not independently observable",
                    )?,
                    WriteAbortOutcome::Indeterminate => unreachable!(),
                }
            }
        }
        self.context
            .record_check(id, Some(FileSystemCapability::Write), ContractCheckOutcome::Passed);
        Ok(())
    }
}

/// Retains a whole-file write operation with the diagnostic that interrupted
/// the cancellation check.
///
/// # Parameters
///
/// - `failure`: Diagnostic produced by cancellation verification.
/// - `operation`: Write operation retained for recovery or inspection.
/// - `id`: Check identity attached to the resulting failure.
///
/// # Returns
///
/// A failure that owns the operation and its original diagnostic.
fn retain_write_operation(
    failure: ContractFailure,
    operation: AsyncWriteAllOperation,
    id: ContractCheckId,
) -> ContractFailure {
    ContractFailure::with_owned_source(
        "write cancellation diagnostic failed; operation retained",
        crate::ContractWriterFailure::new(failure, operation),
    )
    .at(id)
}

#[cfg(test)]
mod tests {
    use super::AsyncFileSystemContractSuite;
    use crate::ContractCheckId;
    use crate::common::AsyncMemoryFixture;
    use crate::common::async_memory_file_system::run_controlled;

    #[test]
    fn test_rejects_a_non_cancellation_check_identity() {
        let fixture = AsyncMemoryFixture::new();
        run_controlled(async {
            let mut suite = AsyncFileSystemContractSuite::new(&fixture);
            let error = suite
                .check_write_cancellation_item(ContractCheckId::ReadBasic)
                .await
                .expect_err("a read check cannot dispatch as write cancellation");
            assert_eq!(error.check(), Some(ContractCheckId::ReadBasic));
            assert!(error.message().contains("not write cancellation"));
        });
    }

    #[test]
    fn test_records_write_cancellation_as_inapplicable_without_write_capability() {
        let fixture = AsyncMemoryFixture::without_core_capabilities();
        run_controlled(async {
            let mut suite = AsyncFileSystemContractSuite::new(&fixture);
            suite
                .context
                .prepare_phase(ContractCheckId::WriteCancelOpen.contract(), true);
            suite
                .check_write_cancellation_item(ContractCheckId::WriteCancelOpen)
                .await
                .expect("missing write capability makes the probe inapplicable");
            let check = suite
                .report()
                .checks()
                .iter()
                .find(|check| check.id() == ContractCheckId::WriteCancelOpen)
                .expect("inapplicable check must be recorded");
            assert!(matches!(
                check.outcome(),
                crate::ContractCheckOutcome::NotApplicable { .. }
            ));
        });
        assert!(fixture.is_empty(), "inapplicable probe must not create resources");
    }
}