From 535ee1cdc03d3f1090296eb7415475739f5bb854 Mon Sep 17 00:00:00 2001 From: bjmeetsfo Date: Mon, 23 Nov 2026 10:36:17 -0800 Subject: [PATCH] Connect initialized object stages to replica I/O --- .github/workflows/ci.yml | 22 + CONTRIBUTING.md | 4 +- docs/native-object-state.md | 58 +- src/chunk_manifest.rs | 8 +- src/cluster/chunk_log_tests.rs | 3 + src/cluster/meta_client.rs | 10 + src/cluster/meta_consensus.rs | 31 + src/cluster/meta_message.rs | 14 + src/cluster/meta_server.rs | 19 + src/cluster/meta_wire.rs | 3 + src/cluster/mod.rs | 4 + src/cluster/native_object_client.rs | 992 +++++++++++++++++++ src/cluster/native_object_commands.rs | 613 ++++++++++++ src/cluster/native_object_path_tests.rs | 476 +++++++++ src/cluster/physical_pinned_reader_tests.rs | 221 +++++ src/cluster/published_tail_reader.rs | 246 ++++- src/initialized_log_manifest.rs | 87 +- src/initialized_log_manifest_tests.rs | 1 + src/lib.rs | 3 + src/native_object_outcome.rs | 73 +- src/native_object_outcome_tests.rs | 16 +- src/native_object_state.rs | 48 +- src/native_object_state_tests.rs | 16 +- src/physical_member_binding_tests.rs | 244 +++++ src/placement_outcome.rs | 6 +- src/protocol/metadata/snapshot_decode.inc.rs | 11 +- src/protocol/metadata/snapshot_encode.inc.rs | 2 +- src/repo_guard_tests.rs | 3 +- 28 files changed, 3177 insertions(+), 57 deletions(-) create mode 100644 src/cluster/native_object_client.rs create mode 100644 src/cluster/native_object_commands.rs create mode 100644 src/cluster/native_object_path_tests.rs create mode 100644 src/cluster/physical_pinned_reader_tests.rs create mode 100644 src/physical_member_binding_tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a37783a..018e3985 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2360,6 +2360,28 @@ jobs: grep -q '^test result: ok. 11 passed' /tmp/native-outcomes.log cargo test --locked --lib cluster::meta_snapshot_file::tests::native_journal:: -- --test-threads=1 2>&1 | tee /tmp/native-journal.log grep -q '^test result: ok. 1 passed' /tmp/native-journal.log + - name: physical metadata bindings and pinned readers + run: | + set -euo pipefail + cargo test --locked --lib physical_member_binding_tests:: -- --test-threads=1 2>&1 | tee /tmp/physical-bindings.log + grep -q '^test result: ok. 6 passed' /tmp/physical-bindings.log + cargo test --locked --lib cluster::chunk_log_tests::physical_pinned_reader_tests:: -- --test-threads=1 2>&1 | tee /tmp/physical-reader.log + grep -q '^test result: ok. 3 passed' /tmp/physical-reader.log + - name: native object RPC admission and binary receipts + run: | + set -euo pipefail + cargo test --locked --features metadata-consensus --lib native_object_commands::tests -- --test-threads=1 2>&1 | tee /tmp/native-object-rpc.log + grep -q '^test result: ok. 4 passed' /tmp/native-object-rpc.log + - name: native object Raft batches restore uncommitted state + run: | + set -euo pipefail + cargo test --locked --features metadata-consensus --lib native_object_batch_tests -- --test-threads=1 2>&1 | tee /tmp/native-object-batches.log + grep -q '^test result: ok. 1 passed' /tmp/native-object-batches.log + - name: initialized objects survive metadata and data process restarts + run: | + set -euo pipefail + cargo test --locked --features metadata-consensus --lib native_object_path_tests -- --test-threads=1 2>&1 | tee /tmp/native-object-processes.log + grep -q '^test result: ok. 1 passed; 0 failed; 1 ignored' /tmp/native-object-processes.log - name: physical storage authority and recovery run: | set -euo pipefail diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7d1081e..3b95eeb7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,10 +75,10 @@ The **network chunk consensus** job runs identity, routing, process, recovery, c capacity, shutdown, and metadata-health tests with the chunk consensus feature. The coupled quorum test additionally enables metadata consensus and starts three voters for each service. -Across these jobs, the workflow explicitly names 249 individual tests. It also +Across these jobs, the workflow explicitly names 250 individual tests. It also runs grouped library filters and integration targets. -**CI does not run the suite.** It compiles everything and runs those 249 guards plus grouped tests and integration targets. A green +**CI does not run the suite.** It compiles everything and runs those 250 guards plus grouped tests and integration targets. A green tick means the tree builds and those guards hold; it does not mean the suite passed. Run `tools/suite_gate.sh` yourself. diff --git a/docs/native-object-state.md b/docs/native-object-state.md index 6fdafcbf..1474911a 100644 --- a/docs/native-object-state.md +++ b/docs/native-object-state.md @@ -25,15 +25,15 @@ an overwrite. Renewal and removal compare the expected deadline. Snapshots encod the manifest once and carry compact per-reader records. A fresh object read still needs an authoritative current view; a cached pin alone does not provide coherence. -Metadata snapshot version 25 carries the canonical binary protobuf native-state +Metadata snapshot version 26 carries the canonical binary protobuf native-state image. Snapshot capture shares immutable state, install restores it, checksums bind its contents and cache stamps track native revisions. Validation rejects future allocation positions, shared native storage across objects, overlapping staged storage and conflicting ownership across manifest catalogs. Earlier snapshots keep their existing representation when the feature is absent. -Placement outcome version 18 carries one canonical binary protobuf native command. -It binds the leader's captured clock and consecutive metadata positions. Begin, +Placement outcome version 19 carries one canonical binary protobuf native command. +Version 19 carries native change version 2 and requires physical identities for new stages and chunks. Historical outcome18/change1 and format2 snapshots remain readable, but cannot mutate a physical namespace. It binds the leader's captured clock and consecutive metadata positions. Begin, extend, publish, abort, expiry, read-pin and writer-lease transitions validate private persistent-table clones before replacing live tables together. The leader checks admission limits; followers validate the committed transition without local limits. @@ -43,7 +43,51 @@ Journal recovery checks checksums, canonical encoding and contiguous positions, skips the prefix included in its starting snapshot and applies later commands. Normal command application continues to reject stale positions. -Feature bit 7 is not advertised or raised by startup. RPC admission, actual read-pin -acquisition, storage retirement, conditional object operations and default-backend -routing still need their coupled implementation. The default object backend remains -unchanged. +Feature bit 7 is not advertised or raised by startup. The guarded command and +client path now connects durable stage allocation, initialized data writes, +publication and authoritative read-pin acquisition. Ordinary deployments cannot +activate this experimental path. The default object backend remains paged. + +`NativeObjectClient` uses metadata-approved three-member Star routes and physical +storage incarnations. Stage creation assigns the leader's clock and allocation +positions. Requests carry a separate TTL; clients cannot choose committed epochs +or absolute deadlines. The metadata journal and replicated command path use the +same binary protobuf outcomes. Raft batch preparation restores all native draft +tables before proposals commit. + +`NativeTailWriter` contacts data members for steady appends, requiring all three +durable replies. It retains the original attempt and at most one record fragment +on an unsettled request. Intermediate fragments keep the earlier complete-prefix +marker; only the final fragment publishes the complete append. A correlated +successful APPEND reply acknowledges its original tagged request. Probe lengths, +uncertain exchanges and equal bytes from another attempt cannot acknowledge it. +Lease deadlines are derived conservatively from the leader clock and local +monotonic time. Fencing stops further writes from the old writer. + +A six-process test uses three metadata voters and three separate data processes. +It writes sealed chunks and an active tail, verifies 64 appends with no metadata +commits, retries the original attempt after losing a member, rejects a foreign +equal-byte attempt and a released read pin, then verifies every byte after +restarting all six processes. This fixture explicitly seeds the guarded feature; +it does not prove default activation or TemporalStore end-to-end latency. + +Writer handoff/reopen and automatic chunk switching, active-object replacement, +data-derived version and modification-time attributes, storage retirement, +namespace migration, the complete object API and TemporalStore routing remain +unfinished. The network command rejects an active-tail replacement until its +storage handoff is implemented. + +Physical member bindings use manifest format 3 and contain each replica's durable +storage incarnation in configured member order. Format 2 forbids those fields; +format 3 requires distinct nonzero physical identities. Native state images use +inner version 2 when physical bindings are retained or staged. Snapshot floor 26 +prevents older readers from dropping those identities; downgraded envelopes are +refused even when their outer checksums are valid. + +A read pin resolves an immutable physical binding for one extent, with work bounded +by its three members. The protocol5 pinned reader checks physical identities on +probes, record identity inspection, repair writes and payload reads. It never +initializes, fences or truncates a member. Old pins do not accept a higher observed +epoch as newly authorized. The native client acquires and revalidates actual +metadata pins. Sealed reads also check the metadata footer. Effective epoch updates +through writer handoff and the full object API remain unfinished. diff --git a/src/chunk_manifest.rs b/src/chunk_manifest.rs index 585d552f..6e28d0ef 100644 --- a/src/chunk_manifest.rs +++ b/src/chunk_manifest.rs @@ -18,8 +18,8 @@ //! * `CHUNK_KIND_LOG`: an append-only chunk of up to 512 MiB written under a writer lease, which //! starts at chunk byte zero. Only the last extent may still be open. //! -//! This module holds the types, the validation rules and the framed encoding. Nothing publishes or -//! reads this manifest yet. +//! This module holds the types, validation rules and framed encoding. Catalog commands and +//! data clients publish and read manifests through their respective storage-kind paths. use crate::object_manifest::{frame, unframe}; use crate::{ChunkId, ObjectError, ObjectId}; use prost::Message; @@ -311,7 +311,7 @@ impl ChunkManifest { pub fn validate(&self) -> Result<(), ObjectError> { crate::validate_bucket(&self.bucket)?; crate::validate_key(&self.key)?; - if !matches!(self.format_version, CHUNK_MANIFEST_FORMAT | crate::initialized_log_manifest::CHUNK_MANIFEST_INITIALIZED_FORMAT) + if !matches!(self.format_version, CHUNK_MANIFEST_FORMAT | crate::initialized_log_manifest::CHUNK_MANIFEST_INITIALIZED_FORMAT | crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT) || self.generation == 0 || self.extents.len() > MAX_CHUNK_EXTENTS || self.encoded_len() > MAX_CHUNK_MANIFEST @@ -320,7 +320,7 @@ impl ChunkManifest { } match (&self.initialized_log, self.format_version) { (None, CHUNK_MANIFEST_FORMAT) => {} - (Some(initialized), crate::initialized_log_manifest::CHUNK_MANIFEST_INITIALIZED_FORMAT) => initialized.validate_for(self)?, + (Some(initialized), crate::initialized_log_manifest::CHUNK_MANIFEST_INITIALIZED_FORMAT | crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT) => initialized.validate_for(self)?, _ => return Err(invalid("chunk manifest initialization fields do not match its version")), } if self.deleted { diff --git a/src/cluster/chunk_log_tests.rs b/src/cluster/chunk_log_tests.rs index 33394415..3c2a0bd7 100644 --- a/src/cluster/chunk_log_tests.rs +++ b/src/cluster/chunk_log_tests.rs @@ -874,3 +874,6 @@ mod initialized_member_binding_tests; #[path = "storage_incarnation_tests.rs"] mod storage_incarnation_tests; + +#[path="physical_pinned_reader_tests.rs"] +mod physical_pinned_reader_tests; diff --git a/src/cluster/meta_client.rs b/src/cluster/meta_client.rs index 60d510f6..e88f75bb 100644 --- a/src/cluster/meta_client.rs +++ b/src/cluster/meta_client.rs @@ -326,6 +326,16 @@ impl RemoteMetaClient { other => Err(unexpected_reply("a cluster feature set", &other)), } } + /// One recoverable stage or read-pin operation. Mutations are never replayed after + /// an uncertain exchange; query the original stage or pinned view to resolve it. + pub fn native_object(&mut self, request: super::native_object_commands::NativeObjectRequest) -> Result { + request.validate()?; + match self.call(MetaRequest::NativeObject(request))? { + MetaReply::NativeObject(reply) => Ok(reply), + other => Err(unexpected_reply("a native object reply", &other)), + } + } + /// Lease `bucket/key` for log writing to `holder` and, if no chunk is open, open one in `group`. pub fn grant_log_chunk(&mut self, bucket: &str, key: &str, holder: &str, ttl_ms: u64, group: &str) -> Result { self.log_chunk_call(super::LogChunkRequest::grant(bucket, key, holder, ttl_ms, group)) diff --git a/src/cluster/meta_consensus.rs b/src/cluster/meta_consensus.rs index 7a0c5ff3..d0d30c1f 100644 --- a/src/cluster/meta_consensus.rs +++ b/src/cluster/meta_consensus.rs @@ -794,6 +794,7 @@ fn read_only(request: &MetaRequest) -> bool { MetaRequest::Membership(command) => command.is_read(), MetaRequest::Features(command) => command.is_read(), MetaRequest::LogChunk(command) => command.is_read(), + MetaRequest::NativeObject(command) => command.is_read(), MetaRequest::ReadManifest { .. } | MetaRequest::ReadManifestRoutes { .. } | MetaRequest::ReadManifestRoutesWide { .. } @@ -1523,7 +1524,11 @@ fn prepare_batch( .into_iter() .filter(|id| service.nodes.contains_key(id)) .collect(); + let native = queued.iter().any(|r| matches!(&r.request, MetaRequest::NativeObject(c) if !c.is_read())).then(|| ( + service.native_objects.clone(), service.chunk_catalog.clone(), service.writer_leases.clone(), + )); let mut draft = PlacementDraft::with_records(service, nodes, objects.into_iter().collect()); + draft.native = native; draft.chunks = chunk_keys.into_iter().map(|id| { let entry = draft.service.chunk_catalog.entry(&id); (id, entry) @@ -1728,6 +1733,12 @@ fn prepare_with_inner( }); } } + if let MetaRequest::NativeObject(command) = request { + if !command.is_read() { + let (outcome, reply) = super::native_object_commands::prepare(service, groups, command, limit, super::staged_lease_sweeper::now_ms()?)?; + return Ok((outcome.to_payload()?, Some(reply))); + } + } if let MetaRequest::LogChunk(command) = request { if !command.is_read() { return Ok( @@ -1865,6 +1876,7 @@ fn log_chunk_records( /// Undo state for the closed set of placement mutations admitted by `prepare`. /// Never use this for membership, health reports, or other metadata operations. struct PlacementDraft<'a> { + native: Option<(crate::native_object_state::NativeObjectState, crate::chunk_catalog::ChunkCatalog, crate::log_chunk_outcome::WriterLeaseTable)>, chunks: Vec<(crate::ObjectId, Option>)>, chunk_revision: u64, service: &'a mut MatrixMetaService, @@ -1918,6 +1930,7 @@ impl<'a> PlacementDraft<'a> { let features = service.cluster_features.clone(); let chunk_revision = service.chunk_catalog.revision(); Self { + native: None, chunks: Vec::new(), chunk_revision, service, @@ -1973,6 +1986,11 @@ impl Drop for PlacementDraft<'_> { for (id, entry) in self.chunks.drain(..) { self.service.chunk_catalog.restore_entry(&id, entry, self.chunk_revision); } + if let Some((state, catalog, leases)) = self.native.take() { + self.service.native_objects = state; + self.service.chunk_catalog = catalog; + self.service.writer_leases = leases; + } self.service.placement_commit_index = self.index; self.service.invalidate_snapshot_export_cache(); } @@ -4376,3 +4394,16 @@ mod read_failure_tests { } } } + +#[cfg(test)] +mod native_object_batch_tests { + use super::*; + #[test] + fn native_stage_batches_restore_every_live_table_before_committed_replay() { + let mut leader=crate::native_object_outcome_tests::service();let before=leader.export_snapshot().to_bytes().unwrap();let mut followers=[leader.clone(),leader.clone(),leader.clone()]; + let mut queued:VecDeque<_>=["a","b"].into_iter().map(|key|{let (reply,_receiver)=mpsc::sync_channel(1);Request{request:MetaRequest::NativeObject(super::super::native_object_commands::tests::begin_request(key)),reply,deadline:Instant::now()+Duration::from_secs(30),progress:RequestProgress::new(false)}}).collect(); + let membership=matrixraft::peer_runtime::MembershipState{voters:vec![1],outgoing_voters:vec![],learners:vec![],next_learners:vec![],auto_leave:false};let (payloads,prepared)=prepare_batch(&mut leader,&super::super::ChunkGroupCatalog::default(),1<<20,&mut queued,None,&membership).unwrap();assert_eq!(payloads.len(),2);assert!(prepared.iter().all(|(_,reply)|matches!(reply,Some(Ok(MetaReply::NativeObject(_))))));assert_eq!(leader.export_snapshot().to_bytes().unwrap(),before); + for follower in &mut followers {for payload in &payloads {let entry=Entry::decode(payload.as_slice()).unwrap();PlacementOutcome::from_payload(&entry.outcome).unwrap().apply(follower).unwrap();}assert_eq!(follower.native_objects.stage_count(),2);assert_eq!(follower.placement_commit_index,3);} + assert_eq!(followers[0].export_snapshot().to_bytes().unwrap(),followers[1].export_snapshot().to_bytes().unwrap());assert_eq!(followers[1].export_snapshot().to_bytes().unwrap(),followers[2].export_snapshot().to_bytes().unwrap()); + } +} diff --git a/src/cluster/meta_message.rs b/src/cluster/meta_message.rs index 1156a5a7..4544aa5b 100644 --- a/src/cluster/meta_message.rs +++ b/src/cluster/meta_message.rs @@ -209,6 +209,7 @@ pub fn object_id(bucket: &str, key: &str) -> ObjectId { pub enum MetaRequest { Features(super::features_commands::FeaturesRequest), LogChunk(super::log_chunk_commands::LogChunkRequest), + NativeObject(super::native_object_commands::NativeObjectRequest), PublishChunkManifest(crate::chunk_catalog::ChunkOutcome), ReadChunkManifest { bucket: String, @@ -347,6 +348,7 @@ impl MetaRequest { MetaRequest::StagedAllocation(_) => MetaRequestCode::StagedAllocation, MetaRequest::Features(_) => MetaRequestCode::Features, MetaRequest::LogChunk(_) => MetaRequestCode::LogChunk, + MetaRequest::NativeObject(_) => MetaRequestCode::NativeObject, MetaRequest::PublishChunkManifest(_) => MetaRequestCode::PublishChunkManifest, MetaRequest::ReadChunkManifest { .. } => MetaRequestCode::ReadChunkManifest, MetaRequest::ListChunkManifests(_) => MetaRequestCode::ListChunkManifests, @@ -432,6 +434,7 @@ impl MetaRequest { MetaRequest::StagedAllocation(request) => return request.encode_to_vec(), MetaRequest::Features(request) => return request.encode_to_vec(), MetaRequest::LogChunk(request) => return request.encode_to_vec(), + MetaRequest::NativeObject(request) => return request.encode_to_vec(), // An outcome that cannot be framed encodes to nothing, which the server refuses by name. MetaRequest::PublishChunkManifest(outcome) => return outcome.to_bytes().unwrap_or_default(), MetaRequest::PlanAppendRoutes(request) => return request.encode_to_vec(), @@ -601,6 +604,9 @@ impl MetaRequest { if code == MetaRequestCode::Features { return super::features_commands::FeaturesRequest::from_payload(payload).map(Self::Features); } + if code == MetaRequestCode::NativeObject { + return super::native_object_commands::NativeObjectRequest::from_payload(payload).map(Self::NativeObject); + } if code == MetaRequestCode::LogChunk { return super::log_chunk_commands::LogChunkRequest::from_payload(payload).map(Self::LogChunk); } @@ -752,6 +758,7 @@ impl MetaRequest { | MetaRequestCode::StagedAllocation | MetaRequestCode::Features | MetaRequestCode::LogChunk + | MetaRequestCode::NativeObject | MetaRequestCode::PlanAppendRoutes | MetaRequestCode::ReportChunkNode | MetaRequestCode::AllocateObjectPages @@ -929,6 +936,7 @@ pub enum MetaReply { StagedAllocation(crate::staged_allocation::StagedAllocationReply), Features(crate::placement_outcome::FeatureTable), LogChunk(super::log_chunk_commands::LogChunkReply), + NativeObject(super::native_object_commands::NativeObjectReply), /// The manifest a chunk publication left in the catalog. ChunkManifest(crate::chunk_manifest::ChunkManifest), AppendPlan(super::append_plan::AppendPlanReply), @@ -999,6 +1007,7 @@ impl MetaReply { Self::StagedAllocation(reply) => reply.encoded_len(), Self::Features(reply) => reply.encoded_len(), Self::LogChunk(reply) => reply.encoded_len(), + Self::NativeObject(reply) => reply.encoded_len(), Self::ChunkManifest(manifest) => manifest.to_bytes().map_or(0, |bytes| bytes.len()), Self::AppendPlan(reply) => reply.encoded_len(), Self::PlacementNode(node) => node_payload_len( @@ -1068,6 +1077,7 @@ impl MetaReply { MetaReply::StagedAllocation(reply) => return reply.encode_to_vec(), MetaReply::Features(reply) => return reply.encode_to_vec(), MetaReply::LogChunk(reply) => return reply.encode_to_vec(), + MetaReply::NativeObject(reply) => return reply.encode_to_vec(), MetaReply::ChunkManifest(manifest) => return manifest.to_bytes().unwrap_or_default(), MetaReply::AppendPlan(reply) => return reply.encode_to_vec(), MetaReply::PlacementNode(node) => put_node(&mut out, node), @@ -1280,6 +1290,9 @@ impl MetaReply { if code == MetaRequestCode::Features { return super::features_commands::reply_from_payload(payload).map(Self::Features); } + if code == MetaRequestCode::NativeObject { + return super::native_object_commands::NativeObjectReply::from_payload(payload).map(Self::NativeObject); + } if code == MetaRequestCode::LogChunk { return super::log_chunk_commands::reply_from_payload(payload).map(Self::LogChunk); } @@ -1327,6 +1340,7 @@ impl MetaReply { | MetaRequestCode::StagedAllocation | MetaRequestCode::Features | MetaRequestCode::LogChunk + | MetaRequestCode::NativeObject | MetaRequestCode::PublishChunkManifest | MetaRequestCode::ReadChunkManifest | MetaRequestCode::ListChunkManifests diff --git a/src/cluster/meta_server.rs b/src/cluster/meta_server.rs index 63b59f12..0c82be1f 100644 --- a/src/cluster/meta_server.rs +++ b/src/cluster/meta_server.rs @@ -875,6 +875,12 @@ fn apply( } None => return Ok(super::features_commands::reply(&guard.service.cluster_features)), }, + MetaRequest::NativeObject(command) if !command.is_read() => { + if guard.storage.is_none() { + return Err(ObjectError::PreconditionFailed("native object mutation requires durable metadata storage".into())); + } + Some(super::native_object_commands::prepare(&guard.service, &guard.groups, command, max_payload_bytes, super::staged_lease_sweeper::now_ms()?)?) + } MetaRequest::LogChunk(command) if !command.is_read() => { match super::log_chunk_commands::prepare(&guard.service, &guard.groups, command, super::staged_lease_sweeper::now_ms()?)? { super::log_chunk_commands::Decision::Change(outcome, reply) => Some((outcome, reply)), @@ -1217,6 +1223,13 @@ pub(super) fn apply_with_groups( super::chunk_manifest_command::Decision::Unchanged(manifest) => Ok(MetaReply::ChunkManifest(manifest)), }; } + if let MetaRequest::NativeObject(command) = &request { + if !command.is_read() { + let (outcome, reply) = super::native_object_commands::prepare(service, groups, command, limit, super::staged_lease_sweeper::now_ms()?)?; + outcome.apply(service)?; + return Ok(reply); + } + } if let MetaRequest::LogChunk(command) = &request { if !command.is_read() { return match super::log_chunk_commands::prepare(service, groups, command, super::staged_lease_sweeper::now_ms()?)? { @@ -1476,6 +1489,8 @@ pub(super) fn apply_to_meta( match request { MetaRequest::Features(command) if command.is_read() => super::features_commands::read(guard, &command), MetaRequest::Features(_) => Err(ObjectError::InvalidArgument("feature changes require catalog dispatch".into())), + MetaRequest::NativeObject(command) if command.is_read() => super::native_object_commands::read(guard, &command, max_payload_bytes, super::staged_lease_sweeper::now_ms()?), + MetaRequest::NativeObject(_) => Err(ObjectError::InvalidArgument("native object mutations require catalog dispatch".into())), MetaRequest::LogChunk(command) if command.is_read() => super::log_chunk_commands::read(guard, &command), MetaRequest::LogChunk(_) => Err(ObjectError::InvalidArgument("log chunk changes require catalog dispatch".into())), MetaRequest::PublishChunkManifest(_) => Err(ObjectError::InvalidArgument("chunk manifest publication requires durable dispatch".into())), @@ -2283,3 +2298,7 @@ mod snapshot_bound_tests { assert!(bound.admits_without_measuring(1)); } } + +#[cfg(all(test, feature = "metadata-consensus"))] +#[path = "native_object_path_tests.rs"] +mod native_object_path_tests; diff --git a/src/cluster/meta_wire.rs b/src/cluster/meta_wire.rs index 448e9218..4708286e 100644 --- a/src/cluster/meta_wire.rs +++ b/src/cluster/meta_wire.rs @@ -121,6 +121,7 @@ pub enum MetaRequestCode { ReadManifestRange = 100, /// List a page of the chunk manifest catalog. ListChunkManifests = 101, + NativeObject = 102, } impl MetaRequestCode { @@ -168,6 +169,7 @@ impl MetaRequestCode { 99 => Some(MetaRequestCode::ReadChunkManifest), 100 => Some(MetaRequestCode::ReadManifestRange), 101 => Some(MetaRequestCode::ListChunkManifests), + 102 => Some(MetaRequestCode::NativeObject), _ => None, } } @@ -208,6 +210,7 @@ impl MetaRequestCode { MetaRequestCode::PlanAppendRoutes, MetaRequestCode::Features, MetaRequestCode::LogChunk, + MetaRequestCode::NativeObject, MetaRequestCode::PublishChunkManifest, MetaRequestCode::ReadChunkManifest, MetaRequestCode::ReadManifestRange, diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs index 4c1c0847..0e9f3f97 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -364,3 +364,7 @@ pub use wal_zero_fill::{ validate_wal_zero_fill_bytes, wal_zero_fill_from_env, WAL_ZERO_FILL_ENV, WAL_ZERO_FILL_MAX_BYTES, WAL_ZERO_FILL_MIN_BYTES, }; + +pub mod native_object_commands; + +pub mod native_object_client; diff --git a/src/cluster/native_object_client.rs b/src/cluster/native_object_client.rs new file mode 100644 index 00000000..ebb8709c --- /dev/null +++ b/src/cluster/native_object_client.rs @@ -0,0 +1,992 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +//! Recoverable initialized object I/O. This client does not select the gateway backend. +use super::native_object_commands::{NativeObjectRead, NativeObjectReply, NativeObjectRequest}; +use super::{ + AppendIdentity, ChunkGroupConfig, ChunkLogError, ChunkLogReader, LogCallError, LogOpReply, + LogOpRequest, MetaCallOutcome, MetaReply, MetaRequest, RemoteMetaClient, RemoteReplicaClient, + ReplicaClientOptions, SealedFooter, +}; +use crate::chunk_manifest::{ + ChunkExtent, ChunkManifest, CHUNK_FLAG_SEALED, CHUNK_FLAG_TAIL, CHUNK_KIND_LOG, +}; +use crate::initialized_log_manifest::{ + InitializedChunk, InitializedLogManifest, InitializedReplica, PhysicalMemberBinding, + CHUNK_MANIFEST_PHYSICAL_FORMAT, +}; +use crate::native_object_outcome::{ + native_operation::Operation, NativeBegin, NativeExtend, NativePublish, NativeStageRef, +}; +use crate::native_object_state::{ + NativeOwnedChunk, NativeReadPin, NativeStageStart, STAGE_REPLACE, +}; +use crate::ObjectError; +use std::time::{Duration, Instant}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NativeObjectError { + Refused(ObjectError), + Data(ChunkLogError), + /// Keep the original nonce, stage and append identity. Do not create a new attempt. + Unknown(ObjectError), +} +impl std::fmt::Display for NativeObjectError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Refused(error) => write!(formatter, "{error}"), + Self::Data(error) => write!(formatter, "{error}"), + Self::Unknown(error) => { + write!(formatter, "native operation outcome is unknown: {error}") + } + } + } +} +impl std::error::Error for NativeObjectError {} +impl From for NativeObjectError { + fn from(e: ObjectError) -> Self { + Self::Refused(e) + } +} +impl From for NativeObjectError { + fn from(e: ChunkLogError) -> Self { + Self::Data(e) + } +} +impl From for NativeObjectError { + fn from(e: LogCallError) -> Self { + match e { + LogCallError::Transport(e) => Self::Unknown(e), + e => Self::Data(e.into()), + } + } +} +fn invalid(message: &str) -> ObjectError { + ObjectError::InvalidArgument(message.into()) +} + +#[derive(Clone, Debug)] +pub struct NativeStageHandle { + pub start: NativeStageStart, + pub revision: u64, + pub chunks: Vec, +} +#[derive(Clone, Debug)] +pub struct NativePublishedObject { + pub manifest: ChunkManifest, + start: NativeStageStart, + deadline: Instant, +} +#[derive(Clone, Debug)] +pub struct NativePinnedObject { + pub manifest: ChunkManifest, + pin: NativeReadPin, +} +/// Metadata is contacted at object/chunk transitions and read-pin boundaries, not for +/// every append to a leased initialized tail. +pub struct NativeObjectClient { + meta: RemoteMetaClient, + replica: ReplicaClientOptions, + chunk_bytes: u64, +} +impl NativeObjectClient { + pub fn new(meta: RemoteMetaClient, replica: ReplicaClientOptions) -> Self { + Self { + meta, + replica, + chunk_bytes: 64 * 1024 * 1024, + } + } + pub fn with_chunk_bytes(mut self, bytes: u64) -> Result { + if bytes == 0 || bytes > 512 * 1024 * 1024 { + return Err(invalid("native chunk capacity is out of range")); + } + self.chunk_bytes = bytes; + Ok(self) + } + fn call( + &mut self, + request: NativeObjectRequest, + ) -> Result<(NativeObjectReply, Instant), NativeObjectError> { + request.validate()?; + let sent = Instant::now(); + let read = request.is_read(); + match self.meta.try_call(MetaRequest::NativeObject(request)) { + MetaCallOutcome::Answered(MetaReply::NativeObject(reply)) => Ok((reply, sent)), + MetaCallOutcome::Answered(_) => Err(NativeObjectError::Unknown( + ObjectError::Corruption("unexpected native object reply".into()), + )), + MetaCallOutcome::Refused(e) if read => Err(NativeObjectError::Refused(e)), + MetaCallOutcome::Refused(e) | MetaCallOutcome::Unreachable(e) => { + Err(NativeObjectError::Unknown(e)) + } + } + } + pub fn metadata_position(&mut self) -> Result { + Ok(self + .call(NativeObjectRequest::query(NativeObjectRead { + kind: 4, + ..Default::default() + }))? + .0 + .commit_index) + } + /// Begin a replacement in an explicitly owned chunk-catalog namespace. The original + /// nonce identifies recovery; publication keeps any current object visible until commit. + pub fn begin( + &mut self, + bucket: &str, + key: &str, + holder: &str, + nonce: [u8; 32], + length: u64, + expected: Option<&ChunkManifest>, + ttl_ms: u64, + ) -> Result { + let generation = expected + .map_or(0, |m| m.generation) + .checked_add(1) + .ok_or_else(|| invalid("object generation exhausted"))?; + if expected.is_some_and(|m| m.bucket != bucket || m.key != key) { + return Err(invalid("expected object names differ").into()); + } + let mut header = ChunkManifest { + format_version: CHUNK_MANIFEST_PHYSICAL_FORMAT, + bucket: bucket.into(), + key: key.into(), + generation, + kind: CHUNK_KIND_LOG, + initialized_log: Some(InitializedLogManifest::default()), + ..Default::default() + }; + if let Some(before) = expected { + crate::chunk_manifest::ChunkAttributes::of(before).put_on(&mut header); + } + let start = NativeStageStart { + kind: STAGE_REPLACE, + header: Some(header), + holder: holder.into(), + request_nonce: nonce.to_vec(), + target_length: length, + expected_generation: generation - 1, + expected_manifest_digest: expected + .map(|m| { + m.to_bytes() + .map(|b| crate::chunk_integrity::sha256(&b).to_vec()) + }) + .transpose()? + .unwrap_or_default(), + ..Default::default() + }; + let reply = self + .call(NativeObjectRequest::mutation( + Operation::Begin(NativeBegin { + start: Some(start), + ..Default::default() + }), + ttl_ms, + ))? + .0; + Ok(NativeStageHandle { + start: reply + .start + .ok_or_else(|| invalid("native begin omitted its stage"))?, + revision: reply.stage_revision, + chunks: reply.chunks, + }) + } + pub fn recover_stage( + &mut self, + bucket: &str, + key: &str, + holder: &str, + nonce: [u8; 32], + ) -> Result { + let reply = self + .call(NativeObjectRequest::query(NativeObjectRead { + kind: 1, + bucket: bucket.into(), + key: key.into(), + holder: holder.into(), + request_nonce: nonce.to_vec(), + ..Default::default() + }))? + .0; + Ok(NativeStageHandle { + start: reply + .start + .ok_or_else(|| invalid("native query omitted its stage"))?, + revision: reply.stage_revision, + chunks: reply.chunks, + }) + } + fn group(&mut self, id: &str) -> Result { + let route = self.meta.read_chunk_route(id)?; + let (endpoints, quorum) = route + .standalone_star_route()? + .ok_or_else(|| invalid("native object writes require a Star group"))?; + let group = route.group.unwrap(); + if quorum != 3 || endpoints.len() != 3 || group.member_ids.len() != 3 { + return Err(invalid("native object writes require three durable members").into()); + } + Ok(group) + } + pub fn allocate( + &mut self, + stage: &mut NativeStageHandle, + group_id: &str, + length: u64, + ) -> Result { + if length == 0 || length > self.chunk_bytes { + return Err(invalid("allocation exceeds configured native chunk capacity").into()); + } + let group = self.group(group_id)?; + let mut replicas = Vec::with_capacity(3); + for (id, endpoint) in group.member_ids.iter().zip(&group.api_endpoints) { + let mut client = RemoteReplicaClient::connect(endpoint, &self.replica)?; + let probe = client.log_call(LogOpRequest::storage_probe())?; + let root = probe + .storage_incarnation() + .ok_or_else(|| invalid("storage probe omitted its incarnation"))?; + if !probe.has_storage_write_protocol(root) { + return Err(invalid("storage publication writes are unavailable").into()); + } + replicas.push(InitializedReplica { + member_id: id.clone(), + storage_incarnation: root.to_vec(), + ..Default::default() + }); + } + let offset = stage + .chunks + .last() + .map_or(Ok(stage.start.base_length), |c| { + c.extent + .as_ref() + .unwrap() + .object_offset + .checked_add(c.extent.as_ref().unwrap().length) + .ok_or_else(|| invalid("stage offset overflow")) + })?; + let owned = NativeOwnedChunk { + extent: Some(ChunkExtent { + group: group_id.into(), + kind: CHUNK_KIND_LOG, + object_offset: offset, + length, + ..Default::default() + }), + initialization: Some(InitializedChunk { + extent_index: stage + .chunks + .len() + .try_into() + .map_err(|_| invalid("too many chunks"))?, + replicas, + ..Default::default() + }), + ..Default::default() + }; + let reply = self + .call(NativeObjectRequest::mutation( + Operation::Extend(NativeExtend { + stage: Some(stage.reference()), + chunk: Some(owned), + }), + 0, + ))? + .0; + let owned = reply + .chunks + .into_iter() + .next() + .ok_or_else(|| invalid("native extension omitted its allocation"))?; + stage.revision = reply.stage_revision; + stage.chunks.push(owned.clone()); + Ok(owned) + } + pub fn write_chunk( + &mut self, + stage: &NativeStageHandle, + owned: &NativeOwnedChunk, + data: &[u8], + attempt: [u8; 16], + ) -> Result<(), NativeObjectError> { + let extent = owned + .extent + .as_ref() + .ok_or_else(|| invalid("chunk range is missing"))?; + if extent.length != data.len() as u64 || !stage.chunks.iter().any(|c| c == owned) { + return Err(invalid("payload does not name an owned stage range").into()); + } + let group = self.group(&extent.group)?; + let binding = owned.initialization.as_ref().unwrap(); + let mut clients = Vec::with_capacity(3); + let mut capacity = super::log_op::MAX_OP_DATA; + for (i, endpoint) in group.api_endpoints.iter().enumerate() { + let root: [u8; 16] = binding.replicas[i] + .storage_incarnation + .as_slice() + .try_into() + .map_err(|_| invalid("invalid storage incarnation"))?; + let init: [u8; 16] = binding.replicas[i] + .initialization + .as_slice() + .try_into() + .map_err(|_| invalid("invalid storage initialization"))?; + let mut client = RemoteReplicaClient::connect(endpoint, &self.replica)?; + let reply = client.log_call( + LogOpRequest::initialize_publication( + extent.volume_id, + extent.chunk_id, + binding.chunk_generation, + binding.writer_epoch, + init, + ) + .for_storage(root, init), + )?; + check_member(&reply, root, init, binding.writer_epoch)?; + capacity = capacity.min(capacity_of(&reply, &self.replica)?); + clients.push(client); + } + let identity = AppendIdentity { + object_incarnation: stage + .start + .header()? + .initialized_log + .as_ref() + .unwrap() + .object_incarnation + .as_slice() + .try_into() + .map_err(|_| invalid("invalid object incarnation"))?, + attempt_id: attempt, + request_offset: 0, + request_length: stage.start.target_length, + }; + for (part, body) in data.chunks(capacity).enumerate() { + let offset = (part * capacity) as u64; + let end = offset + body.len() as u64; + let tag = identity.record_tag( + extent.volume_id, + extent.chunk_id, + binding.chunk_generation, + offset, + extent.object_offset + offset, + body.len() as u32, + )?; + for (i, client) in clients.iter_mut().enumerate() { + let root = binding.replicas[i] + .storage_incarnation + .as_slice() + .try_into() + .unwrap(); + let init = binding.replicas[i] + .initialization + .as_slice() + .try_into() + .unwrap(); + let reply = client.log_call( + LogOpRequest::append_published( + extent.volume_id, + extent.chunk_id, + binding.chunk_generation, + binding.writer_epoch, + offset, + body.to_vec(), + tag, + end, + init, + ) + .for_storage(root, init), + )?; + check_append( + &reply, + root, + init, + binding.writer_epoch, + offset, + body.len() as u32, + tag, + end, + )?; + } + } + Ok(()) + } + pub fn publish( + &mut self, + stage: &NativeStageHandle, + open_tail: bool, + ) -> Result { + let mut manifest = stage.start.header()?.clone(); + manifest.length = stage.start.target_length; + for (index, owned) in stage.chunks.iter().enumerate() { + let mut extent = owned.extent.as_ref().unwrap().clone(); + let binding = owned.initialization.as_ref().unwrap(); + let group = self.group(&extent.group)?; + let tail = open_tail && index + 1 == stage.chunks.len(); + let mut footer = None; + for (i, endpoint) in group.api_endpoints.iter().enumerate() { + let root = binding.replicas[i] + .storage_incarnation + .as_slice() + .try_into() + .unwrap(); + let init = binding.replicas[i] + .initialization + .as_slice() + .try_into() + .unwrap(); + let mut client = RemoteReplicaClient::connect(endpoint, &self.replica)?; + let op = if tail { + LogOpRequest::publication_probe( + extent.volume_id, + extent.chunk_id, + binding.chunk_generation, + ) + } else { + LogOpRequest::seal_publication( + extent.volume_id, + extent.chunk_id, + binding.chunk_generation, + binding.writer_epoch, + init, + false, + ) + }; + let reply = client.log_call(op.for_storage(root, init))?; + check_member(&reply, root, init, binding.writer_epoch)?; + if reply.published_length != extent.length + || reply.durable_length != extent.length + || (!tail && !reply.sealed) + { + return Err( + invalid("stage publication lacks every durable complete chunk").into(), + ); + } + if !tail { + let current = SealedFooter { + length: reply.length, + crc: reply.crc, + sha256: reply.sha256, + }; + if footer.as_ref().is_some_and(|f| f != ¤t) { + return Err(invalid("sealed stage footers differ").into()); + } + footer = Some(current); + } + } + extent.flags = if tail { + CHUNK_FLAG_TAIL + } else { + CHUNK_FLAG_SEALED + }; + if let Some(footer) = footer { + extent.footer_crc = footer.crc; + extent.footer_sha256 = footer.sha256; + } + manifest.extents.push(extent); + manifest + .initialized_log + .as_mut() + .unwrap() + .chunks + .push(binding.clone()); + } + manifest.validate()?; + let (reply, sent) = self.call(NativeObjectRequest::mutation( + Operation::Publish(NativePublish { + stage: Some(stage.reference()), + manifest: Some(manifest), + expected_lease: None, + }), + 0, + ))?; + let remaining = stage.start.expires_at_ms.saturating_sub(reply.now_ms); + let deadline = sent + .checked_add(Duration::from_millis(remaining)) + .ok_or_else(|| invalid("lease deadline overflow"))?; + Ok(NativePublishedObject { + manifest: reply + .manifest + .ok_or_else(|| invalid("native publication omitted its object"))?, + start: stage.start.clone(), + deadline, + }) + } + pub fn writer( + &mut self, + published: &NativePublishedObject, + ) -> Result { + let manifest = &published.manifest; + let index = manifest + .extents + .len() + .checked_sub(1) + .ok_or_else(|| invalid("empty object has no tail"))?; + let extent = &manifest.extents[index]; + if extent.flags != CHUNK_FLAG_TAIL { + return Err(invalid("object has no open tail").into()); + } + let binding = manifest + .initialized_log + .as_ref() + .unwrap() + .physical_binding(manifest, index)?; + let group = self.group(&extent.group)?; + if binding.member_ids.as_slice() != group.member_ids { + return Err(invalid("tail route members changed").into()); + } + let mut clients = Vec::with_capacity(3); + let mut capacity = super::log_op::MAX_OP_DATA; + for (i, endpoint) in group.api_endpoints.iter().enumerate() { + let mut client = RemoteReplicaClient::connect(endpoint, &self.replica)?; + let reply = client.log_call( + LogOpRequest::publication_probe( + binding.volume_id, + binding.chunk_id, + binding.generation, + ) + .for_storage(binding.storage_incarnations[i], binding.initializations[i]), + )?; + check_member( + &reply, + binding.storage_incarnations[i], + binding.initializations[i], + binding.writer_epoch, + )?; + if reply.published_length != extent.length { + return Err(invalid("tail advanced before this creation writer opened").into()); + } + capacity = capacity.min(capacity_of(&reply, &self.replica)?); + clients.push(Some(client)); + } + Ok(NativeTailWriter { + binding, + group, + options: self.replica.clone(), + clients, + capacity, + chunk_bytes: self.chunk_bytes, + deadline: published.deadline, + length: extent.length, + object_offset: extent.object_offset, + incarnation: manifest + .initialized_log + .as_ref() + .unwrap() + .object_incarnation + .as_slice() + .try_into() + .unwrap(), + pending: None, + holder: published.start.holder.clone(), + }) + } + pub fn pin( + &mut self, + bucket: &str, + key: &str, + ttl_ms: u64, + ) -> Result { + let reply = self + .call(NativeObjectRequest::mutation( + Operation::OpenPin(NativeReadPin { + bucket: bucket.into(), + key: key.into(), + ..Default::default() + }), + ttl_ms, + ))? + .0; + Ok(NativePinnedObject { + manifest: reply + .manifest + .ok_or_else(|| invalid("native pin omitted its manifest"))?, + pin: reply + .pin + .ok_or_else(|| invalid("native pin omitted its identity"))?, + }) + } + fn check_pin(&mut self, pin: &NativeReadPin) -> Result<(), NativeObjectError> { + let reply = self + .call(NativeObjectRequest::query(NativeObjectRead { + kind: 3, + pin_id: pin.pin_id, + ..Default::default() + }))? + .0; + if reply.pin.as_ref() != Some(pin) { + return Err(invalid("read pin changed").into()); + } + Ok(()) + } + pub fn close_pin(&mut self, pinned: &NativePinnedObject) -> Result<(), NativeObjectError> { + self.call(NativeObjectRequest::mutation( + Operation::ClosePin(crate::native_object_outcome::NativePinRelease { + pin_id: pinned.pin.pin_id, + expected_expiry: pinned.pin.expires_at_ms, + }), + 0, + ))?; + Ok(()) + } + fn reader( + &mut self, + pinned: &NativePinnedObject, + index: usize, + ) -> Result<(ChunkLogReader, PhysicalMemberBinding), NativeObjectError> { + let manifest = &pinned.manifest; + let extent = &manifest.extents[index]; + let group = self.group(&extent.group)?; + let binding = manifest + .initialized_log + .as_ref() + .ok_or_else(|| invalid("pin lacks initialized chunks"))? + .physical_binding(manifest, index)?; + if binding.member_ids.as_slice() != group.member_ids { + return Err(invalid("pinned route members changed").into()); + } + Ok(( + ChunkLogReader::new( + &group.api_endpoints, + binding.volume_id, + binding.chunk_id, + binding.generation, + self.replica.clone(), + ), + binding, + )) + } + pub fn length(&mut self, pinned: &NativePinnedObject) -> Result { + self.check_pin(&pinned.pin)?; + let manifest = &pinned.manifest; + if !manifest + .extents + .last() + .is_some_and(|e| e.flags == CHUNK_FLAG_TAIL) + { + return Ok(manifest.length); + } + let index = manifest.extents.len() - 1; + let (mut reader, binding) = self.reader(pinned, index)?; + let mut error = None; + let length = reader + .physical_published_length(&binding, || self.pin_callback(&pinned.pin, &mut error)); + if let Some(error) = error { + return Err(error); + } + Ok(manifest.extents[index].object_offset + length?) + } + fn pin_callback( + &mut self, + pin: &NativeReadPin, + error: &mut Option, + ) -> Result<(), ChunkLogError> { + match self.check_pin(pin) { + Ok(()) => Ok(()), + Err(e) => { + *error = Some(e); + Err(ChunkLogError::Refused(ObjectError::PreconditionFailed( + "authoritative native pin validation failed".into(), + ))) + } + } + } + pub fn read_range( + &mut self, + pinned: &NativePinnedObject, + offset: u64, + length: usize, + ) -> Result, NativeObjectError> { + offset + .checked_add(length as u64) + .ok_or_else(|| invalid("object range overflow"))?; + self.check_pin(&pinned.pin)?; + let mut bytes = Vec::with_capacity(length); + let manifest = &pinned.manifest; + while bytes.len() < length { + let at = offset + bytes.len() as u64; + let index = manifest + .extents + .partition_point(|e| e.object_offset <= at) + .checked_sub(1) + .ok_or_else(|| invalid("object range has no extent"))?; + let extent = &manifest.extents[index]; + let physical = at - extent.object_offset; + let count = if extent.flags == CHUNK_FLAG_TAIL { + length - bytes.len() + } else { + let remaining = extent + .length + .checked_sub(physical) + .filter(|n| *n > 0) + .ok_or_else(|| invalid("read exceeds sealed object range"))?; + (length - bytes.len()).min(remaining as usize) + }; + let (mut reader, binding) = self.reader(pinned, index)?; + let mut error = None; + let value = if extent.flags == CHUNK_FLAG_TAIL { + reader.read_physical_pinned(&binding, physical, count, || { + self.pin_callback(&pinned.pin, &mut error) + }) + } else { + reader.read_physical_sealed( + &binding, + &SealedFooter { + length: extent.length, + crc: extent.footer_crc, + sha256: extent.footer_sha256.clone(), + }, + physical, + count, + || self.pin_callback(&pinned.pin, &mut error), + ) + }; + if let Some(error) = error { + return Err(error); + } + bytes.extend_from_slice(&value?); + } + self.check_pin(&pinned.pin)?; + Ok(bytes) + } +} +impl NativeStageHandle { + pub fn reference(&self) -> NativeStageRef { + NativeStageRef { + stage_id: self.start.stage_id, + expected_revision: self.revision, + holder: self.start.holder.clone(), + } + } +} +fn check_member( + reply: &LogOpReply, + root: [u8; 16], + init: [u8; 16], + epoch: u64, +) -> Result<(), NativeObjectError> { + if reply.epoch != epoch { + return Err(ChunkLogError::StaleEpoch { + current: reply.epoch, + } + .into()); + } + if reply.storage_incarnation() != Some(root) + || reply.publication_initialization() != Some(init) + || !reply.publication_mode + { + return Err(invalid("unqualified initialized storage reply").into()); + } + Ok(()) +} +fn check_append( + reply: &LogOpReply, + root: [u8; 16], + init: [u8; 16], + epoch: u64, + offset: u64, + length: u32, + tag: [u8; 16], + published: u64, +) -> Result<(), NativeObjectError> { + // Only a successful response to this exact tagged APPEND reaches here. Each + // socket has one exchange in flight; storage checks the original range, tag + // and bytes before replying. A tail probe or an uncertain exchange is not an ACK. + check_member(reply, root, init, epoch)?; + if reply.durable_length < offset + u64::from(length) + || reply.published_length < published + || reply + .record_identity() + .is_some_and(|r| r.offset != offset || r.length != length || r.attempt_tag != Some(tag)) + { + return Err(ChunkLogError::AttemptMismatch { offset }.into()); + } + Ok(()) +} +fn capacity_of(reply: &LogOpReply, options: &ReplicaClientOptions) -> Result { + usize::try_from(reply.publication_payload_limit) + .ok() + .map(|n| { + n.min(options.max_payload_bytes) + .min(super::log_op::MAX_OP_DATA + 512) + }) + .and_then(|n| n.checked_sub(512)) + .filter(|n| *n > 0) + .ok_or_else(|| invalid("native storage payload capacity is too small")) +} +struct PendingAppend { + identity: AppendIdentity, + progress: usize, + fragment: Vec, +} +/// One existing initialized tail. A pending whole append owns at most one record buffer; +/// only its final record advances the complete-prefix marker. +pub struct NativeTailWriter { + binding: PhysicalMemberBinding, + group: ChunkGroupConfig, + options: ReplicaClientOptions, + clients: Vec>, + capacity: usize, + chunk_bytes: u64, + deadline: Instant, + length: u64, + object_offset: u64, + incarnation: [u8; 16], + pending: Option, + holder: String, +} +impl NativeTailWriter { + pub fn length(&self) -> u64 { + self.object_offset + self.length + } + pub fn holder(&self) -> &str { + &self.holder + } + pub fn pending_identity(&self) -> Option { + self.pending.as_ref().map(|p| p.identity) + } + pub fn append( + &mut self, + data: &[u8], + identity: AppendIdentity, + ) -> Result { + let result = self.append_inner(data, identity); + if matches!( + &result, + Err(NativeObjectError::Data( + ChunkLogError::StaleEpoch { .. } | ChunkLogError::Sealed + )) + ) { + self.deadline = Instant::now(); + } + match result { + Err(error) + if self.pending.is_some() && !matches!(&error, NativeObjectError::Unknown(_)) => + { + Err(NativeObjectError::Unknown(ObjectError::PreconditionFailed( + format!("original native append remains unsettled: {error:?}"), + ))) + } + other => other, + } + } + fn append_inner( + &mut self, + data: &[u8], + identity: AppendIdentity, + ) -> Result { + if data.is_empty() + || identity.attempt_id == [0; 16] + || identity.object_incarnation != self.incarnation + || identity.request_offset != self.length() + || identity.request_length != data.len() as u64 + { + return Err(invalid("native append does not bind the original object range").into()); + } + let end = self + .length + .checked_add(data.len() as u64) + .filter(|n| *n <= self.chunk_bytes) + .ok_or_else(|| invalid("native append needs a chunk switch"))?; + if self + .pending + .as_ref() + .is_some_and(|p| p.identity != identity) + { + return Err(invalid("settle the original pending append first").into()); + } + let pending = self.pending.get_or_insert_with(|| PendingAppend { + identity, + progress: 0, + fragment: Vec::new(), + }); + while pending.progress < data.len() { + if Instant::now() >= self.deadline { + return Err(NativeObjectError::Unknown(invalid( + "native writer lease deadline reached", + ))); + } + let count = (data.len() - pending.progress).min(self.capacity); + let bytes = &data[pending.progress..pending.progress + count]; + if pending.fragment.is_empty() { + pending.fragment.extend_from_slice(bytes); + } else if pending.fragment != bytes { + return Err(invalid("pending append bytes changed").into()); + } + let offset = self.length + pending.progress as u64; + let published = if pending.progress + count == data.len() { + end + } else { + self.length + }; + let tag = identity.record_tag( + self.binding.volume_id, + self.binding.chunk_id, + self.binding.generation, + offset, + self.object_offset + offset, + count as u32, + )?; + for member in 0..3 { + if Instant::now() >= self.deadline { + return Err(NativeObjectError::Unknown(invalid( + "native writer lease deadline reached", + ))); + } + if self.clients[member].is_none() { + self.clients[member] = Some( + RemoteReplicaClient::connect( + &self.group.api_endpoints[member], + &self.options, + ) + .map_err(NativeObjectError::Unknown)?, + ); + } + let root = self.binding.storage_incarnations[member]; + let init = self.binding.initializations[member]; + let request = LogOpRequest::append_published( + self.binding.volume_id, + self.binding.chunk_id, + self.binding.generation, + self.binding.writer_epoch, + offset, + pending.fragment.clone(), + tag, + published, + init, + ) + .for_storage(root, init); + match self.clients[member].as_mut().unwrap().log_call(request) { + Ok(reply) => check_append( + &reply, + root, + init, + self.binding.writer_epoch, + offset, + count as u32, + tag, + published, + )?, + Err(error) => { + if matches!(error, LogCallError::Transport(_)) { + self.clients[member] = None; + } + return Err(error.into()); + } + } + } + pending.progress += count; + pending.fragment.clear(); + } + if Instant::now() >= self.deadline { + return Err(NativeObjectError::Unknown(invalid( + "native append confirmation exceeded its lease deadline", + ))); + } + self.length = end; + self.pending = None; + Ok(self.length()) + } +} diff --git a/src/cluster/native_object_commands.rs b/src/cluster/native_object_commands.rs new file mode 100644 index 00000000..fb1d344b --- /dev/null +++ b/src/cluster/native_object_commands.rs @@ -0,0 +1,613 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +//! Network admission for recoverable LOG object stages and authoritative read pins. +use crate::native_object_outcome::{native_operation::Operation, NativeObjectChange}; +use crate::native_object_state::{NativeOwnedChunk, NativeReadPin, NativeStageStart}; +use crate::{MatrixMetaService, ObjectError, ObjectId}; +use prost::Message; + +fn invalid(s: &str) -> ObjectError { + ObjectError::InvalidArgument(s.into()) +} +fn refused(s: &str) -> ObjectError { + ObjectError::PreconditionFailed(s.into()) +} +const LIMIT: usize = 4 * 1024 * 1024; +#[derive(Clone, PartialEq, Eq, Message)] +pub struct NativeObjectRead { + /// 1: owned stage, 2: pinned manifest, 3: pin validity, 4: metadata position. + #[prost(uint32, tag = "1")] + pub kind: u32, + #[prost(uint64, tag = "2")] + pub stage_id: u64, + #[prost(uint64, tag = "3")] + pub pin_id: u64, + #[prost(string, tag = "4")] + pub bucket: String, + #[prost(string, tag = "5")] + pub key: String, + #[prost(string, tag = "6")] + pub holder: String, + #[prost(bytes = "vec", tag = "7")] + pub request_nonce: Vec, +} +/// Leader-assigned positions, clocks, allocation coordinates and resulting leases must +/// be zero/absent on input. The TTL is separate from every persisted absolute deadline. +#[derive(Clone, PartialEq, Eq, Message)] +pub struct NativeObjectRequest { + #[prost(uint32, tag = "1")] + pub version: u32, + #[prost(uint64, tag = "2")] + pub ttl_ms: u64, + #[prost( + oneof = "crate::native_object_outcome::native_operation::Operation", + tags = "3,4,5,6,7,8,9,10,11,12,13" + )] + pub operation: Option, + #[prost(message, optional, tag = "14")] + pub read: Option, +} +#[derive(Clone, PartialEq, Eq, Message)] +pub struct NativeObjectReply { + #[prost(uint32, tag = "1")] + pub version: u32, + #[prost(uint64, tag = "2")] + pub commit_index: u64, + #[prost(message, optional, tag = "3")] + pub start: Option, + #[prost(uint64, tag = "4")] + pub stage_revision: u64, + #[prost(message, repeated, tag = "5")] + pub chunks: Vec, + #[prost(message, optional, tag = "6")] + pub manifest: Option, + #[prost(message, optional, tag = "7")] + pub pin: Option, + #[prost(uint64, tag = "9")] + pub now_ms: u64, + #[prost(message, optional, tag = "8")] + pub lease: Option, +} +impl NativeObjectRequest { + pub fn mutation(operation: Operation, ttl_ms: u64) -> Self { + Self { + version: 1, + ttl_ms, + operation: Some(operation), + read: None, + } + } + pub fn query(read: NativeObjectRead) -> Self { + Self { + version: 1, + read: Some(read), + ..Default::default() + } + } + pub fn is_read(&self) -> bool { + self.read.is_some() + } + pub fn validate(&self) -> Result<(), ObjectError> { + if self.version != 1 || self.operation.is_some() == self.read.is_some() { + return Err(invalid("invalid native object request shape")); + } + let timed = matches!( + self.operation, + Some( + Operation::Begin(_) + | Operation::OpenPin(_) + | Operation::RenewPin(_) + | Operation::RenewWriter(_) + ) + ); + if (timed && !(1000..=3_600_000).contains(&self.ttl_ms)) || (!timed && self.ttl_ms != 0) { + return Err(invalid("invalid native object request TTL")); + } + if let Some(read) = &self.read { + let object = read.stage_id == 0 + && read.pin_id == 0 + && crate::validate_bucket(&read.bucket).is_ok() + && crate::validate_key(&read.key).is_ok(); + let named = read.bucket.is_empty() && read.key.is_empty(); + let stage = read.kind == 1 + && read.pin_id == 0 + && !read.holder.is_empty() + && read.holder.len() <= 256 + && !read.holder.contains('\0') + && read.request_nonce.len() == 32 + && read.request_nonce.iter().any(|b| *b != 0) + && ((read.stage_id != 0 && named) || object); + let pin = matches!(read.kind, 2 | 3) + && read.pin_id != 0 + && read.stage_id == 0 + && named + && read.holder.is_empty() + && read.request_nonce.is_empty(); + let position = read.kind == 4 + && read.pin_id == 0 + && read.stage_id == 0 + && named + && read.holder.is_empty() + && read.request_nonce.is_empty(); + if !(stage || pin || position) { + return Err(invalid("invalid native object query")); + } + } + Ok(()) + } + pub fn from_payload(bytes: &[u8]) -> Result { + if bytes.len() > LIMIT { + return Err(invalid("native object request exceeds its bound")); + } + let value = + Self::decode(bytes).map_err(|_| invalid("invalid native object request protobuf"))?; + if value.encode_to_vec() != bytes { + return Err(invalid("noncanonical native object request")); + } + value.validate()?; + Ok(value) + } +} +impl NativeObjectReply { + pub fn from_payload(bytes: &[u8]) -> Result { + if bytes.len() > LIMIT { + return Err(invalid("native object reply exceeds its bound")); + } + let value = + Self::decode(bytes).map_err(|_| invalid("invalid native object reply protobuf"))?; + if value.version != 1 + || value.commit_index == 0 + || value.now_ms == 0 + || value.encode_to_vec() != bytes + { + return Err(invalid("noncanonical native object reply")); + } + Ok(value) + } +} +fn enabled(service: &MatrixMetaService) -> Result<(), ObjectError> { + if !service.cluster_features.has( + crate::cluster_features::FEATURE_NATIVE_OBJECT_STATE + | crate::cluster_features::FEATURE_UNIFIED_LOG_WRITERS, + ) { + return Err(refused("native object commands are not activated")); + } + Ok(()) +} +fn reply(service: &MatrixMetaService, now: u64) -> NativeObjectReply { + NativeObjectReply { + version: 1, + commit_index: service.placement_commit_index, + now_ms: now, + ..Default::default() + } +} +pub(super) fn read( + service: &MatrixMetaService, + request: &NativeObjectRequest, + limit: usize, + now: u64, +) -> Result { + request.validate()?; + enabled(service)?; + let command = request + .read + .as_ref() + .ok_or_else(|| invalid("native query required"))?; + let state = &service.native_objects; + let mut result = reply(service, now); + match command.kind { + 1 => { + let start = if command.stage_id != 0 { + state.stage_start(command.stage_id) + } else { + state.stage_for_object(&ObjectId::new(&command.bucket, &command.key)) + } + .ok_or_else(|| refused("native stage is missing"))?; + if start.holder != command.holder || start.request_nonce != command.request_nonce { + return Err(refused("native stage attempt does not match")); + } + result.start = Some(start.clone()); + result.stage_revision = state.stage_revision(start.stage_id).unwrap(); + result.chunks = state.owned_chunks(start.stage_id).cloned().collect(); + } + 2 | 3 => { + let pin = state + .pin(command.pin_id) + .ok_or_else(|| refused("native read pin is missing"))?; + if now >= pin.expires_at_ms { + return Err(refused("native read pin has expired")); + } + if command.kind == 2 { + result.manifest = Some((*state.pinned_manifest(pin.pin_id, now)?).clone()); + } + result.pin = Some(pin.clone()); + } + 4 => {} + _ => return Err(invalid("invalid native query action")), + } + super::message::check_reply_size(result.encoded_len(), limit)?; + Ok(super::MetaReply::NativeObject(result)) +} +pub(super) fn prepare( + service: &MatrixMetaService, + groups: &super::ChunkGroupCatalog, + request: &NativeObjectRequest, + limit: usize, + now: u64, +) -> Result<(crate::placement_outcome::PlacementOutcome, super::MetaReply), ObjectError> { + request.validate()?; + enabled(service)?; + let after = service + .placement_commit_index + .checked_add(1) + .ok_or_else(|| refused("native metadata position exhausted"))?; + let mut operation = request + .operation + .clone() + .ok_or_else(|| invalid("native mutation required"))?; + let expires = now + .checked_add(request.ttl_ms) + .ok_or_else(|| invalid("native deadline overflow"))?; + let mut result = reply(service, now); + result.commit_index = after; + match &mut operation { + Operation::Begin(command) => { + if command.expected_lease.is_some() { + return Err(invalid("native begin resulting lease is leader assigned")); + } + let start = command + .start + .as_mut() + .ok_or_else(|| invalid("native begin lacks a stage"))?; + if start.stage_id != 0 + || start.writer_epoch != 0 + || start.created_ms != 0 + || start.expires_at_ms != 0 + { + return Err(invalid( + "native begin positions and clock are leader assigned", + )); + } + let header = start + .header + .as_mut() + .ok_or_else(|| invalid("native begin lacks its header"))?; + if header.format_version + != crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT + { + return Err(invalid( + "native network objects require physical member bindings", + )); + } + if service + .chunk_catalog + .get(&header.object_id()) + .is_some_and(|m| { + m.extents + .last() + .is_some_and(|e| e.flags == crate::chunk_manifest::CHUNK_FLAG_TAIL) + }) + { + return Err(refused( + "active native replacement requires completed storage handoff", + )); + } + command.expected_lease = service.writer_leases.get(&header.bucket, &header.key); + header.modified_ms = now; + start.stage_id = after; + start.writer_epoch = after; + start.created_ms = now; + start.expires_at_ms = expires; + if start.kind == crate::native_object_state::STAGE_REPLACE { + let incarnation = start.replacement_incarnation()?; + start + .header + .as_mut() + .unwrap() + .initialized_log + .as_mut() + .ok_or_else(|| invalid("native begin lacks its identity"))? + .object_incarnation = incarnation.to_vec(); + } + result.start = Some(start.clone()); + result.stage_revision = after; + } + Operation::Extend(command) => { + let reference = command + .stage + .as_ref() + .ok_or_else(|| invalid("native extension lacks its owner"))?; + let start = service + .native_objects + .stage_start(reference.stage_id) + .ok_or_else(|| refused("native stage is missing"))?; + let chunk = command + .chunk + .as_mut() + .ok_or_else(|| invalid("native extension lacks its chunk"))?; + let extent = chunk + .extent + .as_mut() + .ok_or_else(|| invalid("native extension lacks its range"))?; + let binding = chunk + .initialization + .as_mut() + .ok_or_else(|| invalid("native extension lacks its members"))?; + if chunk.allocation_id != 0 + || extent.volume_id != 0 + || extent.chunk_id != 0 + || binding.chunk_generation != 0 + || binding.writer_epoch != 0 + { + return Err(invalid( + "native chunk coordinates and epochs are leader assigned", + )); + } + let group = groups + .get(&extent.group) + .ok_or_else(|| refused("native allocation group is missing"))?; + if !group + .identity + .as_ref() + .is_some_and(|i| i.is_standalone_star()) + || group.member_ids.len() != 3 + || binding.replicas.len() != 3 + || !binding + .replicas + .iter() + .zip(&group.member_ids) + .all(|(r, id)| &r.member_id == id && r.initialization.is_empty()) + { + return Err(refused( + "native allocation members do not match the configured group", + )); + } + chunk.allocation_id = after; + let (volume, id) = crate::object_manifest::chunk_identity_of_index(after); + extent.volume_id = volume; + extent.chunk_id = id; + binding.chunk_generation = 1; + binding.writer_epoch = start.writer_epoch; + for member in &mut binding.replicas { + let mut material = b"MONATIVE-MEMBER-BIRTH1".to_vec(); + material.extend_from_slice(&start.stage_id.to_le_bytes()); + material.extend_from_slice(&after.to_le_bytes()); + material.extend_from_slice(&start.request_nonce); + material.extend_from_slice(&(member.member_id.len() as u64).to_le_bytes()); + material.extend_from_slice(member.member_id.as_bytes()); + material.extend_from_slice(&member.storage_incarnation); + member.initialization = crate::chunk_integrity::sha256(&material)[..16].to_vec(); + } + result.chunks.push(chunk.clone()); + result.stage_revision = after; + } + Operation::Publish(command) => { + if command.expected_lease.is_some() { + return Err(invalid("native publication lease is leader captured")); + } + let manifest = command + .manifest + .as_ref() + .ok_or_else(|| invalid("native publication lacks its manifest"))?; + if manifest.format_version + != crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT + { + return Err(invalid( + "native publication requires physical member bindings", + )); + } + command.expected_lease = service.writer_leases.get(&manifest.bucket, &manifest.key); + result.manifest = Some(manifest.clone()); + } + Operation::OpenPin(pin) => { + if pin.pin_id != 0 + || pin.expires_at_ms != 0 + || pin.generation != 0 + || !pin.manifest_digest.is_empty() + { + return Err(invalid("native pin view and deadline are leader assigned")); + } + let manifest = service + .chunk_catalog + .get(&ObjectId::new(&pin.bucket, &pin.key)) + .ok_or_else(|| refused("native pinned object is missing"))?; + if manifest.deleted + || manifest.format_version + != crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT + { + return Err(refused("native pin requires a live physical object")); + } + pin.pin_id = after; + pin.generation = manifest.generation; + pin.expires_at_ms = expires; + pin.manifest_digest = crate::chunk_integrity::sha256(&manifest.to_bytes()?).to_vec(); + result.pin = Some(pin.clone()); + result.manifest = Some((**manifest).clone()); + } + Operation::RenewPin(command) => { + if command.expires_at_ms != 0 { + return Err(invalid("native pin deadline is leader assigned")); + } + command.expires_at_ms = expires; + let mut pin = service + .native_objects + .pin(command.pin_id) + .ok_or_else(|| refused("native pin is missing"))? + .clone(); + pin.expires_at_ms = expires; + result.pin = Some(pin); + } + Operation::RenewWriter(command) => { + if command.after.is_some() { + return Err(invalid("native lease deadline is leader assigned")); + } + let mut lease = command + .before + .clone() + .ok_or_else(|| invalid("native renewal lacks its prior lease"))?; + lease.expires_at_ms = expires; + result.lease = Some(lease.clone()); + command.after = Some(lease); + } + Operation::Abort(_) + | Operation::ExpireStage(_) + | Operation::ClosePin(_) + | Operation::ExpirePin(_) + | Operation::ReleaseWriter(_) => {} + } + let outcome = NativeObjectChange::decide(service, operation, now)?; + // Admission must reject an oversized answer before the mutation enters a journal or Raft. + super::message::check_reply_size(result.encoded_len(), limit)?; + Ok((outcome, super::MetaReply::NativeObject(result))) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + pub(crate) fn begin_request(key: &str) -> NativeObjectRequest { + let header = crate::chunk_manifest::ChunkManifest { + format_version: crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT, + bucket: "bucket".into(), + key: key.into(), + generation: 1, + kind: crate::chunk_manifest::CHUNK_KIND_LOG, + initialized_log: Some( + crate::initialized_log_manifest::InitializedLogManifest::default(), + ), + ..Default::default() + }; + NativeObjectRequest::mutation( + Operation::Begin(crate::native_object_outcome::NativeBegin { + start: Some(NativeStageStart { + kind: crate::native_object_state::STAGE_REPLACE, + header: Some(header), + holder: "writer".into(), + request_nonce: vec![9; 32], + target_length: 4, + ..Default::default() + }), + ..Default::default() + }), + 2000, + ) + } + #[test] + fn native_rpc_is_canonical_and_rejects_ambiguous_requests() { + let request = begin_request("object"); + let bytes = request.encode_to_vec(); + assert_eq!(NativeObjectRequest::from_payload(&bytes).unwrap(), request); + for suffix in [vec![8, 1], vec![0x80, 1, 1]] { + let mut malformed = bytes.clone(); + malformed.extend(suffix); + assert!(NativeObjectRequest::from_payload(&malformed).is_err()); + } + let mut ambiguous = request; + ambiguous.read = Some(NativeObjectRead { + kind: 4, + ..Default::default() + }); + assert!(ambiguous.validate().is_err()); + } + #[test] + fn leader_assigns_clock_positions_and_receipts_without_mutating_live_state() { + let mut service = crate::native_object_outcome_tests::service(); + let before = service.export_snapshot().to_bytes().unwrap(); + let request = begin_request("object"); + let (outcome, reply) = prepare( + &service, + &super::super::ChunkGroupCatalog::default(), + &request, + 1 << 20, + 1000, + ) + .unwrap(); + assert_eq!(service.export_snapshot().to_bytes().unwrap(), before); + let super::super::MetaReply::NativeObject(reply) = reply else { + panic!("native receipt missing") + }; + let start = reply.start.as_ref().unwrap(); + assert_eq!( + ( + start.stage_id, + start.writer_epoch, + start.created_ms, + start.expires_at_ms + ), + (2, 2, 1000, 3000) + ); + assert_eq!(reply.now_ms, 1000); + assert_eq!(reply.stage_revision, 2); + assert_eq!( + NativeObjectReply::from_payload(&reply.encode_to_vec()).unwrap(), + reply + ); + outcome.apply(&mut service).unwrap(); + assert_eq!(service.native_objects.stage_start(2), Some(start)); + } + #[test] + fn native_rpc_rejects_client_allocated_epochs_and_oversized_receipts_before_commit() { + let service = crate::native_object_outcome_tests::service(); + let before = service.export_snapshot().to_bytes().unwrap(); + let groups = super::super::ChunkGroupCatalog::default(); + for field in 0..4 { + let mut request = begin_request("object"); + let Some(Operation::Begin(begin)) = &mut request.operation else { + unreachable!() + }; + let start = begin.start.as_mut().unwrap(); + match field { + 0 => start.stage_id = 1, + 1 => start.writer_epoch = 1, + 2 => start.created_ms = 1, + _ => start.expires_at_ms = 1, + }; + assert!(prepare(&service, &groups, &request, 1 << 20, 1000).is_err()); + assert_eq!(service.export_snapshot().to_bytes().unwrap(), before); + } + assert!(prepare(&service, &groups, &begin_request("object"), 24, 1000).is_err()); + assert_eq!(service.export_snapshot().to_bytes().unwrap(), before); + let mut disabled = service.clone(); + disabled.cluster_features.raised = 0; + assert!(prepare(&disabled, &groups, &begin_request("object"), 1 << 20, 1000).is_err()); + } + #[test] + fn native_read_pin_captures_current_view_and_uses_the_leader_deadline() { + let mut service = crate::native_object_outcome_tests::service(); + for (operation, now) in crate::native_object_outcome_tests::commands() { + NativeObjectChange::decide(&service, operation, now) + .unwrap() + .apply(&mut service) + .unwrap(); + } + let manifest = service.chunk_catalog.iter().next().unwrap().1.clone(); + let request = NativeObjectRequest::mutation( + Operation::OpenPin(NativeReadPin { + bucket: manifest.bucket.clone(), + key: manifest.key.clone(), + ..Default::default() + }), + 2000, + ); + let groups = super::super::ChunkGroupCatalog::default(); + let (outcome, reply) = prepare(&service, &groups, &request, 1 << 20, 2000).unwrap(); + let super::super::MetaReply::NativeObject(reply) = reply else { + unreachable!() + }; + let pin = reply.pin.unwrap(); + assert_eq!(pin.generation, manifest.generation); + assert_eq!(pin.expires_at_ms, 4000); + assert_eq!( + pin.manifest_digest, + crate::chunk_integrity::sha256(&manifest.to_bytes().unwrap()) + ); + outcome.apply(&mut service).unwrap(); + let query = NativeObjectRequest::query(NativeObjectRead { + kind: 3, + pin_id: pin.pin_id, + ..Default::default() + }); + assert!(read(&service, &query, 1 << 20, 3999).is_ok()); + assert!(read(&service, &query, 1 << 20, 4000).is_err()); + } +} diff --git a/src/cluster/native_object_path_tests.rs b/src/cluster/native_object_path_tests.rs new file mode 100644 index 00000000..2aa627ce --- /dev/null +++ b/src/cluster/native_object_path_tests.rs @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +use super::*; +use crate::cluster::native_object_client::{NativeObjectClient, NativeObjectError}; +use crate::cluster::{ + AppendIdentity, ChunkGroupCatalog, ChunkGroupConfig, ChunkGroupIdentity, MetaClientOptions, + MetaRaftOptions, RemoteMetaClient, ReplicaClientOptions, ReplicaNodeOptions, ReplicaNodeServer, +}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; +const HELPER: &str = "cluster::meta_server::native_object_path_tests::native_object_process_node"; +static NEXT: AtomicU64 = AtomicU64::new(0); + +#[test] +#[ignore = "owned child process entry"] +fn native_object_process_node() { + let Ok(role) = std::env::var("MATRIXOBJECT_NATIVE_PROCESS_ROLE") else { + return; + }; + let root = PathBuf::from(std::env::var("MATRIXOBJECT_NATIVE_PROCESS_ROOT").unwrap()); + std::fs::create_dir_all(&root).unwrap(); + let address = std::env::var("MATRIXOBJECT_NATIVE_PROCESS_ADDRESS").unwrap(); + if role == "data" { + let server = ReplicaNodeServer::bind_with_journal( + &address, + ReplicaNodeOptions { + publication_writes: true, + max_payload_bytes: 64 * 1024, + ..Default::default() + }, + &root.join("journal"), + ) + .unwrap(); + println!("NATIVE_READY {}", server.local_addr().unwrap()); + std::io::stdout().flush().unwrap(); + server.serve().unwrap(); + return; + } + assert_eq!(role, "meta"); + let endpoints: Vec = std::env::var("MATRIXOBJECT_NATIVE_PROCESS_DATA") + .unwrap() + .split(',') + .map(str::to_owned) + .collect(); + let group = ChunkGroupConfig { + placement_id: "native-group".into(), + failure_domain: "local".into(), + identity: Some(ChunkGroupIdentity { + version: 3, + group_id: 11, + node_id: 1, + voters: vec![1, 2, 3], + capacity_bytes: 1 << 30, + max_pages: 1024, + peer_endpoints: Vec::new(), + bootstrap_id: 0, + bootstrap_voters: Vec::new(), + }), + api_endpoints: endpoints, + member_ids: vec!["native-1".into(), "native-2".into(), "native-3".into()], + }; + let mut server = MetaNodeServer::bind( + &address, + MetaNodeOptions { + max_payload_bytes: 2 * 1024 * 1024, + ..Default::default() + }, + ) + .unwrap(); + server + .seed_chunk_groups(ChunkGroupCatalog::new(vec![group]).unwrap()) + .unwrap(); + { + // Exercise the guarded protocol without advertising it to ordinary operators. + let mut guard = server.meta.lock().unwrap(); + guard.service.cluster_features.raised = crate::cluster_features::FEATURE_NATIVE_OBJECT_STATE + | crate::cluster_features::FEATURE_UNIFIED_LOG_WRITERS; + guard.service.placement_commit_index = 1; + guard.service.next_commit_index = 2; + guard.service.invalidate_snapshot_export_cache(); + } + let peers = std::env::var("MATRIXOBJECT_NATIVE_PROCESS_PEERS") + .unwrap() + .split(',') + .enumerate() + .map(|(i, address)| (i as u64 + 1, address.parse().unwrap())) + .collect(); + let directory = root.join("raft"); + std::fs::create_dir_all(&directory).unwrap(); + server + .enable_raft(MetaRaftOptions { + node_id: std::env::var("MATRIXOBJECT_NATIVE_PROCESS_ID") + .unwrap() + .parse() + .unwrap(), + group_id: 71, + peers, + directory, + request_timeout: Duration::from_secs(3), + checkpoint_after_bytes: 1024, + bootstrap_voters: None, + peer_tls: None, + wal_zero_fill_bytes: None, + }) + .unwrap(); + println!("NATIVE_READY {}", server.local_addr().unwrap()); + std::io::stdout().flush().unwrap(); + server.serve().unwrap(); +} +struct ServerProcess { + child: Child, + address: String, + root: PathBuf, + role: String, + id: usize, + data: String, + peers: String, +} +impl ServerProcess { + fn start(root: &Path, role: &str, id: usize, address: &str, data: &str, peers: &str) -> Self { + std::fs::create_dir_all(root).unwrap(); + let log = root.join("process.stderr"); + let stderr = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&log) + .unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + HELPER, + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("MATRIXOBJECT_NATIVE_PROCESS_ROLE", role) + .env("MATRIXOBJECT_NATIVE_PROCESS_ROOT", root) + .env("MATRIXOBJECT_NATIVE_PROCESS_ADDRESS", address) + .env("MATRIXOBJECT_NATIVE_PROCESS_ID", id.to_string()) + .env("MATRIXOBJECT_NATIVE_PROCESS_DATA", data) + .env("MATRIXOBJECT_NATIVE_PROCESS_PEERS", peers) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(stderr) + .spawn() + .unwrap(); + let output = child.stdout.take().unwrap(); + let mut result = Self { + child, + address: String::new(), + root: root.into(), + role: role.into(), + id, + data: data.into(), + peers: peers.into(), + }; + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(output).lines() { + let Ok(line) = line else { break }; + if let Some((_, address)) = line.split_once("NATIVE_READY ") { + let _ = tx.send(address.trim().to_owned()); + return; + } + } + }); + match rx.recv_timeout(Duration::from_secs(15)) { + Ok(address) => result.address = address, + Err(error) => panic!( + "{role} {id} did not start: {error}; {}", + std::fs::read_to_string(log).unwrap_or_default() + ), + }; + result + } + fn halt(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + fn restart(&mut self) { + self.halt(); + *self = Self::start( + &self.root, + &self.role, + self.id, + &self.address, + &self.data, + &self.peers, + ); + } +} +impl Drop for ServerProcess { + fn drop(&mut self) { + self.halt(); + } +} +struct Cluster { + root: PathBuf, + data: Vec, + meta: Vec, +} +impl Cluster { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "native-object-processes-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&root).unwrap(); + let mut result = Self { + root, + data: Vec::new(), + meta: Vec::new(), + }; + for i in 1..=3 { + result.data.push(ServerProcess::start( + &result.root.join(format!("data-{i}")), + "data", + i, + "127.0.0.1:0", + "", + "", + )); + } + let data = result + .data + .iter() + .map(|p| p.address.as_str()) + .collect::>() + .join(","); + let reservations: Vec<_> = (0..3) + .map(|_| std::net::TcpListener::bind("127.0.0.1:0").unwrap()) + .collect(); + let peers = reservations + .iter() + .map(|p| p.local_addr().unwrap().to_string()) + .collect::>() + .join(","); + drop(reservations); + for i in 1..=3 { + result.meta.push(ServerProcess::start( + &result.root.join(format!("meta-{i}")), + "meta", + i, + "127.0.0.1:0", + &data, + &peers, + )); + } + let pids: std::collections::HashSet<_> = result + .data + .iter() + .chain(&result.meta) + .map(|p| p.child.id()) + .collect(); + assert_eq!(pids.len(), 6); + result + } + fn client(&self) -> NativeObjectClient { + let options = MetaClientOptions { + read_timeout: Duration::from_secs(10), + connect_timeout: Duration::from_secs(2), + ..Default::default() + }; + let endpoints: Vec<_> = self.meta.iter().map(|p| p.address.clone()).collect(); + let until = Instant::now() + Duration::from_secs(20); + loop { + match RemoteMetaClient::connect_raft_catalog(&endpoints, 71, &options) { + Ok(meta) => { + let mut client = NativeObjectClient::new( + meta, + ReplicaClientOptions { + max_payload_bytes: 64 * 1024, + read_timeout: Duration::from_secs(2), + connect_timeout: Duration::from_millis(300), + ..Default::default() + }, + ); + if client.metadata_position().is_ok() { + return client; + } + } + Err(_) => {} + }; + assert!( + Instant::now() < until, + "metadata group did not become ready" + ); + std::thread::sleep(Duration::from_millis(30)); + } + } +} +impl Drop for Cluster { + fn drop(&mut self) { + self.meta.clear(); + self.data.clear(); + let _ = std::fs::remove_dir_all(&self.root); + } +} + +#[test] +fn native_object_stages_pins_and_data_only_appends_survive_six_process_restarts() { + let mut cluster = Cluster::new(); + let mut client = cluster.client(); + let mut stage = client + .begin( + "bucket", + "native-log", + "writer", + [9; 32], + 2 * 96 * 1024 + 4, + None, + 120_000, + ) + .unwrap(); + let parts = [vec![17; 96 * 1024], vec![31; 96 * 1024], b"init".to_vec()]; + let mut expected = Vec::new(); + for (index, body) in parts.iter().enumerate() { + let owned = client + .allocate(&mut stage, "native-group", body.len() as u64) + .unwrap(); + client + .write_chunk(&stage, &owned, body, [100 + index as u8; 16]) + .unwrap(); + expected.extend_from_slice(body); + } + let recovered = client + .recover_stage("bucket", "native-log", "writer", [9; 32]) + .unwrap(); + assert_eq!(recovered.revision, stage.revision); + assert_eq!(recovered.chunks, stage.chunks); + let published = client.publish(&stage, true).unwrap(); + let incarnation = published + .manifest + .initialized_log + .as_ref() + .unwrap() + .object_incarnation + .as_slice() + .try_into() + .unwrap(); + let mut writer = client.writer(&published).unwrap(); + let before = client.metadata_position().unwrap(); + for index in 1..=64 { + let body = vec![index as u8; 4096]; + let identity = AppendIdentity { + object_incarnation: incarnation, + attempt_id: [index as u8; 16], + request_offset: writer.length(), + request_length: body.len() as u64, + }; + assert_eq!( + writer.append(&body, identity).unwrap(), + expected.len() as u64 + body.len() as u64 + ); + assert!(writer.pending_identity().is_none()); + expected.extend_from_slice(&body); + } + assert_eq!( + client.metadata_position().unwrap(), + before, + "steady appends committed metadata" + ); + cluster.data[2].halt(); + let body = vec![80; 4096]; + let identity = AppendIdentity { + object_incarnation: incarnation, + attempt_id: [80; 16], + request_offset: writer.length(), + request_length: body.len() as u64, + }; + assert!( + matches!( + writer.append(&body, identity), + Err(NativeObjectError::Unknown(_)) + ), + "missing third replica did not retain an unknown outcome" + ); + assert_eq!(writer.pending_identity(), Some(identity)); + cluster.data[2].restart(); + assert_eq!( + writer.append(&body, identity).unwrap(), + expected.len() as u64 + body.len() as u64 + ); + expected.extend_from_slice(&body); + assert_eq!(client.metadata_position().unwrap(), before); + let last = published.manifest.extents.last().unwrap(); + let binding = published + .manifest + .initialized_log + .as_ref() + .unwrap() + .physical_binding(&published.manifest, published.manifest.extents.len() - 1) + .unwrap(); + let physical = writer.length() - last.object_offset; + let foreign = vec![81; 4096]; + for (member, node) in cluster.data.iter().enumerate() { + let mut direct = crate::cluster::RemoteReplicaClient::connect( + &node.address, + &ReplicaClientOptions::default(), + ) + .unwrap(); + direct + .log_call( + crate::cluster::LogOpRequest::append_published( + binding.volume_id, + binding.chunk_id, + binding.generation, + binding.writer_epoch, + physical, + foreign.clone(), + [200; 16], + physical + foreign.len() as u64, + binding.initializations[member], + ) + .for_storage( + binding.storage_incarnations[member], + binding.initializations[member], + ), + ) + .unwrap(); + } + let own = AppendIdentity { + object_incarnation: incarnation, + attempt_id: [81; 16], + request_offset: writer.length(), + request_length: foreign.len() as u64, + }; + assert!( + matches!( + writer.append(&foreign, own), + Err(NativeObjectError::Unknown(_)) + ), + "equal foreign bytes acknowledged the wrong original attempt" + ); + assert_eq!(writer.pending_identity(), Some(own)); + expected.extend_from_slice(&foreign); + let pin = client.pin("bucket", "native-log", 30_000).unwrap(); + assert_eq!(client.length(&pin).unwrap(), expected.len() as u64); + let bytes = client.read_range(&pin, 0, expected.len()).unwrap(); + assert!( + bytes == expected, + "native range differed from original writes" + ); + client.close_pin(&pin).unwrap(); + assert!( + client.read_range(&pin, 0, 1).is_err(), + "released pin still admitted reads" + ); + drop(writer); + drop(client); + for process in &mut cluster.meta { + process.halt(); + } + for process in &mut cluster.data { + process.halt(); + } + for process in &mut cluster.data { + process.restart(); + } + for process in &mut cluster.meta { + process.restart(); + } + let mut client = cluster.client(); + let pin = client.pin("bucket", "native-log", 30_000).unwrap(); + assert_eq!(client.length(&pin).unwrap(), expected.len() as u64); + assert!( + client.read_range(&pin, 0, expected.len()).unwrap() == expected, + "restarted native object bytes differed" + ); + client.close_pin(&pin).unwrap(); + println!("NATIVE_OBJECT_PROCESS_EVIDENCE metadata=3 data=3 restarts=6 steady_appends=64 steady_metadata_commits=0 exact_bytes={} original_pending_retry=passed released_pin=refused",expected.len()); +} diff --git a/src/cluster/physical_pinned_reader_tests.rs b/src/cluster/physical_pinned_reader_tests.rs new file mode 100644 index 00000000..ea68d2c4 --- /dev/null +++ b/src/cluster/physical_pinned_reader_tests.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +use super::*; +use crate::native_object_outcome::{native_operation::Operation, *}; +use crate::native_object_state_tests::{chunk, hash, publication}; +use crate::physical_member_binding_tests::{commit, physical_start, stage_ref}; +fn setup() -> ( + Directory, + Vec, + crate::MatrixMetaService, + crate::initialized_log_manifest::PhysicalMemberBinding, +) { + let directory = Directory::new(); + let nodes: Vec<_> = (0..3) + .map(|i| { + Node::start_with_options( + &directory.0.join(format!("n{i}")), + "127.0.0.1:0", + ReplicaNodeOptions { + publication_writes: true, + ..Default::default() + }, + ) + }) + .collect(); + let call = |node: &Node, request: LogOpRequest| { + RemoteReplicaClient::connect(&node.addr, &options()) + .unwrap() + .log_call(request) + .unwrap() + }; + let roots: Vec<_> = nodes + .iter() + .map(|n| { + call(n, LogOpRequest::storage_probe()) + .storage_incarnation() + .unwrap() + }) + .collect(); + let mut service = crate::native_object_outcome_tests::service(); + let start = physical_start(2, None, 4); + let mut owned = chunk(&start, 3, 0, 4, 0); + for (i, r) in owned + .initialization + .as_mut() + .unwrap() + .replicas + .iter_mut() + .enumerate() + { + r.storage_incarnation = roots[i].to_vec(); + } + commit( + &mut service, + Operation::Begin(NativeBegin { + start: Some(start.clone()), + ..Default::default() + }), + 1000, + ); + commit( + &mut service, + Operation::Extend(NativeExtend { + stage: Some(stage_ref(2, 2)), + chunk: Some(owned.clone()), + }), + 1001, + ); + for i in 0..3 { + let init: [u8; 16] = owned.initialization.as_ref().unwrap().replicas[i] + .initialization + .as_slice() + .try_into() + .unwrap(); + call( + &nodes[i], + LogOpRequest::initialize_publication(0, 3, 1, 2, init).for_storage(roots[i], init), + ); + call( + &nodes[i], + LogOpRequest::append_published(0, 3, 1, 2, 0, b"abcd".to_vec(), [11; 16], 4, init) + .for_storage(roots[i], init), + ); + } + let manifest = publication(&start, &[owned]); + let id = manifest.object_id(); + commit( + &mut service, + Operation::Publish(NativePublish { + stage: Some(stage_ref(2, 3)), + manifest: Some(manifest.clone()), + expected_lease: None, + }), + 1002, + ); + commit( + &mut service, + Operation::OpenPin(crate::native_object_state::NativeReadPin { + pin_id: 5, + bucket: id.bucket.to_string(), + key: id.key.to_string(), + generation: manifest.generation, + manifest_digest: hash(&manifest), + expires_at_ms: 5000, + }), + 1003, + ); + let binding = service + .native_objects + .physical_read_binding(5, 0, 1003) + .unwrap(); + (directory, nodes, service, binding) +} +fn call(node: &Node, request: LogOpRequest) -> LogOpReply { + RemoteReplicaClient::connect(&node.addr, &options()) + .unwrap() + .log_call(request) + .unwrap() +} +#[test] +fn committed_physical_pin_reads_and_repairs_after_source_loss_and_restart() { + let (_d, mut nodes, service, binding) = setup(); + let request = LogOpRequest::append_published( + 0, + 3, + 1, + 2, + 4, + b"ef".to_vec(), + [12; 16], + 6, + binding.initializations[0], + ) + .for_storage(binding.storage_incarnations[0], binding.initializations[0]); + call(&nodes[0], request); + let endpoints = endpoints(&nodes); + let mut reader = ChunkLogReader::new(&endpoints, 0, 3, 1, options()); + let check = || { + service + .native_objects + .physical_read_binding(5, 0, 1004) + .map(|_| ()) + .map_err(|e| ChunkLogError::Refused(e)) + }; + assert_eq!( + reader.read_physical_pinned(&binding, 0, 6, check).unwrap(), + b"abcdef" + ); + nodes[0].halt(); + assert_eq!( + reader.read_physical_pinned(&binding, 0, 6, check).unwrap(), + b"abcdef" + ); + for i in 1..3 { + nodes[i].restart(); + let observed = call( + &nodes[i], + LogOpRequest::identity_initialized_publication(0, 3, 1, 4, binding.initializations[i]) + .for_storage(binding.storage_incarnations[i], binding.initializations[i]), + ); + assert_eq!( + observed.record_identity().unwrap().attempt_tag, + Some([12; 16]) + ); + } + assert_eq!( + reader.read_physical_pinned(&binding, 0, 6, check).unwrap(), + b"abcdef" + ); +} +#[test] +fn expired_pins_wrong_physical_members_and_wrong_chunks_refuse_reads() { + let (_d, nodes, service, binding) = setup(); + let endpoints = endpoints(&nodes); + let mut reader = ChunkLogReader::new(&endpoints, 0, 3, 1, options()); + assert!(reader + .read_physical_pinned(&binding, 0, 4, || service + .native_objects + .physical_read_binding(5, 0, 5000) + .map(|_| ()) + .map_err(ChunkLogError::Refused)) + .is_err()); + let mut wrong = binding.clone(); + wrong.storage_incarnations = [[80; 16], [81; 16], [82; 16]]; + assert!(reader + .read_physical_pinned(&wrong, 0, 4, || Ok(())) + .is_err()); + let mut wrong = binding.clone(); + wrong.chunk_id += 1; + assert!(reader + .read_physical_pinned(&wrong, 0, 4, || Ok(())) + .is_err()); + assert_eq!( + reader + .read_physical_pinned(&binding, 0, 4, || Ok(())) + .unwrap(), + b"abcd" + ); +} +#[test] +fn a_higher_storage_epoch_never_becomes_qualified_by_an_old_pin() { + let (_d, nodes, _service, binding) = setup(); + call( + &nodes[0], + LogOpRequest::fence_publication(0, 3, 1, 3, binding.initializations[0]) + .for_storage(binding.storage_incarnations[0], binding.initializations[0]), + ); + let mut reader = ChunkLogReader::new(&endpoints(&nodes), 0, 3, 1, options()); + assert!(matches!( + reader.read_physical_pinned(&binding, 0, 4, || Ok(())), + Err(ChunkLogError::StaleEpoch { current: 3 }) + )); + for i in 1..3 { + let observed = call( + &nodes[i], + LogOpRequest::publication_tail(0, 3, 1) + .for_storage(binding.storage_incarnations[i], binding.initializations[i]), + ); + assert_eq!(observed.epoch, 2); + } +} diff --git a/src/cluster/published_tail_reader.rs b/src/cluster/published_tail_reader.rs index c0eda8a6..04d72ae9 100644 --- a/src/cluster/published_tail_reader.rs +++ b/src/cluster/published_tail_reader.rs @@ -26,7 +26,7 @@ impl ChunkLogReader { mut check_route: impl FnMut() -> Result<(), ChunkLogError>, ) -> Result { let (_, length, _) = - self.stabilize_publication_inner(epoch, initializations, &mut check_route)?; + self.stabilize_publication_inner(epoch, initializations, None, None, &mut check_route)?; check_route()?; Ok(length) } @@ -40,10 +40,108 @@ impl ChunkLogReader { initializations: &[[u8; 16]; LOG_REPLICAS], offset: u64, length: usize, + check_route: impl FnMut() -> Result<(), ChunkLogError>, + ) -> Result, ChunkLogError> { + self.read_publication_bound( + epoch, + initializations, + None, + None, + offset, + length, + check_route, + ) + } + /// Read through an actual metadata read pin's physical binding. The caller maps the + /// binding's configured member order to endpoints and checks pin validity throughout. + /// Probes, identity checks, repair appends and payload reads use protocol5 exclusively. + pub fn read_physical_pinned( + &mut self, + binding: &crate::initialized_log_manifest::PhysicalMemberBinding, + offset: u64, + length: usize, + check_route: impl FnMut() -> Result<(), ChunkLogError>, + ) -> Result, ChunkLogError> { + if self.volume != binding.volume_id + || self.chunk != binding.chunk_id + || self.generation != binding.generation + { + return Err(refused("physical pin does not bind this chunk")); + } + self.read_publication_bound( + binding.writer_epoch, + &binding.initializations, + Some(&binding.storage_incarnations), + None, + offset, + length, + check_route, + ) + } + pub fn physical_published_length( + &mut self, + binding: &crate::initialized_log_manifest::PhysicalMemberBinding, mut check_route: impl FnMut() -> Result<(), ChunkLogError>, + ) -> Result { + self.check_physical_coordinates(binding)?; + let (_, length, _) = self.stabilize_publication_inner( + binding.writer_epoch, + &binding.initializations, + Some(&binding.storage_incarnations), + None, + &mut check_route, + )?; + check_route()?; + Ok(length) + } + pub fn read_physical_sealed( + &mut self, + binding: &crate::initialized_log_manifest::PhysicalMemberBinding, + footer: &SealedFooter, + offset: u64, + length: usize, + check_route: impl FnMut() -> Result<(), ChunkLogError>, ) -> Result, ChunkLogError> { - let (source, published, capacity) = - self.stabilize_publication_inner(epoch, initializations, &mut check_route)?; + self.check_physical_coordinates(binding)?; + self.read_publication_bound( + binding.writer_epoch, + &binding.initializations, + Some(&binding.storage_incarnations), + Some(footer), + offset, + length, + check_route, + ) + } + fn check_physical_coordinates( + &self, + binding: &crate::initialized_log_manifest::PhysicalMemberBinding, + ) -> Result<(), ChunkLogError> { + if self.volume != binding.volume_id + || self.chunk != binding.chunk_id + || self.generation != binding.generation + { + return Err(refused("physical pin does not bind this chunk")); + } + Ok(()) + } + fn read_publication_bound( + &mut self, + epoch: u64, + initializations: &[[u8; 16]; LOG_REPLICAS], + storage: Option<&[[u8; 16]; LOG_REPLICAS]>, + footer: Option<&SealedFooter>, + offset: u64, + length: usize, + mut check_route: impl FnMut() -> Result<(), ChunkLogError>, + ) -> Result, ChunkLogError> { + let (source, published, capacity) = self.stabilize_publication_inner( + epoch, + initializations, + storage, + footer, + &mut check_route, + )?; let end = offset .checked_add(length as u64) .ok_or_else(|| refused("read range overflow"))?; @@ -61,8 +159,17 @@ impl ChunkLogReader { count, initializations[source], ); + let request = bind_storage(request, source, initializations, storage); let reply = self.read_call(source, |c| c.log_call(request.clone()))?; - self.check_publication_reply(&reply, epoch, initializations[source])?; + self.check_publication_reply( + &reply, + epoch, + initializations[source], + storage.map(|r| r[source]), + )?; + if footer.is_some_and(|footer| !matches_footer(&reply, footer)) { + return Err(refused("sealed physical read footer changed")); + } if reply.data.len() != count as usize { return Err(refused("short complete-prefix read")); } @@ -77,13 +184,18 @@ impl ChunkLogReader { reply: &LogOpReply, epoch: u64, initialization: [u8; 16], + storage: Option<[u8; 16]>, ) -> Result<(), ChunkLogError> { if reply.epoch != epoch { return Err(ChunkLogError::StaleEpoch { current: reply.epoch, }); } - if reply.publication_initialization() != Some(initialization) || !reply.publication_mode { + if (storage.is_some() && reply.storage_incarnation() != storage) + || (storage.is_none() && reply.publication_protocol != 4) + || reply.publication_initialization() != Some(initialization) + || !reply.publication_mode + { return Err(refused("unqualified publication member")); } Ok(()) @@ -95,6 +207,7 @@ impl ChunkLogReader { offset: u64, epoch: u64, initialization: [u8; 16], + storage: Option<[u8; 16]>, ) -> Result { let request = LogOpRequest::identity_initialized_publication( self.volume, @@ -103,18 +216,39 @@ impl ChunkLogReader { offset, initialization, ); + let request = storage.map_or_else( + || request.clone(), + |root| request.clone().for_storage(root, initialization), + ); let reply = self.read_call(member, |c| c.log_call(request.clone()))?; - self.check_publication_reply(&reply, epoch, initialization)?; + self.check_publication_reply(&reply, epoch, initialization, storage)?; Ok(reply) } // Start every qualified member's read-only probe before waiting for any reply. // Still collect all replies: a later member may report a newer writer epoch. - fn publication_probes(&mut self) -> [Result; LOG_REPLICAS] { + fn publication_probes( + &mut self, + initializations: &[[u8; 16]; LOG_REPLICAS], + storage: Option<&[[u8; 16]; LOG_REPLICAS]>, + ) -> [Result; LOG_REPLICAS] { let request = LogOpRequest::publication_probe(self.volume, self.chunk, self.generation); - let frame = std::sync::Arc::new(crate::cluster::message::encode_request( - &crate::cluster::message::ReplicaRequest::LogOp(request.clone()), - )); + let requests: [LogOpRequest; LOG_REPLICAS] = std::array::from_fn(|member| { + bind_storage(request.clone(), member, initializations, storage) + }); + let encode = |request: &LogOpRequest| { + std::sync::Arc::new(crate::cluster::message::encode_request( + &crate::cluster::message::ReplicaRequest::LogOp(request.clone()), + )) + }; + let first = encode(&requests[0]); + let frames: [std::sync::Arc>; LOG_REPLICAS] = std::array::from_fn(|member| { + if storage.is_none() || member == 0 { + first.clone() + } else { + encode(&requests[member]) + } + }); let reused: [bool; LOG_REPLICAS] = std::array::from_fn(|i| self.clients[i].is_some()); let mut failures: [Option; LOG_REPLICAS] = std::array::from_fn(|_| None); for (member, failure) in failures.iter_mut().enumerate() { @@ -133,7 +267,7 @@ impl ChunkLogReader { } match client.as_mut().unwrap().begin_encoded_before( crate::cluster::wire::RequestCode::LogOp, - frame.clone(), + frames[member].clone(), self.options.deadline, ) { Ok(reply) => pending[member] = Some(reply), @@ -182,7 +316,7 @@ impl ChunkLogReader { // Match read_call: retry an idle connection once, only for this read. return self .client(member) - .and_then(|client| client.log_call(request.clone())); + .and_then(|client| client.log_call(requests[member].clone())); } } result @@ -193,6 +327,8 @@ impl ChunkLogReader { &mut self, epoch: u64, initializations: &[[u8; 16]; LOG_REPLICAS], + storage: Option<&[[u8; 16]; LOG_REPLICAS]>, + footer: Option<&SealedFooter>, check_route: &mut impl FnMut() -> Result<(), ChunkLogError>, ) -> Result<(usize, u64, usize), ChunkLogError> { check_route()?; @@ -201,6 +337,19 @@ impl ChunkLogReader { "publication read requires three members and a writer epoch", )); } + if let Some(roots) = storage { + let mut ids = std::collections::HashSet::new(); + let mut tags = std::collections::HashSet::new(); + if roots.iter().any(|r| *r == [0; 16] || !ids.insert(*r)) + || initializations + .iter() + .any(|r| *r == [0; 16] || !tags.insert(*r)) + { + return Err(refused( + "physical read needs distinct nonzero member identities", + )); + } + } let mut addresses = std::collections::HashSet::new(); for endpoint in &self.endpoints { let address: std::net::SocketAddr = endpoint @@ -218,7 +367,11 @@ impl ChunkLogReader { } } let mut answers = Vec::with_capacity(LOG_REPLICAS); - for (member, result) in self.publication_probes().into_iter().enumerate() { + for (member, result) in self + .publication_probes(initializations, storage) + .into_iter() + .enumerate() + { let initialization = initializations[member]; let answer = match result { Ok(reply) => { @@ -228,6 +381,11 @@ impl ChunkLogReader { }); } (reply.epoch == epoch + && footer.is_none_or(|footer| matches_footer(&reply, footer)) + && match storage { + Some(roots) => reply.storage_incarnation() == Some(roots[member]), + None => reply.publication_protocol == 4, + } && reply .initialized_publication_prefix(initialization) .is_some()) @@ -277,6 +435,7 @@ impl ChunkLogReader { short_tip.offset, epoch, initializations[source], + storage.map(|r| r[source]), )?; if observed.record_identity() != Some(short_tip) || !observed.record_publication @@ -295,7 +454,11 @@ impl ChunkLogReader { let Some(answer) = answers[target].as_ref() else { continue; }; - if target == source || !answer.has_publication_write_protocol() { + let writable = match storage { + Some(roots) => answer.has_storage_write_protocol(roots[target]), + None => answer.has_publication_write_protocol(), + }; + if target == source || !writable { continue; } let mut route_error = None; @@ -304,6 +467,7 @@ impl ChunkLogReader { target, epoch, initializations, + storage, published, &mut || { let result = check_route(); @@ -341,6 +505,7 @@ impl ChunkLogReader { target: usize, epoch: u64, initializations: &[[u8; 16]; LOG_REPLICAS], + storage: Option<&[[u8; 16]; LOG_REPLICAS]>, published: u64, check_route: &mut impl FnMut() -> Result<(), ChunkLogError>, ) -> Result<(), ChunkLogError> { @@ -348,8 +513,13 @@ impl ChunkLogReader { // compares both identity and bytes on retries; no payload equality creates ownership. let mut offset = 0; while offset < published { - let record = - self.publication_identity_at(source, offset, epoch, initializations[source])?; + let record = self.publication_identity_at( + source, + offset, + epoch, + initializations[source], + storage.map(|r| r[source]), + )?; let identity = record .record_identity() .ok_or(ChunkLogError::AttemptMismatch { offset })?; @@ -375,8 +545,14 @@ impl ChunkLogReader { identity.length, initializations[source], ); + let request = bind_storage(request, source, initializations, storage); let data = self.read_call(source, |c| c.log_call(request.clone()))?; - self.check_publication_reply(&data, epoch, initializations[source])?; + self.check_publication_reply( + &data, + epoch, + initializations[source], + storage.map(|r| r[source]), + )?; if data.data.len() != identity.length as usize { return Err(refused("short repair record")); } @@ -392,14 +568,26 @@ impl ChunkLogReader { record.record_published_length, initializations[target], ); + let request = bind_storage(request, target, initializations, storage); // A transport error is unknown. Only a later fresh probe may certify durability. let reply = self.client(target)?.log_call(request)?; - self.check_publication_reply(&reply, epoch, initializations[target])?; + self.check_publication_reply( + &reply, + epoch, + initializations[target], + storage.map(|r| r[target]), + )?; offset = end; } let request = LogOpRequest::publication_probe(self.volume, self.chunk, self.generation); + let request = bind_storage(request, target, initializations, storage); let reply = self.read_call(target, |c| c.log_call(request.clone()))?; - self.check_publication_reply(&reply, epoch, initializations[target])?; + self.check_publication_reply( + &reply, + epoch, + initializations[target], + storage.map(|r| r[target]), + )?; if reply.published_length < published { return Err(refused("repair is not durable")); } @@ -407,3 +595,23 @@ impl ChunkLogReader { Ok(()) } } + +fn bind_storage( + request: LogOpRequest, + member: usize, + initializations: &[[u8; 16]; LOG_REPLICAS], + storage: Option<&[[u8; 16]; LOG_REPLICAS]>, +) -> LogOpRequest { + match storage { + Some(roots) => request.for_storage(roots[member], initializations[member]), + None => request, + } +} + +fn matches_footer(reply: &LogOpReply, footer: &SealedFooter) -> bool { + reply.sealed + && reply.length == footer.length + && reply.published_length == footer.length + && reply.crc == footer.crc + && reply.sha256 == footer.sha256 +} diff --git a/src/initialized_log_manifest.rs b/src/initialized_log_manifest.rs index 91d43f5b..4c406f78 100644 --- a/src/initialized_log_manifest.rs +++ b/src/initialized_log_manifest.rs @@ -10,6 +10,8 @@ use std::collections::BTreeSet; /// A manifest whose LOG extents carry explicit initialization and writer identities. /// Earlier manifest readers reject this version instead of dropping those identities. pub const CHUNK_MANIFEST_INITIALIZED_FORMAT: u32 = 2; +/// Physical storage qualification is mandatory in this format. +pub const CHUNK_MANIFEST_PHYSICAL_FORMAT: u32 = 3; #[derive(Clone, PartialEq, Eq, Message)] pub struct InitializedReplica { @@ -20,6 +22,8 @@ pub struct InitializedReplica { /// and must catch up before metadata publishes that replacement as a ready member. #[prost(bytes = "vec", tag = "2")] pub initialization: Vec, + #[prost(bytes = "vec", tag = "3")] + pub storage_incarnation: Vec, } #[derive(Clone, PartialEq, Eq, Message)] pub struct InitializedChunk { @@ -58,8 +62,10 @@ fn member_name(name: &str) -> bool { } impl InitializedLogManifest { pub fn validate_for(&self, manifest: &ChunkManifest) -> Result<(), ObjectError> { - if manifest.format_version != CHUNK_MANIFEST_INITIALIZED_FORMAT - || !identity(&self.object_incarnation) + if !matches!( + manifest.format_version, + CHUNK_MANIFEST_INITIALIZED_FORMAT | CHUNK_MANIFEST_PHYSICAL_FORMAT + ) || !identity(&self.object_incarnation) || self.chunks.len() != manifest.extents.len() || (!manifest.deleted && manifest.kind != CHUNK_KIND_LOG) || (manifest.deleted && !self.chunks.is_empty()) @@ -80,11 +86,17 @@ impl InitializedLogManifest { )); } let mut members = BTreeSet::new(); + let mut storage = BTreeSet::new(); for replica in &chunk.replicas { if !member_name(&replica.member_id) || !identity(&replica.initialization) || !members.insert(&replica.member_id) || !initializations.insert(&replica.initialization) + || (manifest.format_version == CHUNK_MANIFEST_INITIALIZED_FORMAT + && !replica.storage_incarnation.is_empty()) + || (manifest.format_version == CHUNK_MANIFEST_PHYSICAL_FORMAT + && (!identity(&replica.storage_incarnation) + || !storage.insert(&replica.storage_incarnation))) { return Err(invalid( "initialized LOG chunk repeats or omits a storage identity", @@ -95,3 +107,74 @@ impl InitializedLogManifest { Ok(()) } } + +/// One extent's immutable metadata-qualified physical member identities. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PhysicalMemberBinding { + pub writer_epoch: u64, + pub generation: u32, + pub volume_id: u64, + pub chunk_id: u64, + pub initializations: [[u8; 16]; 3], + pub storage_incarnations: [[u8; 16]; 3], + pub member_ids: [String; 3], +} +impl InitializedLogManifest { + pub fn physical_binding( + &self, + manifest: &ChunkManifest, + index: usize, + ) -> Result { + // This is a lookup in an immutable metadata-validated manifest. Recheck only the + // selected extent, keeping per-read binding work independent of corpus size. + if !identity(&self.object_incarnation) || self.chunks.len() != manifest.extents.len() { + return Err(invalid("physical binding shape differs")); + } + if manifest.format_version != CHUNK_MANIFEST_PHYSICAL_FORMAT { + return Err(invalid("physical member binding requires manifest format3")); + } + let chunk = self + .chunks + .get(index) + .ok_or_else(|| invalid("physical binding extent is absent"))?; + let extent = &manifest.extents[index]; + if chunk.extent_index as usize != index + || chunk.chunk_generation == 0 + || chunk.writer_epoch == 0 + || chunk.replicas.len() != 3 + || chunk.replicas.iter().enumerate().any(|(i, r)| { + !member_name(&r.member_id) + || !identity(&r.storage_incarnation) + || !identity(&r.initialization) + || chunk.replicas[..i].iter().any(|old| { + old.member_id == r.member_id + || old.storage_incarnation == r.storage_incarnation + || old.initialization == r.initialization + }) + }) + { + return Err(invalid("selected physical member binding is invalid")); + } + Ok(PhysicalMemberBinding { + writer_epoch: chunk.writer_epoch, + generation: chunk.chunk_generation, + volume_id: extent.volume_id, + chunk_id: extent.chunk_id, + initializations: std::array::from_fn(|i| { + chunk.replicas[i] + .initialization + .as_slice() + .try_into() + .unwrap() + }), + storage_incarnations: std::array::from_fn(|i| { + chunk.replicas[i] + .storage_incarnation + .as_slice() + .try_into() + .unwrap() + }), + member_ids: std::array::from_fn(|i| chunk.replicas[i].member_id.clone()), + }) + } +} diff --git a/src/initialized_log_manifest_tests.rs b/src/initialized_log_manifest_tests.rs index 90baf5a6..fe390dee 100644 --- a/src/initialized_log_manifest_tests.rs +++ b/src/initialized_log_manifest_tests.rs @@ -31,6 +31,7 @@ pub(crate) fn fixture() -> ChunkManifest { replicas: (0..3) .map(|i| InitializedReplica { member_id: format!("member-{i}"), + storage_incarnation: Vec::new(), initialization: vec![i + 2; 16], }) .collect(), diff --git a/src/lib.rs b/src/lib.rs index 4d453681..1d4128df 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -317,3 +317,6 @@ mod repo_guard_tests; #[cfg(test)] mod native_object_outcome_tests; + +#[cfg(test)] +mod physical_member_binding_tests; diff --git a/src/native_object_outcome.rs b/src/native_object_outcome.rs index 3353efe7..45c37530 100644 --- a/src/native_object_outcome.rs +++ b/src/native_object_outcome.rs @@ -204,7 +204,7 @@ impl NativeObjectChange { .checked_add(1) .ok_or_else(|| invalid("native metadata position exhausted"))?; let change = Self { - version: 1, + version: 2, now_ms, operation: Some(operation), }; @@ -215,7 +215,7 @@ impl NativeObjectChange { Some(crate::object_manifest::admission_cap()), )?; let outcome = crate::placement_outcome::PlacementOutcome { - version: 18, + version: 19, before_index, after_index, native: Some(change), @@ -225,7 +225,7 @@ impl NativeObjectChange { Ok(outcome) } pub fn validate(&self, before: u64, after: u64) -> Result<(), ObjectError> { - if self.version != 1 + if !matches!(self.version, 1 | 2) || self.now_ms == 0 || before == 0 || before.checked_add(1) != Some(after) @@ -243,6 +243,14 @@ impl NativeObjectChange { .as_ref() .ok_or_else(|| invalid("native begin lacks its stage"))?; start.validate()?; + if (self.version == 2) + != (start.header()?.format_version + == crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT) + { + return Err(invalid( + "native command version does not bind physical member identities", + )); + } prior_lease(command.expected_lease.as_ref(), before)?; if start.stage_id != after || start.writer_epoch != after @@ -265,6 +273,17 @@ impl NativeObjectChange { .chunk .as_ref() .ok_or_else(|| invalid("native extension lacks its chunk"))?; + if chunk.initialization.as_ref().is_some_and(|c| { + c.replicas.iter().any(|r| { + (self.version == 2) + != (r.storage_incarnation.len() == 16 + && r.storage_incarnation.iter().any(|b| *b != 0)) + }) + }) { + return Err(invalid( + "native extension version does not bind physical members", + )); + } if chunk.allocation_id != after || chunk.extent.is_none() || chunk.initialization.is_none() @@ -287,6 +306,14 @@ impl NativeObjectChange { .as_ref() .ok_or_else(|| invalid("native publication lacks its manifest"))?; manifest.validate()?; + if (self.version == 2) + != (manifest.format_version + == crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT) + { + return Err(invalid( + "native publication version does not bind physical members", + )); + } prior_lease(command.expected_lease.as_ref(), before)?; if manifest.deleted || manifest.initialized_log.is_none() { return Err(invalid("native publication is not initialized live data")); @@ -401,6 +428,46 @@ impl NativeObjectChange { "native outcome does not follow the activated metadata state", )); } + if self.version == 1 { + let physical = |m: &ChunkManifest| { + m.format_version == crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT + }; + let state = &service.native_objects; + let stage_id = match self.operation.as_ref().unwrap() { + Operation::Extend(c) => c.stage.as_ref().map(|s| s.stage_id), + Operation::Publish(c) => c.stage.as_ref().map(|s| s.stage_id), + Operation::Abort(c) => Some(c.stage_id), + Operation::ExpireStage(c) => Some(c.stage_id), + _ => None, + }; + let pin_id = match self.operation.as_ref().unwrap() { + Operation::RenewPin(c) => Some(c.pin_id), + Operation::ClosePin(c) | Operation::ExpirePin(c) => Some(c.pin_id), + _ => None, + }; + let object = match self.operation.as_ref().unwrap() { + Operation::Begin(c) => Some(c.start.as_ref().unwrap().header()?.object_id()), + Operation::OpenPin(c) => Some(names(&c.bucket, &c.key)?), + Operation::RenewWriter(c) => Some(names(&c.bucket, &c.key)?), + Operation::ReleaseWriter(c) => Some(names(&c.bucket, &c.key)?), + _ => None, + }; + if stage_id + .and_then(|id| state.stage_start(id)) + .is_some_and(|s| physical(s.header.as_ref().unwrap())) + || pin_id + .and_then(|id| state.pin(id)) + .and_then(|p| state.pinned_manifest(p.pin_id, p.expires_at_ms - 1).ok()) + .is_some_and(|m| physical(&m)) + || object + .and_then(|id| service.chunk_catalog.get(&id)) + .is_some_and(|m| physical(m)) + { + return Err(refused( + "physical member state requires native command version2", + )); + } + } let mut draft = NativeDraft { state: service.native_objects.clone(), catalog: service.chunk_catalog.clone(), diff --git a/src/native_object_outcome_tests.rs b/src/native_object_outcome_tests.rs index 7ddf66a1..c1b60106 100644 --- a/src/native_object_outcome_tests.rs +++ b/src/native_object_outcome_tests.rs @@ -2,7 +2,17 @@ // Copyright 2026 MatrixArkAI use crate::native_object_outcome::{native_operation::Operation, *}; use crate::native_object_state::NativeReadPin; -use crate::native_object_state_tests::{chunk, hash, publication, start}; +use crate::native_object_state_tests::{chunk, hash, publication, start as legacy_start}; +fn start( + id: u64, + before: Option<&crate::chunk_manifest::ChunkManifest>, + target: u64, +) -> crate::native_object_state::NativeStageStart { + let mut s = legacy_start(id, before, target); + s.header.as_mut().unwrap().format_version = + crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT; + s +} use crate::placement_outcome::PlacementOutcome; use crate::MatrixMetaService; @@ -188,7 +198,7 @@ fn rejected_stage_commands_leave_full_metadata_snapshot_unchanged() { } } let change = NativeObjectChange { - version: 1, + version: 2, now_ms: 1001, operation: Some(Operation::Extend(command)), }; @@ -210,7 +220,7 @@ fn outcome_version_and_envelope_fields_are_exclusive() { match field { 0 => bad.version = 17, 1 => bad.native = None, - 2 => bad.native.as_mut().unwrap().version = 2, + 2 => bad.native.as_mut().unwrap().version = 3, 3 => bad.native.as_mut().unwrap().now_ms = 0, 4 => bad.after_index += 1, _ => bad.forget = true, diff --git a/src/native_object_state.rs b/src/native_object_state.rs index b7b4a8c4..9134e1a8 100644 --- a/src/native_object_state.rs +++ b/src/native_object_state.rs @@ -104,7 +104,11 @@ impl NativeStageStart { || self.request_nonce.len() != 32 || self.request_nonce.iter().all(|b| *b == 0) || header.deleted - || header.format_version != CHUNK_MANIFEST_INITIALIZED_FORMAT + || !matches!( + header.format_version, + CHUNK_MANIFEST_INITIALIZED_FORMAT + | crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT + ) || header.kind != CHUNK_KIND_LOG || header.length != 0 || !header.extents.is_empty() @@ -205,7 +209,8 @@ impl Stage { (STAGE_REPLACE, None) => {} (STAGE_ADD_TAIL, Some(base)) => { base.validate()?; - if base.deleted + if base.format_version != start.header()?.format_version + || base.deleted || base.initialized_log.is_none() || base.object_id() != start.header()?.object_id() || base.generation != start.expected_generation @@ -492,6 +497,19 @@ struct StateImage { retired_stages: Vec, } impl NativeObjectState { + pub fn has_physical_bindings(&self) -> bool { + let physical = |m: &ChunkManifest| { + m.format_version == crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT + }; + self.stages + .values() + .any(|s| physical(s.start.header.as_ref().unwrap())) + || self + .retired_stages + .values() + .any(|s| physical(s.stage.start.header.as_ref().unwrap())) + || self.retained.values().any(|r| physical(&r.manifest)) + } pub fn image_size_bound(&self) -> usize { self.body_bytes + IMAGE_HEADER_ALLOWANCE } @@ -608,6 +626,9 @@ impl NativeObjectState { pub fn last_position(&self) -> u64 { self.last_position } + pub(crate) fn stage_for_object(&self, id: &ObjectId) -> Option<&NativeStageStart> { + self.owners.get(id).and_then(|id| self.stage_start(*id)) + } pub fn stage_start(&self, id: u64) -> Option<&NativeStageStart> { self.stages.get(&id).map(|s| &s.start) } @@ -945,6 +966,19 @@ impl NativeObjectState { .manifest .clone()) } + pub fn physical_read_binding( + &self, + pin_id: u64, + extent_index: usize, + now: u64, + ) -> Result { + let manifest = self.pinned_manifest(pin_id, now)?; + manifest + .initialized_log + .as_ref() + .ok_or_else(|| corrupt("pin lacks initialized members"))? + .physical_binding(&manifest, extent_index) + } pub fn renew_pin( &mut self, id: u64, @@ -1031,7 +1065,7 @@ impl NativeObjectState { } pub fn to_bytes(&self) -> Result, ObjectError> { let image = StateImage { - version: 1, + version: if self.has_physical_bindings() { 2 } else { 1 }, revision: self.revision, last_position: self.last_position, stages: self.stages.values().map(|s| s.image()).collect(), @@ -1055,7 +1089,8 @@ impl NativeObjectState { } pub fn from_bytes(bytes: &[u8]) -> Result { let image: StateImage = unframe(b"MONS", bytes, MAX_IMAGE)?; - if image.version != 1 + let image_version = image.version; + if !matches!(image.version, 1 | 2) || image .stages .len() @@ -1193,6 +1228,11 @@ impl NativeObjectState { if state.retained.values().any(|r| r.readers == 0) { return Err(corrupt("native state retains an unpinned generation")); } + if (image_version == 2) != state.has_physical_bindings() { + return Err(corrupt( + "native state version does not bind physical identities", + )); + } Ok(state) } } diff --git a/src/native_object_state_tests.rs b/src/native_object_state_tests.rs index 38ea8c0a..b9812a69 100644 --- a/src/native_object_state_tests.rs +++ b/src/native_object_state_tests.rs @@ -76,6 +76,13 @@ pub(crate) fn chunk( replicas: (0..3) .map(|i| InitializedReplica { member_id: format!("member-{i}"), + storage_incarnation: if s.header.as_ref().unwrap().format_version + == CHUNK_MANIFEST_PHYSICAL_FORMAT + { + vec![40 + i; 16] + } else { + Vec::new() + }, initialization: vec![(allocation as u8).wrapping_mul(3).wrapping_add(i); 16], }) .collect(), @@ -412,7 +419,7 @@ fn native_service() -> crate::MatrixMetaService { service } #[test] -fn metadata_snapshot_25_preserves_staged_ownership_and_immutable_captures() { +fn metadata_snapshot_26_preserves_staged_ownership_and_immutable_captures() { let mut service = native_service(); let s = start(10, None, 4); let owned = chunk(&s, 11, 0, 4, 0); @@ -427,7 +434,7 @@ fn metadata_snapshot_25_preserves_staged_ownership_and_immutable_captures() { service.placement_commit_index = 11; let captured = service.export_snapshot(); let bytes = captured.to_bytes().unwrap(); - assert!(bytes.windows(11).any(|b| b == b"MOSRSMETA25")); + assert!(bytes.windows(11).any(|b| b == b"MOSRSMETA26")); let decoded = crate::MetaSnapshot::from_bytes(&bytes).unwrap(); assert_eq!(decoded, captured); let streamed = @@ -520,8 +527,8 @@ fn native_snapshot_rejects_downgraded_and_future_floor_and_corrupted_state_blob( .unwrap(); service.placement_commit_index = 10; let bytes = service.export_snapshot().to_bytes().unwrap(); - let magic = bytes.windows(11).position(|b| b == b"MOSRSMETA25").unwrap(); - for last in [b'4', b'6'] { + let magic = bytes.windows(11).position(|b| b == b"MOSRSMETA26").unwrap(); + for last in [b'4', b'5', b'7'] { let mut bad = bytes.clone(); bad[magic + 10] = last; assert!(crate::MetaSnapshot::from_bytes(&bad).is_err()); @@ -637,6 +644,7 @@ fn many_read_pins_encode_one_large_retained_manifest_per_generation() { key.extend_from_slice(&slot.to_le_bytes()); InitializedReplica { member_id: format!("member-{slot}"), + storage_incarnation: Vec::new(), initialization: crate::chunk_integrity::sha256(&key)[..16].to_vec(), } }) diff --git a/src/physical_member_binding_tests.rs b/src/physical_member_binding_tests.rs new file mode 100644 index 00000000..c951857d --- /dev/null +++ b/src/physical_member_binding_tests.rs @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +use crate::initialized_log_manifest::*; +use crate::native_object_outcome::{native_operation::Operation, *}; +use crate::native_object_state_tests::{chunk, hash, publication, start}; +use crate::{MatrixMetaService, MetaSnapshot}; +pub(crate) fn physical_start( + id: u64, + before: Option<&crate::chunk_manifest::ChunkManifest>, + length: u64, +) -> crate::native_object_state::NativeStageStart { + let mut s = start(id, before, length); + s.header.as_mut().unwrap().format_version = CHUNK_MANIFEST_PHYSICAL_FORMAT; + s +} +pub(crate) fn commit(s: &mut MatrixMetaService, op: Operation, now: u64) { + let decided = NativeObjectChange::decide(s, op, now).unwrap(); + assert_eq!(decided.version, 19); + crate::placement_outcome::PlacementOutcome::from_payload(&decided.to_payload().unwrap()) + .unwrap() + .apply(s) + .unwrap(); +} +pub(crate) fn stage_ref(id: u64, revision: u64) -> NativeStageRef { + NativeStageRef { + stage_id: id, + expected_revision: revision, + holder: "writer".into(), + } +} +pub(crate) fn published() -> MatrixMetaService { + let mut s = crate::native_object_outcome_tests::service(); + for (op, now) in crate::native_object_outcome_tests::commands() { + commit(&mut s, op, now); + } + s +} +#[test] +fn physical_manifest_and_selected_binding_preserve_member_order_and_coordinates() { + let start = physical_start(2, None, 4); + let owned = chunk(&start, 3, 0, 4, 0); + let m = publication(&start, &[owned]); + let decoded = crate::chunk_manifest::ChunkManifest::from_bytes(&m.to_bytes().unwrap()).unwrap(); + assert_eq!(decoded, m); + let binding = m + .initialized_log + .as_ref() + .unwrap() + .physical_binding(&m, 0) + .unwrap(); + assert_eq!( + ( + binding.volume_id, + binding.chunk_id, + binding.generation, + binding.writer_epoch + ), + (0, 3, 1, 2) + ); + assert_eq!(binding.storage_incarnations, [[40; 16], [41; 16], [42; 16]]); + assert!(m + .initialized_log + .as_ref() + .unwrap() + .physical_binding(&m, 1) + .is_err()); +} +#[test] +fn versioned_manifests_refuse_missing_repeated_and_silently_dropped_physical_ids() { + let start = physical_start(2, None, 4); + let good = publication(&start, &[chunk(&start, 3, 0, 4, 0)]); + for field in 0..5 { + let mut m = good.clone(); + let replicas = &mut m.initialized_log.as_mut().unwrap().chunks[0].replicas; + match field { + 0 => replicas[0].storage_incarnation.clear(), + 1 => replicas[0].storage_incarnation = vec![0; 16], + 2 => replicas[1].storage_incarnation = replicas[0].storage_incarnation.clone(), + 3 => replicas[0].storage_incarnation.push(1), + _ => m.format_version = CHUNK_MANIFEST_INITIALIZED_FORMAT, + }; + assert!(m.to_bytes().is_err(), "accepted field{field}"); + } +} +fn set_floor(mut bytes: Vec, floor: &[u8]) -> Vec { + let at = bytes.windows(11).position(|s| s == b"MOSRSMETA26").unwrap(); + bytes[at..at + 11].copy_from_slice(floor); + let mut placeholder = String::new(); + crate::append_etag_of_digest(&mut placeholder, 0); + bytes.truncate(bytes.len() - 8 - placeholder.len()); + let mut checksum = String::new(); + crate::append_etag_of_digest(&mut checksum, crate::fnv1a64(&bytes)); + crate::append_string(&mut bytes, &checksum); + bytes +} +#[test] +fn snapshot26_binds_physical_state_and_resigned_snapshot25_cannot_hide_it() { + let s = published(); + let bytes = s.export_snapshot().to_bytes().unwrap(); + assert_eq!( + MetaSnapshot::from_bytes(&bytes).unwrap(), + s.export_snapshot() + ); + assert_eq!( + MetaSnapshot::read_from(&mut std::io::Cursor::new(&bytes), bytes.len() as u64).unwrap(), + s.export_snapshot() + ); + let downgraded = set_floor(bytes, b"MOSRSMETA25"); + assert!(MetaSnapshot::from_bytes(&downgraded) + .unwrap_err() + .to_string() + .contains("snapshot26")); +} +#[test] +fn historical_snapshot25_and_outcome18_remain_readable() { + let mut s = crate::native_object_outcome_tests::service(); + let start = start(2, None, 4); + let change = NativeObjectChange { + version: 1, + now_ms: 1000, + operation: Some(Operation::Begin(NativeBegin { + start: Some(start), + ..Default::default() + })), + }; + let outcome = crate::placement_outcome::PlacementOutcome { + version: 18, + before_index: 1, + after_index: 2, + native: Some(change), + ..Default::default() + }; + let bytes = outcome.to_payload().unwrap(); + crate::placement_outcome::PlacementOutcome::from_payload(&bytes) + .unwrap() + .apply(&mut s) + .unwrap(); + let snapshot = s.export_snapshot(); + let old = set_floor(snapshot.to_bytes().unwrap(), b"MOSRSMETA25"); + assert_eq!(MetaSnapshot::from_bytes(&old).unwrap(), snapshot); +} +#[test] +fn retained_pin_keeps_physical_members_across_a_new_object_incarnation() { + let mut s = published(); + let id = start(2, None, 4).header.unwrap().object_id(); + let old = (**s.chunk_catalog.get(&id).unwrap()).clone(); + commit( + &mut s, + Operation::OpenPin(crate::native_object_state::NativeReadPin { + pin_id: 5, + bucket: id.bucket.to_string(), + key: id.key.to_string(), + generation: old.generation, + manifest_digest: hash(&old), + expires_at_ms: 5000, + }), + 1003, + ); + let captured = s.native_objects.physical_read_binding(5, 0, 1003).unwrap(); + let lease = s.writer_leases.get(&id.bucket, &id.key); + let replacement = physical_start(6, Some(&old), 4); + let owned = chunk(&replacement, 7, 0, 4, 0); + let after = publication(&replacement, &[owned.clone()]); + commit( + &mut s, + Operation::Begin(NativeBegin { + start: Some(replacement), + expected_lease: lease.clone(), + bypass_governance: false, + }), + 1000, + ); + commit( + &mut s, + Operation::Extend(NativeExtend { + stage: Some(stage_ref(6, 6)), + chunk: Some(owned), + }), + 1004, + ); + commit( + &mut s, + Operation::Publish(NativePublish { + stage: Some(stage_ref(6, 7)), + manifest: Some(after), + expected_lease: lease, + }), + 1005, + ); + assert_eq!( + s.native_objects.physical_read_binding(5, 0, 1006).unwrap(), + captured + ); + let mut restored = MatrixMetaService::new(); + restored + .install_snapshot( + MetaSnapshot::from_bytes(&s.export_snapshot().to_bytes().unwrap()).unwrap(), + ) + .unwrap(); + assert_eq!( + restored + .native_objects + .physical_read_binding(5, 0, 1006) + .unwrap(), + captured + ); + assert!(restored + .native_objects + .physical_read_binding(5, 0, 5000) + .is_err()); +} +#[test] +fn legacy_native_commands_cannot_operate_on_physical_member_state() { + let mut s = published(); + let id = start(2, None, 4).header.unwrap().object_id(); + let m = (**s.chunk_catalog.get(&id).unwrap()).clone(); + let change = NativeObjectChange { + version: 1, + now_ms: 1003, + operation: Some(Operation::OpenPin( + crate::native_object_state::NativeReadPin { + pin_id: 5, + bucket: m.bucket, + key: m.key, + generation: m.generation, + manifest_digest: hash(s.chunk_catalog.get(&id).unwrap()), + expires_at_ms: 5000, + }, + )), + }; + let saved = s.export_snapshot().to_bytes().unwrap(); + assert!(change.apply(&mut s, 4, 5).is_err()); + assert_eq!(s.export_snapshot().to_bytes().unwrap(), saved); + assert!(NativeObjectChange::decide( + &s, + Operation::Begin(NativeBegin { + start: Some(start(5, Some(s.chunk_catalog.get(&id).unwrap()), 4)), + expected_lease: s.writer_leases.get(&id.bucket, &id.key), + bypass_governance: false + }), + 1000 + ) + .is_err()); +} diff --git a/src/placement_outcome.rs b/src/placement_outcome.rs index 45b7936d..769d8af6 100644 --- a/src/placement_outcome.rs +++ b/src/placement_outcome.rs @@ -434,9 +434,9 @@ impl PlacementOutcome { /// `manifest_validated` says the publication's manifests were validated by the caller /// (the expansion of a compact append), so they are not walked again. fn validate_manifest_binding_with(&self, manifest_validated: bool) -> Result<(), ObjectError> { - if self.native.is_some() || self.version == 18 { - let change = self.native.as_ref().filter(|_| self.version == 18) - .ok_or_else(|| invalid("a native outcome is version 18 and carries its change"))?; + if self.native.is_some() || matches!(self.version,18|19) { + let change = self.native.as_ref().filter(|c| (self.version==18 && c.version==1)||(self.version==19 && c.version==2)) + .ok_or_else(|| invalid("native outcome version and change version must agree"))?; change.validate(self.before_index, self.after_index)?; if self.manifest.is_some() || self.retention.is_some() || self.staging.is_some() || self.publication_fence.is_some() || self.copy_source.is_some() || self.retention_deadline.is_some() diff --git a/src/protocol/metadata/snapshot_decode.inc.rs b/src/protocol/metadata/snapshot_decode.inc.rs index b7796b5f..69a9ad6e 100644 --- a/src/protocol/metadata/snapshot_decode.inc.rs +++ b/src/protocol/metadata/snapshot_decode.inc.rs @@ -29,7 +29,7 @@ impl MetaSnapshot { let version = magic .strip_prefix("MOSRSMETA") .and_then(|suffix| suffix.parse::().ok()) - .filter(|version| (1..=25).contains(version)) + .filter(|version| (1..=26).contains(version)) .ok_or_else(|| { ObjectError::Corruption("metadata snapshot byte magic mismatch".to_string()) })?; @@ -38,8 +38,8 @@ impl MetaSnapshot { "metadata snapshot byte magic mismatch".to_string(), )); } - if cursor.stream.is_some() && !(18..=25).contains(&version) { - return Err(ObjectError::Corruption("streamed metadata snapshot needs version 18 through 25".into())); + if cursor.stream.is_some() && !(18..=26).contains(&version) { + return Err(ObjectError::Corruption("streamed metadata snapshot needs version 18 through 26".into())); } let has_transaction_read_versions = version >= 2; let has_tombstone_compaction_counters = version >= 3; @@ -371,7 +371,7 @@ impl MetaSnapshot { if (version >= 24) != cluster_features.has(crate::cluster_features::FEATURE_UNIFIED_LOG_WRITERS) { return Err(ObjectError::Corruption("unified writer snapshot reader floor mismatch".into())); } - if (version == 25) != cluster_features.has(crate::cluster_features::FEATURE_NATIVE_OBJECT_STATE) { + if (version >= 25) != cluster_features.has(crate::cluster_features::FEATURE_NATIVE_OBJECT_STATE) { return Err(ObjectError::Corruption("native object snapshot reader floor mismatch".into())); } let writer_leases = if version >= 22 { @@ -409,6 +409,9 @@ impl MetaSnapshot { let bytes = cursor.read_owned_blob(64 * 1024 * 1024 + 12)?; crate::native_object_state::NativeObjectState::from_bytes(&bytes)? } else { Default::default() }; + if version<26 && (native_objects.has_physical_bindings() || chunk_catalog.iter().any(|(_,m)| m.format_version==crate::initialized_log_manifest::CHUNK_MANIFEST_PHYSICAL_FORMAT)) { + return Err(ObjectError::Corruption("physical storage bindings require snapshot26".into())); + } let checksum = cursor.read_string()?; let envelope_digest = cursor.prefix_digest(); let envelope_checksum = cursor.read_string()?; diff --git a/src/protocol/metadata/snapshot_encode.inc.rs b/src/protocol/metadata/snapshot_encode.inc.rs index 5237fb3f..34e67176 100644 --- a/src/protocol/metadata/snapshot_encode.inc.rs +++ b/src/protocol/metadata/snapshot_encode.inc.rs @@ -42,7 +42,7 @@ impl MetaSnapshot { let has_features = !self.cluster_features.is_default() || has_leases; let has_group_bytes = has_group_bytes || has_features; let version = if native_objects { - "MOSRSMETA25" + "MOSRSMETA26" } else if unified_writers { "MOSRSMETA24" } else if has_chunk_catalog { diff --git a/src/repo_guard_tests.rs b/src/repo_guard_tests.rs index 0254516d..7a589486 100644 --- a/src/repo_guard_tests.rs +++ b/src/repo_guard_tests.rs @@ -797,6 +797,7 @@ fn every_durable_format_constant_is_accounted_for() { "MOSRSMETA23", "MOSRSMETA24", "MOSRSMETA25", + "MOSRSMETA26", "MOSRSOWNER1", "MOSRSANCHOR1", "MOSRSCHUNKS1", @@ -942,7 +943,7 @@ fn every_durable_format_constant_is_accounted_for() { ); assert_eq!( found.len(), - 120, + 121, "the count is pinned as well, so a rename that happens to swap two names cannot pass" ); }