Skip to main content

rocketmq_runtime/
metadata_io.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Bounded, generation-aware metadata persistence.
16//!
17//! [`MetadataIoActor`] is the sole owner of admitted metadata snapshots. It
18//! coalesces queued generations for the same logical resource, executes
19//! synchronous filesystem work on a dedicated [`BlockingExecutor`] lane, and
20//! advances the durable generation only after the atomic replacement protocol
21//! completes.
22//!
23//! Acceptance reserves ownership and bytes; it is not a durability result.
24//! An observation timeout stops waiting, not an already-started filesystem
25//! write. Unconfirmed writes retain ordering and reconciliation obligations.
26//! Target ownership is process-local and does not replace an application's
27//! cross-process locking or format-specific recovery protocol.
28
29mod filesystem;
30
31use std::collections::HashMap;
32use std::collections::VecDeque;
33use std::fmt;
34use std::num::NonZeroUsize;
35use std::path::Path;
36use std::path::PathBuf;
37use std::sync::atomic::AtomicUsize;
38use std::sync::atomic::Ordering;
39use std::sync::Arc;
40use std::sync::Weak;
41use std::time::Duration;
42
43use futures::stream::FuturesUnordered;
44use futures::StreamExt;
45use parking_lot::Mutex;
46use tokio::sync::mpsc;
47use tokio::sync::oneshot;
48use tokio::sync::Notify;
49use tokio_util::sync::CancellationToken;
50
51use crate::metadata_target::MetadataTargetIdentity;
52use crate::metadata_target::MetadataTargetRegistration;
53use crate::metadata_target::MetadataTargetRegistrationStatus;
54use crate::metadata_target::MetadataTargetRegistry;
55use crate::metadata_target::MetadataTargetRetirementStatus;
56use crate::resource_budget::BudgetCapacity;
57use crate::resource_budget::BudgetLimit;
58use crate::resource_budget::FullPolicy;
59use crate::resource_budget::ResourceBudget;
60use crate::resource_budget::ResourcePermit;
61use crate::shutdown_deadline::ShutdownDeadline;
62use crate::BlockingExecutor;
63use crate::BlockingPoolPolicy;
64use crate::ChildServiceContext;
65use crate::RuntimeContractPolicy;
66use crate::RuntimeContractViolation;
67use crate::RuntimeError;
68use crate::RuntimeResult;
69
70/// An immutable absolute deadline for metadata admission and durability waits.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct MetadataDeadline {
73    at: tokio::time::Instant,
74}
75
76impl MetadataDeadline {
77    /// Freezes a relative timeout into one absolute Tokio deadline.
78    #[must_use]
79    pub fn after(timeout: Duration) -> Self {
80        let now = tokio::time::Instant::now();
81        Self {
82            at: now.checked_add(timeout).unwrap_or(now),
83        }
84    }
85
86    /// Uses an existing absolute Tokio deadline.
87    #[must_use]
88    pub const fn at(at: tokio::time::Instant) -> Self {
89        Self { at }
90    }
91
92    /// Returns the immutable absolute expiry instant.
93    #[must_use]
94    pub const fn instant(self) -> tokio::time::Instant {
95        self.at
96    }
97
98    /// Returns the remaining budget without extending the deadline.
99    #[must_use]
100    pub fn remaining(self) -> Duration {
101        self.at.saturating_duration_since(tokio::time::Instant::now())
102    }
103
104    /// Returns whether the absolute deadline has elapsed.
105    #[must_use]
106    pub fn is_expired(self) -> bool {
107        tokio::time::Instant::now() >= self.at
108    }
109}
110
111/// A monotonically increasing generation for one metadata resource.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
113pub struct MetadataGeneration(u64);
114
115impl MetadataGeneration {
116    /// Creates a generation identifier.
117    #[must_use]
118    pub const fn new(value: u64) -> Self {
119        Self(value)
120    }
121
122    /// Returns the underlying generation value.
123    #[must_use]
124    pub const fn get(self) -> u64 {
125        self.0
126    }
127}
128
129impl From<u64> for MetadataGeneration {
130    fn from(value: u64) -> Self {
131        Self::new(value)
132    }
133}
134
135/// The caller-visible completion boundary for a persistence request.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum MetadataDurability {
138    /// The immutable snapshot has been accepted by the bounded actor.
139    Accepted,
140    /// The snapshot generation, or a newer coalesced generation, is durable.
141    Durable(MetadataGeneration),
142}
143
144/// A filesystem step in the atomic replacement protocol.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum MetadataIoOperation {
147    /// Represents the create parent case.
148    CreateParent,
149    /// Represents the create temporary case.
150    CreateTemporary,
151    /// Represents the write temporary case.
152    WriteTemporary,
153    /// Represents the sync temporary case.
154    SyncTemporary,
155    /// Represents the replace target case.
156    ReplaceTarget,
157    /// Represents the sync parent case.
158    SyncParent,
159    /// Represents the remove temporary case.
160    RemoveTemporary,
161}
162
163impl fmt::Display for MetadataIoOperation {
164    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165        let value = match self {
166            Self::CreateParent => "create parent directory",
167            Self::CreateTemporary => "create temporary file",
168            Self::WriteTemporary => "write temporary file",
169            Self::SyncTemporary => "sync temporary file",
170            Self::ReplaceTarget => "replace target file",
171            Self::SyncParent => "sync parent directory",
172            Self::RemoveTemporary => "remove temporary file",
173        };
174        formatter.write_str(value)
175    }
176}
177
178impl MetadataIoOperation {
179    /// Returns the closed runtime diagnostic operation for this filesystem step.
180    #[must_use]
181    pub const fn runtime_operation(self) -> crate::RuntimeOperation {
182        match self {
183            Self::CreateParent => crate::RuntimeOperation::MetadataCreateParent,
184            Self::CreateTemporary => crate::RuntimeOperation::MetadataCreateTemporary,
185            Self::WriteTemporary => crate::RuntimeOperation::MetadataWriteTemporary,
186            Self::SyncTemporary => crate::RuntimeOperation::MetadataSyncTemporary,
187            Self::ReplaceTarget => crate::RuntimeOperation::MetadataReplaceTarget,
188            Self::SyncParent => crate::RuntimeOperation::MetadataSyncParent,
189            Self::RemoveTemporary => crate::RuntimeOperation::MetadataRemoveTemporary,
190        }
191    }
192}
193
194fn metadata_io_failure(operation: MetadataIoOperation, _path: &Path, source: std::io::Error) -> RuntimeError {
195    RuntimeError::io(operation.runtime_operation(), source)
196}
197
198/// An immutable write request accepted by [`MetadataIoActor`].
199#[derive(Debug, Clone)]
200pub struct MetadataWriteRequest {
201    resource: Arc<str>,
202    generation: MetadataGeneration,
203    target: Arc<Path>,
204    bytes: Arc<[u8]>,
205    lane_deadline: Option<MetadataDeadline>,
206}
207
208impl MetadataWriteRequest {
209    /// Creates an immutable resource snapshot.
210    #[must_use]
211    pub fn new(
212        resource: impl Into<Arc<str>>,
213        generation: impl Into<MetadataGeneration>,
214        target: impl Into<PathBuf>,
215        bytes: impl Into<Vec<u8>>,
216    ) -> Self {
217        Self {
218            resource: resource.into(),
219            generation: generation.into(),
220            target: Arc::from(target.into()),
221            bytes: Arc::from(bytes.into()),
222            lane_deadline: None,
223        }
224    }
225
226    /// Bounds this request against the shared blocking lane.
227    ///
228    /// The value is combined with the lane's phase budgets, so it can only
229    /// tighten them and can never widen a shared lane limit. It is deliberately
230    /// separate from the durability deadline passed to
231    /// [`MetadataIoActor::submit`]: an admitted write keeps its ordering and
232    /// byte charge when the caller stops observing it, while a request whose
233    /// lane deadline has already elapsed is refused instead of started.
234    #[must_use]
235    pub fn with_lane_deadline(mut self, deadline: MetadataDeadline) -> Self {
236        self.lane_deadline = Some(deadline);
237        self
238    }
239
240    /// Returns the optional request-level lane deadline.
241    #[must_use]
242    pub const fn lane_deadline(&self) -> Option<MetadataDeadline> {
243        self.lane_deadline
244    }
245
246    /// Returns the logical resource identifier.
247    #[must_use]
248    pub fn resource(&self) -> &str {
249        &self.resource
250    }
251
252    /// Returns the immutable generation.
253    #[must_use]
254    pub const fn generation(&self) -> MetadataGeneration {
255        self.generation
256    }
257
258    /// Returns the target path.
259    #[must_use]
260    pub fn target(&self) -> &Path {
261        &self.target
262    }
263
264    /// Returns the retained snapshot size.
265    #[must_use]
266    pub fn len(&self) -> usize {
267        self.bytes.len()
268    }
269
270    /// Returns whether the immutable snapshot is empty.
271    #[must_use]
272    pub fn is_empty(&self) -> bool {
273        self.bytes.is_empty()
274    }
275}
276
277/// Filesystem abstraction used by the metadata actor.
278///
279/// Implementations must not publish partial target files. Production callers
280/// should use [`LocalMetadataFileSystem`]; the abstraction also permits
281/// deterministic fault injection without relying on a particular host
282/// filesystem.
283pub trait MetadataFileSystem: fmt::Debug + Send + Sync + 'static {
284    /// Atomically persists one immutable snapshot.
285    ///
286    /// # Errors
287    ///
288    /// Returns a typed error that identifies the failed durability step and
289    /// retains the original I/O source.
290    fn persist_atomic(&self, target: &Path, bytes: &[u8]) -> RuntimeResult<()>;
291}
292
293/// The production local filesystem implementation.
294#[derive(Debug, Default)]
295pub struct LocalMetadataFileSystem;
296
297impl MetadataFileSystem for LocalMetadataFileSystem {
298    fn persist_atomic(&self, target: &Path, bytes: &[u8]) -> RuntimeResult<()> {
299        filesystem::persist_atomic_local(target, bytes)
300    }
301}
302
303/// Metadata actor admission limits and legacy blocking-lane fields.
304///
305/// The actor owns its admission bounds, `max_pending_operations` and
306/// `max_pending_bytes`. The shared blocking lane policy owns lane capacity,
307/// phase timeouts, and the warn threshold, so the three `blocking_*` fields are
308/// accepted for source compatibility and never override the lane.
309/// [`MetadataIoActor::effective_profile`] reports the value that applies to each
310/// one.
311#[derive(Debug, Clone)]
312pub struct MetadataIoConfig {
313    /// The max pending operations value.
314    pub max_pending_operations: usize,
315    /// The max pending size in bytes.
316    pub max_pending_bytes: usize,
317    /// Legacy lane queue wait, retained for source compatibility.
318    ///
319    /// The shared blocking lane policy owns the queue wait in force, so this
320    /// value does not change admission. Use
321    /// [`MetadataWriteRequest::with_lane_deadline`] to tighten a single request.
322    pub blocking_queue_timeout: Duration,
323    /// Legacy lane execution budget, retained for source compatibility.
324    ///
325    /// The shared blocking lane policy owns the execution budget in force, so
326    /// this value does not bound a running write. It is still validated for
327    /// compatibility with existing configuration literals.
328    pub blocking_task_timeout: Duration,
329    /// Legacy lane warn threshold, retained for source compatibility.
330    ///
331    /// The warn threshold belongs to the shared blocking lane policy, so this
332    /// value is never emitted.
333    pub blocking_warn_after: Duration,
334}
335
336/// Metadata actor settings that passed deterministic admission validation.
337#[derive(Debug, Clone)]
338pub struct MetadataIoPlan {
339    config: MetadataIoConfig,
340    max_concurrent_writes: NonZeroUsize,
341}
342
343impl MetadataIoConfig {
344    /// Validates bounded metadata actor configuration before startup.
345    ///
346    /// The zero `blocking_task_timeout` check is retained for compatibility with
347    /// existing configuration literals, even though the field does not drive
348    /// execution.
349    ///
350    /// # Errors
351    ///
352    /// Returns a deterministic contract violation when an admission bound or
353    /// blocking duration is invalid. This method performs no I/O.
354    pub fn validate(&self) -> Result<(), RuntimeContractViolation> {
355        if self.max_pending_operations == 0 {
356            return Err(RuntimeContractViolation::InvalidMetadataConfiguration {
357                policy: RuntimeContractPolicy::MetadataMaxPendingOperationsPositive,
358            });
359        }
360        if self.max_pending_bytes == 0 {
361            return Err(RuntimeContractViolation::InvalidMetadataConfiguration {
362                policy: RuntimeContractPolicy::MetadataMaxPendingBytesPositive,
363            });
364        }
365        if self.blocking_task_timeout.is_zero() {
366            return Err(RuntimeContractViolation::InvalidMetadataConfiguration {
367                policy: RuntimeContractPolicy::MetadataBlockingTaskTimeoutPositive,
368            });
369        }
370        Ok(())
371    }
372
373    /// Creates a validated metadata actor startup plan.
374    ///
375    /// # Errors
376    ///
377    /// Returns a deterministic contract violation when an admission bound or
378    /// blocking duration is invalid.
379    pub fn into_plan(self) -> Result<MetadataIoPlan, RuntimeContractViolation> {
380        self.validate()?;
381        Ok(MetadataIoPlan {
382            config: self,
383            max_concurrent_writes: NonZeroUsize::MIN,
384        })
385    }
386}
387
388impl MetadataIoPlan {
389    /// Lets the actor write up to `writes` different resources at the same time.
390    ///
391    /// The default is one: resources are written one after another, so one
392    /// slow write delays every other resource of the actor. A larger value lets
393    /// independent resources proceed while a write is slow. Generations of one
394    /// resource are still written one at a time and in order, and its queued
395    /// generations still coalesce. The actor never runs more writes than the
396    /// shared metadata lane admits at once; [`MetadataIoActor::effective_profile`]
397    /// reports the value in force.
398    #[must_use]
399    pub fn with_max_concurrent_writes(mut self, writes: NonZeroUsize) -> Self {
400        self.max_concurrent_writes = writes;
401        self
402    }
403
404    /// Starts the validated actor with the production filesystem.
405    ///
406    /// # Errors
407    ///
408    /// Returns an operational lifecycle error when the owned coordinator
409    /// cannot start.
410    pub fn start(self, service_context: &ChildServiceContext) -> RuntimeResult<MetadataIoActor> {
411        MetadataIoActor::start_validated(service_context, self, Arc::new(LocalMetadataFileSystem))
412    }
413
414    /// Starts the validated actor with an injected filesystem implementation.
415    ///
416    /// # Errors
417    ///
418    /// Returns an operational lifecycle error when the owned coordinator
419    /// cannot start.
420    pub fn start_with_file_system(
421        self,
422        service_context: &ChildServiceContext,
423        file_system: Arc<dyn MetadataFileSystem>,
424    ) -> RuntimeResult<MetadataIoActor> {
425        MetadataIoActor::start_validated(service_context, self, file_system)
426    }
427}
428
429impl Default for MetadataIoConfig {
430    fn default() -> Self {
431        Self {
432            max_pending_operations: 1_024,
433            max_pending_bytes: 64 * 1024 * 1024,
434            blocking_queue_timeout: Duration::from_secs(5),
435            blocking_task_timeout: Duration::from_secs(30),
436            blocking_warn_after: Duration::from_secs(1),
437        }
438    }
439}
440
441/// Identifies the owner of one effective metadata limit.
442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
443pub enum MetadataLimitSource {
444    /// The shared root blocking lane policy owns the value.
445    BlockingLanePolicy,
446    /// The metadata actor configuration owns the value.
447    ActorConfiguration,
448}
449
450/// One retained actor field together with the value that applies instead.
451#[derive(Debug, Clone, PartialEq, Eq)]
452pub struct MetadataIoLegacyBlockingField {
453    /// The configuration field name.
454    pub field: &'static str,
455    /// The value a caller configured.
456    pub configured: Duration,
457    /// The value that drives execution.
458    pub effective: Duration,
459    /// The owner of the effective value.
460    pub effective_source: MetadataLimitSource,
461}
462
463/// The shared blocking lane limits in force for the metadata actor.
464#[derive(Debug, Clone, PartialEq, Eq)]
465pub struct MetadataIoBlockingLaneProfile {
466    /// The lane name from the root blocking lane policy.
467    pub name: String,
468    /// The admitted concurrency ceiling.
469    pub max_concurrency: usize,
470    /// The admitted queue depth ceiling.
471    pub max_queue_depth: usize,
472    /// The queue wait budget.
473    pub queue_timeout: Duration,
474    /// The execution budget.
475    pub task_timeout: Duration,
476    /// The warn threshold for work that completed above it.
477    pub warn_after: Duration,
478}
479
480/// The admission limits the metadata actor owns.
481#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct MetadataIoActorLimitsProfile {
483    /// The admitted pending operation ceiling.
484    pub max_pending_operations: usize,
485    /// The admitted retained byte ceiling.
486    pub max_pending_bytes: usize,
487    /// The waiter ceiling derived from `max_pending_operations`.
488    pub max_waiters: usize,
489    /// The number of different resources written at the same time: the
490    /// planned value, capped by the concurrency of the shared metadata lane.
491    pub max_concurrent_writes: usize,
492}
493
494/// A read-only view of the metadata I/O limits actually in force.
495///
496/// `blocking_lane` carries the shared lane limits owned by the root
497/// [`BlockingLanePolicies`](crate::BlockingLanePolicies), `actor_limits` carries
498/// the admission bounds the actor owns, and `legacy_blocking_fields` reports
499/// each retained configuration field beside the value that applies instead.
500///
501/// A request may tighten the lane phase budgets with
502/// [`MetadataWriteRequest::with_lane_deadline`]. The executor combines the
503/// request deadline with the lane budget by taking the earlier expiry, so no
504/// request can widen a shared lane limit.
505#[derive(Debug, Clone, PartialEq, Eq)]
506pub struct MetadataIoEffectiveProfile {
507    /// The shared blocking lane limits in force.
508    pub blocking_lane: MetadataIoBlockingLaneProfile,
509    /// The admission limits owned by the actor.
510    pub actor_limits: MetadataIoActorLimitsProfile,
511    /// The retained configuration fields that do not override the lane.
512    pub legacy_blocking_fields: [MetadataIoLegacyBlockingField; 3],
513}
514
515/// The waiter ceiling derived from the admitted pending-operation bound.
516fn max_metadata_waiters(max_pending_operations: usize) -> usize {
517    max_pending_operations.saturating_mul(4).max(1)
518}
519
520/// Caps the planned write concurrency by the lane, so the actor never queues
521/// its own writes behind lane capacity it cannot use.
522fn effective_concurrent_writes(planned: NonZeroUsize, blocking_policy: &BlockingPoolPolicy) -> usize {
523    planned.get().min(blocking_policy.max_concurrency).max(1)
524}
525
526fn effective_profile(
527    config: &MetadataIoConfig,
528    blocking_policy: &BlockingPoolPolicy,
529    max_concurrent_writes: usize,
530) -> MetadataIoEffectiveProfile {
531    let legacy_blocking_field =
532        |field: &'static str, configured: Duration, effective: Duration| MetadataIoLegacyBlockingField {
533            field,
534            configured,
535            effective,
536            effective_source: MetadataLimitSource::BlockingLanePolicy,
537        };
538    MetadataIoEffectiveProfile {
539        blocking_lane: MetadataIoBlockingLaneProfile {
540            name: blocking_policy.name.clone(),
541            max_concurrency: blocking_policy.max_concurrency,
542            max_queue_depth: blocking_policy.max_queue_depth,
543            queue_timeout: blocking_policy.queue_timeout,
544            task_timeout: blocking_policy.task_timeout,
545            warn_after: blocking_policy.warn_after,
546        },
547        actor_limits: MetadataIoActorLimitsProfile {
548            max_pending_operations: config.max_pending_operations,
549            max_pending_bytes: config.max_pending_bytes,
550            max_waiters: max_metadata_waiters(config.max_pending_operations),
551            max_concurrent_writes,
552        },
553        legacy_blocking_fields: [
554            legacy_blocking_field(
555                "blocking_queue_timeout",
556                config.blocking_queue_timeout,
557                blocking_policy.queue_timeout,
558            ),
559            legacy_blocking_field(
560                "blocking_task_timeout",
561                config.blocking_task_timeout,
562                blocking_policy.task_timeout,
563            ),
564            legacy_blocking_field(
565                "blocking_warn_after",
566                config.blocking_warn_after,
567                blocking_policy.warn_after,
568            ),
569        ],
570    }
571}
572
573/// Reports retained blocking fields that a caller configured away from their
574/// defaults.
575///
576/// The notice is emitted once per actor start, so a non-default value cannot
577/// turn into per-operation logging. The lane policy always owns the value in
578/// force, which [`MetadataIoEffectiveProfile`] reports for every field.
579fn warn_legacy_blocking_fields(config: &MetadataIoConfig, blocking_policy: &BlockingPoolPolicy) {
580    let defaults = MetadataIoConfig::default();
581    let changed = [
582        (
583            "blocking_queue_timeout",
584            config.blocking_queue_timeout,
585            defaults.blocking_queue_timeout,
586        ),
587        (
588            "blocking_task_timeout",
589            config.blocking_task_timeout,
590            defaults.blocking_task_timeout,
591        ),
592        (
593            "blocking_warn_after",
594            config.blocking_warn_after,
595            defaults.blocking_warn_after,
596        ),
597    ]
598    .into_iter()
599    .filter(|(_field, configured, default)| configured != default)
600    .map(|(field, _configured, _default)| field)
601    .collect::<Vec<_>>();
602    if changed.is_empty() {
603        return;
604    }
605    tracing::warn!(
606        fields = ?changed,
607        lane = %blocking_policy.name,
608        "metadata blocking fields are retained for source compatibility and do not override the shared blocking lane policy"
609    );
610}
611
612/// A snapshot of one logical metadata resource.
613#[derive(Debug, Clone, PartialEq, Eq)]
614pub struct MetadataIoResourceSnapshot {
615    /// The resource value.
616    pub resource: Arc<str>,
617    /// The target value.
618    pub target: Option<Arc<Path>>,
619    /// The durable generation value.
620    pub durable_generation: Option<MetadataGeneration>,
621    /// The in flight generation value.
622    pub in_flight_generation: Option<MetadataGeneration>,
623    /// The queued generation value.
624    pub queued_generation: Option<MetadataGeneration>,
625    /// The number of waiter entries.
626    pub waiter_count: usize,
627}
628
629/// A point-in-time actor snapshot.
630#[derive(Debug, Clone, PartialEq, Eq)]
631pub struct MetadataIoSnapshot {
632    /// Whether accepting.
633    pub accepting: bool,
634    /// The pending operations value.
635    pub pending_operations: usize,
636    /// The pending size in bytes.
637    pub pending_bytes: usize,
638    /// The max pending operations value.
639    pub max_pending_operations: usize,
640    /// The max pending size in bytes.
641    pub max_pending_bytes: usize,
642    /// The resources value.
643    pub resources: Vec<MetadataIoResourceSnapshot>,
644}
645
646/// Result of stopping admission and draining accepted work.
647#[derive(Debug, Clone, PartialEq, Eq)]
648pub struct MetadataIoShutdownReport {
649    /// Whether timed out.
650    pub timed_out: bool,
651    /// The pending operations value.
652    pub pending_operations: usize,
653    /// The pending size in bytes.
654    pub pending_bytes: usize,
655    /// The unfinished value.
656    pub unfinished: Vec<MetadataIoResourceSnapshot>,
657}
658
659/// A receipt for an accepted immutable snapshot.
660#[derive(Debug)]
661pub struct MetadataIoReceipt {
662    generation: MetadataGeneration,
663    identity: MetadataTargetIdentity,
664    durable: oneshot::Receiver<RuntimeResult<MetadataWritePersistenceStatus>>,
665}
666
667/// Describes request submission for one metadata write request.
668/// Persistence is observed through the receipt.
669///
670/// A target conflict retains the original immutable request so the caller can
671/// retry it after reconciling the resource-to-target mapping.
672#[derive(Debug)]
673pub enum MetadataWriteSubmissionStatus {
674    /// The actor accepted the snapshot and returned its durability receipt.
675    Accepted(MetadataIoReceipt),
676    /// The resource already has pending work for a different target path.
677    TargetConflict(MetadataWriteRequest),
678}
679
680/// Reports durable completion or a target conflict for a metadata write.
681#[derive(Debug)]
682pub enum MetadataWriteDurabilityStatus {
683    /// The accepted snapshot, or a coalesced newer snapshot, became durable.
684    Durable(MetadataGeneration),
685    /// The request was not admitted because its resource has a pending
686    /// snapshot for a different target path.
687    TargetConflict(MetadataWriteRequest),
688}
689
690/// The real persistence conclusion for an accepted metadata snapshot.
691#[derive(Debug, Clone)]
692pub enum MetadataWritePersistenceStatus {
693    /// The snapshot or a newer coalesced snapshot completed the persistence
694    /// protocol and is durable.
695    Durable(MetadataGeneration),
696    /// The target file was not replaced.
697    FailedBeforeCommit(RuntimeError),
698    /// The replacement may be visible, but its durability was not confirmed.
699    /// Reconcile before publishing or retrying.
700    DurabilityUnconfirmed(RuntimeError),
701}
702
703/// Reports the persistence conclusion for an accepted write or a target conflict.
704#[derive(Debug)]
705pub enum MetadataWriteCompletionStatus {
706    /// The accepted snapshot reached a terminal persistence conclusion.
707    Completed(MetadataWritePersistenceStatus),
708    /// The request was not admitted because the resource or target has a
709    /// different process-local writer binding.
710    TargetConflict(MetadataWriteRequest),
711}
712
713/// What a caller actually confirmed about one admitted metadata snapshot.
714///
715/// Unlike [`MetadataWritePersistenceStatus`], this models the case where the caller
716/// stopped observing before the persistence protocol reached a terminal
717/// conclusion. An unobserved generation is not evidence that the write did not
718/// happen: the admitted snapshot keeps its ordering and byte charge, so it may
719/// still become durable, fail, or end unconfirmed after the caller's deadline.
720/// Business owners must treat that generation as unconfirmed rather than as a
721/// definite failure.
722///
723/// Every conclusion except a target conflict carries the observed generation,
724/// so a caller can record the change identity and later resolve it against
725/// [`MetadataIoActor::confirmed_durable_generation`].
726#[derive(Debug)]
727pub enum MetadataIoCommitObservation {
728    /// The persistence protocol reached a terminal conclusion within the
729    /// caller's deadline.
730    Settled {
731        /// The generation the caller observed.
732        generation: MetadataGeneration,
733        /// The persistence status of the write, which may cover a newer coalesced generation.
734        persistence_status: MetadataWritePersistenceStatus,
735    },
736    /// The caller stopped observing first. The generation identifies the
737    /// change whose durability was not confirmed.
738    Unobserved {
739        /// The generation whose durability was not confirmed.
740        generation: MetadataGeneration,
741    },
742    /// The request was not admitted because the resource is bound to a
743    /// different process-local target.
744    TargetConflict(MetadataWriteRequest),
745}
746
747impl MetadataIoCommitObservation {
748    /// Returns whether the caller must treat durable state as unconfirmed.
749    ///
750    /// True for an unobserved generation and for a replacement that the
751    /// durability protocol did not confirm. False for a confirmed durable
752    /// write, a failure before target replacement, and a target conflict.
753    #[must_use]
754    pub fn requires_reconciliation(&self) -> bool {
755        match self {
756            MetadataIoCommitObservation::Settled { persistence_status, .. } => {
757                matches!(
758                    persistence_status,
759                    MetadataWritePersistenceStatus::DurabilityUnconfirmed(_)
760                )
761            }
762            MetadataIoCommitObservation::Unobserved { .. } => true,
763            MetadataIoCommitObservation::TargetConflict(_) => false,
764        }
765    }
766
767    /// Consumes the observation and returns the terminal conclusion, if any.
768    #[must_use]
769    pub fn settled(self) -> Option<MetadataWritePersistenceStatus> {
770        match self {
771            MetadataIoCommitObservation::Settled { persistence_status, .. } => Some(persistence_status),
772            MetadataIoCommitObservation::Unobserved { .. } | MetadataIoCommitObservation::TargetConflict(_) => None,
773        }
774    }
775
776    /// Returns the observed generation, or `None` for a target conflict.
777    #[must_use]
778    pub const fn generation(&self) -> Option<MetadataGeneration> {
779        match self {
780            MetadataIoCommitObservation::Settled { generation, .. }
781            | MetadataIoCommitObservation::Unobserved { generation } => Some(*generation),
782            MetadataIoCommitObservation::TargetConflict(_) => None,
783        }
784    }
785
786    /// Returns the generation whose durability was not confirmed.
787    #[must_use]
788    pub const fn unobserved_generation(&self) -> Option<MetadataGeneration> {
789        match self {
790            MetadataIoCommitObservation::Unobserved { generation } => Some(*generation),
791            MetadataIoCommitObservation::Settled { .. } | MetadataIoCommitObservation::TargetConflict(_) => None,
792        }
793    }
794}
795
796/// The private receipt conclusion that keeps the coordinator-abort case
797/// distinct from a deadline expiry.
798///
799/// [`MetadataIoReceipt::wait_for_persistence_status_until`] reports a stopped
800/// coordinator as an unavailable context, while [`MetadataIoReceipt::observe_until`]
801/// folds it into an unobserved generation. Both mappings are derived from this
802/// single classification so the receipt channel is interpreted in exactly one place.
803enum ReceiptConclusion {
804    /// The receipt channel delivered the actor's result. That is either a
805    /// terminal persistence conclusion or the worker-stopped error, which the
806    /// actor only produces for a generation that never ran.
807    Delivered(RuntimeResult<MetadataWritePersistenceStatus>),
808    /// The caller's absolute deadline elapsed first.
809    Expired,
810    /// The coordinator task was dropped without delivering a conclusion.
811    /// A blocking closure it submitted may still be running.
812    CoordinatorStopped,
813}
814
815impl MetadataIoReceipt {
816    /// Returns the history identity to pair with this receipt's generation.
817    ///
818    /// A retired history cannot prove durability in a later target identity.
819    pub fn target_identity(&self) -> MetadataTargetIdentity {
820        self.identity.clone()
821    }
822    /// Returns the accepted resource generation.
823    #[must_use]
824    pub const fn generation(&self) -> MetadataGeneration {
825        self.generation
826    }
827
828    /// Waits until the absolute `deadline` for the actor to report the terminal
829    /// persistence status of this generation or a newer coalesced generation.
830    ///
831    /// The status can confirm durability, report a failure before target
832    /// replacement, or leave durability unconfirmed. An admitted write can
833    /// still finish after the caller's wait expires.
834    ///
835    /// # Errors
836    ///
837    /// An elapsed deadline returns a [`WaitForDurableMetadata`](crate::RuntimeOperation::WaitForDurableMetadata)
838    /// timeout. A stopped worker or a coordinator channel that closes before
839    /// delivering a status yields a [`MetadataWorkerStopped`](crate::RuntimeOperation::MetadataWorkerStopped) error.
840    pub async fn wait_for_persistence_status_until(
841        self,
842        deadline: MetadataDeadline,
843    ) -> RuntimeResult<MetadataWritePersistenceStatus> {
844        if deadline.is_expired() {
845            return Err(RuntimeError::timed_out(crate::RuntimeOperation::WaitForDurableMetadata));
846        }
847        match self.conclude(deadline).await {
848            ReceiptConclusion::Delivered(result) => result,
849            ReceiptConclusion::CoordinatorStopped => {
850                Err(RuntimeError::closed(crate::RuntimeOperation::MetadataWorkerStopped))
851            }
852            ReceiptConclusion::Expired => Err(RuntimeError::timed_out(crate::RuntimeOperation::WaitForDurableMetadata)),
853        }
854    }
855
856    /// Observes this generation without collapsing an observation timeout into
857    /// the persistence error channel.
858    ///
859    /// Expiry returns [`MetadataIoCommitObservation::Unobserved`] rather than
860    /// an error, because the accepted snapshot retains its ordering and byte
861    /// charge and may still become durable. A caller that needs a definite
862    /// answer must reconcile against the actor's confirmed durable generation
863    /// instead of treating the expiry as a failure.
864    ///
865    /// This method never returns [`MetadataIoCommitObservation::TargetConflict`]:
866    /// a receipt already identifies an admitted write. It retains only the
867    /// result and history identity, not write authority.
868    pub async fn observe_until(self, deadline: MetadataDeadline) -> MetadataIoCommitObservation {
869        let generation = self.generation;
870        match self.conclude(deadline).await {
871            ReceiptConclusion::Delivered(Ok(persistence_status)) => MetadataIoCommitObservation::Settled {
872                generation,
873                persistence_status,
874            },
875            // The actor delivered the worker-stopped error, which it only
876            // produces for a generation that never ran. That is a definite
877            // pre-commit failure rather than an unconfirmed replacement.
878            ReceiptConclusion::Delivered(Err(error)) => MetadataIoCommitObservation::Settled {
879                generation,
880                persistence_status: MetadataWritePersistenceStatus::FailedBeforeCommit(error),
881            },
882            // A stopped coordinator and an elapsed deadline are both
883            // "no conclusion observed": a submitted closure may still be
884            // running, and the target may still change.
885            ReceiptConclusion::CoordinatorStopped | ReceiptConclusion::Expired => {
886                MetadataIoCommitObservation::Unobserved { generation }
887            }
888        }
889    }
890
891    /// Classifies the receipt channel exactly once for every caller.
892    async fn conclude(self, deadline: MetadataDeadline) -> ReceiptConclusion {
893        match tokio::time::timeout_at(deadline.instant(), self.durable).await {
894            Ok(Ok(result)) => ReceiptConclusion::Delivered(result),
895            Ok(Err(_closed)) => ReceiptConclusion::CoordinatorStopped,
896            Err(_elapsed) => ReceiptConclusion::Expired,
897        }
898    }
899
900    /// Waits for this generation, or a newer coalesced generation, to become
901    /// durable without extending the caller's absolute deadline.
902    ///
903    /// Expiry abandons this observation. Accepted writes retain their ordering
904    /// and byte charge until actual completion, and may still become durable.
905    ///
906    /// # Errors
907    ///
908    /// Returns an operational runtime failure if persistence cannot complete.
909    pub async fn wait_until(self, deadline: MetadataDeadline) -> RuntimeResult<MetadataGeneration> {
910        match self.wait_for_persistence_status_until(deadline).await? {
911            MetadataWritePersistenceStatus::Durable(generation) => Ok(generation),
912            MetadataWritePersistenceStatus::FailedBeforeCommit(source)
913            | MetadataWritePersistenceStatus::DurabilityUnconfirmed(source) => Err(source),
914        }
915    }
916}
917
918/// A cloneable handle to the bounded metadata I/O owner.
919#[derive(Debug, Clone)]
920pub struct MetadataIoActor {
921    inner: Arc<ActorInner>,
922    sender: mpsc::Sender<Arc<str>>,
923}
924
925/// Read-only access that does not retain metadata admission or target ownership.
926#[derive(Debug, Clone)]
927pub struct MetadataIoObserver {
928    inner: Weak<ActorInner>,
929}
930
931impl MetadataIoObserver {
932    /// Reads bounded actor state, or returns `None` after its owners are released.
933    ///
934    /// The registry capacity bounds the resource scan. This call performs no I/O.
935    pub fn snapshot(&self) -> Option<MetadataIoSnapshot> {
936        self.inner.upgrade().map(|inner| snapshot(&inner))
937    }
938}
939
940#[derive(Debug)]
941struct ActorInner {
942    config: MetadataIoConfig,
943    blocking_policy: BlockingPoolPolicy,
944    max_concurrent_writes: usize,
945    /// Charges every retained snapshot to the owner's process budget.
946    retained_bytes: ResourceBudget,
947    targets: MetadataTargetRegistry,
948    waiter_count: Arc<AtomicUsize>,
949    state: Mutex<ActorState>,
950    shutdown: Notify,
951    worker_finished: Notify,
952}
953
954#[derive(Debug)]
955struct ActorState {
956    accepting: bool,
957    worker_finished: bool,
958    pending_operations: usize,
959    pending_bytes: usize,
960    resources: HashMap<Arc<str>, ResourceState>,
961}
962
963#[derive(Debug, Default)]
964struct ResourceState {
965    identity: Option<MetadataTargetIdentity>,
966    target: Option<Arc<Path>>,
967    target_registration: Option<MetadataTargetRegistration>,
968    durable_generation: Option<MetadataGeneration>,
969    in_flight: Option<WorkMeta>,
970    queued: Option<QueuedMetadataWrite>,
971    waiters: Vec<GenerationWaiter>,
972}
973
974#[derive(Debug)]
975struct QueuedMetadataWrite {
976    request: MetadataWriteRequest,
977    registration: MetadataTargetRegistration,
978    /// The snapshot's process-budget charge. Replacing a queued generation
979    /// releases it with the replaced snapshot.
980    charge: ResourcePermit,
981}
982
983#[derive(Debug)]
984struct WorkMeta {
985    generation: MetadataGeneration,
986    bytes: usize,
987}
988
989// Field order drops the actual payload before returning its byte reservation,
990// including when Tokio discards a closure before it starts.
991struct ChargedSnapshot {
992    bytes: Arc<[u8]>,
993    _charge: ResourcePermit,
994}
995
996#[derive(Debug)]
997struct GenerationWaiter {
998    generation: MetadataGeneration,
999    sender: oneshot::Sender<RuntimeResult<MetadataWritePersistenceStatus>>,
1000    _permit: WaiterPermit,
1001}
1002
1003#[derive(Debug)]
1004struct WaiterPermit {
1005    waiter_count: Arc<AtomicUsize>,
1006}
1007
1008impl Drop for WaiterPermit {
1009    fn drop(&mut self) {
1010        self.waiter_count.fetch_sub(1, Ordering::AcqRel);
1011    }
1012}
1013
1014impl ActorInner {
1015    fn reserve_waiter(&self, resource_waiters: usize) -> RuntimeResult<WaiterPermit> {
1016        let max_waiters = max_metadata_waiters(self.config.max_pending_operations);
1017        if resource_waiters >= max_waiters {
1018            return Err(RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataOperation));
1019        }
1020
1021        let mut current = self.waiter_count.load(Ordering::Acquire);
1022        loop {
1023            if current >= max_waiters {
1024                return Err(RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataOperation));
1025            }
1026            match self
1027                .waiter_count
1028                .compare_exchange_weak(current, current + 1, Ordering::AcqRel, Ordering::Acquire)
1029            {
1030                Ok(_) => {
1031                    return Ok(WaiterPermit {
1032                        waiter_count: Arc::clone(&self.waiter_count),
1033                    });
1034                }
1035                Err(observed) => current = observed,
1036            }
1037        }
1038    }
1039}
1040
1041impl MetadataIoActor {
1042    fn start_validated(
1043        service_context: &ChildServiceContext,
1044        plan: MetadataIoPlan,
1045        file_system: Arc<dyn MetadataFileSystem>,
1046    ) -> RuntimeResult<Self> {
1047        let MetadataIoPlan {
1048            config,
1049            max_concurrent_writes,
1050        } = plan;
1051        let task_group = service_context.component("metadata-io").task_group().clone();
1052        let blocking = service_context.metadata_io().clone();
1053        let blocking_policy = blocking.policy().clone();
1054        warn_legacy_blocking_fields(&config, &blocking_policy);
1055        let max_concurrent_writes = effective_concurrent_writes(max_concurrent_writes, &blocking_policy);
1056        let retained_bytes = retained_bytes_budget(&service_context.process_budget())?;
1057        let targets = service_context.resources().metadata_targets();
1058        let (sender, receiver) = mpsc::channel(config.max_pending_operations);
1059        let inner = Arc::new(ActorInner {
1060            config,
1061            blocking_policy,
1062            max_concurrent_writes,
1063            retained_bytes,
1064            targets,
1065            waiter_count: Arc::new(AtomicUsize::new(0)),
1066            state: Mutex::new(ActorState {
1067                accepting: true,
1068                worker_finished: false,
1069                pending_operations: 0,
1070                pending_bytes: 0,
1071                resources: HashMap::new(),
1072            }),
1073            shutdown: Notify::new(),
1074            worker_finished: Notify::new(),
1075        });
1076        let actor = Self {
1077            inner: inner.clone(),
1078            sender,
1079        };
1080        let cancellation = task_group.cancellation_token();
1081        task_group
1082            .spawn_service(
1083                "metadata-io.coordinator",
1084                run_actor(inner, receiver, blocking, file_system, cancellation),
1085            )
1086            .map_err(startup_error)?;
1087        Ok(actor)
1088    }
1089
1090    /// Attempts to admit one immutable snapshot without waiting for disk durability.
1091    ///
1092    /// The call is deliberately non-blocking. Queue or byte saturation is
1093    /// returned immediately and the absolute deadline is checked before
1094    /// admission.
1095    ///
1096    /// Returns a normal [`MetadataWriteSubmissionStatus::TargetConflict`] when
1097    /// the same resource already has pending work for a different target.
1098    ///
1099    /// # Errors
1100    ///
1101    /// Returns a typed deadline, capacity, or lifecycle failure.
1102    pub fn submit(
1103        &self,
1104        request: MetadataWriteRequest,
1105        deadline: MetadataDeadline,
1106    ) -> RuntimeResult<MetadataWriteSubmissionStatus> {
1107        if deadline.is_expired() {
1108            return Err(RuntimeError::timed_out(crate::RuntimeOperation::AdmitMetadataSnapshot));
1109        }
1110
1111        let resource = request.resource.clone();
1112        let generation = request.generation;
1113        let (waiter_sender, durable) = oneshot::channel();
1114        let mut state = self.inner.state.lock();
1115        if !state.accepting {
1116            return Err(RuntimeError::closed(crate::RuntimeOperation::MetadataIoClosed));
1117        }
1118
1119        let Some(target_registration) = ensure_target_registration(&mut state, &self.inner.targets, &request)? else {
1120            return Ok(MetadataWriteSubmissionStatus::TargetConflict(request));
1121        };
1122
1123        let existing = state.resources.get(&resource);
1124        if let Some(existing) = existing {
1125            if let Some(durable_generation) = existing.durable_generation {
1126                if generation <= durable_generation {
1127                    let _ = waiter_sender.send(Ok(MetadataWritePersistenceStatus::Durable(durable_generation)));
1128                    return Ok(MetadataWriteSubmissionStatus::Accepted(MetadataIoReceipt {
1129                        generation,
1130                        identity: target_registration.identity(),
1131                        durable,
1132                    }));
1133                }
1134            }
1135            if let Some(in_flight) = &existing.in_flight {
1136                if generation <= in_flight.generation {
1137                    let waiter_permit = self.inner.reserve_waiter(existing.waiters.len())?;
1138                    let Some(resource_state) = state.resources.get_mut(&resource) else {
1139                        return Err(RuntimeError::closed(crate::RuntimeOperation::MetadataWorkerStopped));
1140                    };
1141                    resource_state.waiters.push(GenerationWaiter {
1142                        generation,
1143                        sender: waiter_sender,
1144                        _permit: waiter_permit,
1145                    });
1146                    return Ok(MetadataWriteSubmissionStatus::Accepted(MetadataIoReceipt {
1147                        generation,
1148                        identity: target_registration.identity(),
1149                        durable,
1150                    }));
1151                }
1152            }
1153            if let Some(queued) = &existing.queued {
1154                if generation <= queued.request.generation {
1155                    let waiter_permit = self.inner.reserve_waiter(existing.waiters.len())?;
1156                    let Some(resource_state) = state.resources.get_mut(&resource) else {
1157                        return Err(RuntimeError::closed(crate::RuntimeOperation::MetadataWorkerStopped));
1158                    };
1159                    resource_state.waiters.push(GenerationWaiter {
1160                        generation,
1161                        sender: waiter_sender,
1162                        _permit: waiter_permit,
1163                    });
1164                    return Ok(MetadataWriteSubmissionStatus::Accepted(MetadataIoReceipt {
1165                        generation,
1166                        identity: target_registration.identity(),
1167                        durable,
1168                    }));
1169                }
1170            }
1171        }
1172
1173        let waiter_permit = self
1174            .inner
1175            .reserve_waiter(existing.map_or(0, |resource_state| resource_state.waiters.len()))?;
1176        let old_queued_bytes = existing
1177            .and_then(|resource_state| resource_state.queued.as_ref())
1178            .map_or(0, |queued| queued.request.len());
1179        let adds_operation = existing.is_none_or(|resource_state| resource_state.queued.is_none());
1180        let needs_queue_token =
1181            existing.is_none_or(|resource_state| resource_state.in_flight.is_none() && resource_state.queued.is_none());
1182        let next_operations = state.pending_operations + usize::from(adds_operation);
1183        if next_operations > self.inner.config.max_pending_operations {
1184            return Err(RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataOperation));
1185        }
1186        let retained_without_replaced = state.pending_bytes.saturating_sub(old_queued_bytes);
1187        let next_bytes = retained_without_replaced
1188            .checked_add(request.len())
1189            .ok_or_else(|| RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataBytes))?;
1190        if next_bytes > self.inner.config.max_pending_bytes {
1191            return Err(RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataBytes));
1192        }
1193        let queue_permit = if needs_queue_token {
1194            Some(
1195                self.sender
1196                    .try_reserve()
1197                    .map_err(|_error| RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataOperation))?,
1198            )
1199        } else {
1200            None
1201        };
1202
1203        let resource_state = state.resources.entry(resource.clone()).or_default();
1204        if let Some(queued) = &mut resource_state.queued {
1205            let new_bytes = request.len();
1206            // Only the growth is reserved, and a rejection leaves the old
1207            // generation intact. Shrink only after dropping the old payload.
1208            queued
1209                .charge
1210                .try_resize(new_bytes.max(queued.charge.bytes()))
1211                .map_err(|_rejection| RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataBytes))?;
1212            queued.request = request;
1213            queued.charge.shrink_to(new_bytes);
1214            queued.registration = target_registration.clone();
1215        } else {
1216            let charge = self
1217                .inner
1218                .retained_bytes
1219                .try_acquire_data(request.len())
1220                .map_err(|_rejection| RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataBytes))?;
1221            resource_state.queued = Some(QueuedMetadataWrite {
1222                request,
1223                registration: target_registration.clone(),
1224                charge,
1225            });
1226        }
1227        let identity = target_registration.identity();
1228        resource_state.target = resource_state
1229            .queued
1230            .as_ref()
1231            .map(|queued| queued.request.target.clone());
1232        resource_state.target_registration = Some(target_registration.clone());
1233        resource_state.waiters.push(GenerationWaiter {
1234            generation,
1235            sender: waiter_sender,
1236            _permit: waiter_permit,
1237        });
1238        state.pending_operations = next_operations;
1239        state.pending_bytes = next_bytes;
1240        drop(state);
1241        if let Some(permit) = queue_permit {
1242            permit.send(resource.clone());
1243        }
1244        Ok(MetadataWriteSubmissionStatus::Accepted(MetadataIoReceipt {
1245            generation,
1246            identity,
1247            durable,
1248        }))
1249    }
1250
1251    /// Assigns the next owner-lifetime generation and accepts an immutable
1252    /// snapshot without waiting for durability.
1253    ///
1254    /// Generation values are unique across every metadata actor that shares
1255    /// this runtime owner, so a generation stays a usable change identity
1256    /// after an actor is replaced. Gaps are allowed when admission rejects a
1257    /// request; they do not weaken ordering.
1258    ///
1259    /// # Errors
1260    ///
1261    /// Returns the same normal outcome and typed failures as [`Self::submit`].
1262    pub fn submit_next(
1263        &self,
1264        resource: impl Into<Arc<str>>,
1265        target: impl Into<PathBuf>,
1266        bytes: impl Into<Vec<u8>>,
1267        deadline: MetadataDeadline,
1268    ) -> RuntimeResult<MetadataWriteSubmissionStatus> {
1269        let generation = self.inner.targets.next_generation();
1270        self.submit(MetadataWriteRequest::new(resource, generation, target, bytes), deadline)
1271    }
1272
1273    /// Accepts a snapshot and waits for durable completion using the same
1274    /// absolute deadline.
1275    ///
1276    /// Returns [`MetadataWriteDurabilityStatus::TargetConflict`] without
1277    /// starting I/O when a pending request owns a different target path.
1278    ///
1279    /// # Errors
1280    ///
1281    /// Returns a typed admission, persistence, worker, or deadline failure.
1282    pub async fn submit_durable(
1283        &self,
1284        request: MetadataWriteRequest,
1285        deadline: MetadataDeadline,
1286    ) -> RuntimeResult<MetadataWriteDurabilityStatus> {
1287        match self.submit(request, deadline)? {
1288            MetadataWriteSubmissionStatus::Accepted(receipt) => receipt
1289                .wait_until(deadline)
1290                .await
1291                .map(MetadataWriteDurabilityStatus::Durable),
1292            MetadataWriteSubmissionStatus::TargetConflict(request) => {
1293                Ok(MetadataWriteDurabilityStatus::TargetConflict(request))
1294            }
1295        }
1296    }
1297
1298    /// Accepts a snapshot and returns its real persistence conclusion.
1299    ///
1300    /// This distinguishes a failure before target replacement from an
1301    /// unconfirmed replacement followed by a parent-directory sync failure.
1302    pub async fn submit_commit(
1303        &self,
1304        request: MetadataWriteRequest,
1305        deadline: MetadataDeadline,
1306    ) -> RuntimeResult<MetadataWriteCompletionStatus> {
1307        match self.submit(request, deadline)? {
1308            MetadataWriteSubmissionStatus::Accepted(receipt) => receipt
1309                .wait_for_persistence_status_until(deadline)
1310                .await
1311                .map(MetadataWriteCompletionStatus::Completed),
1312            MetadataWriteSubmissionStatus::TargetConflict(request) => {
1313                Ok(MetadataWriteCompletionStatus::TargetConflict(request))
1314            }
1315        }
1316    }
1317
1318    /// Assigns the next process-lifetime generation, accepts the immutable
1319    /// snapshot, and waits for durable completion using one absolute deadline.
1320    ///
1321    /// # Errors
1322    ///
1323    /// Returns the same normal outcome and typed failures as
1324    /// [`Self::submit_durable`].
1325    pub async fn submit_next_durable(
1326        &self,
1327        resource: impl Into<Arc<str>>,
1328        target: impl Into<PathBuf>,
1329        bytes: impl Into<Vec<u8>>,
1330        deadline: MetadataDeadline,
1331    ) -> RuntimeResult<MetadataWriteDurabilityStatus> {
1332        match self.submit_next(resource, target, bytes, deadline)? {
1333            MetadataWriteSubmissionStatus::Accepted(receipt) => receipt
1334                .wait_until(deadline)
1335                .await
1336                .map(MetadataWriteDurabilityStatus::Durable),
1337            MetadataWriteSubmissionStatus::TargetConflict(request) => {
1338                Ok(MetadataWriteDurabilityStatus::TargetConflict(request))
1339            }
1340        }
1341    }
1342
1343    /// Assigns the next owner-lifetime generation and returns its real
1344    /// persistence conclusion.
1345    pub async fn submit_next_commit(
1346        &self,
1347        resource: impl Into<Arc<str>>,
1348        target: impl Into<PathBuf>,
1349        bytes: impl Into<Vec<u8>>,
1350        deadline: MetadataDeadline,
1351    ) -> RuntimeResult<MetadataWriteCompletionStatus> {
1352        match self.submit_next(resource, target, bytes, deadline)? {
1353            MetadataWriteSubmissionStatus::Accepted(receipt) => receipt
1354                .wait_for_persistence_status_until(deadline)
1355                .await
1356                .map(MetadataWriteCompletionStatus::Completed),
1357            MetadataWriteSubmissionStatus::TargetConflict(request) => {
1358                Ok(MetadataWriteCompletionStatus::TargetConflict(request))
1359            }
1360        }
1361    }
1362
1363    /// Accepts a snapshot and reports what the caller actually confirmed about
1364    /// its persistence.
1365    ///
1366    /// An `Err` result means the request was never admitted, so the caller may
1367    /// safely discard its change. Every other case is expressed as a
1368    /// [`MetadataIoCommitObservation`], including an expiry that leaves the
1369    /// change unconfirmed.
1370    ///
1371    /// # Errors
1372    ///
1373    /// Returns a typed admission, capacity, or lifecycle failure.
1374    pub async fn submit_observed(
1375        &self,
1376        request: MetadataWriteRequest,
1377        deadline: MetadataDeadline,
1378    ) -> RuntimeResult<MetadataIoCommitObservation> {
1379        match self.submit(request, deadline)? {
1380            MetadataWriteSubmissionStatus::Accepted(receipt) => Ok(receipt.observe_until(deadline).await),
1381            MetadataWriteSubmissionStatus::TargetConflict(request) => {
1382                Ok(MetadataIoCommitObservation::TargetConflict(request))
1383            }
1384        }
1385    }
1386
1387    /// Assigns the next owner-lifetime generation and reports what the caller
1388    /// actually confirmed about its persistence.
1389    ///
1390    /// # Errors
1391    ///
1392    /// Returns the same normal outcome and typed failures as
1393    /// [`Self::submit_observed`].
1394    pub async fn submit_next_observed(
1395        &self,
1396        resource: impl Into<Arc<str>>,
1397        target: impl Into<PathBuf>,
1398        bytes: impl Into<Vec<u8>>,
1399        deadline: MetadataDeadline,
1400    ) -> RuntimeResult<MetadataIoCommitObservation> {
1401        match self.submit_next(resource, target, bytes, deadline)? {
1402            MetadataWriteSubmissionStatus::Accepted(receipt) => Ok(receipt.observe_until(deadline).await),
1403            MetadataWriteSubmissionStatus::TargetConflict(request) => {
1404                Ok(MetadataIoCommitObservation::TargetConflict(request))
1405            }
1406        }
1407    }
1408
1409    /// Returns the highest generation this actor confirmed durable for one
1410    /// logical resource.
1411    ///
1412    /// This is the evidence a caller needs to resolve an earlier
1413    /// [`MetadataIoCommitObservation::Unobserved`] conclusion without holding
1414    /// completion history: when the value reaches the unobserved generation,
1415    /// the change is durable after all. The value is seeded from the
1416    /// owner-scoped target registration, so it survives actor replacement for
1417    /// the same resource and target. After explicit retirement, compare
1418    /// [`Self::target_identity`] with the receipt's identity first: generations
1419    /// from a different history are not evidence about the old write.
1420    #[must_use]
1421    pub fn confirmed_durable_generation(&self, resource: &str) -> Option<MetadataGeneration> {
1422        let state = self.inner.state.lock();
1423        state
1424            .resources
1425            .get(resource)
1426            .and_then(|resource_state| resource_state.durable_generation)
1427    }
1428
1429    /// Stops new admission and drains accepted work until the absolute
1430    /// deadline.
1431    #[must_use]
1432    pub async fn shutdown_until(&self, deadline: MetadataDeadline) -> MetadataIoShutdownReport {
1433        self.stop_admission();
1434        loop {
1435            let finished_notification = self.inner.worker_finished.notified();
1436            tokio::pin!(finished_notification);
1437            finished_notification.as_mut().enable();
1438            let finished = self.inner.state.lock().worker_finished;
1439            if finished {
1440                return shutdown_report(&self.inner, false);
1441            }
1442            if deadline.is_expired() {
1443                return shutdown_report(&self.inner, true);
1444            }
1445            if tokio::time::timeout_at(deadline.instant(), finished_notification)
1446                .await
1447                .is_err()
1448            {
1449                return shutdown_report(&self.inner, true);
1450            }
1451        }
1452    }
1453
1454    /// Rejects future submissions while allowing accepted work to drain.
1455    pub fn stop_admission(&self) {
1456        stop_admission(&self.inner);
1457    }
1458
1459    /// Returns current queue, byte, generation, and waiter state.
1460    #[must_use]
1461    pub fn snapshot(&self) -> MetadataIoSnapshot {
1462        snapshot(&self.inner)
1463    }
1464
1465    /// Creates a diagnostic observer without retaining write authority.
1466    pub fn observer(&self) -> MetadataIoObserver {
1467        MetadataIoObserver {
1468            inner: Arc::downgrade(&self.inner),
1469        }
1470    }
1471
1472    /// Returns the target history associated with this actor's resource state.
1473    pub fn target_identity(&self, resource: &str) -> Option<MetadataTargetIdentity> {
1474        self.inner
1475            .state
1476            .lock()
1477            .resources
1478            .get(resource)
1479            .and_then(|state| state.identity.clone())
1480    }
1481
1482    /// Ends a closed, drained resource's durable history to reclaim registry capacity.
1483    ///
1484    /// This is an explicit identity boundary, not ordinary actor replacement.
1485    /// Future actors acquire a new identity and may bind a different resource
1486    /// to the path. Old actors cannot resume that history; retained read-only
1487    /// receipts keep their original result and identity. Compare generations
1488    /// only within the same identity.
1489    ///
1490    /// Unconfirmed replacements retain their fence. The runtime cannot verify
1491    /// business file formats and does not offer unconditional fence clearing.
1492    ///
1493    /// # Errors
1494    ///
1495    /// Returns a typed path normalization error without modifying the history.
1496    pub fn retire_target_for_new_identity(&self, resource: &str) -> RuntimeResult<MetadataTargetRetirementStatus> {
1497        let mut state = self.inner.state.lock();
1498        if state.accepting {
1499            return Ok(MetadataTargetRetirementStatus::AdmissionOpen);
1500        }
1501        if !state.worker_finished {
1502            return Ok(MetadataTargetRetirementStatus::WorkInProgress);
1503        }
1504        let Some(resource_state) = state.resources.get_mut(resource) else {
1505            return Ok(MetadataTargetRetirementStatus::NotFound);
1506        };
1507        if resource_state.in_flight.is_some() || resource_state.queued.is_some() || !resource_state.waiters.is_empty() {
1508            return Ok(MetadataTargetRetirementStatus::WorkInProgress);
1509        }
1510        let (Some(target), Some(identity)) = (&resource_state.target, &resource_state.identity) else {
1511            return Ok(MetadataTargetRetirementStatus::NotFound);
1512        };
1513        // A cached, idle registration has no pending work after coordinator completion.
1514        // Real blocking closures retain their own clone and still prevent retirement.
1515        resource_state.target_registration.take();
1516        let outcome = self
1517            .inner
1518            .targets
1519            .retire(target, resource, identity, resource_state.durable_generation)?;
1520        if outcome == MetadataTargetRetirementStatus::Retired {
1521            state.resources.remove(resource);
1522        }
1523        Ok(outcome)
1524    }
1525
1526    /// Returns the metadata I/O limits that are actually in force.
1527    ///
1528    /// The view is read-only and derived from the validated configuration and
1529    /// the root blocking lane policy captured at startup, so it reports the
1530    /// values that drive execution rather than the values a caller requested.
1531    #[must_use]
1532    pub fn effective_profile(&self) -> MetadataIoEffectiveProfile {
1533        effective_profile(
1534            &self.inner.config,
1535            &self.inner.blocking_policy,
1536            self.inner.max_concurrent_writes,
1537        )
1538    }
1539}
1540
1541/// Derives the ledger node that charges retained snapshots to the process
1542/// budget.
1543///
1544/// The node copies its parent's limits instead of adding its own:
1545/// `max_pending_bytes` stays the actor's admission bound, while the process
1546/// budget bounds what every budgeted component retains together, including the
1547/// other metadata actors of the same owner.
1548fn retained_bytes_budget(process_budget: &ResourceBudget) -> RuntimeResult<ResourceBudget> {
1549    let parent = process_budget.limit();
1550    let limit = BudgetLimit {
1551        capacity: parent.capacity,
1552        control_reserve: BudgetCapacity::default(),
1553        max_age: parent.max_age,
1554        full_policy: FullPolicy::Reject,
1555    };
1556    process_budget.child("metadata-io", limit).map_err(|violation| {
1557        RuntimeError::configuration_failure(crate::RuntimeOperation::AdmitMetadataBytes, violation)
1558    })
1559}
1560
1561fn ensure_target_registration(
1562    state: &mut ActorState,
1563    registry: &MetadataTargetRegistry,
1564    request: &MetadataWriteRequest,
1565) -> RuntimeResult<Option<MetadataTargetRegistration>> {
1566    let resource = &request.resource;
1567    // Retired identities remain tombstones in older actors. Bound this cache
1568    // independently of the shared registry, whose slots can be reused.
1569    if !state.resources.contains_key(resource) && state.resources.len() >= registry.capacity() {
1570        return Err(RuntimeError::capacity(crate::RuntimeOperation::AdmitMetadataOperation));
1571    }
1572    let mut target_changed = false;
1573    if let Some(existing) = state.resources.get(resource) {
1574        if let Some(target) = &existing.target {
1575            target_changed = !registry.same_target(target.as_ref(), request.target.as_ref())?;
1576            if target_changed && (existing.in_flight.is_some() || existing.queued.is_some()) {
1577                return Ok(None);
1578            }
1579            if !target_changed {
1580                if let Some(registration) = &existing.target_registration {
1581                    // Reusing a cached registration skips the registry check
1582                    // below, so it has to consult the target's reconciliation
1583                    // fence explicitly. Without this, a queued generation would
1584                    // write over a target whose previous replacement never
1585                    // completed the durability protocol.
1586                    if registration.reconciliation_required() {
1587                        return Err(RuntimeError::context_unavailable(
1588                            crate::RuntimeOperation::MetadataResourceTarget,
1589                        ));
1590                    }
1591                    return Ok(Some(registration.clone()));
1592                }
1593            }
1594        }
1595    }
1596
1597    let expected = state
1598        .resources
1599        .get(resource)
1600        .filter(|_| !target_changed)
1601        .and_then(|state| state.identity.as_ref());
1602    let registration = match registry.register_with_identity(request.target.as_ref(), Arc::clone(resource), expected)? {
1603        MetadataTargetRegistrationStatus::Registered(registration) => registration,
1604        MetadataTargetRegistrationStatus::Conflict => return Ok(None),
1605        MetadataTargetRegistrationStatus::ReconciliationRequired => {
1606            return Err(RuntimeError::context_unavailable(
1607                crate::RuntimeOperation::MetadataResourceTarget,
1608            ));
1609        }
1610    };
1611    let durable_generation = registration.durable_generation();
1612    let resource_state = state.resources.entry(Arc::clone(resource)).or_default();
1613    if target_changed {
1614        resource_state.target_registration = None;
1615        resource_state.durable_generation = None;
1616    }
1617    resource_state.target = Some(request.target.clone());
1618    resource_state.identity = Some(registration.identity());
1619    resource_state.target_registration = Some(registration.clone());
1620    if let Some(durable_generation) = durable_generation {
1621        resource_state.durable_generation = Some(
1622            resource_state
1623                .durable_generation
1624                .map_or(durable_generation, |current| current.max(durable_generation)),
1625        );
1626    }
1627    Ok(Some(registration))
1628}
1629
1630async fn run_actor(
1631    inner: Arc<ActorInner>,
1632    mut receiver: mpsc::Receiver<Arc<str>>,
1633    blocking: BlockingExecutor,
1634    file_system: Arc<dyn MetadataFileSystem>,
1635    cancellation: CancellationToken,
1636) {
1637    let mut cancellation_observed = false;
1638    let mut channel_closed = false;
1639    // A resource with work is in exactly one place: the channel, `ready`, or
1640    // `writes`. Writes of one resource therefore never overlap, and each keeps
1641    // its generation order however many resources are written at once.
1642    let mut ready: VecDeque<Arc<str>> = VecDeque::new();
1643    let mut writes = FuturesUnordered::new();
1644    loop {
1645        if !cancellation_observed && cancellation.is_cancelled() {
1646            cancellation_observed = true;
1647            stop_admission(&inner);
1648        }
1649        while writes.len() < inner.max_concurrent_writes {
1650            let Some(resource) = ready.pop_front() else {
1651                break;
1652            };
1653            writes.push(write_resource(&inner, &blocking, &file_system, resource));
1654        }
1655        if writes.is_empty() && should_finish(&inner) {
1656            break;
1657        }
1658        tokio::select! {
1659            biased;
1660            _ = cancellation.cancelled(), if !cancellation_observed => {
1661                cancellation_observed = true;
1662                stop_admission(&inner);
1663            }
1664            Some((resource, has_more)) = writes.next(), if !writes.is_empty() => {
1665                // Resources that arrived during the write go first, so a
1666                // resource that keeps receiving generations cannot starve them.
1667                while let Ok(pending) = receiver.try_recv() {
1668                    ready.push_back(pending);
1669                }
1670                if has_more {
1671                    ready.push_back(resource);
1672                }
1673            }
1674            _ = inner.shutdown.notified() => {}
1675            resource = receiver.recv(), if !channel_closed => {
1676                match resource {
1677                    Some(resource) => ready.push_back(resource),
1678                    None => {
1679                        channel_closed = true;
1680                        stop_admission(&inner);
1681                    }
1682                }
1683            }
1684        }
1685    }
1686    finish_worker(&inner);
1687}
1688
1689/// Writes the next generation of `resource` and reports whether another one
1690/// was queued meanwhile.
1691async fn write_resource(
1692    inner: &Arc<ActorInner>,
1693    blocking: &BlockingExecutor,
1694    file_system: &Arc<dyn MetadataFileSystem>,
1695    resource: Arc<str>,
1696) -> (Arc<str>, bool) {
1697    let has_more = process_resource(inner, blocking, file_system, resource.clone()).await;
1698    (resource, has_more)
1699}
1700
1701async fn process_resource(
1702    inner: &Arc<ActorInner>,
1703    blocking: &BlockingExecutor,
1704    file_system: &Arc<dyn MetadataFileSystem>,
1705    resource: Arc<str>,
1706) -> bool {
1707    let Some(QueuedMetadataWrite {
1708        request,
1709        registration,
1710        charge,
1711    }) = take_next_request(inner, &resource)
1712    else {
1713        return false;
1714    };
1715    let MetadataWriteRequest {
1716        target,
1717        bytes,
1718        generation,
1719        lane_deadline,
1720        ..
1721    } = request;
1722    // A request-level deadline is the only value that may tighten the lane
1723    // phase budgets. The durability deadline a caller passes to `submit` is
1724    // deliberately not reused here: an admitted write keeps its ordering and
1725    // byte charge after the caller stops observing it.
1726    let lane_deadline = lane_deadline.map(|deadline| ShutdownDeadline::at(deadline.instant().into_std()));
1727    let worker_file_system = file_system.clone();
1728    let completion_registration = registration.clone();
1729    let snapshot = ChargedSnapshot { bytes, _charge: charge };
1730    let result = match blocking
1731        .submit_io_until(format!("metadata-io:{resource}"), lane_deadline, move || {
1732            // Capture the whole owner, not individual fields: the byte charge
1733            // survives coordinator cancellation and leaves with the payload.
1734            let snapshot = snapshot;
1735            let result = worker_file_system.persist_atomic(&target, &snapshot.bytes);
1736            match &result {
1737                Ok(()) => {
1738                    let _ = completion_registration.record_durable(generation);
1739                }
1740                Err(error) if error.operation() == crate::RuntimeOperation::MetadataSyncParent => {
1741                    let _ = completion_registration.record_reconciliation_required();
1742                }
1743                Err(_) => {}
1744            }
1745            result
1746        })
1747        .await
1748    {
1749        // A caller/lane wait timeout cannot transfer write ownership: Tokio
1750        // may still be running this closure. Receipts have their own deadlines.
1751        Ok(mut task) => task.wait().await.and_then(|result| result),
1752        Err(source) => Err(source),
1753    };
1754    // A request's file mutation and durability accounting are complete once its blocking
1755    // closure returns, so this writer's target authority is released before the completion
1756    // is published. Publishing while the authority is still held would let a caller that
1757    // observes the confirmed generation race this release: the completion clears the
1758    // cached registration, so the follow-up write for this resource and target has to
1759    // re-register and would find the previous generation's registration still alive. A
1760    // queued generation keeps its own clone, so its authority outlives this release.
1761    drop(registration);
1762    finish_request(inner, &resource, generation, result)
1763}
1764
1765fn take_next_request(inner: &ActorInner, resource: &Arc<str>) -> Option<QueuedMetadataWrite> {
1766    let mut state = inner.state.lock();
1767    let resource_state = state.resources.get_mut(resource)?;
1768    let queued = resource_state.queued.take()?;
1769    resource_state.in_flight = Some(WorkMeta {
1770        generation: queued.request.generation,
1771        bytes: queued.request.len(),
1772    });
1773    Some(queued)
1774}
1775
1776fn finish_request(
1777    inner: &ActorInner,
1778    resource: &Arc<str>,
1779    generation: MetadataGeneration,
1780    result: RuntimeResult<()>,
1781) -> bool {
1782    let mut completed_waiters = Vec::new();
1783    let (has_queued, persistence_status) = {
1784        let mut state = inner.state.lock();
1785        let Some(mut resource_state) = state.resources.remove(resource) else {
1786            return false;
1787        };
1788        let Some(in_flight) = resource_state.in_flight.take() else {
1789            state.resources.insert(resource.clone(), resource_state);
1790            return false;
1791        };
1792        debug_assert_eq!(in_flight.generation, generation);
1793        state.pending_operations = state.pending_operations.saturating_sub(1);
1794        state.pending_bytes = state.pending_bytes.saturating_sub(in_flight.bytes);
1795        // The closure has already released its payload charge. Local pending
1796        // counters settle here; they may briefly lag the shared byte ledger.
1797
1798        let persistence_status = classify_persistence_result(generation, result);
1799        if matches!(persistence_status, MetadataWritePersistenceStatus::Durable(_)) {
1800            resource_state.durable_generation = Some(
1801                resource_state
1802                    .durable_generation
1803                    .map_or(generation, |durable| durable.max(generation)),
1804            );
1805        }
1806        let mut retained = Vec::with_capacity(resource_state.waiters.len());
1807        for waiter in resource_state.waiters.drain(..) {
1808            if waiter.generation <= generation {
1809                completed_waiters.push(waiter);
1810            } else {
1811                retained.push(waiter);
1812            }
1813        }
1814        resource_state.waiters = retained;
1815        let has_queued = resource_state.queued.is_some();
1816        if !has_queued {
1817            resource_state.target_registration = None;
1818        }
1819        state.resources.insert(resource.clone(), resource_state);
1820        (has_queued, persistence_status)
1821    };
1822
1823    for waiter in completed_waiters {
1824        let _ = waiter.sender.send(Ok(persistence_status.clone()));
1825    }
1826    has_queued
1827}
1828
1829fn classify_persistence_result(
1830    generation: MetadataGeneration,
1831    result: RuntimeResult<()>,
1832) -> MetadataWritePersistenceStatus {
1833    match result {
1834        Ok(()) => MetadataWritePersistenceStatus::Durable(generation),
1835        Err(error) if error.operation() == crate::RuntimeOperation::MetadataSyncParent => {
1836            MetadataWritePersistenceStatus::DurabilityUnconfirmed(error)
1837        }
1838        Err(error) => MetadataWritePersistenceStatus::FailedBeforeCommit(error),
1839    }
1840}
1841
1842fn stop_admission(inner: &ActorInner) {
1843    let changed = {
1844        let mut state = inner.state.lock();
1845        let changed = state.accepting;
1846        state.accepting = false;
1847        changed
1848    };
1849    if changed {
1850        inner.shutdown.notify_one();
1851    }
1852}
1853
1854fn should_finish(inner: &ActorInner) -> bool {
1855    let state = inner.state.lock();
1856    !state.accepting && state.pending_operations == 0
1857}
1858
1859fn finish_worker(inner: &ActorInner) {
1860    let mut abandoned = Vec::new();
1861    {
1862        let mut state = inner.state.lock();
1863        state.accepting = false;
1864        state.worker_finished = true;
1865        for (resource, resource_state) in &mut state.resources {
1866            for waiter in resource_state.waiters.drain(..) {
1867                abandoned.push((resource.clone(), waiter));
1868            }
1869        }
1870    }
1871    for (_resource, waiter) in abandoned {
1872        let _ = waiter.sender.send(Err(RuntimeError::closed(
1873            crate::RuntimeOperation::MetadataWorkerStopped,
1874        )));
1875    }
1876    inner.worker_finished.notify_waiters();
1877}
1878
1879fn snapshot(inner: &ActorInner) -> MetadataIoSnapshot {
1880    let state = inner.state.lock();
1881    let mut resources = state
1882        .resources
1883        .iter()
1884        .map(|(resource, resource_state)| resource_snapshot(resource, resource_state))
1885        .collect::<Vec<_>>();
1886    resources.sort_by(|left, right| left.resource.cmp(&right.resource));
1887    MetadataIoSnapshot {
1888        accepting: state.accepting,
1889        pending_operations: state.pending_operations,
1890        pending_bytes: state.pending_bytes,
1891        max_pending_operations: inner.config.max_pending_operations,
1892        max_pending_bytes: inner.config.max_pending_bytes,
1893        resources,
1894    }
1895}
1896
1897fn shutdown_report(inner: &ActorInner, timed_out: bool) -> MetadataIoShutdownReport {
1898    let snapshot = snapshot(inner);
1899    let unfinished = snapshot
1900        .resources
1901        .into_iter()
1902        .filter(|resource| resource.in_flight_generation.is_some() || resource.queued_generation.is_some())
1903        .collect();
1904    MetadataIoShutdownReport {
1905        timed_out,
1906        pending_operations: snapshot.pending_operations,
1907        pending_bytes: snapshot.pending_bytes,
1908        unfinished,
1909    }
1910}
1911
1912fn resource_snapshot(resource: &Arc<str>, state: &ResourceState) -> MetadataIoResourceSnapshot {
1913    MetadataIoResourceSnapshot {
1914        resource: resource.clone(),
1915        target: state.target.clone(),
1916        durable_generation: state.durable_generation,
1917        in_flight_generation: state.in_flight.as_ref().map(|work| work.generation),
1918        queued_generation: state.queued.as_ref().map(|queued| queued.request.generation),
1919        waiter_count: state.waiters.len(),
1920    }
1921}
1922
1923fn startup_error(source: RuntimeError) -> RuntimeError {
1924    source
1925}
1926
1927#[cfg(test)]
1928mod tests {
1929    use std::error::Error;
1930
1931    use super::*;
1932
1933    #[test]
1934    fn metadata_io_config_rejects_unbounded_zero_limits() {
1935        let zero_operations = MetadataIoConfig {
1936            max_pending_operations: 0,
1937            ..MetadataIoConfig::default()
1938        };
1939        assert_eq!(
1940            zero_operations.validate(),
1941            Err(RuntimeContractViolation::InvalidMetadataConfiguration {
1942                policy: RuntimeContractPolicy::MetadataMaxPendingOperationsPositive,
1943            })
1944        );
1945
1946        let zero_bytes = MetadataIoConfig {
1947            max_pending_bytes: 0,
1948            ..MetadataIoConfig::default()
1949        };
1950        assert_eq!(
1951            zero_bytes.validate(),
1952            Err(RuntimeContractViolation::InvalidMetadataConfiguration {
1953                policy: RuntimeContractPolicy::MetadataMaxPendingBytesPositive,
1954            })
1955        );
1956
1957        assert!(matches!(
1958            MetadataIoConfig {
1959                max_pending_operations: 0,
1960                ..MetadataIoConfig::default()
1961            }
1962            .into_plan(),
1963            Err(RuntimeContractViolation::InvalidMetadataConfiguration {
1964                policy: RuntimeContractPolicy::MetadataMaxPendingOperationsPositive,
1965            })
1966        ));
1967    }
1968
1969    #[test]
1970    fn metadata_io_error_retains_the_original_io_source() {
1971        let error = metadata_io_failure(
1972            MetadataIoOperation::WriteTemporary,
1973            Path::new("metadata.json"),
1974            std::io::Error::new(std::io::ErrorKind::WriteZero, "partial write"),
1975        );
1976        let source = error.source().expect("metadata error should retain its source");
1977        let source = source
1978            .downcast_ref::<std::io::Error>()
1979            .expect("metadata error source should remain a std::io::Error");
1980        assert_eq!(source.kind(), std::io::ErrorKind::WriteZero);
1981    }
1982
1983    #[test]
1984    fn commit_observation_requires_reconciliation_only_for_unconfirmed_outcomes() {
1985        let step_error = || {
1986            RuntimeError::io(
1987                crate::RuntimeOperation::MetadataSyncParent,
1988                std::io::Error::other("injected failure"),
1989            )
1990        };
1991
1992        let confirmed = [
1993            MetadataIoCommitObservation::Settled {
1994                generation: MetadataGeneration::new(7),
1995                persistence_status: MetadataWritePersistenceStatus::Durable(MetadataGeneration::new(7)),
1996            },
1997            MetadataIoCommitObservation::Settled {
1998                generation: MetadataGeneration::new(7),
1999                persistence_status: MetadataWritePersistenceStatus::FailedBeforeCommit(step_error()),
2000            },
2001        ];
2002        for observation in confirmed {
2003            assert!(
2004                !observation.requires_reconciliation(),
2005                "a settled conclusion cannot require reconciliation"
2006            );
2007            assert_eq!(observation.unobserved_generation(), None);
2008            assert_eq!(observation.generation(), Some(MetadataGeneration::new(7)));
2009        }
2010
2011        let unconfirmed = MetadataIoCommitObservation::Settled {
2012            generation: MetadataGeneration::new(7),
2013            persistence_status: MetadataWritePersistenceStatus::DurabilityUnconfirmed(step_error()),
2014        };
2015        assert!(unconfirmed.requires_reconciliation());
2016        assert_eq!(unconfirmed.generation(), Some(MetadataGeneration::new(7)));
2017        assert!(unconfirmed.settled().is_some());
2018
2019        let unobserved = MetadataIoCommitObservation::Unobserved {
2020            generation: MetadataGeneration::new(9),
2021        };
2022        assert!(unobserved.requires_reconciliation());
2023        assert_eq!(unobserved.unobserved_generation(), Some(MetadataGeneration::new(9)));
2024        assert_eq!(unobserved.generation(), Some(MetadataGeneration::new(9)));
2025        assert!(unobserved.settled().is_none());
2026    }
2027
2028    #[test]
2029    fn target_conflict_observation_is_not_a_durability_conclusion() {
2030        let conflict = MetadataIoCommitObservation::TargetConflict(MetadataWriteRequest::new(
2031            "resource",
2032            MetadataGeneration::new(1),
2033            Path::new("metadata.json"),
2034            b"snapshot".to_vec(),
2035        ));
2036        assert!(!conflict.requires_reconciliation());
2037        assert_eq!(conflict.unobserved_generation(), None);
2038        assert_eq!(conflict.generation(), None);
2039        assert!(conflict.settled().is_none());
2040    }
2041}