qubit-fs-testkit 0.9.2

Reusable provider contract checks for qubit-fs implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Independent temporary file publication and lifecycle evidence.

use qubit_fs::error::FsErrorKind;
use qubit_fs::error::FsOperation;
use qubit_fs::error::OpenFailureStage;
use qubit_fs::metadata::AchievedAtomicity;
use qubit_fs::metadata::AtomicityRequirement;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::path::Path;
use qubit_fs::path::PathSemantics;
use qubit_fs::temp::PersistFailureState;
use qubit_fs::temp::PersistOptions;
use qubit_fs::temp::PersistOutcome;
use qubit_fs::temp::TempOptions;
use qubit_fs::temp::TempResourceState;

use crate::ContractCheckId;
use crate::ContractFailure;
use crate::ContractTempFailure;
use crate::FileSystemContractSuite;
use crate::FixtureSupport;
use crate::internal::verify_condition;

impl FileSystemContractSuite<'_> {
    /// Verifies temporary-file creation, cleanup, retention, and publication.
    ///
    /// The selected check determines which lifecycle transitions are exercised;
    /// capability snapshots gate unsupported operations, while fixture hooks
    /// independently observe whether each source and publication target exists.
    ///
    /// # Parameters
    ///
    /// - `id`: Registered temporary-file lifecycle check to execute.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the selected lifecycle evidence has been recorded.
    ///
    /// # Errors
    ///
    /// Returns a contract failure when creation, cleanup, persistence, or
    /// independent observation violates the selected lifecycle contract.
    pub(super) fn execute_temp_file(&mut self, id: ContractCheckId) -> Result<(), ContractFailure> {
        let filesystem = self.fixture.file_system();
        let mut options = TempOptions::default();
        let basic = id == ContractCheckId::TempFile;
        if basic && self.capable(FileSystemCapability::TempFile) {
            let incompatible = match self.context.properties().info().path_semantics() {
                PathSemantics::Hierarchical => Path::parse_literal("/temp-invalid-parent"),
                _ => Path::parse("/temp-invalid-parent"),
            }
            .expect("invalid-parent probe path is a valid constant");
            let error =
                match filesystem.create_temp_file(TempOptions::default().with_parent(Some(incompatible.clone()))) {
                    Err(error) => error,
                    Ok(resource) => {
                        return Err(ContractFailure::with_owned_source(
                            "invalid temporary parent succeeded",
                            ContractTempFailure::new(
                                ContractFailure::message_only("invalid temporary parent was accepted"),
                                resource,
                            ),
                        )
                        .at(id));
                    }
                };
            if error.recovery().is_some()
                || error.stage() != OpenFailureStage::Preflight
                || error.error().kind() != FsErrorKind::InvalidPath
                || error.error().operation() != FsOperation::CreateTemp
                || error.error().path() != Some(&incompatible)
            {
                return Err(ContractFailure::with_owned_source("temporary parent validation differs", error).at(id));
            }
            if self.capable(FileSystemCapability::CreateDirectory) {
                let relative = self.context.relative_name("temp-file-parent");
                let parent = self.fixture.seed_empty_directory(&relative).map_err(|error| {
                    ContractFailure::with_source("temporary parent preparation failed", error).at(id)
                })?;
                let FixtureSupport::Supported(parent) = parent else {
                    return Err(ContractFailure::message_only(
                        "temporary parent needs independent fixture preparation",
                    )
                    .at(id));
                };
                self.context.record_created(parent.clone());
                options = options.with_parent(Some(parent));
            }
            options = options
                .with_prefix("contract-file-".to_owned())
                .with_suffix(".tmp".to_owned());
        }
        let requested_parent = options.parent().cloned();
        let mut temporary = match filesystem.create_temp_file(options) {
            Ok(resource) => resource,
            Err(error) if !self.capable(FileSystemCapability::TempFile) => {
                if error.recovery().is_some()
                    || error.stage() != OpenFailureStage::Preflight
                    || error.error().kind() != FsErrorKind::UnsupportedCapability
                    || error.error().operation() != FsOperation::CreateTemp
                    || error.error().required_capability() != Some(FileSystemCapability::TempFile)
                {
                    return Err(
                        ContractFailure::with_owned_source("temporary creation rejection differs", error).at(id),
                    );
                }
                return Ok(());
            }
            Err(error) => {
                return Err(ContractFailure::with_owned_source("temporary resource creation failed", error).at(id));
            }
        };
        let source = temporary.path().clone();
        self.context.record_created(source.clone());
        verify_condition(
            self.capable(FileSystemCapability::TempFile),
            id,
            "unavailable temporary creation succeeded",
        )?;
        if basic {
            if let Some(parent) = requested_parent {
                verify_condition(
                    source
                        .as_str()
                        .starts_with(&format!("{}/", parent.as_str().trim_end_matches('/'))),
                    id,
                    "temporary resource ignored requested parent",
                )?;
            }
            verify_condition(
                source
                    .file_name()
                    .is_some_and(|name| name.starts_with("contract-file-") && name.ends_with(".tmp")),
                id,
                "temp/file: requested prefix or suffix was ignored",
            )?;
            if let Err(error) = temporary.cleanup() {
                return Err(ContractFailure::with_owned_source(
                    "temporary cleanup failed",
                    ContractTempFailure::new(error, temporary),
                )
                .at(id));
            }
            let after = self
                .fixture
                .exists_out_of_band(&source)
                .map_err(|error| ContractFailure::with_source("temporary cleanup observation failed", error).at(id))?;
            verify_condition(
                matches!(after, FixtureSupport::Supported(false)),
                id,
                "temp/file: cleanup retained source",
            )?;
            temporary = filesystem.create_temp_file(TempOptions::default()).map_err(|error| {
                ContractFailure::with_owned_source("temporary keep preparation failed", error).at(id)
            })?;
            self.context.record_created(temporary.path().clone());
        }
        let mut content_supported = self.prepare_temp_file_content(temporary.path(), id)?;
        if id != ContractCheckId::TempAtomic {
            let kept_source = temporary.path().clone();
            let kept = match temporary.keep() {
                Ok(outcome) => outcome,
                Err(error) => {
                    return Err(ContractFailure::with_owned_source(
                        "temporary keep failed",
                        ContractTempFailure::new(error, temporary),
                    )
                    .at(id));
                }
            };
            self.context.record_created(kept.target().clone());
            verify_condition(
                temporary.state() == TempResourceState::Kept && kept.target() != &kept_source,
                id,
                "temporary keep state or publication identity differs",
            )?;
            for (path, expected) in [(&kept_source, false), (kept.target(), true)] {
                let observed = self
                    .fixture
                    .exists_out_of_band(path)
                    .map_err(|error| ContractFailure::with_source("temporary keep observation failed", error).at(id))?;
                verify_condition(
                    matches!(observed, FixtureSupport::Supported(actual) if actual == expected),
                    id,
                    "temporary keep publication differs",
                )?;
            }
            if content_supported {
                content_supported = self.verify_temp_file_content(kept.target(), id)?;
            }
            if id == ContractCheckId::TempRepeatedLifecycle {
                let failure = match temporary.keep() {
                    Err(failure) => failure,
                    Ok(_) => {
                        return Err(
                            ContractFailure::message_only("temp/repeated-lifecycle: second keep succeeded").at(id),
                        );
                    }
                };
                if failure.error().kind() != FsErrorKind::InvalidState
                    || failure.state() != PersistFailureState::PublishedSourceReleased
                    || failure.publication_target() != Some(kept.target())
                {
                    return Err(ContractFailure::with_owned_source(
                        "temp/repeated-lifecycle: publication facts lost",
                        ContractTempFailure::new(failure, temporary),
                    )
                    .at(id));
                }
                let error = match temporary.cleanup() {
                    Err(error) => error,
                    Ok(_) => {
                        return Err(
                            ContractFailure::message_only("temp/repeated-lifecycle: kept target reclaimed").at(id),
                        );
                    }
                };
                if error.kind() != FsErrorKind::InvalidState {
                    return Err(ContractFailure::with_owned_source(
                        "repeated cleanup rejection differs",
                        ContractTempFailure::new(error, temporary),
                    )
                    .at(id));
                }
                verify_condition(temporary.state() == TempResourceState::Kept, id, "kept state changed")?;
                let after = self.fixture.exists_out_of_band(kept.target()).map_err(|error| {
                    ContractFailure::with_source("repeated keep publication observation failed", error).at(id)
                })?;
                verify_condition(
                    matches!(after, FixtureSupport::Supported(true)),
                    id,
                    "kept publication disappeared",
                )?;
                if content_supported {
                    self.verify_temp_file_content(kept.target(), id)?;
                }
                let mut cleaned = filesystem.create_temp_file(TempOptions::default()).map_err(|error| {
                    ContractFailure::with_owned_source("repeated cleanup preparation failed", error).at(id)
                })?;
                let cleaned_source = cleaned.path().clone();
                self.context.record_created(cleaned_source.clone());
                if let Err(error) = cleaned.cleanup() {
                    return Err(ContractFailure::with_owned_source(
                        "initial cleanup failed",
                        ContractTempFailure::new(error, cleaned),
                    )
                    .at(id));
                }
                let after = self.fixture.exists_out_of_band(&cleaned_source).map_err(|error| {
                    ContractFailure::with_source("repeated cleanup observation failed", error).at(id)
                })?;
                verify_condition(
                    matches!(after, FixtureSupport::Supported(false)),
                    id,
                    "cleanup retained temporary source",
                )?;
                let error = match cleaned.cleanup() {
                    Err(error) => error,
                    Ok(_) => {
                        return Err(
                            ContractFailure::message_only("temp/repeated-lifecycle: cleaned resource reused").at(id),
                        );
                    }
                };
                if error.kind() != FsErrorKind::InvalidState || cleaned.state() != TempResourceState::Cleaned {
                    return Err(ContractFailure::with_owned_source(
                        "repeated cleanup state differs",
                        ContractTempFailure::new(error, cleaned),
                    )
                    .at(id));
                }
                let mut first = filesystem.create_temp_file(TempOptions::default()).map_err(|error| {
                    ContractFailure::with_owned_source("interleaved temporary preparation failed", error).at(id)
                })?;
                self.context.record_created(first.path().clone());
                let mut second = filesystem.create_temp_file(TempOptions::default()).map_err(|error| {
                    ContractFailure::with_owned_source("interleaved temporary preparation failed", error).at(id)
                })?;
                let second_path = second.path().clone();
                self.context.record_created(second_path.clone());
                let content_supported = self.prepare_temp_file_content(&second_path, id)?;
                if let Err(error) = first.cleanup() {
                    return Err(ContractFailure::with_owned_source(
                        "interleaved temporary cleanup failed",
                        ContractTempFailure::new(error, first),
                    )
                    .at(id));
                }
                let mut third = filesystem.create_temp_file(TempOptions::default()).map_err(|error| {
                    ContractFailure::with_owned_source("interleaved temporary preparation failed", error).at(id)
                })?;
                self.context.record_created(third.path().clone());
                verify_condition(
                    third.path() != &second_path,
                    id,
                    "temp/repeated-lifecycle: live file path was reused",
                )?;
                if content_supported {
                    self.verify_temp_file_content(&second_path, id)?;
                }
                if let Err(error) = second.cleanup() {
                    return Err(ContractFailure::with_owned_source(
                        "interleaved temporary cleanup failed",
                        ContractTempFailure::new(error, second),
                    )
                    .at(id));
                }
                if let Err(error) = third.cleanup() {
                    return Err(ContractFailure::with_owned_source(
                        "interleaved temporary cleanup failed",
                        ContractTempFailure::new(error, third),
                    )
                    .at(id));
                }
                return Ok(());
            }
            temporary = filesystem.create_temp_file(TempOptions::default()).map_err(|error| {
                ContractFailure::with_owned_source("temporary persistence preparation failed", error).at(id)
            })?;
            self.context.record_created(temporary.path().clone());
            content_supported = self.prepare_temp_file_content(temporary.path(), id)?;
        }
        let source = temporary.path().clone();
        let target = self
            .fixture
            .path(&self.context.relative_name("persisted-file"))
            .map_err(|error| {
                ContractFailure::with_source("temporary publication target preparation failed", error).at(id)
            })?;
        self.context.record_created(target.clone());
        let atomic = id == ContractCheckId::TempAtomic;
        let options = PersistOptions::default().with_atomicity(if atomic {
            AtomicityRequirement::Required
        } else {
            AtomicityRequirement::Preferred
        });
        let publication = temporary.persist(&target, options);
        if atomic && !self.capable(FileSystemCapability::AtomicTempPersist) {
            let failure = match publication {
                Err(failure) => failure,
                Ok(_) => {
                    return Err(ContractFailure::message_only("unsupported atomic persistence succeeded").at(id));
                }
            };
            let error = failure.error();
            if error.kind() != FsErrorKind::RequirementNotMet
                || error.operation() != FsOperation::PersistTemp
                || error.path() != Some(&source)
                || error.target() != Some(&target)
                || error.required_capability() != Some(FileSystemCapability::AtomicTempPersist)
                || error.provider() != Some(self.context.properties().info().provider_id())
                || failure.state() != PersistFailureState::NotPublished
            {
                return Err(ContractFailure::with_owned_source(
                    "atomic persistence rejection differs",
                    ContractTempFailure::new(failure, temporary),
                )
                .at(id));
            }
            let before = self.fixture.exists_out_of_band(&source).map_err(|error| {
                ContractFailure::with_source("atomic rejection source observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(before, FixtureSupport::Supported(true)),
                id,
                "atomic preflight removed source",
            )?;
            verify_condition(
                temporary.state() == TempResourceState::Owned,
                id,
                "atomic preflight changed resource ownership",
            )?;
            let target_after = self.fixture.exists_out_of_band(&target).map_err(|error| {
                ContractFailure::with_source("atomic rejection target observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(target_after, FixtureSupport::Supported(false)),
                id,
                "atomic preflight published a target",
            )?;
            if let Err(error) = temporary.cleanup() {
                return Err(ContractFailure::with_owned_source(
                    "atomic rejection cleanup failed",
                    ContractTempFailure::new(error, temporary),
                )
                .at(id));
            }
            let after = self.fixture.exists_out_of_band(&source).map_err(|error| {
                ContractFailure::with_source("atomic rejection cleanup observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(after, FixtureSupport::Supported(false)),
                id,
                "atomic rejection cleanup retained source",
            )?;
            return Ok(());
        }
        let outcome = match publication {
            Ok(outcome) => outcome,
            Err(error) => {
                return Err(ContractFailure::with_owned_source(
                    "temp/atomic: persistence failed",
                    ContractTempFailure::new(error, temporary),
                )
                .at(id));
            }
        };
        self.verify_temp_publication(&outcome, &source, &target, atomic, content_supported, id)
    }

    /// Checks the published target identity, achieved atomicity, and externally
    /// observed source and target states after temporary-file persistence.
    ///
    /// # Parameters
    ///
    /// - `outcome`: Provider-reported persistence result.
    /// - `source`: Temporary source path expected to be released.
    /// - `target`: Destination path expected in the result and observation.
    /// - `atomic`: Whether this check requires atomic publication.
    /// - `content_supported`: Whether fixture hooks confirmed content evidence.
    /// - `id`: Registered temporary persistence check receiving failures.
    ///
    /// # Returns
    ///
    /// `Ok(())` when publication metadata and independent path observations
    /// satisfy the selected check.
    ///
    /// # Errors
    ///
    /// Returns a contract failure when publication metadata, path state, or
    /// supported content evidence differs from expectations.
    fn verify_temp_publication(
        &mut self,
        outcome: &PersistOutcome,
        source: &Path,
        target: &Path,
        atomic: bool,
        content_supported: bool,
        id: ContractCheckId,
    ) -> Result<(), ContractFailure> {
        verify_condition(outcome.target() == target, id, "temporary persist target mismatch")?;
        if atomic {
            verify_condition(
                outcome.atomicity() == AchievedAtomicity::Atomic,
                id,
                "temp/atomic: non-atomic publication",
            )?;
        }
        for (path, expected) in [(source, false), (target, true)] {
            let observed = self
                .fixture
                .exists_out_of_band(path)
                .map_err(|error| ContractFailure::with_source("temporary persist observation failed", error).at(id))?;
            verify_condition(
                matches!(observed, FixtureSupport::Supported(actual) if actual == expected),
                id,
                "temporary persistence source release or target publication differs",
            )?;
        }
        if content_supported {
            self.verify_temp_file_content(outcome.target(), id)?;
        }
        Ok(())
    }

    /// Seeds and independently confirms content in a temporary file.
    ///
    /// # Parameters
    ///
    /// - `path`: Temporary file to seed and read back.
    /// - `id`: Registered check receiving setup or observation failures.
    ///
    /// # Returns
    ///
    /// `true` when fixture hooks confirm the seeded bytes; `false` when a
    /// required hook is unsupported.
    ///
    /// # Errors
    ///
    /// Returns a contract failure when seeding or observation fails, or the
    /// observed bytes differ.
    fn prepare_temp_file_content(&mut self, path: &Path, id: ContractCheckId) -> Result<bool, ContractFailure> {
        const CONTENT: &[u8] = b"temp-data";
        match self
            .fixture
            .write_file_out_of_band(path, CONTENT)
            .map_err(|error| ContractFailure::with_source("temporary file content preparation failed", error).at(id))?
        {
            FixtureSupport::Unsupported => {
                self.record_temp_file_content_unverified(id, "fixture write_file_out_of_band hook is unsupported");
                Ok(false)
            }
            FixtureSupport::Supported(()) => {
                match self.fixture.read_file(path).map_err(|error| {
                    ContractFailure::with_source("temporary file content setup observation failed", error).at(id)
                })? {
                    FixtureSupport::Supported(actual) => {
                        verify_condition(actual == CONTENT, id, "temporary file setup bytes differ")?;
                        Ok(true)
                    }
                    FixtureSupport::Unsupported => {
                        self.record_temp_file_content_unverified(id, "fixture read_file hook is unsupported");
                        Ok(false)
                    }
                }
            }
        }
    }

    /// Verifies that publication preserved the independently seeded bytes.
    ///
    /// # Parameters
    ///
    /// - `path`: Published temporary file to inspect.
    /// - `id`: Registered check receiving observation failures.
    ///
    /// # Returns
    ///
    /// `true` when the expected bytes are confirmed; `false` when the fixture
    /// read hook is unsupported.
    ///
    /// # Errors
    ///
    /// Returns a contract failure when observation fails or published bytes
    /// differ from the seed.
    fn verify_temp_file_content(&mut self, path: &Path, id: ContractCheckId) -> Result<bool, ContractFailure> {
        const CONTENT: &[u8] = b"temp-data";
        match self
            .fixture
            .read_file(path)
            .map_err(|error| ContractFailure::with_source("temporary file content observation failed", error).at(id))?
        {
            FixtureSupport::Supported(actual) => {
                verify_condition(actual == CONTENT, id, "temporary file publication changed contents")?;
                Ok(true)
            }
            FixtureSupport::Unsupported => {
                self.record_temp_file_content_unverified(id, "fixture read_file hook is unsupported after publication");
                Ok(false)
            }
        }
    }

    /// Records that temporary-file content could not be independently verified.
    ///
    /// # Parameters
    ///
    /// - `id`: Registered temporary-file check whose evidence is incomplete.
    /// - `reason`: Fixture limitation explaining why contents were not
    ///   verified.
    fn record_temp_file_content_unverified(&mut self, id: ContractCheckId, reason: &str) {
        self.context.record_check(
            id,
            crate::internal::check_catalog::specification(id).capability,
            crate::ContractCheckOutcome::Unverified {
                reason: reason.to_owned(),
            },
        );
    }
}