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
// =============================================================================
// 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::ContractCheckId;
use crate::ContractCheckOutcome;
use crate::ContractFailure;
use crate::FileSystemContract;
use crate::FileSystemContractSuite;
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 FileSystemContractSuite<'_> {
/// Executes each registered read entry with its own request and setup.
///
/// # Returns
///
/// Returns successfully after every read check has recorded an outcome.
///
/// # Errors
///
/// Returns the first failure produced while executing or recording a check.
pub(super) fn check_read(&mut self) -> Result<(), ContractFailure> {
self.context.begin("read");
for spec in check_catalog::for_contract(FileSystemContract::Read, false) {
self.check_read_item(spec.id)?;
}
Ok(())
}
/// Executes exactly one read check; it never completes another check.
///
/// # Parameters
///
/// * `id` - Identifies the registered read check to execute.
///
/// # Returns
///
/// Returns `Ok(())` after recording the check's outcome.
///
/// # Errors
///
/// Returns a failure if dispatch, execution, or outcome recording fails.
pub(super) 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
) {
let outcome = self.execute_random_access(id)?;
self.context.record_check(id, Some(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)?;
self.context.record_check(id, spec.capability, outcome);
Ok(())
}
/// Executes one read scenario and associates any failure with its check ID.
///
/// The helper first evaluates capability availability, then prepares an
/// independent fixture and observes the request appropriate to `scenario`.
/// Optional unsupported scenarios are reported as skipped or not
/// applicable; required capability failures are verified as filesystem
/// errors. Versioned scenarios use fixture-provided current or stale
/// versions, and bounded range scenarios probe both the accepted
/// boundary and the first rejected length.
///
/// # Parameters
///
/// * `id` - Registered read check whose result and failures are attributed.
/// * `scenario` - Read behavior to prepare and verify.
///
/// # Returns
///
/// Returns the outcome describing whether the scenario passed, was rejected
/// as expected, was skipped, or could not be verified.
///
/// # Errors
///
/// Returns a contract failure if fixture preparation, filesystem
/// observation, or any expected condition fails.
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);
if let Some(outcome) = self.check_read_capability(id, scenario, capability, spec.optional, limit, &relative)? {
return Ok(outcome);
}
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)
.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 version = match self.read_request_version(id, scenario, &path)? {
Ok(version) => version,
Err(reason) => {
return Ok(ContractCheckOutcome::Unverified {
reason: reason.to_owned(),
});
}
};
if scenario == ReadScenario::RangeLimit {
self.check_read_range_limit(id, &path, boundary)?;
return Ok(ContractCheckOutcome::Passed);
}
let options = read_expectations::options(scenario, limit, version);
let result = self.fixture.file_system().read_all(&path, options, 64);
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)?;
Ok(ContractCheckOutcome::Passed)
}
/// Verifies capability declarations before preparing scenario evidence.
///
/// # Parameters
///
/// - `id`: Registered read check whose applicability is evaluated.
/// - `scenario`: Read request behavior represented by the check.
/// - `capability`: Capability required by the scenario.
/// - `optional`: Whether unavailable capability is an optional outcome.
/// - `limit`: Advertised maximum range size used to build requests.
/// - `relative`: Fixture-relative resource path for the scenario.
///
/// # Returns
///
/// `Some(outcome)` when the check is inapplicable or a missing required
/// capability has been verified as rejected; otherwise `None` when the
/// scenario has the capabilities needed to proceed.
///
/// # Errors
///
/// Returns a failure when a required capability is not rejected as
/// declared or the fixture request cannot be prepared.
fn check_read_capability(
&self,
id: ContractCheckId,
scenario: ReadScenario,
capability: FileSystemCapability,
optional: bool,
limit: FileSystemLimit,
relative: &str,
) -> Result<Option<ContractCheckOutcome>, ContractFailure> {
let read_available = self.capable(FileSystemCapability::Read);
if !read_available && id != ContractCheckId::ReadBasic {
return Ok(Some(ContractCheckOutcome::NotApplicable {
reason: "Read capability is unavailable".to_owned(),
}));
}
if read_available && self.capable(capability) {
return Ok(None);
}
if optional {
return Ok(Some(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) {
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,
)?;
Ok(Some(ContractCheckOutcome::RejectedAsExpected))
}
/// Observes the current or stale version required by a conditional read.
///
/// # Parameters
///
/// - `id`: Registered read check receiving observation failures.
/// - `scenario`: Determines whether current or stale version evidence is
/// needed.
/// - `path`: Prepared resource whose version is observed.
///
/// # Returns
///
/// The version to use, or a reason when the fixture cannot provide the
/// required version evidence.
///
/// # Errors
///
/// Returns a contract failure if version observation fails or stale
/// evidence equals the current version.
fn read_request_version(
&self,
id: ContractCheckId,
scenario: ReadScenario,
path: &Path,
) -> Result<Result<ResourceVersion, &'static str>, ContractFailure> {
let mut version = ResourceVersion::new("version-unused-by-request");
if !read_expectations::uses_version(scenario) {
return Ok(Ok(version));
}
let current = self
.fixture
.resource_version(path)
.map_err(|error| ContractFailure::with_source("read current version observation failed", error).at(id))?;
let FixtureSupport::Supported(current) = current else {
return Ok(Err("fixture current version unavailable"));
};
version = current.clone();
if read_expectations::uses_stale(scenario) {
let stale = self
.fixture
.stale_resource_version(path)
.map_err(|error| ContractFailure::with_source("read stale version observation failed", error).at(id))?;
let FixtureSupport::Supported(stale) = stale else {
return Ok(Err("fixture stale version unavailable"));
};
verify_condition(stale != current, id, "fixture stale version equals current version")?;
version = stale;
}
Ok(Ok(version))
}
/// Checks reads at and beyond the configured range boundary.
///
/// # Parameters
///
/// - `id`: Registered bounded-range check receiving failures.
/// - `path`: Independently prepared resource to read.
/// - `boundary`: Accepted maximum length and first over-limit length.
///
/// # Returns
///
/// `Ok(())` when the boundary read matches the seed and the first larger
/// request is rejected.
///
/// # Errors
///
/// Returns a contract failure when boundary evidence is unavailable,
/// bytes differ, or the over-limit request is accepted.
fn check_read_range_limit(
&self,
id: ContractCheckId,
path: &Path,
boundary: Option<(u64, u64)>,
) -> Result<(), ContractFailure> {
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,
)
.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)))
{
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,
)
}
/// Verifies additional range and caller-buffer-limit read requirements.
///
/// # Parameters
///
/// - `id`: Registered read check receiving any failure.
/// - `scenario`: Selects range EOF probes or the basic caller-buffer probe.
/// - `limit`: Advertised range limit used to size the EOF request.
/// - `path`: Independently prepared resource to read.
///
/// # Returns
///
/// `Ok(())` when the applicable zero-length, EOF, or caller-buffer
/// requirement is satisfied.
///
/// # Errors
///
/// Returns a contract failure when a probe errors unexpectedly, returns
/// bytes outside the requested range, or exceeds its caller byte limit.
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)
.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)
{
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)
.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) {
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(())
}
}