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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Executes individual read checks with independent typed preparation.

use qubit_fs::error::FsErrorKind;
use qubit_fs::error::FsOperation;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::metadata::FileSystemLimit;
use qubit_fs::metadata::ResourceVersion;
use qubit_fs::path::Path;
use qubit_fs::read::ReadOptions;

use crate::AsyncFileSystemContractSuite;
use crate::ContractCheckId;
use crate::ContractCheckOutcome;
use crate::ContractFailure;
use crate::FileSystemContract;
use crate::FixturePreparation;
use crate::FixtureSupport;
use crate::ReadScenario;
use crate::internal::check_catalog;
use crate::internal::limit_probe_plan::MAX_PROBE_BYTES;
use crate::internal::limit_probe_plan::finite_probe;
use crate::internal::read_expectations;
use crate::internal::verify_condition;
use crate::internal::verify_fs_error;

impl AsyncFileSystemContractSuite<'_> {
    /// Executes each registered read entry with its own request and setup.
    ///
    /// # Returns
    ///
    /// `Ok(())` after every registered read check completes.
    ///
    /// # Errors
    ///
    /// Returns the first failure raised while executing a read check.
    pub(super) async fn check_read(&mut self) -> Result<(), ContractFailure> {
        self.context.begin("read");
        for spec in check_catalog::for_contract(FileSystemContract::Read, true) {
            self.check_read_item(spec.id).await?;
        }
        Ok(())
    }

    /// Executes exactly one read check; it never completes another check.
    ///
    /// # Parameters
    ///
    /// * `id` - Registered read check to execute.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the selected check's outcome is recorded.
    ///
    /// # Errors
    ///
    /// Returns a failure raised while preparing or verifying the selected
    /// check.
    pub(super) async fn check_read_item(&mut self, id: ContractCheckId) -> Result<(), ContractFailure> {
        self.context.begin_check(id);
        if matches!(
            id,
            ContractCheckId::RandomAccessBasic
                | ContractCheckId::RandomAccessBounds
                | ContractCheckId::RandomAccessRangeLimit
                | ContractCheckId::RandomAccessIdentity
                | ContractCheckId::RandomAccessCancel
        ) {
            let outcome = self.execute_random_access(id).await?;
            self.context
                .record_check(id, Some(qubit_fs::metadata::FileSystemCapability::Read), outcome);
            return Ok(());
        }
        let spec = check_catalog::specification(id);
        let scenario = spec.read_scenario.expect("dispatch selected a non-read check");
        let outcome = self.execute_read_scenario(id, scenario).await?;
        self.context.record_check(id, spec.capability, outcome);
        Ok(())
    }

    /// Prepares, observes, and verifies one read scenario independently.
    ///
    /// Observation and request failures remain attached to their actual entry.
    ///
    /// # Parameters
    ///
    /// - `id`: Read check identity that receives the result and any failure.
    /// - `scenario`: Read behavior to prepare and verify.
    ///
    /// # Returns
    ///
    /// The outcome recorded for the read scenario.
    ///
    /// # Errors
    ///
    /// Returns a failure when preparation or filesystem observation fails.
    async fn execute_read_scenario(
        &mut self,
        id: ContractCheckId,
        scenario: ReadScenario,
    ) -> Result<ContractCheckOutcome, ContractFailure> {
        let spec = check_catalog::specification(id);
        let capability = spec.capability.expect("read check has no capability");
        let limit = self.context.properties().limits().max_read_range_bytes();
        let name = if scenario == ReadScenario::ChecksumCorruption {
            "checksum-failure".to_owned()
        } else {
            id.as_str().replace('/', "-")
        };
        let relative = self.context.relative_name(&name);
        let read_available = self.capable(FileSystemCapability::Read);
        if !read_available && id != ContractCheckId::ReadBasic {
            return Ok(ContractCheckOutcome::NotApplicable {
                reason: "Read capability is unavailable".to_owned(),
            });
        }
        if !read_available || !self.capable(capability) {
            if spec.optional {
                return Ok(ContractCheckOutcome::NotApplicable {
                    reason: format!("{capability:?} capability is unavailable"),
                });
            }
            let path = self
                .fixture
                .path(&relative)
                .map_err(|error| ContractFailure::with_source("read request path preparation failed", error).at(id))?;
            let options =
                read_expectations::options(scenario, limit, ResourceVersion::new("missing-capability-version"));
            let error = match self.fixture.file_system().open_reader(&path, options).await {
                Err(error) => error,
                Ok(_) => {
                    return Err(
                        ContractFailure::message_only(format!("{id}: unavailable read request succeeded")).at(id),
                    );
                }
            };
            verify_fs_error(
                error,
                if read_available {
                    FsErrorKind::RequirementNotMet
                } else {
                    FsErrorKind::UnsupportedCapability
                },
                FsOperation::OpenReader,
                &path,
                self.context.properties().info().provider_id(),
                Some(capability),
                id,
            )?;
            return Ok(ContractCheckOutcome::RejectedAsExpected);
        }
        let boundary = finite_probe(limit, MAX_PROBE_BYTES);
        if scenario == ReadScenario::RangeLimit && boundary.is_none() {
            return Ok(ContractCheckOutcome::SkippedOptional {
                reason: "range limit is unknown, unbounded, inapplicable, or exceeds the bounded probe budget"
                    .to_owned(),
            });
        }
        let prepared = self
            .fixture
            .prepare_read(scenario, &relative, read_expectations::CONTENT)
            .await
            .map_err(|error| ContractFailure::with_source("read scenario preparation failed", error).at(id))?;
        let path = match prepared {
            FixturePreparation::Ready(path) => path,
            FixturePreparation::NotApplicable { reason } => {
                return Ok(ContractCheckOutcome::Unverified {
                    reason: format!("declared read capability requires scenario evidence: {reason}"),
                });
            }
            FixturePreparation::Unavailable { reason } => {
                return Ok(if spec.optional {
                    ContractCheckOutcome::SkippedOptional { reason }
                } else {
                    ContractCheckOutcome::Unverified { reason }
                });
            }
        };
        self.context.record_created(path.clone());
        let mut version = ResourceVersion::new("version-unused-by-request");
        if read_expectations::uses_version(scenario) {
            let current = self.fixture.resource_version(&path).await.map_err(|error| {
                ContractFailure::with_source("read current version observation failed", error).at(id)
            })?;
            let FixtureSupport::Supported(current) = current else {
                return Ok(ContractCheckOutcome::Unverified {
                    reason: "fixture current version unavailable".to_owned(),
                });
            };
            version = current.clone();
            if read_expectations::uses_stale(scenario) {
                let stale = self.fixture.stale_resource_version(&path).await.map_err(|error| {
                    ContractFailure::with_source("read stale version observation failed", error).at(id)
                })?;
                let FixtureSupport::Supported(stale) = stale else {
                    return Ok(ContractCheckOutcome::Unverified {
                        reason: "fixture stale version unavailable".to_owned(),
                    });
                };
                verify_condition(stale != current, id, "fixture stale version equals current version")?;
                version = stale;
            }
        };
        if scenario == ReadScenario::RangeLimit {
            let (maximum, over) =
                boundary.ok_or_else(|| ContractFailure::message_only("bounded range check has no boundary").at(id))?;
            let actual = self
                .fixture
                .file_system()
                .read_all(
                    &path,
                    ReadOptions::default().with_length(Some(maximum)),
                    maximum as usize,
                )
                .await
                .map_err(|error| {
                    ContractFailure::with_source("read at declared range boundary failed", error).at(id)
                })?;
            let expected = &read_expectations::CONTENT[..(maximum as usize).min(read_expectations::CONTENT.len())];
            verify_condition(
                actual == expected,
                id,
                "range boundary bytes differ from seeded content",
            )?;
            let error = match self
                .fixture
                .file_system()
                .open_reader(&path, ReadOptions::default().with_length(Some(over)))
                .await
            {
                Err(error) => error,
                Ok(_) => {
                    return Err(ContractFailure::message_only("read range limit was ignored").at(id));
                }
            };
            verify_fs_error(
                error,
                FsErrorKind::ResourceLimitExceeded,
                FsOperation::OpenReader,
                &path,
                self.context.properties().info().provider_id(),
                None,
                id,
            )?;
            return Ok(ContractCheckOutcome::Passed);
        }
        let options = read_expectations::options(scenario, limit, version);
        let result = self.fixture.file_system().read_all(&path, options, 64).await;
        if let Some(kind) = read_expectations::rejection(scenario) {
            let error = match result {
                Err(error) => error,
                Ok(_) => {
                    return Err(ContractFailure::message_only(format!(
                        "{id}: read accepted a request requiring rejection"
                    ))
                    .at(id));
                }
            };
            let operation = if kind == FsErrorKind::DataCorruption && error.operation() == FsOperation::Read {
                FsOperation::Read
            } else {
                FsOperation::OpenReader
            };
            verify_fs_error(
                error,
                kind,
                operation,
                &path,
                self.context.properties().info().provider_id(),
                None,
                id,
            )?;
            return Ok(ContractCheckOutcome::RejectedAsExpected);
        } else {
            let actual = result
                .map_err(|error| ContractFailure::with_source(format!("{id}: read request failed"), error).at(id))?;
            verify_condition(
                actual == read_expectations::bytes(scenario, limit),
                id,
                "read bytes differ from independent seed",
            )?;
        }
        self.check_read_result(id, scenario, limit, &path).await?;
        Ok(ContractCheckOutcome::Passed)
    }

    /// Verifies additional range and caller-buffer-limit read requirements.
    ///
    /// # Parameters
    ///
    /// - `id`: Check identity associated with failures.
    /// - `scenario`: Read scenario whose extra guarantees are checked.
    /// - `limit`: Provider's declared maximum read-range length.
    /// - `path`: Prepared resource path to read.
    ///
    /// # Errors
    ///
    /// Returns a failure when range or buffer-limit behavior violates the
    /// check.
    async fn check_read_result(
        &self,
        id: ContractCheckId,
        scenario: ReadScenario,
        limit: FileSystemLimit,
        path: &Path,
    ) -> Result<(), ContractFailure> {
        if scenario == ReadScenario::Range {
            let (offset, length, accepted_budget, rejected_budget) = read_expectations::window_budget_plan(limit);
            let window_options = ReadOptions::default()
                .with_offset(Some(offset))
                .with_length(Some(length));
            let actual = self
                .fixture
                .file_system()
                .read_all(path, window_options.clone(), accepted_budget)
                .await
                .map_err(|error| ContractFailure::with_source("range caller budget read failed", error).at(id))?;
            let expected = &read_expectations::CONTENT[offset as usize..(offset + length) as usize];
            verify_condition(actual == expected, id, "range caller budget returned different bytes")?;
            if let Some(rejected_budget) = rejected_budget {
                let error = match self
                    .fixture
                    .file_system()
                    .read_all(path, window_options, rejected_budget)
                    .await
                {
                    Err(error) => error,
                    Ok(_) => {
                        return Err(ContractFailure::message_only("range caller byte budget was ignored").at(id));
                    }
                };
                verify_fs_error(
                    error,
                    FsErrorKind::ResourceLimitExceeded,
                    FsOperation::Read,
                    path,
                    self.context.properties().info().provider_id(),
                    None,
                    id,
                )?;
            }
            let eof = read_expectations::CONTENT.len() as u64;
            let length = limit.maximum().unwrap_or(1).min(1);
            for options in [
                ReadOptions::default().with_length(Some(0)),
                ReadOptions::default().with_offset(Some(eof)).with_length(Some(length)),
                ReadOptions::default()
                    .with_offset(Some(eof + 1))
                    .with_length(Some(length)),
            ] {
                let actual = self
                    .fixture
                    .file_system()
                    .read_all(path, options, 64)
                    .await
                    .map_err(|error| ContractFailure::with_source("empty range observation failed", error).at(id))?;
                verify_condition(actual.is_empty(), id, "empty or beyond-EOF range returned bytes")?;
            }
        }
        if scenario == ReadScenario::Basic {
            let error = match self
                .fixture
                .file_system()
                .read_all(path, ReadOptions::default(), 4)
                .await
            {
                Err(error) => error,
                Ok(_) => {
                    return Err(ContractFailure::message_only("read caller byte limit was ignored").at(id));
                }
            };
            verify_fs_error(
                error,
                FsErrorKind::ResourceLimitExceeded,
                FsOperation::Read,
                path,
                self.context.properties().info().provider_id(),
                None,
                id,
            )?;
        }
        Ok(())
    }
}

#[cfg(all(test, feature = "async"))]
mod tests {
    use qubit_fs::metadata::FileSystemLimits;

    use super::super::AsyncFileSystemContractSuite;
    use crate::ContractCheckId;
    use crate::tests::common::AsyncMemoryFixture;
    use crate::tests::common::async_memory_file_system::run_controlled;

    #[test]
    fn test_optional_conditional_read_is_rejected_when_capability_is_absent() {
        let fixture = AsyncMemoryFixture::without_optional_capabilities();
        run_controlled(async {
            let mut suite = AsyncFileSystemContractSuite::new(&fixture);
            suite
                .run_check(ContractCheckId::ReadIfMatchCurrent)
                .await
                .assert_satisfied();
        });
        assert!(fixture.is_empty(), "conditional-read rejection must clean up");
    }

    #[test]
    fn test_range_limit_is_skipped_when_provider_limit_is_unknown() {
        let fixture = AsyncMemoryFixture::with_limits(FileSystemLimits::unknown());
        run_controlled(async {
            let mut suite = AsyncFileSystemContractSuite::new(&fixture);
            suite
                .run_check(ContractCheckId::ReadRangeLimit)
                .await
                .assert_satisfied();
        });
        assert!(fixture.is_empty(), "unknown-limit read check must clean up");
    }
}