mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-06 04:26:02 +08:00
fix(vector): verify cached reads and preserve signed query sessions (#9896)
This commit is contained in:
@@ -46,6 +46,8 @@ jobs:
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Validate worker provenance
|
||||
env:
|
||||
CATALOG_TEST_HOSTED_SUDO: '1'
|
||||
run: python3 scripts/test_e2e_catalog_worker.py
|
||||
|
||||
- name: Build identified native worker
|
||||
@@ -66,9 +68,18 @@ jobs:
|
||||
run: |
|
||||
env -u MAKEFLAGS -u MFLAGS -u GNUMAKEFLAGS -u MAKEFILES -u MAKEOVERRIDES -u BASH_ENV -u ENV make -j4 -f - <<'MAKE'
|
||||
.PHONY: catalog-fault
|
||||
catalog-fault: ; rm -f target/nextest/e2e-distributed/junit.xml && cargo nextest list --locked -p e2e_test --features catalog-fault-worker --profile e2e-distributed -E 'test(distributed::catalog_fault_acceptance_test::)' --message-format json > target/catalog-fault-listing.json && python3 scripts/check_test_wiring.py --check-catalog-fault target/catalog-fault-listing.json && python3 scripts/e2e_catalog_worker.py run -- cargo nextest run --locked -p e2e_test --features catalog-fault-worker --profile e2e-distributed -E 'test(distributed::catalog_fault_acceptance_test::)' --test-threads 1 --retries 0 --no-tests fail && python3 scripts/check_test_wiring.py --check-catalog-fault target/catalog-fault-listing.json target/nextest/e2e-distributed/junit.xml
|
||||
catalog-fault: ; rm -f target/nextest/e2e-distributed/junit.xml && cargo nextest list --locked -p e2e_test --features catalog-fault-worker --profile e2e-distributed -E 'test(distributed::catalog_fault_acceptance_test::)' --message-format json > target/catalog-fault-listing.json && python3 scripts/check_test_wiring.py --check-catalog-fault target/catalog-fault-listing.json && CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="python3 $(CURDIR)/scripts/e2e_catalog_worker.py ci-case --" python3 scripts/e2e_catalog_worker.py run -- cargo nextest run --locked -p e2e_test --features catalog-fault-worker --profile e2e-distributed -E 'test(distributed::catalog_fault_acceptance_test::)' --test-threads 1 --retries 0 --no-tests fail && python3 scripts/check_test_wiring.py --check-catalog-fault target/catalog-fault-listing.json target/nextest/e2e-distributed/junit.xml
|
||||
MAKE
|
||||
|
||||
- name: Return private device evidence to the runner
|
||||
if: always()
|
||||
env:
|
||||
DEVICE_EVIDENCE: ${{ runner.temp }}/rustfs-catalog-fault/devices
|
||||
run: |
|
||||
if [[ -d "$DEVICE_EVIDENCE" ]]; then
|
||||
sudo -n chown -Rh -- "$(id -u):$(id -g)" "$DEVICE_EVIDENCE"
|
||||
fi
|
||||
|
||||
- name: Upload Catalog fault evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
|
||||
@@ -12,7 +12,7 @@ Each session generates a fresh 32-byte `session_signing_key` using the operating
|
||||
|
||||
The immutable session object is stored in the Vector bucket at `.rustfs-table/<table_id>/query-results/<session_id>.session`. It is created through Managed Object I/O with the original request identity, quotas, audit and the Index's effective encryption configuration. Ordinary S3 access to these objects remains blocked by the Vector bucket boundary. Nodes share the existing ECStore object storage; local memory and process identity are not session authorities.
|
||||
|
||||
Record version 1 starts with the eight ASCII bytes `RFSVPG01`, followed by the raw 32-byte `session_signing_key` and strict JSON `SessionState`. The state binds the resource, verified credential and session identity, normalized request digest, committed manifest version and digest, fixed issue and expiry times, and the operation-specific results. Unknown and duplicate fields are rejected. Query results encode distance as IEEE-754 f64 bits in an unsigned integer to preserve exact values through JSON decoding. List sessions store no ranked results. The record has a 64 MiB limit and QueryVectors retains at most 10,000 candidates. See `rustfs/src/vector/pagination.rs`.
|
||||
Record version 1 starts with the eight ASCII bytes `RFSVPG01`, followed by the raw 32-byte `session_signing_key` and a JSON `SessionState`. The state binds the resource, verified credential and session identity, normalized request digest, committed manifest version and digest, fixed issue and expiry times, and the operation-specific results. Readers ignore additive fields and reject duplicate known fields. Query results persist the row locator under `row_id` and encode distance as IEEE-754 f64 bits in an unsigned integer. The signed state digest uses these same field names. List sessions store no ranked results. The record has a 64 MiB limit and QueryVectors retains at most 10,000 candidates. See `rustfs/src/vector/pagination.rs`.
|
||||
|
||||
The opaque `nextToken` contains base64url-encoded JSON claims followed by a base64url HMAC-SHA256 tag. The MAC covers the domain `rustfs.s3vectors.pagination.session.v1` followed by a zero byte and the complete claims bytes. Claims include the public identifier, session-state digest, binding digests, manifest version and digest, page position, and issue and expiry times. The signing key never appears in the token. A node uses only the bounded canonical identifier for the initial object lookup, then verifies the signature and all bindings before reopening the Catalog-selected historical manifest. Canonical request digests ignore JSON object member order and normalize omitted defaults. Clients return the opaque token and original parameters unchanged.
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ RustFS S3 Vectors implements an AWS S3 Vectors REST-JSON vector bucket and index
|
||||
| 4-column cold/hot UTF-8 JSON schema | Vectors are stored in `rustfs/src/vector/lance/schema.rs` using four plain Arrow columns without `lance-jsonb` wire coupling: `key: Utf8` (non-null), `vector: FixedSizeList(Float32, dim)` (non-null), `filter_metadata: Utf8` (nullable hot filterable JSON, `<= 40,960` B), and `payload_metadata: LargeBinary` (nullable cold `nonFilterableMetadataKeys` JSON, up to `102,400` B combined). Filtered `QueryVectors` scans never project `payload_metadata`; cold payloads are hydrated via `take_rows` only for final result rows when `returnMetadata: true`, preserving lossless distinction between `None` and `Some({})`. |
|
||||
| Zero-knob adaptive indexing | `build_ann` in `rustfs/src/vector/lance/dataset.rs` adapts automatically without external tuning flags: `< 1,024` rows use exact columnar scan (no ANN index); `1,024..25,000` rows build `IVF_FLAT` (`partitions = (rows / 256).clamp(1, 64)`); `>= 25,000` rows build `IVF_SQ` scalar-quantized partitions (`partitions = sqrt(rows).clamp(16, 4096)`) with `take_rows` exact `f64` reranking; `>= 10,000` rows also build/refresh a `BTree` scalar index (`rustfs_vector_key_btree`) on `key` for point lookups and upserts, independently of ANN numeric eligibility and ANN fragment coverage. ANN numeric-eligibility proof (`numeric_eligible`, `ann_partitions`) is persisted directly in the Catalog descriptor. |
|
||||
| I/O and KMS efficiency | Validated snapshots cache object metadata by runtime owner and exact Catalog descriptor digest. All runtimes share a 16 MiB budget and a 1,024-entry limit. A snapshot larger than the budget uses the ordinary validation path. Bound range reads skip repeated `HEAD` probes, managed requests cache unpacked SSE DEKs per `(object_key, body_revision)`, and multipart parts upload concurrently. |
|
||||
| Two-Phase Rolling-Upgrade contract | **Phase 1 (Reader tolerance + pinned writer):** Readers enforce security and GC invariants (`can_read_dataset`/`can_write_dataset`, empty `base_paths`/`base_id`, prefix confinement, Catalog SHA-256 + `body_revision` binding) while accepting any non-empty `library_version` and unknown additive JSON fields on descriptors, bindings, initialization payloads, and pagination sessions. Writers pin `LanceFileVersion::V2_2`, ordinary fragment addressing (`enable_stable_row_ids = false`), `skip_auto_cleanup = true`, and external `_deletions/*` files so mixed-version nodes read and commit interoperably during rolling restarts. **Phase 2 (Writer advancement):** New storage format versions or sticky Lance feature flags are enabled on writers only in a later release after every supported rolling-upgrade/rollback node ships reader support, guarded by `rustfs/src/vector/lance/golden_corpus_tests.rs`. |
|
||||
| Rolling upgrades | Rolling updates serving Vector traffic require a shared logical schema and compatible Catalog records. For the pre-GA three-column to four-column change, export and recreate the indexes with the Vector service offline during the mixed-version interval. Within the four-column format, writers pin Lance 2.2 and readers validate supported dataset features and manifest bindings. See the [upgrade procedure](../operations/s3-vectors-maintenance.md#upgrading-vector-indexes). |
|
||||
| Zero-fork supply chain (`paste-compat`) | All Vector and Lance dependencies resolve from `crates.io` without git forks. Transitive `paste 1.x` macro calls in `lance-bitpacking` and `simba` route through the workspace `crates/paste-compat` bridge to maintained `pastey` (`paste-1-pastey-bridge` in `docs/architecture/compat-cleanup-register.md`). |
|
||||
|
||||
## Intentional Deviations And Non-Claims
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
## Configuration and identity
|
||||
|
||||
Background Vector maintenance is **disabled by default**. A fresh installation or an upgrade with no maintenance setting starts the S3 Vectors endpoint with background maintenance off. Vector reads and writes remain available. Adaptive index builds, compaction, physical cleanup of expired snapshots and sessions, and retirement of previously populated buckets require a running worker.
|
||||
Background Vector maintenance is **disabled by default**. A fresh installation or an upgrade with no maintenance setting starts the S3 Vectors endpoint with background maintenance off. The endpoint serves reads and writes for indexes using the supported schema. Adaptive index builds, compaction, physical cleanup of expired snapshots and sessions, and retirement of previously populated buckets require a running worker.
|
||||
|
||||
Configure the `s3vectors_maintenance` server subsystem at the default target `_` and restart the server.
|
||||
|
||||
@@ -46,20 +46,18 @@ Catalog cleanup publishes an immutable retirement authority under `s3vectors/cat
|
||||
|
||||
New admissions stop when the worker loses authorization, reaches its concurrency/memory/queue budget, or receives shutdown cancellation. In-flight operations retain their Catalog and storage guards until underlying I/O completes so recorded outcomes reflect actual storage state. Shutdown drains worker handles and propagates nested errors or timeouts; inspect `vector_maintenance_admission` events and `.rustfs.sys` job/retirement records before retrying failed work, and never manually delete uncertain candidate or journal files.
|
||||
|
||||
## Rolling upgrades and compatibility contract
|
||||
## Upgrading Vector indexes
|
||||
|
||||
RustFS S3 Vectors supports rolling upgrades across cluster nodes under a **Two-Phase Rolling-Upgrade Contract** (verified by `rustfs/src/vector/lance/golden_corpus_tests.rs`):
|
||||
This release writes a four-column Arrow schema. Earlier pre-GA releases used three columns. Both layouts use `schema_version = 1`, and the Lance file format version alone cannot identify the Vector schema.
|
||||
|
||||
1. **Phase 1 — Reader-first tolerance with pinned writer output**:
|
||||
- **Readers** enforce true security, isolation, and GC-closure invariants (`lance_table::feature_flags::{can_read_dataset, can_write_dataset}`, empty `base_paths`/`base_id`, dataset prefix confinement, and Catalog SHA-256 + `body_revision` + encryption bindings) while tolerating arbitrary non-empty `library_version` strings (for example across Lance `14.x`, `15.x`, or `16.x`) and ignoring unknown additive JSON fields on `CatalogFormatDescriptor`, `VectorManifestBindingV1`, initialization payloads, and `RFSVPG01` pagination sessions.
|
||||
- **Writers** explicitly pin `LanceFileVersion::V2_2` (`"2.2"`), ordinary fragment addressing (`enable_stable_row_ids = false`), `skip_auto_cleanup = true`, and external `_deletions/*` files so commits produced by upgraded nodes remain readable and writable by peers on the previous release during a rolling restart.
|
||||
2. **Phase 2 — Writer format advancement**:
|
||||
- Advancing the pinned writer `LanceFileVersion` (for example to `2.3`) or enabling new sticky Lance feature flags may occur only in a subsequent release after every supported rolling-upgrade and rollback node already ships Phase 1 reader support for those capabilities. Once a newer sticky capability has been written to a manifest, rolling back below the reader release that introduced support for that flag is unsupported.
|
||||
For a deployment with three-column indexes, pause Vector writes and export the index definitions, keys, vectors and metadata with the old release, or verify that you can restore them from your original data source. If you need to reuse bucket or index names, finish retiring those resources with the old release after verifying the export. Keep Vector traffic and maintenance stopped during the mixed-version interval. Once all nodes run the new release, recreate the indexes, reload the vectors, and verify counts and representative queries before resuming Vector traffic. Start fresh pagination sessions for recreated indexes. This procedure applies only to Vector resources.
|
||||
|
||||
### Rolling upgrade procedure
|
||||
### Rolling upgrades within the four-column format
|
||||
|
||||
A rolling upgrade serving Vector traffic requires both releases to read and write the same Vector schema and Catalog records. Writers pin `LanceFileVersion::V2_2`, use ordinary fragment addressing, disable automatic Lance cleanup, and use external deletion files. Readers validate the dataset features, prefix and manifest bindings while accepting additive JSON fields. The persisted-format tests in `rustfs/src/vector/lance/golden_corpus_tests.rs` cover these rules for the current layout. A later writer format or sticky Lance feature requires reader support on every node, including any intended rollback version.
|
||||
|
||||
1. Check the effective maintenance settings before restarting nodes. An upgrade preserves explicit server settings and environment overrides. If the existing configuration has no maintenance section or override, upgraded nodes keep the worker disabled. To opt in after the rollout, set `enable=on` and restart the nodes that should run maintenance.
|
||||
2. Verify that every target node will deploy the exact intended binary SHA-256 or immutable container image digest, with matching region, KMS/SSE reachability, and compatible `s3vectors_maintenance` settings. (Workspace builds use the zero-fork `crates/paste-compat` bridge tracked under `paste-1-pastey-bridge` in [Compatibility Cleanup Register](../architecture/compat-cleanup-register.md).)
|
||||
3. Upgrade one node (or failure domain) at a time: drain incoming HTTP requests on that node and allow its graceful shutdown to cancel new maintenance admissions and finish or cleanly release active job leases. Preserve all `.rustfs.sys` Catalog, candidate, and retirement records.
|
||||
4. Start the upgraded node, verify health, KMS/SSE readiness, and absence of `vector_maintenance_admission` or Catalog validation errors before proceeding to the next node.
|
||||
5. Wait until all cluster nodes have converged on the new release and passed post-upgrade health checks before activating any Phase 2 format migration in future releases.
|
||||
5. Confirm that all nodes can read and write the deployed Vector format before enabling background maintenance.
|
||||
|
||||
@@ -108,7 +108,7 @@ Membership is pinned by `.config/e2e-distributed-selection.txt`. Update the Linu
|
||||
|
||||
## Native Catalog fault acceptance
|
||||
|
||||
The `catalog-fault-worker` feature of `e2e_test` enables the Catalog-specific four-process suite. It uses a RustFS library test executable, so each process runs the normal startup and ECStore with the test-only Lance preparation and Catalog driver available. The dedicated [workflow](../../.github/workflows/e2e-catalog-fault.yml) builds and runs this executable through [e2e_catalog_worker.py](../../scripts/e2e_catalog_worker.py). Ordinary production builds retain their existing E2E identity and entry point.
|
||||
The `catalog-fault-worker` feature of `e2e_test` enables the Catalog-specific four-process suite. It uses a RustFS library test executable, so each process runs the normal startup and ECStore with the test-only Lance preparation and Catalog driver available. The dedicated [workflow](../../.github/workflows/e2e-catalog-fault.yml) builds and runs this executable through [e2e_catalog_worker.py](../../scripts/e2e_catalog_worker.py). On the hosted Linux runner, nextest lists and executes tests as the runner user. Its case launcher uses noninteractive sudo for the three D07 loop-device recovery cases, creating their private receipts and launching each worker as root. The workflow returns ownership of device evidence to the runner before uploading it.
|
||||
|
||||
```bash
|
||||
CARGO_BUILD_JOBS=4 CARGO_INCREMENTAL=0 make -j4 -f - <<'MAKE'
|
||||
@@ -121,7 +121,7 @@ export RUSTFS_CATALOG_FAULT_ARTIFACT_DIR="${PWD}/target/catalog-fault-artifacts"
|
||||
CARGO_BUILD_JOBS=4 CARGO_INCREMENTAL=0 make -j4 -f - <<'MAKE'
|
||||
.PHONY: catalog-fault
|
||||
catalog-fault:
|
||||
python3 scripts/e2e_catalog_worker.py run -- cargo nextest run --locked -p e2e_test --features catalog-fault-worker --profile e2e-distributed -E 'test(distributed::catalog_fault_acceptance_test::)' --test-threads 1 --retries 0 --no-tests fail
|
||||
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="python3 $(CURDIR)/scripts/e2e_catalog_worker.py ci-case --" python3 scripts/e2e_catalog_worker.py run -- cargo nextest run --locked -p e2e_test --features catalog-fault-worker --profile e2e-distributed -E 'test(distributed::catalog_fault_acceptance_test::)' --test-threads 1 --retries 0 --no-tests fail
|
||||
MAKE
|
||||
```
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::storage::storage_api::ecstore_object::{
|
||||
};
|
||||
use std::collections::VecDeque;
|
||||
use std::ops::Range;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const MANAGED_OBJECT_READ_CACHE_CAPACITY: usize = 256;
|
||||
|
||||
@@ -29,16 +30,10 @@ pub(crate) enum ManagedEncryption {
|
||||
}
|
||||
|
||||
struct CachedDekMaterial {
|
||||
key_bytes: [u8; 32],
|
||||
key_bytes: Zeroizing<[u8; 32]>,
|
||||
mode: ReadEncryptionMode,
|
||||
}
|
||||
|
||||
impl Drop for CachedDekMaterial {
|
||||
fn drop(&mut self) {
|
||||
self.key_bytes.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
struct CachedManagedReadEncryptionResolver {
|
||||
bucket: String,
|
||||
key: String,
|
||||
@@ -70,7 +65,7 @@ impl ObjectEncryptionResolver for CachedManagedReadEncryptionResolver {
|
||||
.await;
|
||||
}
|
||||
Ok(self.material.as_ref().map(|material| ReadEncryptionMaterial {
|
||||
key_bytes: material.key_bytes,
|
||||
key_bytes: *material.key_bytes,
|
||||
mode: material.mode,
|
||||
}))
|
||||
}
|
||||
@@ -1066,7 +1061,7 @@ impl DefaultObjectUsecase {
|
||||
expected_raw_metadata: info.user_defined.clone(),
|
||||
principal: principal.clone(),
|
||||
material: Some(CachedDekMaterial {
|
||||
key_bytes: material.key_bytes,
|
||||
key_bytes: Zeroizing::new(material.key_bytes),
|
||||
mode,
|
||||
}),
|
||||
});
|
||||
@@ -3342,6 +3337,17 @@ pub(super) mod tests {
|
||||
assert_eq!(managed_range(None, 0).expect("empty object").1, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_dek_bytes_require_zeroization_on_drop() {
|
||||
fn requires_zeroize_on_drop(_: &impl zeroize::ZeroizeOnDrop) {}
|
||||
|
||||
let material = CachedDekMaterial {
|
||||
key_bytes: [0x5a; 32].into(),
|
||||
mode: ReadEncryptionMode::Object,
|
||||
};
|
||||
requires_zeroize_on_drop(&material.key_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_read_cache_is_bounded_and_isolated_by_principal_and_revision() {
|
||||
let mut cache = ManagedObjectReadCache::default();
|
||||
|
||||
@@ -1191,6 +1191,22 @@ fn vector_system_maintenance_executes_active_dual_gate_history_gc() {
|
||||
.into_iter()
|
||||
.filter(|job| *job.job().state() == VectorMaintenanceJobState::Queued)
|
||||
{
|
||||
let plan_ref = CatalogMetadataRef::try_from(job.job().input().plan_ref().as_ref().unwrap()).unwrap();
|
||||
let evidence = catalog.retirement_plan_evidence_for_test(&plan_ref).await;
|
||||
match kind {
|
||||
VectorMaintenanceKind::HistoryGc => assert!(
|
||||
evidence
|
||||
.history_refs()
|
||||
.iter()
|
||||
.all(|reference| reference.object_key.ends_with(".manifest")),
|
||||
"active history batches retire only manifest roots"
|
||||
),
|
||||
VectorMaintenanceKind::OrphanGc => assert!(
|
||||
evidence.history_refs().is_empty(),
|
||||
"a new orphan plan must not copy history from prior retirement batches"
|
||||
),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let outcome = execute_vector_maintenance_job(
|
||||
catalog.as_ref().clone(),
|
||||
resource.clone(),
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
use super::*;
|
||||
use crate::table_catalog::tests::prepared_commit::{PreparedFixture, prepared_v3_fixture};
|
||||
|
||||
impl<B: TableCatalogObjectBackend> ObjectTableCatalogStore<B> {
|
||||
pub(crate) async fn retirement_plan_evidence_for_test(&self, plan_ref: &CatalogMetadataRef) -> VectorRetirementEvidenceV1 {
|
||||
let object = self.maintenance_read_ref(plan_ref).await.unwrap();
|
||||
let plan: VectorRetirementPlanV1 = decode_vector_maintenance_record(&object.data).unwrap();
|
||||
let evidence = self
|
||||
.maintenance_read_ref(&CatalogMetadataRef::try_from(&plan.evidence_ref).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
decode_vector_maintenance_record(&evidence.data).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
async fn maintenance_fixture() -> (PreparedFixture, VectorMaintenanceJobSpec) {
|
||||
let mut fixture = prepared_v3_fixture().await;
|
||||
fixture.entry.version = 4;
|
||||
@@ -1694,15 +1706,54 @@ async fn object_maintenance_candidate_page_advances_past_a_long_retirement_chain
|
||||
&metadata,
|
||||
)
|
||||
.unwrap();
|
||||
let evidence_ref: CatalogMetadataRefRecordV1 = (&fixture.initial).into();
|
||||
for batch in 0..65 {
|
||||
let root_ref: CatalogMetadataRefRecordV1 = (&fixture.initial).into();
|
||||
let refs_per_batch = 1024;
|
||||
let batches = VECTOR_RETIREMENT_MAX_REFERENCES / refs_per_batch + 1;
|
||||
let write_record = async |directory: &str, bytes: Vec<u8>| {
|
||||
let digest = hex_simd::encode_to_string(Sha256::digest(&bytes), hex_simd::AsciiCase::Lower);
|
||||
fixture
|
||||
.store
|
||||
.maintenance_write_immutable(
|
||||
&resource,
|
||||
format!("{prefix}{directory}/{digest}.json"),
|
||||
bytes,
|
||||
&TableCatalogObjectMutationFence::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
};
|
||||
for batch in 0..batches {
|
||||
let current = VectorCatalogEntry::from_entry(fixture.entry.clone()).unwrap();
|
||||
let head = VectorMaintenanceHeadV1::from_entry(¤t).unwrap();
|
||||
if batch < 64 {
|
||||
if batch + 1 < batches {
|
||||
target.object_key = format!("{}data/removed-{batch}.lance", resource.dataset_prefix());
|
||||
} else {
|
||||
target.object_key.clone_from(&listed_key);
|
||||
}
|
||||
let old_refs = (0..refs_per_batch)
|
||||
.map(|index| CatalogMetadataRefRecordV1 {
|
||||
object_key: format!("{}data/history-{batch}-{index}.lance", resource.dataset_prefix()),
|
||||
..root_ref.clone()
|
||||
})
|
||||
.collect();
|
||||
let evidence = VectorRetirementEvidenceV1::try_new(
|
||||
spec.resource.clone(),
|
||||
head.clone(),
|
||||
None,
|
||||
old_refs,
|
||||
vec![root_ref.clone()],
|
||||
Vec::new(),
|
||||
VectorHistoryRetentionV1::All,
|
||||
)
|
||||
.unwrap();
|
||||
let evidence_ref = write_record("evidence", encode_vector_maintenance_record(&evidence).unwrap()).await;
|
||||
let plan = VectorRetirementPlanV1 {
|
||||
version: 1,
|
||||
resource: spec.resource.clone(),
|
||||
evidence_ref: (&evidence_ref).into(),
|
||||
targets: vec![target.clone()],
|
||||
};
|
||||
let plan_ref = write_record("plans", encode_vector_maintenance_record(&plan).unwrap()).await;
|
||||
let binding = fixture.entry.vector_maintenance_binding.as_mut().unwrap();
|
||||
let retirement_id = Uuid::new_v4();
|
||||
let authorization = VectorRetirementAuthorizationV1 {
|
||||
@@ -1717,9 +1768,9 @@ async fn object_maintenance_candidate_page_advances_past_a_long_retirement_chain
|
||||
previous_ref: binding.retirement_tip.clone(),
|
||||
base_head: head,
|
||||
delete_intent_ref: None,
|
||||
plan_ref: evidence_ref.clone(),
|
||||
reference_evidence_ref: evidence_ref.clone(),
|
||||
targets: vec![target.clone()],
|
||||
plan_ref: (&plan_ref).into(),
|
||||
reference_evidence_ref: plan.evidence_ref,
|
||||
targets: plan.targets,
|
||||
};
|
||||
let path = format!("{prefix}authorizations/{}.json", table_catalog_path_hash(&retirement_id.to_string()));
|
||||
let reference = fixture
|
||||
@@ -1762,13 +1813,33 @@ async fn object_maintenance_candidate_page_advances_past_a_long_retirement_chain
|
||||
.expect("a full retiring history must not exhaust the LIST page budget")
|
||||
.into_parts();
|
||||
assert!(next.is_none());
|
||||
fixture
|
||||
let (history, _) = fixture
|
||||
.store
|
||||
.read_vector_gc_history_with_guard(&guard, &mut page, &VectorHistoryRetentionV1::All)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(page.iter().any(|(k, _)| k.as_str() == live_key));
|
||||
assert_eq!(history.len(), 1);
|
||||
assert_eq!(history[0].metadata(), &fixture.initial);
|
||||
assert!(page.iter().all(|(k, _)| k.as_str() != listed_key));
|
||||
let (key, metadata) = page.into_iter().find(|(k, _)| k.as_str() == live_key).unwrap();
|
||||
let target = VectorRetirementTargetV1::from_object_metadata(&resource, key, &metadata).unwrap();
|
||||
let current = VectorCatalogEntry::from_entry(fixture.entry).unwrap();
|
||||
let evidence = VectorRetirementEvidenceV1::try_new(
|
||||
spec.resource,
|
||||
VectorMaintenanceHeadV1::from_entry(¤t).unwrap(),
|
||||
None,
|
||||
Vec::new(),
|
||||
vec![root_ref],
|
||||
Vec::new(),
|
||||
VectorHistoryRetentionV1::All,
|
||||
)
|
||||
.unwrap();
|
||||
let prepared = fixture
|
||||
.store
|
||||
.prepare_vector_retirement(&guard, evidence.clone(), vec![target])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fixture.store.retirement_plan_evidence_for_test(prepared.plan_ref()).await, evidence);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -3236,7 +3236,7 @@ impl<B: TableCatalogObjectBackend> LanceManifestAdapter<B> {
|
||||
if purpose == ReferenceClosure::SdkFaultReceipt {
|
||||
return self.inner.objects.sdk_receipt_data_reference(&file.key).await;
|
||||
}
|
||||
self.inner.objects.exact_data_reference(&file.key).await
|
||||
self.inner.objects.gc_data_reference(&file.key)
|
||||
})
|
||||
.buffer_unordered(self.inner.limits.max_concurrent_reads.get());
|
||||
futures::pin_mut!(references);
|
||||
|
||||
@@ -312,9 +312,17 @@ impl ManagedObjectStore {
|
||||
expected: TableCatalogObjectMetadata,
|
||||
) -> object_store_lance::Result<GetResult> {
|
||||
let key = CatalogObjectKey::try_new(location.to_string()).map_err(|source| object_error(source.into()))?;
|
||||
let actual = if !options.head && expected.body_revision.is_some() && expected.etag.is_some() {
|
||||
expected.clone()
|
||||
} else {
|
||||
let range = options
|
||||
.range
|
||||
.as_ref()
|
||||
.map_or(Ok(0..expected.size), |range| range.as_range(expected.size));
|
||||
let has_body = range.as_ref().is_ok_and(|range| !range.is_empty());
|
||||
let conditional = options.if_match.is_some()
|
||||
|| options.if_none_match.is_some()
|
||||
|| options.if_modified_since.is_some()
|
||||
|| options.if_unmodified_since.is_some();
|
||||
// Empty and conditional responses can finish before a revision-bound range read checks the object.
|
||||
let actual = if options.head || !has_body || conditional || expected.etag.is_none() {
|
||||
self.access
|
||||
.check(key.as_str(), ManagedObjectOperation::Head)
|
||||
.map_err(|source| object_error(source.into()))?;
|
||||
@@ -325,6 +333,8 @@ impl ManagedObjectStore {
|
||||
}));
|
||||
}
|
||||
actual
|
||||
} else {
|
||||
expected
|
||||
};
|
||||
let revision = require_revision(actual.body_revision).map_err(object_error)?;
|
||||
let meta = object_meta(location, &actual).map_err(object_error)?;
|
||||
@@ -339,21 +349,15 @@ impl ManagedObjectStore {
|
||||
source: "Dataset body revision differs".into(),
|
||||
});
|
||||
}
|
||||
let range = options
|
||||
.range
|
||||
.as_ref()
|
||||
.map(|range| range.as_range(meta.size))
|
||||
.transpose()
|
||||
.map_err(|source| object_store_lance::Error::Generic {
|
||||
store: "RustFS managed Lance objects",
|
||||
source: Box::new(source),
|
||||
})?
|
||||
.unwrap_or(0..meta.size);
|
||||
let range = range.map_err(|source| object_store_lance::Error::Generic {
|
||||
store: "RustFS managed Lance objects",
|
||||
source: Box::new(source),
|
||||
})?;
|
||||
let stream_end = if options.head { range.start } else { range.end };
|
||||
let objects = self.objects.clone();
|
||||
let access = self.access.clone();
|
||||
let permits = self.read_permits.clone();
|
||||
let expected_etag = expected.etag;
|
||||
let expected_etag = actual.etag;
|
||||
let control = self.control.get().cloned();
|
||||
let io_owner = match &control {
|
||||
Some(control) => Some(Arc::new(control.acquire_io().await.map_err(|error| object_error(error.into()))?)),
|
||||
@@ -425,6 +429,16 @@ impl ManagedObjectStore {
|
||||
pub(super) fn bind_reference(&self, reference: &CatalogMetadataRef) -> Result<(), LanceManifestError> {
|
||||
self.access
|
||||
.check(reference.object_key().as_str(), ManagedObjectOperation::Get)?;
|
||||
if !reference
|
||||
.object_key()
|
||||
.as_str()
|
||||
.strip_prefix(self.access.allowed_prefix())
|
||||
.is_some_and(|relative| relative.starts_with("_versions/"))
|
||||
{
|
||||
return Err(LanceManifestError::ReferenceMismatch {
|
||||
reason: "manifest reference is outside the Dataset versions directory",
|
||||
});
|
||||
}
|
||||
require_revision(reference.body_revision().map(|revision| revision.as_uuid()))?;
|
||||
self.check_length(reference.content_length())?;
|
||||
let path = Path::from(reference.object_key().as_str());
|
||||
@@ -923,7 +937,11 @@ impl ObjectStore for ManagedObjectStore {
|
||||
if let Some(reference) = self.data_reference(location).map_err(object_error)? {
|
||||
let result = self.get_data(location, options, reference).await?;
|
||||
let length = result.range.end - result.range.start;
|
||||
let Some(control) = self.control.get().filter(|_| length > DATA_READ_CHUNK_BYTES) else {
|
||||
let Some(control) = self
|
||||
.control
|
||||
.get()
|
||||
.filter(|_| operation != ManagedObjectOperation::Head && length > DATA_READ_CHUNK_BYTES)
|
||||
else {
|
||||
return Ok(result);
|
||||
};
|
||||
let reservation = control.reserve_memory(length).map_err(|error| object_error(error.into()))?;
|
||||
@@ -1131,12 +1149,9 @@ fn data_metadata_reference(
|
||||
}
|
||||
|
||||
impl ManagedObjectStore {
|
||||
pub(super) async fn exact_data_reference(&self, key: &CatalogObjectKey) -> Result<CatalogMetadataRef, LanceManifestError> {
|
||||
let metadata = self
|
||||
.data_reference(&Path::from(key.as_str()))?
|
||||
.ok_or(LanceManifestError::ReferenceMismatch {
|
||||
reason: "reference closure contains an unbound object",
|
||||
})?;
|
||||
/// Data-file evidence binds physical object metadata. Manifest references carry a digest of the bytes.
|
||||
pub(super) fn gc_data_reference(&self, key: &CatalogObjectKey) -> Result<CatalogMetadataRef, LanceManifestError> {
|
||||
let metadata = self.bound_data_metadata(key)?;
|
||||
let revision = require_revision(metadata.body_revision)?;
|
||||
data_metadata_reference(key.clone(), metadata.size, revision, metadata.etag)
|
||||
}
|
||||
|
||||
@@ -331,7 +331,8 @@ async fn sdk_fault_receipt_hashes_chunked_data_at_the_bound_revision() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let gc = store.exact_data_reference(&key).await.unwrap();
|
||||
let gc = store.gc_data_reference(&key).unwrap();
|
||||
assert!(matches!(store.read_exact(&gc).await, Err(LanceManifestError::ReferenceMismatch { .. })));
|
||||
assert!(objects.ranges.lock().unwrap().is_empty());
|
||||
let receipt = store.sdk_receipt_data_reference(&key).await.unwrap();
|
||||
assert_eq!(receipt.body_revision(), gc.body_revision());
|
||||
|
||||
@@ -301,6 +301,7 @@ async fn lance_primitive_list_retains_outer_nullability() {
|
||||
struct TestManagedObjects {
|
||||
objects: Arc<std::sync::Mutex<HashMap<String, crate::table_catalog::TableCatalogObject>>>,
|
||||
gets: Arc<std::sync::atomic::AtomicUsize>,
|
||||
heads: Arc<std::sync::atomic::AtomicUsize>,
|
||||
deny_create: Arc<std::sync::atomic::AtomicBool>,
|
||||
ranges: Arc<std::sync::Mutex<Vec<Option<std::ops::Range<u64>>>>>,
|
||||
}
|
||||
@@ -398,6 +399,7 @@ impl super::ManagedManifestObjects for TestManagedObjects {
|
||||
key: &crate::table_catalog::CatalogObjectKey,
|
||||
) -> Result<crate::table_catalog::TableCatalogObjectMetadata, LanceManifestError> {
|
||||
access.check(key.as_str(), crate::storage_api::vector::ManagedObjectOperation::Head)?;
|
||||
self.heads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let objects = self.objects.lock().unwrap();
|
||||
let object = objects.get(key.as_str()).ok_or_else(|| LanceManifestError::ObjectNotFound {
|
||||
key: key.as_str().into(),
|
||||
@@ -1420,6 +1422,58 @@ async fn managed_data_put_and_streamed_ranges_preserve_exact_identity() {
|
||||
assert_eq!(store.get(&path).await.unwrap().bytes().await.unwrap(), data);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_data_reads_verify_replaced_and_missing_objects() {
|
||||
use object_store_lance::{Error, GetOptions, GetRange, ObjectStore as _};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let objects = Arc::new(TestManagedObjects::default());
|
||||
let store = super::object_store::ManagedObjectStore::new(objects.clone(), dataset_access(), io_limits());
|
||||
for (path, bytes) in [
|
||||
(native_data_path(1), Bytes::new()),
|
||||
(native_data_path(2), Bytes::from_static(b"original")),
|
||||
] {
|
||||
store.put(&path, bytes.clone().into()).await.unwrap();
|
||||
let mut options = vec![
|
||||
GetOptions::new().with_head(true),
|
||||
GetOptions::new().with_range(Some(GetRange::Suffix(0))),
|
||||
GetOptions::new().with_if_none_match(Some("*")),
|
||||
];
|
||||
if bytes.is_empty() {
|
||||
options.push(GetOptions::default());
|
||||
} else {
|
||||
let heads = objects.heads.load(Ordering::SeqCst);
|
||||
assert_eq!(store.get_range(&path, 0..4).await.unwrap(), bytes.slice(..4));
|
||||
assert_eq!(objects.heads.load(Ordering::SeqCst), heads);
|
||||
}
|
||||
for option in &options {
|
||||
let result = store.get_opts(&path, option.clone()).await;
|
||||
if option.if_none_match.is_some() {
|
||||
assert!(matches!(result, Err(Error::NotModified { .. })));
|
||||
} else {
|
||||
assert!(result.unwrap().bytes().await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
objects.objects.lock().unwrap().get_mut(path.as_ref()).unwrap().body_revision = Some(uuid::Uuid::new_v4());
|
||||
for option in &options {
|
||||
assert!(matches!(store.get_opts(&path, option.clone()).await, Err(Error::Generic { source, .. })
|
||||
if matches!(source.downcast_ref::<LanceManifestError>(), Some(LanceManifestError::ReferenceMismatch { .. }))));
|
||||
}
|
||||
if !bytes.is_empty() {
|
||||
assert!(store.get_range(&path, 0..4).await.is_err());
|
||||
}
|
||||
|
||||
objects.objects.lock().unwrap().remove(path.as_ref()).unwrap();
|
||||
for option in options {
|
||||
assert!(matches!(store.get_opts(&path, option).await, Err(Error::NotFound { .. })));
|
||||
}
|
||||
if !bytes.is_empty() {
|
||||
assert!(matches!(store.get_range(&path, 0..4).await, Err(Error::NotFound { .. })));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_data_stream_rejects_revision_change_between_chunks() {
|
||||
use futures::StreamExt;
|
||||
@@ -4722,6 +4776,41 @@ fn maintenance_index_paths_reject_external_and_duplicate_layouts() {
|
||||
assert!(super::files::validate_writable_relative_path("_indices/00000000-0000-0000-0000-000000000000/index.idx").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maintenance_head_reads_large_object_metadata_with_small_memory_budget() {
|
||||
use crate::table_catalog::{VectorMaintenanceBudgets, VectorMaintenanceControl, VectorMaintenanceRuntimeConfig};
|
||||
use object_store_lance::{GetOptions, ObjectStore as _};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let objects = Arc::new(TestManagedObjects::default());
|
||||
let store = super::object_store::ManagedObjectStore::new(objects.clone(), dataset_access(), io_limits());
|
||||
let path = native_data_path(91);
|
||||
let body = Bytes::from(vec![1; 2 * 1024 * 1024]);
|
||||
let size = body.len() as u64;
|
||||
let put = store.put(&path, body.into()).await.unwrap();
|
||||
let config = VectorMaintenanceRuntimeConfig {
|
||||
memory_bytes: NonZeroU64::new(1024 * 1024).unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
store
|
||||
.set_maintenance_control(VectorMaintenanceControl::new(
|
||||
tokio_util::sync::CancellationToken::new(),
|
||||
tokio::time::Instant::now() + std::time::Duration::from_secs(30),
|
||||
VectorMaintenanceBudgets::new(&config, None).unwrap(),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let heads = objects.heads.load(Ordering::SeqCst);
|
||||
let gets = objects.gets.load(Ordering::SeqCst);
|
||||
let result = store.get_opts(&path, GetOptions::new().with_head(true)).await.unwrap();
|
||||
assert_eq!(result.meta.size, size);
|
||||
assert_eq!(result.meta.e_tag, put.e_tag);
|
||||
assert_eq!(result.meta.version, put.version);
|
||||
assert!(result.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(objects.heads.load(Ordering::SeqCst), heads + 1);
|
||||
assert_eq!(objects.gets.load(Ordering::SeqCst), gets);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maintenance_budget_follows_cloned_read_buffers_and_open_streams() {
|
||||
use crate::table_catalog::*;
|
||||
@@ -6023,17 +6112,30 @@ async fn collect_references_deduplicates_shared_files_and_rejects_competing_revi
|
||||
.collect_references(head.metadata(), head.format_descriptor())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(closure.len() >= 9);
|
||||
{
|
||||
let state = fixture.backend.state.lock().await;
|
||||
for key in &data_keys {
|
||||
let after = state.read_attempts.get(&(bucket.clone(), key.clone())).copied().unwrap_or(0);
|
||||
assert_eq!(
|
||||
after - reads_before[key],
|
||||
0,
|
||||
"shared data file {key} must not be streamed during metadata-bound reference collection"
|
||||
);
|
||||
}
|
||||
assert!(closure.contains(head.metadata()));
|
||||
let state = fixture.backend.state.lock().await;
|
||||
assert_eq!(
|
||||
head.metadata().content_sha256(),
|
||||
CatalogContentSha256::digest(&state.objects[&(bucket.clone(), head.metadata().object_key().as_str().to_owned())].data)
|
||||
);
|
||||
let data_refs: Vec<_> = closure
|
||||
.iter()
|
||||
.filter(|r| r.object_key().as_str().contains("/data/"))
|
||||
.collect();
|
||||
assert_eq!(data_refs.len(), data_keys.len());
|
||||
for reference in data_refs {
|
||||
let key = reference.object_key().as_str();
|
||||
let stored_key = (bucket.clone(), key.to_owned());
|
||||
let stored = &state.objects[&stored_key];
|
||||
assert_eq!(reference.body_revision().map(|r| r.as_uuid()), stored.body_revision);
|
||||
assert_eq!(reference.content_length(), stored.data.len() as u64);
|
||||
assert_eq!(reference.etag(), Some(stored.etag.as_str()));
|
||||
assert_ne!(reference.content_sha256(), CatalogContentSha256::digest(&stored.data));
|
||||
assert_eq!(
|
||||
state.read_attempts.get(&stored_key).copied().unwrap_or(0),
|
||||
reads_before[key],
|
||||
"shared data file {key} must not be streamed during metadata-bound reference collection"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ pub(crate) struct SessionBinding {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub(crate) struct StoredMatch {
|
||||
pub key: String,
|
||||
#[serde(alias = "row_id")]
|
||||
#[serde(rename = "row_id")]
|
||||
pub locator: EngineRowLocator,
|
||||
pub distance_bits: u64,
|
||||
}
|
||||
@@ -153,6 +153,7 @@ pub(crate) fn digest_session_state(state: &SessionState) -> Result<[u8; 32], Pag
|
||||
struct CanonicalStoredMatchRef<'a> {
|
||||
distance_bits: u64,
|
||||
key: &'a str,
|
||||
#[serde(rename = "row_id")]
|
||||
locator: EngineRowLocator,
|
||||
}
|
||||
|
||||
|
||||
@@ -161,9 +161,17 @@ fn token_and_session_decoders_reject_duplicates_and_tolerate_additive_rolling_up
|
||||
let parsed_unsigned = ParsedToken::parse(&unsigned_extra_token).unwrap();
|
||||
assert!(session.verify(&parsed_unsigned, &session.state.binding, 1100).is_err());
|
||||
|
||||
// Persisted session JSON with additive rolling-upgrade fields and legacy row_id alias decodes cleanly.
|
||||
// The v1 query token signs the canonical JSON containing the persisted row_id.
|
||||
assert_eq!(
|
||||
hex_simd::encode_to_string(original.claims.state_digest, hex_simd::AsciiCase::Lower),
|
||||
"848336776012c4e114c3eb6152c726c7730807842737fcaa0ffb738597855fc7"
|
||||
);
|
||||
let encoded = session.encode().unwrap();
|
||||
let mut json: serde_json::Value = serde_json::from_slice(&encoded[40..]).unwrap();
|
||||
assert_eq!(
|
||||
json["results"]["matches"][1],
|
||||
serde_json::json!({"key": "key-1", "row_id": 1, "distance_bits": 1.0_f64.to_bits()})
|
||||
);
|
||||
json["future_session_hint"] = serde_json::json!("v2-node");
|
||||
json["binding"]["future_binding_flag"] = serde_json::json!(true);
|
||||
json["results"]["matches"][0]["future_match_field"] = serde_json::json!(7);
|
||||
|
||||
@@ -604,7 +604,8 @@ def catalog_fault_workflow_run() -> str:
|
||||
f"rm -f {CATALOG_FAULT_JUNIT}",
|
||||
f"cargo nextest list {selection} --message-format json > {CATALOG_FAULT_LISTING}",
|
||||
verify,
|
||||
("python3 scripts/e2e_catalog_worker.py run -- cargo nextest run " + selection
|
||||
('CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="python3 $(CURDIR)/scripts/e2e_catalog_worker.py ci-case --" '
|
||||
+ "python3 scripts/e2e_catalog_worker.py run -- cargo nextest run " + selection
|
||||
+ " --test-threads 1 --retries 0 --no-tests fail"),
|
||||
f"{verify} {CATALOG_FAULT_JUNIT}",
|
||||
]
|
||||
@@ -629,8 +630,8 @@ def check_catalog_fault_wiring(root: Path) -> list[str]:
|
||||
lines = (root / ".github/workflows/e2e-catalog-fault.yml").read_text().splitlines()
|
||||
require(not any("GITHUB_ENV" in line and not line.lstrip().startswith("#") for line in lines),
|
||||
"unsupported Catalog workflow environment-file mutation")
|
||||
require(yaml_block(yaml_block(lines, "on", 0) or [], "workflow_dispatch", 2) is not None,
|
||||
"missing Catalog workflow dispatch trigger")
|
||||
triggers = [line for line in yaml_block(lines, "on", 0) or [] if line.strip() and not line.lstrip().startswith("#")]
|
||||
require(triggers == [" workflow_dispatch:"], "privileged Catalog workflow requires manual dispatch")
|
||||
require(not any(re.search(r"\b(?:defaults|shell|MAKEFLAGS|MFLAGS|GNUMAKEFLAGS|MAKEFILES|BASH_ENV|ENV)\s*['\"]?:", line)
|
||||
for line in lines),
|
||||
"unsupported Catalog workflow shell override")
|
||||
@@ -6021,6 +6022,9 @@ class SelfTests(unittest.TestCase):
|
||||
("paused workflow", ".github/scheduled-validations.json", '"active"', '"paused"'),
|
||||
("wrong workflow", ".github/scheduled-validations.json", "e2e-catalog-fault.yml", "other.yml"),
|
||||
("missing trigger", ".github/workflows/e2e-catalog-fault.yml", " workflow_dispatch:", " push:"),
|
||||
("untrusted trigger", ".github/workflows/e2e-catalog-fault.yml", " workflow_dispatch:",
|
||||
" workflow_dispatch:\n pull_request_target:"),
|
||||
("missing device runner", ".github/workflows/e2e-catalog-fault.yml", "scripts/e2e_catalog_worker.py ci-case --", "other"),
|
||||
("disabled job", ".github/workflows/e2e-catalog-fault.yml", " runs-on:", " if: false\n runs-on:"),
|
||||
("disabled step", ".github/workflows/e2e-catalog-fault.yml", " run: |", " if: false\n run: |"),
|
||||
("quoted disabled step", ".github/workflows/e2e-catalog-fault.yml", " run: |", " 'if' : false\n run: |"),
|
||||
|
||||
@@ -5,6 +5,7 @@ import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
@@ -20,6 +21,11 @@ WORKER_TEST = "startup_entrypoint::tests::catalog_worker_native_lifecycle"
|
||||
RECEIPT_ENV = "RUSTFS_CATALOG_WORKER_RECEIPT"
|
||||
LAUNCHER_ENV = "RUSTFS_CATALOG_WORKER_LAUNCHER"
|
||||
ARTIFACT_ENV = "RUSTFS_CATALOG_FAULT_ARTIFACT_DIR"
|
||||
DEVICE_CASES = {
|
||||
"distributed::catalog_fault_acceptance_test::catalog_empty_directory_recovers_from_quorum",
|
||||
"distributed::catalog_fault_acceptance_test::catalog_stale_directory_cannot_replace_later_head",
|
||||
"distributed::catalog_fault_acceptance_test::catalog_replacement_directory_preserves_acknowledged_data",
|
||||
}
|
||||
NODE_ENV = {
|
||||
RECEIPT_ENV, LAUNCHER_ENV, ARTIFACT_ENV,
|
||||
"RUSTFS_VOLUMES", "RUSTFS_ADDRESS", "RUSTFS_ACCESS_KEY", "RUSTFS_SECRET_KEY",
|
||||
@@ -166,13 +172,7 @@ def verify_manifest(manifest, profile=None, requested=None):
|
||||
return record
|
||||
|
||||
|
||||
def launch(receipt_path, extra):
|
||||
if extra:
|
||||
raise ValueError("Catalog worker launcher accepts configuration through its environment only")
|
||||
worker_env = {key: value for key, value in os.environ.items() if key not in TEST_BUILD_ENV}
|
||||
unexpected = sorted(key for key in worker_env if (key.startswith("RUSTFS_") and key not in NODE_ENV) or key.startswith(("MINIO_", "OTEL_")))
|
||||
if unexpected:
|
||||
raise ValueError("Unexpected inherited Catalog worker settings: " + ", ".join(unexpected))
|
||||
def private_receipt(receipt_path):
|
||||
if os.environ.get(RECEIPT_ENV) != str(receipt_path):
|
||||
raise ValueError("Catalog worker receipt differs from the parent test invocation")
|
||||
if receipt_path.is_symlink() or stat.S_IMODE(receipt_path.stat().st_mode) != 0o600:
|
||||
@@ -183,6 +183,17 @@ def launch(receipt_path, extra):
|
||||
if not isinstance(receipt, dict) or set(receipt) != RECEIPT_KEYS or type(receipt["version"]) is not int or receipt["version"] != 1:
|
||||
raise ValueError("Invalid Catalog worker run receipt")
|
||||
uuid.UUID(receipt["run_id"])
|
||||
return receipt
|
||||
|
||||
|
||||
def launch(receipt_path, extra):
|
||||
if extra:
|
||||
raise ValueError("Catalog worker launcher accepts configuration through its environment only")
|
||||
worker_env = {key: value for key, value in os.environ.items() if key not in TEST_BUILD_ENV}
|
||||
unexpected = sorted(key for key in worker_env if (key.startswith("RUSTFS_") and key not in NODE_ENV) or key.startswith(("MINIO_", "OTEL_")))
|
||||
if unexpected:
|
||||
raise ValueError("Unexpected inherited Catalog worker settings: " + ", ".join(unexpected))
|
||||
receipt = private_receipt(receipt_path)
|
||||
manifest = Path(receipt["build_manifest_path"])
|
||||
if provenance.file_hash(manifest) != receipt["build_manifest_sha256"]:
|
||||
raise ValueError("Catalog worker build manifest changed during the test invocation")
|
||||
@@ -204,11 +215,14 @@ def launch(receipt_path, extra):
|
||||
os.execve(worker, [worker, "--exact", WORKER_TEST, "--nocapture", "--test-threads=1"], worker_env)
|
||||
|
||||
|
||||
def run(manifest, profile, requested, command):
|
||||
def run(manifest, profile, requested, command, *, device_manifest_sha256=None):
|
||||
if not command:
|
||||
raise ValueError("run requires a test command after --")
|
||||
record = verify_manifest(manifest, profile, requested)
|
||||
before_manifest = provenance.file_hash(manifest)
|
||||
device_case = device_manifest_sha256 is not None
|
||||
if device_case and before_manifest != device_manifest_sha256:
|
||||
raise ValueError("Device worker manifest differs from the suite receipt")
|
||||
with tempfile.TemporaryDirectory(prefix="catalog-worker-run-") as temporary:
|
||||
directory = Path(temporary).resolve()
|
||||
directory.chmod(0o700)
|
||||
@@ -230,11 +244,15 @@ def run(manifest, profile, requested, command):
|
||||
if ARTIFACT_ENV in os.environ:
|
||||
env[ARTIFACT_ENV] = os.environ[ARTIFACT_ENV]
|
||||
env.update({RECEIPT_ENV: str(receipt), LAUNCHER_ENV: str(launcher)})
|
||||
with subprocess.Popen(command, cwd=ROOT, env=env, start_new_session=True) as process:
|
||||
# nextest owns the individual test's process group and timeout.
|
||||
with subprocess.Popen(command, cwd=None if device_case else ROOT, env=env, start_new_session=not device_case) as process:
|
||||
try:
|
||||
status = process.wait()
|
||||
except BaseException:
|
||||
provenance.terminate_command(process)
|
||||
if device_case:
|
||||
process.kill()
|
||||
else:
|
||||
provenance.terminate_command(process)
|
||||
raise
|
||||
try:
|
||||
if (
|
||||
@@ -250,9 +268,48 @@ def run(manifest, profile, requested, command):
|
||||
return status
|
||||
|
||||
|
||||
def nextest_case(command, device_manifest_sha256):
|
||||
"""Run one hosted test under its receipt owner. Only the Linux block-device cases need root."""
|
||||
if not command:
|
||||
raise ValueError("ci-case requires a nextest command")
|
||||
binary = Path(command[0]).resolve(strict=True)
|
||||
args = command[1:]
|
||||
if device_manifest_sha256 is None and args in (["--list", "--format", "terse"], ["--list", "--format", "terse", "--ignored"]):
|
||||
os.execv(binary, command)
|
||||
if len(args) != 3 or args[0] != "--exact" or args[2] != "--nocapture":
|
||||
raise ValueError("Expected an exact nextest Catalog case")
|
||||
target = ROOT / "target"
|
||||
if binary.parent != target / "debug/deps" or not re.fullmatch(r"e2e_test-[0-9a-f]+", binary.name):
|
||||
raise ValueError("Expected the prebuilt e2e_test debug binary")
|
||||
manifest = manifest_path(target, "debug")
|
||||
if device_manifest_sha256 is not None:
|
||||
if os.geteuid() != 0 or args[1] not in DEVICE_CASES:
|
||||
raise ValueError("Only privileged device cases can adopt a suite receipt")
|
||||
# The outer run owns the suite-wide manifest lock. Create a private receipt under the device test's UID.
|
||||
return run(manifest, "debug", [], [str(binary), *args], device_manifest_sha256=device_manifest_sha256)
|
||||
if args[1] not in DEVICE_CASES or os.geteuid() == 0:
|
||||
os.execv(binary, command)
|
||||
receipt = private_receipt(Path(os.environ.get(RECEIPT_ENV, "")))
|
||||
if receipt["build_manifest_path"] != str(manifest):
|
||||
raise ValueError("Unexpected Catalog worker manifest for hosted device case")
|
||||
artifacts = Path(os.environ.get(ARTIFACT_ENV, ""))
|
||||
if not artifacts.is_absolute():
|
||||
raise ValueError("Expected an absolute Catalog artifact directory")
|
||||
artifacts.mkdir(parents=True, exist_ok=True)
|
||||
sudo = "/usr/bin/sudo"
|
||||
os.execv(sudo, [
|
||||
sudo, "-n", "--", "/usr/bin/env", "-i", "PATH=/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
"HOME=/root", "NO_PROXY=127.0.0.1,localhost,::1",
|
||||
"GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=safe.directory", f"GIT_CONFIG_VALUE_0={ROOT}",
|
||||
f"{ARTIFACT_ENV}={artifacts / 'devices'}", "/usr/bin/python3", str(Path(__file__).resolve()),
|
||||
"ci-case", "--device-manifest-sha256", receipt["build_manifest_sha256"], "--", str(binary), *args,
|
||||
])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("mode", choices=("build", "run", "launch"))
|
||||
parser.add_argument("mode", choices=("build", "run", "launch", "ci-case"))
|
||||
parser.add_argument("--device-manifest-sha256")
|
||||
parser.add_argument("--features", default="")
|
||||
parser.add_argument("--profile", choices=("debug", "release"), default="debug")
|
||||
parser.add_argument("--receipt", type=Path)
|
||||
@@ -266,6 +323,10 @@ def main():
|
||||
try:
|
||||
if os.name != "posix":
|
||||
raise ValueError("The native Catalog worker requires Unix sockets")
|
||||
if options.mode == "ci-case":
|
||||
return nextest_case(command, options.device_manifest_sha256)
|
||||
if options.device_manifest_sha256 is not None:
|
||||
raise ValueError("--device-manifest-sha256 is reserved for ci-case")
|
||||
if options.mode == "launch":
|
||||
if options.receipt is None:
|
||||
raise ValueError("launch requires a run receipt")
|
||||
|
||||
@@ -89,6 +89,71 @@ print(receipt)
|
||||
self.assertFalse(Path(result.stdout.strip()).exists())
|
||||
self.assertFalse(self.manifest.with_name(self.manifest.name + ".e2e.lock").exists())
|
||||
|
||||
def ci_case_binary(self, probe_namespace=False):
|
||||
self.build()
|
||||
binary = self.manifest.parent / "deps/e2e_test-deadbeef"
|
||||
binary.write_text(f"#!{sys.executable}\nprobe_namespace = {probe_namespace!r}\n" + '''import json, os, pathlib, subprocess, sys
|
||||
if sys.argv[1] != "--list":
|
||||
receipt = pathlib.Path(os.environ["RUSTFS_CATALOG_WORKER_RECEIPT"])
|
||||
assert receipt.stat().st_uid == os.geteuid()
|
||||
assert receipt.stat().st_mode & 0o777 == 0o600
|
||||
subprocess.run([os.environ["RUSTFS_CATALOG_WORKER_LAUNCHER"]], check=True, stdout=subprocess.DEVNULL)
|
||||
assert "RUSTFS_NOTIFY_ENDPOINT" not in os.environ
|
||||
if probe_namespace:
|
||||
child = subprocess.check_output(["unshare", "--mount", "--propagation", "private", "--", "readlink", "/proc/self/ns/mnt"], text=True)
|
||||
assert child.strip() != os.readlink("/proc/self/ns/mnt")
|
||||
print(json.dumps([os.geteuid(), sys.argv[1:], os.environ.get("RUNNER_SENTINEL"), os.environ.get("RUSTFS_CATALOG_FAULT_ARTIFACT_DIR")]))
|
||||
''')
|
||||
binary.chmod(0o755)
|
||||
return str(binary)
|
||||
|
||||
def invoke_ci_case(self, binary, *args, env=None):
|
||||
return self.invoke("run", "--", sys.executable, str(self.root / "scripts/e2e_catalog_worker.py"),
|
||||
"ci-case", "--", binary, *args, env=env)
|
||||
|
||||
def test_ci_case_lists_and_runs_ordinary_cases_as_caller(self):
|
||||
binary = self.ci_case_binary()
|
||||
case = "distributed::catalog_fault_acceptance_test::catalog_empty_directory_recovers_from_quorum_extra"
|
||||
for args in (["--list", "--format", "terse"], ["--list", "--format", "terse", "--ignored"], ["--exact", case, "--nocapture"]):
|
||||
with self.subTest(args=args):
|
||||
result = self.invoke_ci_case(binary, *args, env=dict(self.env, RUNNER_SENTINEL="present", RUSTFS_NOTIFY_ENDPOINT="unused"))
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)[:3], [os.geteuid(), args, "present"])
|
||||
device = "distributed::catalog_fault_acceptance_test::catalog_empty_directory_recovers_from_quorum"
|
||||
self.assertNotEqual(self.invoke_ci_case(binary, "--exact", device, "--include-ignored").returncode, 0)
|
||||
self.assertNotEqual(self.invoke_ci_case(sys.executable, "--exact", device, "--nocapture").returncode, 0)
|
||||
|
||||
@unittest.skipUnless(os.environ.get("CATALOG_TEST_HOSTED_SUDO") == "1", "requires a hosted Linux runner with noninteractive sudo")
|
||||
def test_ci_device_cases_create_private_root_receipts_with_clean_environment(self):
|
||||
self.assertEqual(sys.platform, "linux")
|
||||
self.assertNotEqual(os.geteuid(), 0)
|
||||
binary = self.ci_case_binary(probe_namespace=True)
|
||||
artifacts = self.root / "target/artifacts"
|
||||
env = dict(self.env, RUNNER_SENTINEL="private", RUSTFS_CATALOG_FAULT_ARTIFACT_DIR=str(artifacts))
|
||||
for name in ("catalog_empty_directory_recovers_from_quorum", "catalog_stale_directory_cannot_replace_later_head",
|
||||
"catalog_replacement_directory_preserves_acknowledged_data"):
|
||||
args = ["--exact", "distributed::catalog_fault_acceptance_test::" + name, "--nocapture"]
|
||||
with self.subTest(name=name):
|
||||
result = self.invoke_ci_case(binary, *args, env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout), [0, args, None, str(artifacts / "devices")])
|
||||
self.assertEqual(artifacts.stat().st_uid, os.geteuid())
|
||||
result = self.run_code('''import json, os, pathlib, subprocess, sys
|
||||
receipt = pathlib.Path(os.environ["RUSTFS_CATALOG_WORKER_RECEIPT"])
|
||||
original = receipt.read_text()
|
||||
record = json.loads(original)
|
||||
record["build_manifest_sha256"] = "0" * 64
|
||||
receipt.write_text(json.dumps(record))
|
||||
try:
|
||||
result = subprocess.run([sys.executable, "scripts/e2e_catalog_worker.py", "ci-case", "--", ''' + repr(binary) + ''',
|
||||
"--exact", "distributed::catalog_fault_acceptance_test::catalog_empty_directory_recovers_from_quorum",
|
||||
"--nocapture"], capture_output=True)
|
||||
assert result.returncode != 0 and b"manifest differs from the suite receipt" in result.stderr, result
|
||||
finally:
|
||||
receipt.write_text(original)
|
||||
''', env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_failed_build_removes_previous_identity(self):
|
||||
self.build()
|
||||
result = self.invoke("build", env=dict(self.env, FAKE_BUILD_FAIL="1"))
|
||||
|
||||
Reference in New Issue
Block a user