You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by "spetz (via GitHub)" <gi...@apache.org> on 2026/09/08 09:03:11 UTC

[PR] feat(cluster): add per-topic durability and flatten server config [iggy]

spetz opened a new pull request, #4092:
URL: https://github.com/apache/iggy/pull/4092

   Producer acknowledgments could precede recoverable disk storage.
   enforce_fsync synchronized segment flushes but did not make PrepareOk
   durable on replicas. Consumer-offset synchronization was also global,
   preventing independent policies for mixed workloads.
   
   Add create-only durability and consumer_offset_durability options with
   replicated and persisted values. Both independently default to
   replicated, without inheritance. Replicate the options with topic
   metadata so every replica applies the same policy.
   
   Keep VSR quorum commit as the acknowledgment rule. Persisted
   additionally requires recoverable stable-storage copies on the
   required quorum. Both policies retain ordinary disk persistence. Name
   the policies by their guarantees so a future Direct I/O backend can
   preserve the same API contract.
   
   Add a bounded partition prepare WAL when either policy is persisted.
   Use 4 KiB-padded records, checksums, parent-chain validation and a
   durable frontier. Retain mixed-operation predecessors so durable
   offsets cannot leave gaps in the recoverable message history.
   
   Forward prepares before waiting for local persistence and deliver
   durable completion through shard lifecycle messages. Fence stale
   completions by instance and generation. Replicated/replicated topics
   stay off the disk WAL path and avoid extra prepare cloning.
   Single-node persisted operations synchronize committed local state
   before replying, without a prepare WAL.
   
   Reclaim WAL history only after materialized state is durable. Cover
   truncation, purge, repair and delete/recreate, and retain rollback
   state across destructive transfer installation. Restore checksum
   anchors after checkpoint-only restart and carry them in ICO3
   state-transfer artifacts. Fail closed on missing history or storage
   errors.
   
   Flatten system.* into root runtime, logging, encryption, stream,
   topic, partition, memory_pool and sharding tables. Move the data root
   to path and IGGY_PATH, merge partition storage settings with partition
   limits, and remove unsupported archive_expired and
   recreate_missing_state settings. Update Rust plumbing, environment
   mappings, CI, Helm, scripts and fixtures.
   
   Expose idiomatic enums in Rust, Java, C#, Go, Node, Python, PHP and
   C++. Update CLI and benchmark flags, option catalogs, generated
   declarations, documentation and cross-SDK golden vectors. Preserve
   HTTP option provenance and report replicated or persisted on awaited
   produce, with none on early dispatch acceptance. Keep poll auto-commit
   and existing no-ack dispatch asynchronous.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5623231108

   Thanks for explaining, @hubcio. That helps a lot. I’ll try to help with the review
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5631309350

   Thanks for the fixes, Hubert. I'd like to help strengthen confidence in the PR's core acknowledgment guarantee. Awaited success requires quorum commit under the selected policy, and `persisted` additionally requires recoverable copies of the operation and its required predecessors on the quorum.
   
   The existing storage tests already exercise the predecessor dependency. I'd like to extend that coverage to the client reply through the partition and consensus code, starting with `durability=replicated` and `consumer_offset_durability=persisted`. The test would delay synchronization of preceding message bodies so a durable quorum cannot form, verify that the offset request receives no success, then allow enough replicas to finish and verify completion.
   
   I'll first check how this fits the existing partition fixtures. From there, I'd look for missing cases involving persistence failures and stale completions after fencing, alongside controls for successful progress and independent policy selection. Let me know if someone is already covering this path.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3982179930


##########
core/shard/src/lib.rs:
##########
@@ -7381,6 +7416,24 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();
+        for namespace in namespace_scratch.iter() {

Review Comment:
   I added a [regression](https://github.com/diegomrsantos/iggy/commit/76248cf515e9523c4e746bba9d9ded627e306c80) on top of `7343be420`. It parks a backup acknowledgment, waits for the prepare to become durable, calls `fence_flush_failure()` while the WAL remains healthy, and asserts that `drive_persistence()` emits no acknowledgment. It fails on both Linux and macOS; the existing promotion and deferred purge controls pass.
   
   I’ll work on a focused fix covering the persistence completion and tick paths.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5621040296

   @diegomrsantos your comment is valid, let me can explain,it grew in 3 steps.
   
   first we fixed the producer ACK. ACKs didn't always wait for recoverable storage, so we added the `durability` and `consumer_offset_durability` topic options. they're part of the `TopicOptions` API, which is why every SDK changed too.
   
   Then config changes: no more fsync settings, and `system.*` got flattened along the way.
   
   when we ran it on AWS EC2 i4i, persisted perf wasn't what we expected. a 3-node cluster missed an 800 MB/s target and p999 sat around XX ms. after that we added 40b6e6d08 (persisted bodies no longer go to both the wal and the segment) and 20ee88498 (drops an extra memset per produce request). p999 latency dropped to single digit.
   
   the PR description is behind on all this, I'll fix it today. we want to deliver it as is to not prolong the release due to github actions being constantly overloaded.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983320200


##########
core/simulator/src/replica.rs:
##########
@@ -379,8 +379,7 @@ pub fn new_shard(
     let partitions_config = PartitionsConfig {
         messages_required_to_save: 1000,
         size_of_messages_required_to_save: IggyByteSize::from(4 * 1024 * 1024),
-        enforce_fsync: false, //Disable fsync for simulation
-        consumer_offset_enforce_fsync: false,
+
         validate_checksum: true,
         segment_size: IggyByteSize::from(1024 * 1024 * 1024),

Review Comment:
   reused the shared segment-size default in the simulator.



##########
core/shard/src/lib.rs:
##########
@@ -7553,6 +7606,14 @@ where
                         walk_cursor.get_or_insert(namespace);
                     }
                 }
+                if partition.needs_persistence_checkpoint() {

Review Comment:
   fixed; checkpoint failures are returned in the same sweep.



##########
core/shard/src/lib.rs:
##########
@@ -7381,6 +7416,24 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();
+        for namespace in namespace_scratch.iter() {

Review Comment:
   fixed; fatal partitions can't checkpoint or send pending acks.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,8 +727,510 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        self.open_persistence_with_recovered(capacity, None).await
+    }
+
+    /// # Errors
+    /// Returns an error if durable history cannot be opened, migrated, or replayed.
+    #[allow(clippy::too_many_lines)]
+    pub async fn open_persistence_with_recovered(
+        &mut self,
+        capacity: u64,
+        recovered: Option<(Rc<PartitionPersistence>, Vec<Message<PrepareHeader>>)>,
+    ) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = if let Some(recovered) = recovered {
+            recovered
+        } else {
+            PartitionPersistence::open_with_capacity(
+                &directory,
+                self.namespace().inner(),
+                self.created_revision,
+                journal::durable_storage::DiskStorage,
+                capacity,
+                self.runtime_options
+                    .preallocate_segments
+                    .unwrap_or(iggy_common::DEFAULT_PREALLOCATE_SEGMENTS),
+            )
+            .await
+            .map_err(|error| {
+                warn!(%error, "cannot open partition prepare WAL");
+                IggyError::CannotReadFile
+            })?
+        };
+        if self.durability().is_persisted() && !self.materialization_missing {
+            let segment = self.log.active_segment();
+            let length = segment.size.as_bytes_u64();
+            let initial = journal::partition_journal::SegmentPosition {
+                start_offset: segment.start_offset,
+                length,
+                next_offset: if length == 0 {
+                    segment.start_offset
+                } else {
+                    segment
+                        .end_offset
+                        .checked_add(1)
+                        .ok_or(IggyError::CannotReadFile)?
+                },
+            };
+            persistence.enable_segment_storage(initial, segment.max_size.as_bytes_u64());
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(&persistence).run());
+            }
+            persistence.drain_with_timeout().await.map_err(|error| {
+                warn!(%error, "cannot enable partition segment persistence");
+                IggyError::CannotSyncFile
+            })?;
+        }
+        self.restore_certified_log_view(&persistence).await?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    async fn restore_certified_log_view(
+        &mut self,
+        persistence: &Rc<PartitionPersistence>,
+    ) -> Result<(), IggyError> {
+        if !self.materialization_missing
+            && self.recovered_log_view.is_none()
+            && persistence.head() == 0
+        {
+            persistence.certify_log_view(self.consensus.log_view(), 0, 0);
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(persistence).run());
+            }
+            persistence
+                .drain_with_timeout()
+                .await
+                .map_err(|_| IggyError::CannotSyncFile)?;
+        }
+        if !self.materialization_missing {
+            match persistence.certified_log_view() {
+                Some(view) if view >= self.consensus.log_view() => {
+                    if view > self.consensus.view() {
+                        self.consensus.set_view(view);
+                    }
+                    self.consensus.set_log_view(view);
+                }
+                _ => {
+                    self.materialization_missing = true;
+                    self.ensure_materialization_recovery();
+                }
+            }
+        }
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.commit_messages_inner(config, true, through_op).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let mut directories = Vec::with_capacity(4);
+        for directory in [
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        {
+            let path = std::path::PathBuf::from(directory);
+            directories.push(path.clone());
+            if let Some(parent) = path.parent()
+                && !directories.iter().any(|existing| existing == parent)
+            {
+                directories.push(parent.to_path_buf());
+            }
+        }
+        if let Some(directory) = &self.partition_dir {
+            directories.push(std::path::PathBuf::from(directory));
+        }
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        if self.materialization_missing || !self.ensure_wal_view() {
+            return;
+        }
+        let durable_op = persistence.durable_op();
+        loop {
+            let ready = self
+                .pending_persisted_acks
+                .borrow()
+                .first_key_value()
+                .is_some_and(|(op, _)| *op <= durable_op);
+            if !ready {
+                break;
+            }
+            let Some((_, header)) = self.pending_persisted_acks.borrow_mut().pop_first() else {
+                break;
+            };
+            if persistence.checksum(header.op) == Some(header.checksum)

Review Comment:
   fixed; pending acks survive until they're actually queued.



##########
core/shard/src/lib.rs:
##########
@@ -8501,11 +8562,10 @@ where
     /// disk as they complete, so this bounds corruption, not memory.
     const PARTITION_TRANSFER_TOTAL_LEN_MAX: u64 = 1 << 40;
 
-    /// Alloc cap for the `CONSUMER_OFFSETS` artifact, which accumulates whole
-    /// in `ArtifactProgress::buf` before decode can reject it. Its decoder
-    /// ceilings imply ~24 MiB (two sections of 2^20 12-byte entries); this
-    /// leaves headroom without letting a hostile manifest stage gigabytes.
-    const CONSUMER_OFFSETS_ARTIFACT_LEN_MAX: u64 = 32 << 20;
+    /// Bound the buffered offset and dedup state plus one maximum-sized

Review Comment:
   kept the cap for full checkpoint prepares; corrected the size docs.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,8 +727,510 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        self.open_persistence_with_recovered(capacity, None).await
+    }
+
+    /// # Errors
+    /// Returns an error if durable history cannot be opened, migrated, or replayed.
+    #[allow(clippy::too_many_lines)]
+    pub async fn open_persistence_with_recovered(
+        &mut self,
+        capacity: u64,
+        recovered: Option<(Rc<PartitionPersistence>, Vec<Message<PrepareHeader>>)>,
+    ) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = if let Some(recovered) = recovered {
+            recovered
+        } else {
+            PartitionPersistence::open_with_capacity(
+                &directory,
+                self.namespace().inner(),
+                self.created_revision,
+                journal::durable_storage::DiskStorage,
+                capacity,
+                self.runtime_options
+                    .preallocate_segments
+                    .unwrap_or(iggy_common::DEFAULT_PREALLOCATE_SEGMENTS),
+            )
+            .await
+            .map_err(|error| {
+                warn!(%error, "cannot open partition prepare WAL");
+                IggyError::CannotReadFile
+            })?
+        };
+        if self.durability().is_persisted() && !self.materialization_missing {
+            let segment = self.log.active_segment();
+            let length = segment.size.as_bytes_u64();
+            let initial = journal::partition_journal::SegmentPosition {
+                start_offset: segment.start_offset,
+                length,
+                next_offset: if length == 0 {
+                    segment.start_offset
+                } else {
+                    segment
+                        .end_offset
+                        .checked_add(1)
+                        .ok_or(IggyError::CannotReadFile)?
+                },
+            };
+            persistence.enable_segment_storage(initial, segment.max_size.as_bytes_u64());
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(&persistence).run());
+            }
+            persistence.drain_with_timeout().await.map_err(|error| {
+                warn!(%error, "cannot enable partition segment persistence");
+                IggyError::CannotSyncFile
+            })?;
+        }
+        self.restore_certified_log_view(&persistence).await?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    async fn restore_certified_log_view(
+        &mut self,
+        persistence: &Rc<PartitionPersistence>,
+    ) -> Result<(), IggyError> {
+        if !self.materialization_missing
+            && self.recovered_log_view.is_none()
+            && persistence.head() == 0
+        {
+            persistence.certify_log_view(self.consensus.log_view(), 0, 0);
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(persistence).run());
+            }
+            persistence
+                .drain_with_timeout()
+                .await
+                .map_err(|_| IggyError::CannotSyncFile)?;
+        }
+        if !self.materialization_missing {
+            match persistence.certified_log_view() {
+                Some(view) if view >= self.consensus.log_view() => {
+                    if view > self.consensus.view() {
+                        self.consensus.set_view(view);
+                    }
+                    self.consensus.set_log_view(view);
+                }
+                _ => {
+                    self.materialization_missing = true;
+                    self.ensure_materialization_recovery();
+                }
+            }
+        }
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.commit_messages_inner(config, true, through_op).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {

Review Comment:
   covered by the fatal guard; the first fault stays intact.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983524204


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   I've published the reproducer in [7a229f9ba](https://github.com/diegomrsantos/iggy/commit/7a229f9baf4eeda6f5ea0d7cb2995bdfed96b362), on `test/http-durability-topic-identity` in my fork. It adds only the test and its imports, on top of `4a38798a5`.
   
   To run it:
   
   ```sh
   cargo test --locked -p server --all-features --lib named_produce_attests_the_dispatched_topic
   ```
   
   It deliberately fails on that baseline with actual `Persisted`, expected `Replicated`. I verified this on Linux; the existing `completed_produce_checks_the_stored_topic_incarnation` test passes, and Clippy passes for the server with all features and targets.
   
   This isolates the current metadata and policy helper sequence. It does not run a full HTTP request. If the fix binds the target earlier, the regression should move to that request boundary so it tests the resulting behavior. Happy to adapt it to the chosen approach.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983325827


##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)

Review Comment:
   added a regression test that stops checkpoint boundaries rewinding.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))

Review Comment:
   added migration coverage with an existing segment reference.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;
+            Some(reference)
+        } else {
+            None
+        };
+        Ok((buffer, frame_length, reference))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+        checkpoint_prepare: Option<(Frozen<4096>, Option<SegmentReference>)>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            checkpoint_prepare: false,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            if checkpoint > self.state.checkpoint {
+                segments.checkpoint = self
+                    .segment_boundary(checkpoint)
+                    .ok_or_else(|| invalid("missing segment checkpoint boundary"))?;
+            }
+            if let Some(from_op) = truncate.filter(|from_op| *from_op > 0) {
+                segments.tail = self
+                    .segment_boundary(from_op - 1)
+                    .ok_or_else(|| invalid("missing segment rollback boundary"))?;
+            }
+        }
+        if let Some((prepare, reference)) = checkpoint_prepare {
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let mut encoded = Owned::zeroed(length);
+            encode_record_into(
+                prepare.as_slice(),
+                reference,
+                generation,
+                encoded.as_mut_slice(),
+            )?;
+            let length = encoded.as_slice().len();
+            file.write_aligned(0, encoded).await?;
+            entries.insert(
+                checkpoint,
+                StoredPrepare {
+                    position: 0,
+                    length,
+                    checksum,
+                    reference,
+                    next_offset: None,
+                    retained_bytes: record_length(prepare.len())? as u64,
+                },
+            );
+            state.length = length as u64;
+            state.checkpoint_prepare = true;
+        }
+        let previous_entries: Vec<_> = self
+            .entries
+            .iter()
+            .map(|(&op, &entry)| (op, entry))
+            .collect();
+        for (op, entry) in previous_entries {
+            if op < checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let (record, payload_length, mut reference) =
+                self.read_encoded_record(entry.position).await?;
+            let payload = &record.as_slice()[RECORD_PREFIX..RECORD_PREFIX + payload_length];
+            let mut next_offset = entry.next_offset;
+            let mut converted = false;
+            if reference.is_none()
+                && op > state.purge_floor
+                && let Some(segments) = &mut state.segment_storage
+            {
+                let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                    &payload[..size_of::<PrepareHeader>()],
+                )
+                .map_err(|_| invalid("invalid prepare during segment migration"))?;
+                if header.operation == Operation::SendMessages
+                    && segments::decode_batch(payload)?.base_offset
+                        >= segments.tail.position.next_offset
+                {
+                    (reference, next_offset) = segments.reserve(header, payload)?;
+                    if let Some(reference) = reference {
+                        self.write_segment_body(
+                            reference,
+                            &Frozen::from(Owned::copy_from_slice(payload)),
+                        )
+                        .await?;
+                        converted = true;
+                    }
+                }
+            }
+            let encoded_length = if converted {
+                REFERENCED_PREPARE_BYTES
+            } else {
+                payload_length
+            };
+            let mut encoded = Owned::zeroed(record_length(encoded_length)?);
+            if converted {
+                encode_record_into(payload, reference, generation, encoded.as_mut_slice())?;
+            } else {
+                encode_payload_into(
+                    payload,
+                    if reference.is_some() {
+                        SEGMENT_RECORD
+                    } else {
+                        INLINE_RECORD
+                    },
+                    generation,
+                    encoded.as_mut_slice(),
+                )?;
+            }
+            let length = encoded.as_slice().len();
+            file.write_aligned(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: entry.retained_bytes,
+                },
+            );
+            state.length += length as u64;
+            state.checkpoint_prepare |= op == checkpoint;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        self.sync_segment_files().await?;
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        let retained = self.retained_segment_paths(&entries, state.segment_storage);
+        self.obsolete.extend(
+            self.retained_segment_paths(&self.entries, self.state.segment_storage)
+                .into_iter()
+                .filter(|path| !retained.contains(path)),
+        );
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        self.obsolete.push_back(obsolete);
+        self.cleanup_obsolete().await;
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(if self.segment_references {
+            REFERENCE_STATE_MAGIC
+        } else {
+            STATE_MAGIC
+        });
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[97] = u8::from(self.checkpoint_prepare);
+        bytes[98] = u8::from(self.certified_log_view.is_some());
+        bytes[120..124].copy_from_slice(&self.certified_log_view.unwrap_or(0).to_le_bytes());
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        bytes[segments::SEGMENT_STATE_FLAG] = u8::from(self.segment_storage.is_some());
+        if let Some(segments) = self.segment_storage {
+            segments.encode(
+                &mut bytes[segments::SEGMENT_STATE_OFFSET
+                    ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+            );
+        }
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);
+        bytes[8..16].copy_from_slice(&checksum.to_le_bytes());
+        bytes
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != PARTITION_WAL_BLOCK_SIZE
+            || (&bytes[..8] != STATE_MAGIC && &bytes[..8] != REFERENCE_STATE_MAGIC)
+        {
+            return Err(invalid("unknown partition WAL frontier format"));
+        }
+        let read_u64 = |offset| -> io::Result<u64> {
+            Ok(u64::from_le_bytes(
+                bytes[offset..offset + 8]
+                    .try_into()
+                    .map_err(|_| invalid("invalid WAL frontier field"))?,
+            ))
+        };
+        if read_u64(8)? != XxHash3_64::oneshot(&bytes[16..]) {
+            return Err(invalid("partition WAL frontier checksum mismatch"));
+        }
+        let state = Self {
+            segment_references: &bytes[..8] == REFERENCE_STATE_MAGIC,
+            segment_storage: match bytes[segments::SEGMENT_STATE_FLAG] {
+                0 => None,
+                1 if &bytes[..8] == REFERENCE_STATE_MAGIC => Some(SegmentState::decode(
+                    &bytes[segments::SEGMENT_STATE_OFFSET
+                        ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+                )?),
+                _ => return Err(invalid("invalid segment storage flag")),
+            },
+            group: read_u64(16)?,
+            incarnation: read_u64(24)?,
+            generation: read_u64(32)?,
+            length: read_u64(40)?,
+            checkpoint: read_u64(48)?,
+            head: read_u64(72)?,
+            anchor_known: match bytes[96] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid WAL anchor flag")),
+            },
+            checkpoint_prepare: match bytes[97] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid checkpoint prepare flag")),
+            },
+            certified_log_view: match bytes[98] {
+                0 => None,
+                1 => Some(u32::from_le_bytes(
+                    bytes[120..124]
+                        .try_into()
+                        .map_err(|_| invalid("invalid certified view"))?,
+                )),
+                _ => return Err(invalid("invalid certified view flag")),
+            },
+            purge_generation: read_u64(104)?,
+            purge_floor: read_u64(112)?,
+            checkpoint_checksum: u128::from_le_bytes(
+                bytes[56..72]
+                    .try_into()
+                    .map_err(|_| invalid("invalid checkpoint checksum"))?,
+            ),
+            head_checksum: u128::from_le_bytes(
+                bytes[80..96]
+                    .try_into()
+                    .map_err(|_| invalid("invalid head checksum"))?,
+            ),
+        };
+        if state.length > PARTITION_WAL_CAPACITY_MAX
+            || !state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+            || state.head < state.checkpoint
+            || (!state.anchor_known && state.head != state.checkpoint)
+            || (state.checkpoint_prepare
+                && (state.checkpoint == 0 || state.length == 0 || !state.anchor_known))
+        {
+            return Err(invalid("invalid partition WAL frontier bounds"));
+        }
+        Ok(state)
+    }
+}
+
+/// Padded size of a prepare record, including its envelope.
+///
+/// # Errors
+/// Returns an error for a frame outside the protocol size bounds.
+pub fn record_length(frame_length: usize) -> io::Result<usize> {
+    if !(size_of::<PrepareHeader>()..=PREPARE_BYTES_MAX).contains(&frame_length) {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidInput,
+            format!(
+                "partition prepare size {frame_length} exceeds or falls below the supported range {}..={PREPARE_BYTES_MAX} bytes",
+                size_of::<PrepareHeader>()
+            ),
+        ));
+    }
+    Ok((RECORD_PREFIX + frame_length).next_multiple_of(PARTITION_WAL_BLOCK_SIZE))
+}
+
+fn encode_record_into(
+    prepare: &[u8],
+    reference: Option<SegmentReference>,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    if let Some(reference) = reference {
+        let mut payload = [0; REFERENCED_PREPARE_BYTES];
+        payload[..size_of::<PrepareHeader>()]
+            .copy_from_slice(&prepare[..size_of::<PrepareHeader>()]);
+        reference.encode(&mut payload[size_of::<PrepareHeader>()..]);
+        encode_payload_into(&payload, SEGMENT_RECORD, generation, bytes)
+    } else {
+        encode_payload_into(prepare, INLINE_RECORD, generation, bytes)
+    }
+}
+
+fn encode_payload_into(
+    payload: &[u8],
+    kind: u32,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    let length = u32::try_from(payload.len()).map_err(|_| invalid("oversized prepare"))?;
+    bytes[..4].copy_from_slice(&length.to_le_bytes());
+    bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+        .copy_from_slice(&kind.to_le_bytes());
+    bytes[8..16].copy_from_slice(&generation.to_le_bytes());
+    bytes[RECORD_PREFIX..RECORD_PREFIX + payload.len()].copy_from_slice(payload);
+    let checksum = XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + payload.len()]);
+    bytes[16..24].copy_from_slice(&checksum.to_le_bytes());
+    Ok(())
+}
+
+impl SegmentReference {
+    fn validate(self, header: &PrepareHeader, frame_length: usize) -> io::Result<()> {
+        if header.command != Command::Prepare
+            || header.operation != Operation::SendMessages
+            || header.size as usize != frame_length
+            || !(size_of::<PrepareHeader>() + BATCH_HEADER_SIZE..=PREPARE_BYTES_MAX)
+                .contains(&frame_length)
+            || self.length != (frame_length - size_of::<PrepareHeader>()) as u64
+            || self.position.checked_add(self.length).is_none()
+        {
+            return Err(invalid("invalid partition WAL segment reference"));
+        }
+        Ok(())
+    }
+
+    fn path(self, directory: &Path) -> PathBuf {
+        directory.join(format!(
+            "segment-{}-{}.log",
+            self.generation, self.start_offset
+        ))
+    }
+
+    fn encode(self, bytes: &mut [u8]) {
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip([
+                self.generation,
+                self.start_offset,
+                self.position,
+                self.length,
+            ])
+        {
+            field.copy_from_slice(&value.to_le_bytes());
+        }
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != SEGMENT_REFERENCE_BYTES {
+            return Err(invalid("invalid partition WAL segment reference size"));
+        }
+        let mut fields = [0; SEGMENT_REFERENCE_BYTES / size_of::<u64>()];
+        for (field, bytes) in fields
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *field = u64::from_le_bytes(*bytes);
+        }
+        let [generation, start_offset, position, length] = fields;
+        Ok(Self {
+            generation,
+            start_offset,
+            position,
+            length,
+        })
+    }
+}
+
+fn referenced_segments(
+    entries: &BTreeMap<u64, StoredPrepare>,
+    directory: &Path,
+) -> BTreeSet<PathBuf> {
+    entries
+        .values()
+        .filter_map(|entry| entry.reference.map(|reference| reference.path(directory)))
+        .collect()
+}
+
+fn is_retained_segment_name(name: &str) -> bool {
+    name.strip_prefix("segment-")
+        .and_then(|name| name.strip_suffix(".log"))
+        .and_then(|name| name.split_once('-'))
+        .is_some_and(|(generation, start_offset)| {
+            generation.parse::<u64>().is_ok() && start_offset.parse::<u64>().is_ok()
+        })
+}
+
+fn data_path(directory: &Path, generation: u64) -> PathBuf {
+    directory.join(format!("prepares-{generation}.wal"))
+}
+
+fn invalid(message: &'static str) -> io::Error {
+    io::Error::new(io::ErrorKind::InvalidData, message)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use compio::fs::File;
+    use compio::io::AsyncWriteAtExt;
+    use iggy_binary_protocol::Operation;
+    use iggy_binary_protocol::batch::BatchHeader;
+    use tempfile::tempdir;
+
+    #[cfg(target_os = "linux")]
+    use std::os::unix::fs::MetadataExt;
+
+    const REFERENCE_TEST_BODY_BYTES: usize = 1024 * 1024;
+    #[cfg(target_os = "linux")]
+    const FILE_BLOCK_BYTES: u64 = 512;
+
+    #[compio::test]
+    async fn referenced_bodies_survive_retention_and_checkpoint_without_wal_copies() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        let second_reference = write_segment(partition.path(), 0, 1, &second).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen(), second.clone().into_frozen()],
+                &[Some(first_reference), Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        assert!(!journal.contains(second.header()));
+        journal.sync().await.unwrap();
+        assert_eq!(journal.size_bytes(), 2 * PARTITION_WAL_BLOCK_SIZE as u64);
+        for offset in [0, 1] {
+            DiskStorage
+                .remove_file(&partition.path().join(format!("{offset:020}.log")))
+                .await
+                .unwrap();
+        }
+        DiskStorage.sync_directory(partition.path()).await.unwrap();
+        drop(journal);
+
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), second.as_slice());
+        journal.checkpoint(2).await.unwrap();
+        assert_eq!(journal.size_bytes(), PARTITION_WAL_BLOCK_SIZE as u64);
+        assert!(!first_reference.path(&directory).exists());
+        assert!(second_reference.path(&directory).exists());
+        drop(journal);
+
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered.len(), 1);
+        assert_eq!(recovered[0].as_slice(), second.as_slice());
+    }
+
+    #[compio::test]
+    async fn truncating_a_reference_keeps_the_shared_segment_for_its_retained_prefix() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        let mut segment = DiskStorage
+            .open(
+                &partition.path().join("00000000000000000000.log"),
+                OpenMode::ReadWrite,
+            )
+            .await
+            .unwrap();
+        DurableFile::write(
+            &mut segment,
+            first_reference.length,
+            second.as_slice()[size_of::<PrepareHeader>()..].to_vec(),
+        )
+        .await
+        .unwrap();
+        DurableFile::sync(&segment).await.unwrap();
+        let second_reference = SegmentReference {
+            position: first_reference.length,
+            ..first_reference
+        };
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen(), second.into_frozen()],
+                &[Some(first_reference), Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        journal.truncate_from(2).await.unwrap();
+        assert!(first_reference.path(&directory).exists());
+        DurableFile::truncate(&segment, first_reference.length)
+            .await
+            .unwrap();
+        let replacement = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + BATCH_HEADER_SIZE,
+        );
+        DurableFile::write(
+            &mut segment,
+            first_reference.length,
+            replacement.as_slice()[size_of::<PrepareHeader>()..].to_vec(),
+        )
+        .await
+        .unwrap();
+        DurableFile::sync(&segment).await.unwrap();
+        journal
+            .append_batch_referenced_buffered(
+                &[replacement.clone().into_frozen()],
+                &[Some(SegmentReference {
+                    length: BATCH_HEADER_SIZE as u64,
+                    ..second_reference
+                })],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+    }
+
+    #[compio::test]
+    async fn references_coexist_with_legacy_records_and_survive_purge_name_reuse() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let legacy = prepare(1, 0);
+        journal.append(legacy.clone().into_frozen()).await.unwrap();
+        assert_eq!(
+            &std::fs::read(directory.join("frontier")).unwrap()[..8],
+            STATE_MAGIC
+        );
+        let first = sized_prepare(
+            2,
+            legacy.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen()],
+                &[Some(first_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        assert_eq!(
+            &std::fs::read(directory.join("frontier")).unwrap()[..8],
+            REFERENCE_STATE_MAGIC
+        );
+        journal.mark_purge(1, 2).await.unwrap();
+        DiskStorage
+            .remove_file(&partition.path().join("00000000000000000000.log"))
+            .await
+            .unwrap();
+        let second = sized_prepare(
+            3,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + BATCH_HEADER_SIZE,
+        );
+        let second_reference = write_segment(partition.path(), 1, 0, &second).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[second.clone().into_frozen()],
+                &[Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        drop(journal);
+
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), legacy.as_slice());
+        assert_eq!(recovered[1].as_slice(), first.as_slice());
+        assert_eq!(recovered[2].as_slice(), second.as_slice());
+        assert_eq!(journal.purge_marker(), (1, 2));
+        journal.truncate_from(3).await.unwrap();
+        assert!(first_reference.path(&directory).exists());
+        assert!(!second_reference.path(&directory).exists());
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(
+            journal.prepares().await.unwrap()[1].as_slice(),
+            first.as_slice()
+        );
+    }
+
+    #[compio::test]
+    async fn recovery_sweeps_unpublished_references_and_keeps_the_durable_prefix() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let reference = write_segment(partition.path(), 0, 0, &second).await;
+        journal
+            .append_batch_referenced_buffered(&[second.into_frozen()], &[Some(reference)])
+            .await
+            .unwrap();
+        assert!(reference.path(&directory).exists());
+        drop(journal);
+
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 1);
+        assert_eq!(
+            journal.prepares().await.unwrap()[0].as_slice(),
+            first.as_slice()
+        );
+        assert!(!reference.path(&directory).exists());
+    }
+
+    #[compio::test]
+    async fn recovery_refuses_missing_torn_or_corrupt_referenced_bodies_without_rewriting_evidence()
+    {
+        for damage in ["missing", "torn", "corrupt"] {
+            let partition = tempdir().unwrap();
+            let directory = partition.path().join("prepares-7");
+            let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+                .await
+                .unwrap();
+            let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+            let reference = write_segment(partition.path(), 0, 0, &first).await;
+            journal
+                .append_batch_referenced_buffered(&[first.into_frozen()], &[Some(reference)])
+                .await
+                .unwrap();
+            journal.sync().await.unwrap();
+            drop(journal);
+            let wal = std::fs::read(data_path(&directory, 0)).unwrap();
+            let frontier = std::fs::read(directory.join("frontier")).unwrap();
+            let retained = reference.path(&directory);
+            if damage == "missing" {
+                DiskStorage.remove_file(&retained).await.unwrap();
+            } else {
+                let mut file = DiskStorage
+                    .open(&retained, OpenMode::ReadWrite)
+                    .await
+                    .unwrap();
+                if damage == "torn" {
+                    DurableFile::truncate(&file, reference.length - 1)
+                        .await
+                        .unwrap();
+                } else {
+                    DurableFile::write(&mut file, reference.length - 1, vec![0])
+                        .await
+                        .unwrap();
+                }
+                DurableFile::sync(&file).await.unwrap();
+            }
+            assert!(
+                PartitionPrepareJournal::open(&directory, 42, 7)
+                    .await
+                    .is_err(),
+                "{damage}"
+            );
+            assert_eq!(
+                std::fs::read(data_path(&directory, 0)).unwrap(),
+                wal,
+                "{damage}"
+            );
+            assert_eq!(
+                std::fs::read(directory.join("frontier")).unwrap(),
+                frontier,
+                "{damage}"
+            );
+        }
+    }
+
+    #[compio::test]
+    async fn invalid_references_are_rejected_before_modifying_history() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES)
+            .into_frozen();
+        let reference = SegmentReference {
+            generation: 0,
+            start_offset: 0,
+            position: 0,
+            length: REFERENCE_TEST_BODY_BYTES as u64,
+        };
+        for invalid_reference in [
+            SegmentReference {
+                length: reference.length - 1,
+                ..reference
+            },
+            SegmentReference {
+                position: u64::MAX,
+                ..reference
+            },
+        ] {
+            assert!(
+                journal
+                    .append_batch_referenced_buffered(
+                        std::slice::from_ref(&first),
+                        &[Some(invalid_reference)]
+                    )
+                    .await
+                    .is_err()
+            );
+        }
+        assert!(
+            journal
+                .append_batch_referenced_buffered(&[first], &[])
+                .await
+                .is_err()
+        );
+        assert_eq!(journal.head(), 0);
+        assert_eq!(journal.size_bytes(), 0);
+        assert!(!reference.path(&directory).exists());
+        assert!(!journal.poisoned);
+    }
+
+    async fn write_segment(
+        partition: &Path,
+        generation: u64,
+        start_offset: u64,
+        prepare: &Message<PrepareHeader>,
+    ) -> SegmentReference {
+        let body = &prepare.as_slice()[size_of::<PrepareHeader>()..];
+        let path = partition.join(format!("{start_offset:020}.log"));
+        let mut file = DiskStorage.open(&path, OpenMode::Create).await.unwrap();
+        DurableFile::write(&mut file, 0, body.to_vec())
+            .await
+            .unwrap();
+        DurableFile::sync(&file).await.unwrap();
+        DiskStorage.sync_directory(partition).await.unwrap();
+        SegmentReference {
+            generation,
+            start_offset,
+            position: 0,
+            length: body.len() as u64,
+        }
+    }
+
+    #[compio::test]
+    async fn durable_frontier_recovers_only_covered_prepares() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        journal
+            .append_buffered(second.clone().into_frozen())
+            .await
+            .unwrap();
+        assert!(journal.contains(first.header()));
+        assert!(!journal.contains(second.header()));
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 1);
+        assert_eq!(
+            journal.prepares().await.unwrap()[0].as_slice(),
+            first.as_slice()
+        );
+        assert_eq!(
+            journal.file.metadata().await.unwrap().len(),
+            journal.size_bytes()
+        );
+    }
+
+    #[compio::test]
+    async fn durable_append_covers_buffered_predecessors() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal
+            .append_buffered(first.clone().into_frozen())
+            .await
+            .unwrap();
+        journal.append(second.clone().into_frozen()).await.unwrap();
+        assert!(journal.contains(first.header()));
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let entries = journal.prepares().await.unwrap();
+        assert_eq!(entries.len(), 2);
+        assert_eq!(entries[1].as_slice(), second.as_slice());
+    }
+
+    #[compio::test]
+    async fn zeroed_interior_record_is_not_an_unwritten_tail() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal.append(first.into_frozen()).await.unwrap();
+        journal.append(second.into_frozen()).await.unwrap();
+        let length = journal.size_bytes();
+        let (result, _) = journal
+            .file
+            .write_all_at(vec![0; PARTITION_WAL_BLOCK_SIZE], 0)
+            .await
+            .into();
+        result.unwrap();
+        journal.file.sync_data().await.unwrap();
+        drop(journal);
+        assert!(
+            PartitionPrepareJournal::open(directory.path(), 42, 7)
+                .await
+                .is_err()
+        );
+        assert_eq!(
+            File::open(data_path(directory.path(), 0))
+                .await
+                .unwrap()
+                .metadata()
+                .await
+                .unwrap()
+                .len(),
+            length
+        );
+    }
+
+    #[compio::test]
+    async fn truncate_and_checkpoint_preserve_the_recoverable_history() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        let third = prepare(3, second.header().checksum);
+        for entry in [&first, &second, &third] {
+            journal.append(entry.clone().into_frozen()).await.unwrap();
+        }
+        journal.truncate_from(3).await.unwrap();
+        journal.checkpoint(1).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.checkpoint_op(), 1);
+        assert_eq!(journal.head(), 2);
+        assert_eq!(journal.prepares().await.unwrap().len(), 2);
+        journal.append(third.into_frozen()).await.unwrap();
+        assert_eq!(journal.head(), 3);
+        assert!(journal.truncate_from(1).await.is_err());
+    }
+
+    #[compio::test]
+    async fn missing_durable_tail_and_wrong_incarnation_are_rejected() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        journal.append(prepare(1, 0).into_frozen()).await.unwrap();
+        assert!(
+            PartitionPrepareJournal::open(directory.path(), 42, 8)
+                .await
+                .is_err()
+        );
+        journal.file.set_len(0).await.unwrap();
+        journal.file.sync_data().await.unwrap();
+        drop(journal);
+        assert!(
+            PartitionPrepareJournal::open(directory.path(), 42, 7)
+                .await
+                .is_err()
+        );
+    }
+
+    #[compio::test]
+    async fn same_generation_purge_retry_persists_the_larger_floor() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal.append(first.into_frozen()).await.unwrap();
+        journal.mark_purge(9, 1).await.unwrap();
+        journal.append(second.into_frozen()).await.unwrap();
+        journal.mark_purge(9, 2).await.unwrap();
+        journal.mark_purge(9, 1).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.purge_marker(), (9, 2));
+    }
+
+    #[compio::test]
+    async fn view_certificate_requires_complete_matching_history() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let checksum = first.header().checksum;
+        assert!(journal.certify_log_view(2, 1, checksum).await.is_err());
+        journal.append(first.into_frozen()).await.unwrap();
+        journal.certify_log_view(2, 1, checksum).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.certified_log_view(), Some(2));
+        journal.truncate_from(1).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.certified_log_view(), None);
+    }
+
+    #[compio::test]
+    async fn transferred_checkpoint_retains_its_prepare_after_restart() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let checkpoint = prepare(7, 1234);
+        let checksum = checkpoint.header().checksum;
+        let expected = checkpoint.as_slice().to_vec();
+        journal
+            .reset_with_prepare(checkpoint.into_frozen())
+            .await
+            .unwrap();
+        journal.certify_log_view(2, 7, checksum).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.checkpoint_op(), 7);
+        assert_eq!(journal.certified_log_view(), Some(2));
+        let prepares = journal.take_recovered_prepares();
+        assert_eq!(prepares.len(), 1);
+        assert_eq!(prepares[0].as_slice(), expected);
+        journal
+            .append(prepare(8, checksum).into_frozen())
+            .await
+            .unwrap();
+    }
+
+    #[compio::test]
+    async fn purge_marker_does_not_promote_the_uncommitted_tail_to_checkpoint() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        journal.append(prepare(1, 0).into_frozen()).await.unwrap();
+        journal.mark_purge(9, 1).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.purge_marker(), (9, 1));
+        assert_eq!(journal.checkpoint_op(), 0);
+        assert_eq!(journal.prepares().await.unwrap().len(), 1);
+    }
+
+    #[compio::test]
+    async fn transferred_checkpoint_binds_the_next_accepted_parent() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        journal.reset(7, None).await.unwrap();
+        let next = prepare(8, 1234);
+        journal.append(next.clone().into_frozen()).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.checkpoint_op(), 7);
+        assert_eq!(journal.head(), 8);
+        assert!(journal.contains(next.header()));
+    }
+
+    #[compio::test]
+    async fn reducing_capacity_recovers_existing_history_and_backpressures_new_appends() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let mut buffer = Owned::<4096>::zeroed(PREPARE_BYTES_MAX);
+        let template = prepare(1, 0);
+        buffer.as_mut_slice()[..size_of::<PrepareHeader>()]
+            .copy_from_slice(&template.as_slice()[..size_of::<PrepareHeader>()]);
+        let checksum_body = XxHash3_64::oneshot(&buffer.as_slice()[size_of::<PrepareHeader>()..]);
+        let header = bytemuck::checked::from_bytes_mut::<PrepareHeader>(
+            &mut buffer.as_mut_slice()[..size_of::<PrepareHeader>()],
+        );
+        header.size = u32::try_from(PREPARE_BYTES_MAX).unwrap();
+        header.checksum_body = u128::from(checksum_body);
+        header.checksum = header.identity_checksum();
+        let first = Message::<PrepareHeader>::try_from(buffer).unwrap();
+        let second = sized_prepare(2, first.header().checksum, PREPARE_BYTES_MAX);
+        let third = prepare(3, second.header().checksum);
+        journal.append_buffered(first.into_frozen()).await.unwrap();
+        let fourth = prepare(4, third.header().checksum);
+        journal.append_buffered(second.into_frozen()).await.unwrap();
+        journal.append(third.into_frozen()).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory.path(),
+            42,
+            7,
+            DiskStorage,
+            PARTITION_WAL_CAPACITY_MIN,
+            false,
+        )
+        .await
+        .unwrap();
+        assert_eq!(journal.head(), 3);
+        assert!(journal.size_bytes() > PARTITION_WAL_CAPACITY_MIN);
+        assert!(journal.append(fourth.clone().into_frozen()).await.is_err());
+        journal.checkpoint(3).await.unwrap();
+        journal.append(fourth.into_frozen()).await.unwrap();
+        assert_eq!(journal.head(), 4);
+    }
+
+    #[test]
+    fn record_padding_and_state_checksums_cover_the_format() {
+        assert_eq!(record_length(256).unwrap(), 4096);
+        assert_eq!(record_length(4096).unwrap(), 8192);
+        assert!(record_length(PREPARE_BYTES_MAX + 1).is_err());
+        let state = JournalState {
+            group: 42,
+            incarnation: 7,
+            ..JournalState::default()
+        };
+        let mut bytes = state.encode();
+        assert_eq!(JournalState::decode(&bytes).unwrap(), state);
+        bytes[24] ^= 1;
+        assert!(JournalState::decode(&bytes).is_err());
+    }
+
+    #[compio::test]
+    async fn owned_segments_rollback_physical_tails_without_advancing_the_checkpoint() {
+        const BODY_BYTES: usize = 8192;
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        journal
+            .enable_segment_storage(SegmentPosition::default(), (2 * BODY_BYTES) as u64)
+            .await
+            .unwrap();
+        let first = segment_prepare(1, 0, 0, BODY_BYTES);
+        let second = segment_prepare(2, first.header().checksum, 1, BODY_BYTES);
+        let third = segment_prepare(3, second.header().checksum, 2, BODY_BYTES);
+        journal
+            .append_batch_buffered(&[
+                first.clone().into_frozen(),
+                second.clone().into_frozen(),
+                third.clone().into_frozen(),
+            ])
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        assert_eq!(journal.size_bytes(), (3 * PARTITION_WAL_BLOCK_SIZE) as u64);
+        assert_eq!(
+            journal.segment_checkpoint(),
+            Some(SegmentPosition::default())
+        );
+        journal.checkpoint(1).await.unwrap();
+        let checkpoint = SegmentPosition {
+            start_offset: 0,
+            length: BODY_BYTES as u64,
+            next_offset: 1,
+        };
+        assert_eq!(journal.segment_checkpoint(), Some(checkpoint));
+        journal.truncate_from(2).await.unwrap();
+        assert_eq!(
+            std::fs::metadata(partition.path().join("00000000000000000000.log"))
+                .unwrap()
+                .len(),
+            BODY_BYTES as u64
+        );
+        assert!(!partition.path().join("00000000000000000002.log").exists());
+        let replacement = segment_prepare(2, first.header().checksum, 1, BODY_BYTES / 2);
+        journal
+            .append(replacement.clone().into_frozen())
+            .await
+            .unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.segment_checkpoint(), Some(checkpoint));
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+    }
+
+    #[compio::test]
+    async fn owned_segments_recover_unpublished_bytes_and_keep_purged_prepare_bodies() {
+        const BODY_BYTES: usize = 8192;
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        journal
+            .enable_segment_storage(SegmentPosition::default(), (4 * BODY_BYTES) as u64)
+            .await
+            .unwrap();
+        let first = segment_prepare(1, 0, 0, BODY_BYTES);
+        let second = segment_prepare(2, first.header().checksum, 1, BODY_BYTES);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        journal.append_buffered(second.into_frozen()).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(
+            std::fs::metadata(partition.path().join("00000000000000000000.log"))
+                .unwrap()
+                .len(),
+            BODY_BYTES as u64
+        );
+        journal.mark_purge(1, 1).await.unwrap();
+        let replacement = segment_prepare(2, first.header().checksum, 0, BODY_BYTES / 2);
+        journal
+            .append(replacement.clone().into_frozen())
+            .await
+            .unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+        assert_eq!(
+            std::fs::read(partition.path().join("00000000000000000000.log")).unwrap(),
+            replacement.as_slice()[size_of::<PrepareHeader>()..]
+        );
+    }
+
+    #[cfg(target_os = "linux")]
+    #[compio::test]
+    async fn given_preallocated_segments_when_recovering_and_replacing_should_keep_reservations() {
+        const SEGMENT_BYTES: u64 = 1024 * 1024;
+        const BODY_BYTES: usize = 4096;
+
+        for preallocate in [false, true] {
+            let partition = tempdir().unwrap();
+            let directory = partition.path().join("prepares-7");
+            let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+                &directory,
+                42,
+                7,
+                DiskStorage,
+                PARTITION_WAL_BYTES_MAX,
+                preallocate,
+            )
+            .await
+            .unwrap();
+            journal
+                .enable_segment_storage(SegmentPosition::default(), SEGMENT_BYTES)
+                .await
+                .unwrap();
+            let first = segment_prepare(1, 0, 0, usize::try_from(SEGMENT_BYTES).unwrap());
+            let second = segment_prepare(2, first.header().checksum, 1, BODY_BYTES);
+            journal.append(first.clone().into_frozen()).await.unwrap();
+            journal.append(second.clone().into_frozen()).await.unwrap();
+            journal.checkpoint(1).await.unwrap();
+            drop(journal);
+
+            let active = partition.path().join("00000000000000000001.log");
+            std::fs::OpenOptions::new()
+                .write(true)
+                .open(&active)
+                .unwrap()
+                .set_len(SEGMENT_BYTES + BODY_BYTES as u64)
+                .unwrap();
+            let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+                &directory,
+                42,
+                7,
+                DiskStorage,
+                PARTITION_WAL_BYTES_MAX,
+                preallocate,
+            )
+            .await
+            .unwrap();
+            let metadata = std::fs::metadata(&active).unwrap();
+            assert_eq!(metadata.len(), BODY_BYTES as u64);
+            assert_eq!(
+                metadata.blocks() * FILE_BLOCK_BYTES >= SEGMENT_BYTES,

Review Comment:
   the block-count checks now depend on filesystem reservation support.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983437781


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   **[P2] Bind the durability header to the topic actually dispatched**
   
   I found a separate case from the [earlier policy discussion](https://github.com/apache/iggy/pull/4092#discussion_r3983323849), still present at `4a38798a5`. Neither topic's durability changes.
   
   Reproduction sequence, with a caller authorized for both topics:
   
   1. Topic A is named `orders` with `durability=persisted`; topic B is named `fast` with `durability=replicated`.
   2. An awaited produce to `orders` captures A's policy here, then waits behind another write on [`session.data_gate`](https://github.com/apache/iggy/blob/4a38798a506c9231afdfc83a34ebed394d41dac2/core/server/src/http/submit.rs#L386).
   3. While it waits, rename A to `archived` and B to `orders`. Metadata writes use a separate gate.
   4. Dispatch later [resolves the original name](https://github.com/apache/iggy/blob/4a38798a506c9231afdfc83a34ebed394d41dac2/core/server/src/dispatch/partition.rs#L451) to B. After B commits, [`confirmed_policy_in`](https://github.com/apache/iggy/blob/4a38798a506c9231afdfc83a34ebed394d41dac2/core/server/src/http/reads.rs#L429) validates A's saved numeric identity and creation revision. A still exists, so the response advertises `Iggy-Durability: persisted` for B's replicated write.
   
   The revision check establishes that A survived; it does not establish that A received this operation. The header should attest only the guarantee established by the dispatched operation.
   
   I reran a deterministic unit reproducer on Linux at this head: both real `UpdateTopicRequest` renames succeed, the resolver selects B, and policy confirmation returns `Persisted` where the regression expects `Replicated`. The existing incarnation test passes. This exercises the metadata and policy helpers; the HTTP waiting sequence above is established by code inspection, not a full HTTP test.
   
   Could we derive the response policy from the same resolved topic and incarnation used for dispatch, and retain that association through completion?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983315497


##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {

Review Comment:
   the suggested exemption can't cover the next-op case.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(

Review Comment:
   let's keep packing separate; it needs crash proof and benchmarks.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;

Review Comment:
   keeping the body-byte cap; refs alone don't bound the body work.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;

Review Comment:
   reference frames and rebuilt messages differ in size; both are checked.



##########
core/server/config.toml:
##########
@@ -1005,6 +844,68 @@ clients_table_max = 8192
 # plane), a pipeline exists per partition, so raising this multiplies pinned
 # request-buffer memory by the partition count. Keep it modest.
 [partition]
+# Retention is per topic, set at CreateTopic and readable on GetTopic:
+#   max_topic_size   - delete oldest sealed segments past this size
+#                      ("unlimited" when unset)
+#   message_expiry   - delete sealed segments older than this ("none" when unset)
+# Both policies can be active at once. The active segment is never touched.
+# Call GET /options/topic (or the SDK's describe_options) for the full catalog
+# with this server's defaults.
+
+# Topic durability and flush scheduling are set at creation and returned by GetTopic.
+# durability controls message completion. consumer_offset_durability controls explicit offset stores and deletes.
+# Both independently default to "replicated". Neither inherits the other.
+# In replicated groups, either persisted policy enables the prepare WAL for full message bodies.

Review Comment:
   fixed the docs; both persisted policies share segment bodies.



##########
core/server/src/server_error.rs:
##########
@@ -572,7 +572,7 @@ impl std::fmt::Display for PartitionRecoveryRefusal {
                 durable_position,
             } => write!(
                 f,
-                "segment {start_offset} runs under enforce_fsync with {entry_count} sparse \
+                "segment {start_offset} runs under persisted durability with {entry_count} sparse \
                  index entries, and the byte-0 rebuild proved its log only through byte \
                  {walked_position}, short of byte {durable_position} which the last \
                  entry's own fdatasync ordering proves the log had already made durable; \

Review Comment:
   fixed the error to report the validated prefix accurately.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983318446


##########
core/bench/src/args/examples.rs:
##########
@@ -15,176 +15,220 @@
 // specific language governing permissions and limitations
 // under the License.
 
-const EXAMPLES: &str = r#"EXAMPLES:
+const EXAMPLES: &str = r"EXAMPLES:
 
-1) Pinned Mode Benchmarking:
+Start iggy-server separately. The benchmark connects to a running server.
+Global options precede the kind, kind options precede the transport, and
+transport options precede the optional output subcommand.
 
-    Run benchmarks with pinned producers and consumers. This mode pins specific producers
-    and consumers to specific streams and partitions (one to one):
+Default producer and consumer counts are six. Pinned workloads default to six streams.
+
+1) All benchmark kinds and aliases:
+
+    Pinned producer (pp), consumer (pc), and producer/consumer (ppc):
 
     $ cargo r -r --bin iggy-bench -- pinned-producer --streams 10 --producers 10 tcp
     $ cargo r -r --bin iggy-bench -- pinned-consumer --streams 10 --consumers 10 tcp
     $ cargo r -r --bin iggy-bench -- pinned-producer-and-consumer --streams 10 --producers 10 --consumers 10 tcp
-    $ cargo r -r --bin iggy-bench -- -T 10GB pp --producers 5 tcp
-
-2) Balanced Mode Benchmarking:
 
-    Run benchmarks with balanced distribution of producers and consumers. This mode
-    automatically balances the load across streams and consumer groups:
+    Balanced producer (bp), consumer group (bcg), and producer/consumer group (bpcg):
 
     $ cargo r -r --bin iggy-bench -- balanced-producer --partitions 24 --producers 6 tcp
     $ cargo r -r --bin iggy-bench -- balanced-consumer-group --consumers 6 tcp
     $ cargo r -r --bin iggy-bench -- balanced-producer-and-consumer-group --partitions 24 --producers 6 --consumers 6 tcp
-    $ cargo r -r --bin iggy-bench -- -T 10GB bpc tcp
-
-    Durability-matched run, where every produce ack waits for an fsync
-    (--partitions 1 routes every producer straight to that partition):
-
-    $ cargo r -r --bin iggy-bench -- --enforce-fsync --messages-required-to-save 1 \
-        balanced-producer --partitions 1 --producers 8 tcp
-
-3) End-to-End Benchmarking:
-
-    Run end-to-end benchmarks that measure performance for a producer that is also a consumer:
-
-    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer --producers 12 --streams 12 tcp
-    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer-group --partitions 24 --producers 6 tcp
-
-4) Advanced Configuration:
-
-    You can customize various parameters for any benchmark mode:
-
-    Global options (before the benchmark command):
-    --messages-per-batch (-P): Number of messages per batch [default: 1000]
-                               For random batch sizes, use range format: "100..1000"
-    --message-batches (-b): Total number of batches [default: 1000]
-    --total-messages-size (-T): Total size of messages to send (e.g., "1GB", "500MB")
-                                Mutually exclusive with --message-batches
-    --message-size (-m): Message size in bytes [default: 1000]
-                        For random sizes, use range format: "100..1000"
-    --rate-limit (-r): Optional throughput limit per producer (e.g., "50KB", "10MB")
-    --warmup-time (-w): Warmup duration [default: 0s]
-    --sampling-time (-t): Metrics sampling interval [default: 10ms]
-    --moving-average-window (-W): Window size for moving average [default: 20]
-    --username (-u): Username for server authentication [default: iggy]
-    --password (-p): Password for server authentication [default: iggy]
-    --reuse-streams: Reuse existing bench streams instead of deleting them
-
-    Benchmark-specific options (after the benchmark command):
-    --streams (-s): Number of streams
-    --partitions (-a): Number of partitions
-    --producers (-c): Number of producers
-    --consumers (-c): Number of consumers
-    --max-topic-size (-T): Max topic size (e.g., "1GiB")
-    --message-expiry (-e): Topic message expiry time (e.g., "1s", "5min", "1h")
-
-    Examples with detailed configuration:
-
-    # Fixed message and batch sizes:
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size 1000 \
-        --messages-per-batch 100 \
-        --message-batches 1000 \
-        --rate-limit "100MB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-    # Random message sizes (100-1000 bytes):
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size "100..1000" \
-        --messages-per-batch 100 \
-        --total-messages-size "1GB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-    # Random batch sizes (10-100 messages per batch):
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size 1000 \
-        --messages-per-batch "10..100" \
-        --total-messages-size "500MB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-    # Random message and batch sizes with rate limiting:
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size "500..2000" \
-        --messages-per-batch "50..200" \
-        --total-messages-size "2GB" \
-        --rate-limit "50MB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-5) Remote Server Benchmarking:
-
-    To benchmark a remote server, specify the server address in the transport subcommand.
-    Both IP addresses and hostnames are supported:
-
-    $ cargo r -r --bin iggy-bench -- pinned-producer \
-        --streams 5 --producers 5 \
-        tcp --server-address 192.168.1.100:8090
-    $ cargo r -r --bin iggy-bench -- pinned-producer \
-        --streams 5 --producers 5 \
-        tcp --server-address localhost:8090
-
-    With custom credentials:
-
-    $ cargo r -r --bin iggy-bench -- \
-        --username admin --password secret \
-        pinned-producer --streams 5 --producers 5 \
-        tcp --server-address 192.168.1.100:8090
-
-6) Output Data and Results:
-
-    The benchmark tool can store detailed results for analysis and comparison:
-
-    # Basic result storage (results will be stored in ./performance_results):
-    $ cargo r -r --bin iggy-bench -- pinned-producer --streams 10 --producers 10 tcp output
-
-
-    # Organized benchmarking with metadata:
-    $ cargo r -r --bin iggy-bench -- balanced-producer --partitions 24 --producers 6 tcp \
-        output \
-        --identifier "prod-test-$(date +%Y%m%d)" \
-        --remark "production-config" \
-        --gitref "$(git rev-parse --short HEAD)" \
-        --gitref-date "$(git show -s --format=%cI HEAD)"
-
-    # Quick result visualization:
-    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer --producers 12 --streams 12 tcp \
-        output --open-charts
-
-    Output configuration options:
-    --open-charts (-c)  : Open charts after the benchmark
-    --output-dir (-o)   : Directory for storing results [default: performance_results]
-    --identifier        : Benchmark run ID (if not provided defaults to hostname)
-    --remark            : Additional context (e.g., "production-config")
-    --extra-info        : Custom metadata for future analysis, currently unused
-
-7) Help and Documentation:
-
-    For more details on available options:
-
-    # General help
-    $ cargo r -r --bin iggy-bench -- --help
+    $ cargo r -r --bin iggy-bench -- --total-data 10GiB bpcg tcp
 
-    # Specific benchmark help
-    $ cargo r -r --bin iggy-bench -- pinned-producer --help
+    End-to-end producing consumer (e2e) and producing consumer group (e2ecg):
 
-    # Protocol help
-    $ cargo r -r --bin iggy-bench -- pinned-producer tcp --help
+    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer --producing-consumers 12 --streams 12 tcp
+    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer-group --partitions 24 --producers 6 --consumers 6 tcp
+
+2) All transports:
+
+    $ cargo r -r --bin iggy-bench -- pinned-producer tcp --server-address 127.0.0.1:8090
+    $ cargo r -r --bin iggy-bench -- pinned-producer quic --server-address 127.0.0.1:8080
+    $ cargo r -r --bin iggy-bench -- pinned-producer http --server-address 127.0.0.1:3000
+    $ cargo r -r --bin iggy-bench -- pinned-producer websocket --server-address 127.0.0.1:8092
+
+3) Topic durability:
+
+    --durability controls message completion.
+    --consumer-offset-durability controls explicit offset-store/delete completion.
+    Both independently default to replicated. Neither inherits the other.
+    Both policies normally write to disk. Persisted additionally waits for
+    recoverable stable storage on the required VSR quorum, or the single replica.
+
+    Both replicated (the default):
+    $ cargo r -r --bin iggy-bench -- balanced-producer-and-consumer-group tcp
+
+    Persisted messages, replicated offsets:
+    $ cargo r -r --bin iggy-bench -- --durability persisted balanced-producer-and-consumer-group tcp
+
+    Replicated messages, persisted offsets:
+    $ cargo r -r --bin iggy-bench -- --consumer-offset-durability persisted balanced-producer-and-consumer-group tcp
+
+    Both persisted:
+    $ cargo r -r --bin iggy-bench -- --durability persisted --consumer-offset-durability persisted balanced-producer-and-consumer-group tcp
+
+    These options apply when topics are created. They do not modify topics
+    with --reuse-streams. Consumer polling with auto-commit remains asynchronous.
+    Its poll latency is not an acknowledged offset-store latency measurement.
+    In replicated groups, either persisted policy enables a WAL that also retains
+    message predecessors, even when message durability is replicated.
+
+4) Topic flush cadence and retention:
+
+    --messages-required-to-save is a global create-time topic option.
+    It controls segment flush cadence, not the acknowledgment guarantee.
+    --max-topic-size and --message-expiry are kind-specific topic options.
+    These flags do not change existing topics with --reuse-streams.
+
+    Persisted messages without forcing a segment flush for every message:
+    $ cargo r -r --bin iggy-bench -- --durability persisted --messages-required-to-save 1024 balanced-producer --partitions 1 --producers 8 tcp
 
-    # Output help
+    Replicated acknowledgments with eager segment flushing:
+    $ cargo r -r --bin iggy-bench -- --messages-required-to-save 1 balanced-producer tcp
+
+    Retention can delete data during a long run. Use matching policies when comparing:
+    $ cargo r -r --bin iggy-bench -- balanced-producer --max-topic-size 10GiB --message-expiry 1h tcp
+
+5) Workload configuration:
+
+    --messages-per-batch (-P): Messages per batch, or a range such as 100..1000.
+    --message-batches (-b): Batches per actor, mutually exclusive with --total-data.
+    --total-data (-T): Total message bytes across actors, such as 10GiB.
+    --message-size (-m): Message bytes, or a range such as 100..1000.
+    --rate-limit (-r): Aggregate throughput limit across actors, such as 100MB.
+    --warmup-time (-w): Warmup duration, such as 10s.
+    --sampling-time (-t): Metrics sampling interval.
+    --moving-average-window (-W): Moving-average window size.
+
+    Fixed message and batch sizes:
+    $ cargo r -r --bin iggy-bench -- --message-size 1000 --messages-per-batch 100 --message-batches 1000 --rate-limit 100MB balanced-producer --streams 5 --producers 5 tcp
+
+    Random message sizes:
+    $ cargo r -r --bin iggy-bench -- --message-size 100..1000 --messages-per-batch 100 --total-data 1GiB balanced-producer --streams 5 --producers 5 tcp
+
+    Random batch sizes:
+    $ cargo r -r --bin iggy-bench -- --message-size 1000 --messages-per-batch 10..100 --total-data 500MiB balanced-producer tcp
+
+    Random message and batch sizes with a warmup and aggregate rate limit:
+    $ cargo r -r --bin iggy-bench -- --message-size 500..2000 --messages-per-batch 50..200 --total-data 2GiB --warmup-time 10s --rate-limit 50MB balanced-producer tcp
+
+6) Remote server and output:
+
+    $ cargo r -r --bin iggy-bench -- pinned-producer --streams 5 --producers 5 tcp --server-address localhost:8090
+    $ cargo r -r --bin iggy-bench -- --username admin --password secret pinned-producer tcp --server-address 192.168.1.100:8090
+    $ cargo r -r --bin iggy-bench -- pinned-producer tcp output
+    $ cargo r -r --bin iggy-bench -- --durability persisted balanced-producer tcp output --identifier dedicated-host --remark persisted-messages --gitref abc123
+    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer tcp output --open-charts
+
+    Output options include --output-dir (-o), --identifier, --remark, --gitref,
+    --gitref-date, --extra-info, and --open-charts (-c).
+    Record both durability policies, CPU allocation, host tuning, and storage.
+    See core/bench/README.md and https://iggy.apache.org/docs/server/linux-tuning.
+
+7) Help:
+
+    $ cargo r -r --bin iggy-bench -- --help
+    $ cargo r -r --bin iggy-bench -- pinned-producer --help
+    $ cargo r -r --bin iggy-bench -- pinned-producer tcp --help
     $ cargo r -r --bin iggy-bench -- pinned-producer tcp output --help
-"#;
+";
 
 pub fn print_examples() {
     println!("{EXAMPLES}");
 }
+
+#[cfg(test)]
+mod tests {
+    use super::EXAMPLES;
+    use crate::args::common::IggyBenchArgs;
+    use clap::{CommandFactory, Parser, error::ErrorKind};
+    use iggy::prelude::Durability;
+    use std::collections::BTreeSet;
+
+    #[test]
+    fn published_examples_parse_and_cover_every_kind_and_transport() {

Review Comment:
   added semantic validation for every published example.



##########
core/server/config.toml:
##########
@@ -1005,6 +844,68 @@ clients_table_max = 8192
 # plane), a pipeline exists per partition, so raising this multiplies pinned
 # request-buffer memory by the partition count. Keep it modest.
 [partition]
+# Retention is per topic, set at CreateTopic and readable on GetTopic:
+#   max_topic_size   - delete oldest sealed segments past this size

Review Comment:
   documented retention waiting for a requested wal checkpoint.



##########
core/metadata/src/stm/stream.rs:
##########
@@ -2820,11 +2819,21 @@ mod tests {
         assert_eq!(topic.compression_algorithm, CompressionAlgorithm::None);
 
         // partitions_count is create-consumed, never persisted.
-        assert_eq!(topic.options.len(), 3);
+        assert_eq!(topic.options.len(), 5);
         let expiry_key = HeaderKey::from_str(topic_option_keys::MESSAGE_EXPIRY).unwrap();
         let expiry = topic.options.get(&expiry_key).unwrap();
         assert!(expiry.explicit, "client-sent key keeps its provenance");
         assert_eq!(expiry.value.kind(), HeaderKind::Uint64);

Review Comment:
   the test now checks derived defaults through explicit-wire encoding.



##########
core/bench/src/args/kinds/pinned/consumer.rs:
##########
@@ -16,7 +16,7 @@
 // under the License.

Review Comment:
   fixed the messages to match the inequalities we actually enforce.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors

Review Comment:
   documented the existing-layout segment size mismatch error.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));

Review Comment:
   fixed; damaged wal state is fenced and recovered from peers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3957118704


##########
helm/charts/iggy/templates/_helpers.tpl:
##########
@@ -290,9 +290,9 @@ Secret owns it.
   {{- $server := .Values.server }}
   {{- $generated := include "iggy.secretName" . }}
   {{- if $server.encryption.enabled }}
-- name: IGGY_SYSTEM_ENCRYPTION_ENABLED
+- name: IGGY_ENCRYPTION_ENABLED

Review Comment:
   critical: the default `apache/iggy:0.9.0-edge.6` image ignores these renamed encryption variables, so enabling encryption leaves messages unencrypted. pin a compatible image or render variables supported by the selected image.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3959455117


##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +723,368 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {

Review Comment:
   critical: a crash after saving a newer `log_view` but before its WAL history arrives can discard acknowledged operations during election. persist the log and view together, or prevent incomplete replicas from voting.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -4301,6 +4768,27 @@ where
         }
     }
 
+    fn drain_persistable_commits(&self) -> Vec<PipelineEntry> {
+        let Some(persistence) = &self.persistence else {
+            return drain_committable_prefix(self.consensus());
+        };
+        self.persist_repaired_prefix();
+        let through = self.consensus.commit_max().min(persistence.head());

Review Comment:
   critical: promotion counts the local ACK before its prepare is durable, so a persisted quorum can contain only one stable copy. count that ACK only after the matching prepare is durable in the WAL.



##########
helm/charts/iggy/templates/_helpers.tpl:
##########
@@ -290,9 +290,9 @@ Secret owns it.
   {{- $server := .Values.server }}
   {{- $generated := include "iggy.secretName" . }}
   {{- if $server.encryption.enabled }}
-- name: IGGY_SYSTEM_ENCRYPTION_ENABLED
+- name: IGGY_ENCRYPTION_ENABLED

Review Comment:
   critical: enabling encryption emits variables the default `0.9.0-edge.6` image ignores, leaving payload encryption disabled. align the image and variable names, then verify encryption with that image.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,1133 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use futures::TryStreamExt;
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::{BTreeMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await

Review Comment:
   critical: closing offset writers lets writeback errors disappear after inode eviction, so checkpointing can discard WAL before offsets are durable. sync the original descriptors before closing them, or retain them through checkpoint.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -5059,6 +5565,23 @@ where
             }
         }
 
+        if messages_committed
+            && self.consensus.replica_count() == 1
+            && self.durability().is_persisted()
+            && let Some(directory) = &self.partition_dir
+            && let Err(error) = crate::state_transfer::fsync_dir(directory).await

Review Comment:
   warning: each persisted singleton message batch reopens and syncs the directory even when its file names are already durable. track pending name publication and sync only while needed, including creation, rotation, and recovery.



##########
core/server/src/dispatch/partition.rs:
##########
@@ -104,6 +104,16 @@ where
             return;
         };
         let partitions = shard.plane.partitions();
+        if partitions.with_partition(
+            &namespace,
+            partitions::IggyPartition::requires_state_transfer,
+        ) == Some(true)
+        {
+            let _ = reply.try_send(PartitionReadReply::Rejected(

Review Comment:
   warning: existing fallbacks turn recovery rejection into empty success, a no-op deletion, or the wrong HTTP error. propagate `Rejected(error)` through the offset and deletion callers.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -3143,6 +3266,16 @@ where
         // before the swap.
         self.purge_deferred = false;
 
+        if let Some(persistence) = &self.persistence {
+            persistence.reset(commit_op, offsets_wire.prepare_checksum);

Review Comment:
   warning: this existing checkpoint gap leaves transferred replicas unable to elect when the source disappears before another commit. retain the checkpoint prepare during transfer, or let elections use verified materialized checkpoints.



##########
scripts/ci/test-helm.sh:
##########
@@ -455,7 +455,7 @@ server:
       value: "0.0.0.0:8080"
     - name: IGGY_WEBSOCKET_ADDRESS
       value: "0.0.0.0:8092"
-    - name: IGGY_SYSTEM_SHARDING_CPU_ALLOCATION
+    - name: IGGY_SHARDING_CPU_ALLOCATION

Review Comment:
   warning: the default smoke image ignores `IGGY_SHARDING_CPU_ALLOCATION`, so the requested shard limit is lost. use the variable supported by the selected image.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +723,368 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let mut directories = Vec::with_capacity(4);
+        for directory in [
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        {
+            let path = std::path::PathBuf::from(directory);
+            directories.push(path.clone());
+            if let Some(parent) = path.parent()
+                && !directories.iter().any(|existing| existing == parent)
+            {
+                directories.push(parent.to_path_buf());
+            }
+        }
+        if let Some(directory) = &self.partition_dir {
+            directories.push(std::path::PathBuf::from(directory));
+        }
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        let durable_op = persistence.durable_op();
+        loop {
+            let ready = self
+                .pending_persisted_acks
+                .borrow()
+                .first_key_value()
+                .is_some_and(|(op, _)| *op <= durable_op);
+            if !ready {
+                break;
+            }
+            let Some((_, header)) = self.pending_persisted_acks.borrow_mut().pop_first() else {
+                break;
+            };
+            if persistence.checksum(header.op) == Some(header.checksum) {
+                self.send_prepare_ok(&header).await;
+            }
+        }
+    }
+
+    pub async fn acknowledge_prepare(&self, op: u64) {
+        let Some(prepare) = self.log.journal().inner.repair_entry(op) else {
+            return;
+        };
+        let Ok(header) = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &prepare.as_slice()[..size_of::<PrepareHeader>()],
+        ) else {
+            return;
+        };
+        let header = *header;
+        self.persist_repaired_prefix();
+        self.send_prepare_ok(&header).await;
+    }
+
+    const fn requires_persistence(&self, operation: Operation) -> bool {
+        match operation {
+            Operation::SendMessages => self.durability().is_persisted(),
+            Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset => {
+                self.consumer_offset_durability().is_persisted()
+            }
+            _ => false,
+        }
+    }
+
+    fn submit_prepare_persistence(&self, prepare: Frozen<4096>, operation: Operation) -> bool {
+        let Some(persistence) = &self.persistence else {
+            return self.consensus.replica_count() == 1 || !self.requires_persistence(operation);
+        };
+        if let Err(error) = persistence.append(prepare, self.requires_persistence(operation)) {
+            warn!(%error, namespace_raw = self.namespace().inner(), "partition WAL refused prepare");
+            if error.kind() != std::io::ErrorKind::WouldBlock {
+                persistence.fail(error);
+            }
+            return false;
+        }
+        self.start_persistence();
+        true
+    }
+
+    fn persist_repaired_prefix(&self) {
+        let Some(persistence) = &self.persistence else {
+            return;
+        };
+        while let Some(op) = persistence.head().checked_add(1) {
+            let Some(prepare) = self.log.journal().inner.repair_entry(op) else {

Review Comment:
   warning: a caught-up WAL commit drain still scans the repair ring for a missing next operation. skip repair when the WAL covers the journal, or reject the lookup before scanning.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,1133 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use futures::TryStreamExt;
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::{BTreeMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.state.anchor_known = checksum.is_some();
+        self.rewrite(op, checksum.unwrap_or(0), Some(0)).await
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation <= self.state.purge_generation {

Review Comment:
   critical: retrying a purge in the same generation after the sequencer advances keeps the old durable floor, letting deleted messages return after restart. persist the updated floor before deleting on retry.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +723,368 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let mut directories = Vec::with_capacity(4);
+        for directory in [
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        {
+            let path = std::path::PathBuf::from(directory);
+            directories.push(path.clone());
+            if let Some(parent) = path.parent()
+                && !directories.iter().any(|existing| existing == parent)
+            {
+                directories.push(parent.to_path_buf());
+            }
+        }
+        if let Some(directory) = &self.partition_dir {
+            directories.push(std::path::PathBuf::from(directory));
+        }
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        let durable_op = persistence.durable_op();
+        loop {
+            let ready = self
+                .pending_persisted_acks
+                .borrow()
+                .first_key_value()
+                .is_some_and(|(op, _)| *op <= durable_op);
+            if !ready {
+                break;
+            }
+            let Some((_, header)) = self.pending_persisted_acks.borrow_mut().pop_first() else {
+                break;
+            };
+            if persistence.checksum(header.op) == Some(header.checksum) {
+                self.send_prepare_ok(&header).await;
+            }
+        }
+    }
+
+    pub async fn acknowledge_prepare(&self, op: u64) {
+        let Some(prepare) = self.log.journal().inner.repair_entry(op) else {
+            return;
+        };
+        let Ok(header) = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &prepare.as_slice()[..size_of::<PrepareHeader>()],
+        ) else {
+            return;
+        };
+        let header = *header;
+        self.persist_repaired_prefix();
+        self.send_prepare_ok(&header).await;
+    }
+
+    const fn requires_persistence(&self, operation: Operation) -> bool {
+        match operation {
+            Operation::SendMessages => self.durability().is_persisted(),
+            Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset => {
+                self.consumer_offset_durability().is_persisted()
+            }
+            _ => false,
+        }
+    }
+
+    fn submit_prepare_persistence(&self, prepare: Frozen<4096>, operation: Operation) -> bool {
+        let Some(persistence) = &self.persistence else {
+            return self.consensus.replica_count() == 1 || !self.requires_persistence(operation);
+        };
+        if let Err(error) = persistence.append(prepare, self.requires_persistence(operation)) {

Review Comment:
   critical: a rejected WAL append leaves a gap that makes a later prepare fail out of order and fence the replica. submit the missing prefix before newer prepares, keeping backpressure until it fits.



##########
core/shard/src/lib.rs:
##########
@@ -4272,6 +4310,14 @@ where
         // and `CommitJournal` is a no-op in both.
         dispatch_partition_journal_actions(consensus, partition, &local_actions).await;
         if partition.persist_superblock_if_needed().await {
+            let wire_actions = if partition.requires_state_transfer() {

Review Comment:
   simplification: the same wire-action filter is repeated across dispatch sites; extract one private helper, preserving superblock gates, action order, and both dispatchers.
   
   also at lines 4398, 4584, 4784, 5663, 7354.



##########
core/server/src/http/reads.rs:
##########
@@ -398,6 +398,79 @@ pub(in crate::http) fn authorize_data_plane(
         .authorize(|permissioner| rule(permissioner, user_id, stream_id, topic_id))
 }
 
+static DURABILITY_KEY: std::sync::LazyLock<iggy_common::HeaderKey> =
+    std::sync::LazyLock::new(|| "durability".parse().expect("catalog key is valid"));
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(in crate::http) struct TopicDurability {
+    stream_id: usize,
+    topic_id: usize,
+    created_revision: u64,
+    pub durability: iggy_common::Durability,
+}
+
+impl TopicDurability {
+    pub fn confirmed_policy(self, state: &HttpInner) -> iggy_common::Durability {
+        let unchanged = state
+            .shard
+            .plane
+            .metadata()
+            .mux_stm
+            .streams()
+            .read(|inner| {
+                inner
+                    .items
+                    .get(self.stream_id)
+                    .and_then(|stream| stream.topics.get(self.topic_id))
+                    .and_then(|topic| topic.partitions.first())
+                    .is_some_and(|partition| partition.created_revision == self.created_revision)
+            });
+        self.confirmed_policy_for(unchanged.then_some(self))
+    }
+
+    fn confirmed_policy_for(self, current: Option<Self>) -> iggy_common::Durability {

Review Comment:
   simplification: `confirmed_policy_for` only receives `Some(self)` or `None` in production. select durability directly from `unchanged`, preserving the incarnation check and replicated fallback, and test that lookup.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3957118691


##########
core/server/src/partition_helpers.rs:
##########
@@ -1399,6 +1376,10 @@ pub async fn build_partition_fresh(
         });
     }
 
+    partition
+        .open_persistence_with_capacity(config.partition.wal_bytes_max.as_bytes_u64())

Review Comment:
   critical: quarantine rebuild restores the WAL checkpoint over empty replacement segments, letting the replica rejoin with committed messages missing. require full state transfer before accepting that checkpoint as applied.



##########
core/common/src/types/options/mod.rs:
##########
@@ -800,8 +823,11 @@ impl TopicCreateOptions {
                     let size = parse_byte_size(entry, key)?;
                     parsed.segment_size = (size != 0).then_some(IggyByteSize::from(size));
                 }
-                topic_option_keys::ENFORCE_FSYNC => {
-                    parsed.enforce_fsync = Some(parse_bool(entry, key)?);
+                topic_option_keys::DURABILITY => {

Review Comment:
   critical: existing `enforce_fsync=true` topic metadata silently becomes `Durability::Replicated` after config migration, disabling fsync on reopened writers. explicitly migrate the stored policy or reject it before opening writers.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +720,292 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for prepare in prepares {
+            let mut owned = server_common::iobuf::Owned::<4096>::zeroed(prepare.len());
+            owned.as_mut_slice().copy_from_slice(prepare.as_slice());
+            let message =
+                Message::<PrepareHeader>::try_from(owned).map_err(|_| IggyError::InvalidCommand)?;
+            let header = *message.header();
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min();
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let directories = [

Review Comment:
   critical: checkpointing skips syncing `offsets/`, so power loss can remove consumer or group directories after their WAL history is reclaimed. sync the parent directory before publishing the checkpoint.



##########
helm/charts/iggy/templates/_helpers.tpl:
##########
@@ -290,9 +290,9 @@ Secret owns it.
   {{- $server := .Values.server }}
   {{- $generated := include "iggy.secretName" . }}
   {{- if $server.encryption.enabled }}
-- name: IGGY_SYSTEM_ENCRYPTION_ENABLED
+- name: IGGY_ENCRYPTION_ENABLED

Review Comment:
   critical: the default `apache/iggy:0.9.0-edge.6` image ignores these renamed encryption variables, so enabling encryption leaves messages unencrypted. pin a compatible image or render variables supported by the selected image.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -7034,6 +7429,18 @@ where
         if !self.persist_superblock_if_needed().await {
             return;
         }
+        if self.consensus.replica_count() > 1

Review Comment:
   critical: `StartView` sends `PrepareOk` before the backup WAL is durable, allowing persisted success without durable quorum copies. route every partition acknowledgment through the WAL durability gate.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +720,292 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for prepare in prepares {
+            let mut owned = server_common::iobuf::Owned::<4096>::zeroed(prepare.len());
+            owned.as_mut_slice().copy_from_slice(prepare.as_slice());
+            let message =
+                Message::<PrepareHeader>::try_from(owned).map_err(|_| IggyError::InvalidCommand)?;
+            let header = *message.header();
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min();
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let directories = [
+            &self.partition_dir,
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        .map(std::path::PathBuf::from)
+        .collect();
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        let pending = std::mem::take(&mut *self.pending_persisted_acks.borrow_mut());
+        for header in pending.into_values() {
+            if self
+                .log
+                .journal()
+                .inner
+                .header_by_op(header.op)

Review Comment:
   warning: every tick rescans headers for all pending acknowledgments and rebuilds the waiting map, even without durable progress. process only newly durable entries with indexed lookup and leave the rest queued.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +720,292 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for prepare in prepares {
+            let mut owned = server_common::iobuf::Owned::<4096>::zeroed(prepare.len());
+            owned.as_mut_slice().copy_from_slice(prepare.as_slice());
+            let message =
+                Message::<PrepareHeader>::try_from(owned).map_err(|_| IggyError::InvalidCommand)?;
+            let header = *message.header();
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min();
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);

Review Comment:
   warning: repair can commit entries that the WAL rejected for capacity, so the next checkpoint fails with "unknown WAL checkpoint" and fences the node. keep the checkpoint frontier within accepted WAL history.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {
+            self.storage
+                .open(path, OpenMode::Read)
+                .await?
+                .sync()
+                .await?;
+        }
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.state.anchor_known = checksum.is_some();
+        self.rewrite(op, checksum.unwrap_or(0), Some(0)).await
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation <= self.state.purge_generation {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short WAL prepare"))?,
+        )
+        .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+        if self
+            .entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+        {
+            return Ok(());
+        }
+        if header.op
+            != self
+                .state
+                .head
+                .checked_add(1)
+                .ok_or_else(|| invalid("WAL op exhausted"))?
+            || (self.state.anchor_known && header.parent != self.state.head_checksum)
+            || header.group != self.state.group
+        {
+            return Err(invalid("partition WAL append does not extend its history"));
+        }
+        let encoded = encode_record(prepare.as_slice(), self.state.generation)?;
+        let length = encoded.len();
+        if self.state.length + length as u64 > self.capacity {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL requires checkpoint",
+            ));
+        }
+        self.poisoned = true;
+        self.file.write(self.state.length, encoded).await?;
+        let state = JournalState {
+            length: self.state.length + length as u64,
+            head: header.op,
+            head_checksum: header.checksum,
+            checkpoint_checksum: if self.state.anchor_known {
+                self.state.checkpoint_checksum
+            } else {
+                header.parent
+            },
+            anchor_known: true,
+            ..self.state
+        };
+        self.entries.insert(
+            header.op,
+            StoredPrepare {
+                position: self.state.length,
+                length,
+                checksum: header.checksum,
+            },
+        );
+        self.state = state;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory)? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(&self, position: u64) -> io::Result<(PrepareHeader, usize, Frozen<4096>)> {
+        let prefix = self.file.read(position, RECORD_PREFIX).await?;
+        let frame_length = u32::from_le_bytes(
+            prefix[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut bytes = self.file.read(position, length).await?;
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let mut owned = Owned::<4096>::zeroed(frame_length);
+        owned
+            .as_mut_slice()
+            .copy_from_slice(&bytes[RECORD_PREFIX..RECORD_PREFIX + frame_length]);
+        let message = Message::<PrepareHeader>::try_from(owned)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != frame_length
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        Ok((header, length, message.into_frozen()))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            ..self.state
+        };
+        for (&op, entry) in &self.entries {
+            if op <= checkpoint || truncate.is_some_and(|from| op >= from) {

Review Comment:
   critical: if all replicas checkpoint the same head and restart, the discarded prepare leaves elections without the required commit-point header and body. retain and recover that prepare across checkpoints.



##########
core/shard/src/lib.rs:
##########
@@ -7103,6 +7134,25 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();
+        for namespace in namespace_scratch.iter() {
+            if let Some(partition) = partitions.get_mut_by_ns(namespace) {
+                partition.drive_persistence().await;
+                partition.checkpoint_persistence(partitions.config()).await;

Review Comment:
   warning: this pass serially awaits every eligible partition's checkpoint flush before consensus ticks, delaying unrelated heartbeats and requests during checkpoint bursts. bound checkpoint work using the existing rotating partition budget.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {
+            self.storage
+                .open(path, OpenMode::Read)
+                .await?
+                .sync()
+                .await?;
+        }
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.state.anchor_known = checksum.is_some();
+        self.rewrite(op, checksum.unwrap_or(0), Some(0)).await
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation <= self.state.purge_generation {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short WAL prepare"))?,
+        )
+        .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+        if self
+            .entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+        {
+            return Ok(());
+        }
+        if header.op
+            != self
+                .state
+                .head
+                .checked_add(1)
+                .ok_or_else(|| invalid("WAL op exhausted"))?
+            || (self.state.anchor_known && header.parent != self.state.head_checksum)
+            || header.group != self.state.group
+        {
+            return Err(invalid("partition WAL append does not extend its history"));
+        }
+        let encoded = encode_record(prepare.as_slice(), self.state.generation)?;
+        let length = encoded.len();
+        if self.state.length + length as u64 > self.capacity {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL requires checkpoint",
+            ));
+        }
+        self.poisoned = true;
+        self.file.write(self.state.length, encoded).await?;
+        let state = JournalState {
+            length: self.state.length + length as u64,
+            head: header.op,
+            head_checksum: header.checksum,
+            checkpoint_checksum: if self.state.anchor_known {
+                self.state.checkpoint_checksum
+            } else {
+                header.parent
+            },
+            anchor_known: true,
+            ..self.state
+        };
+        self.entries.insert(
+            header.op,
+            StoredPrepare {
+                position: self.state.length,
+                length,
+                checksum: header.checksum,
+            },
+        );
+        self.state = state;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory)? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(&self, position: u64) -> io::Result<(PrepareHeader, usize, Frozen<4096>)> {
+        let prefix = self.file.read(position, RECORD_PREFIX).await?;
+        let frame_length = u32::from_le_bytes(
+            prefix[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut bytes = self.file.read(position, length).await?;
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let mut owned = Owned::<4096>::zeroed(frame_length);
+        owned
+            .as_mut_slice()
+            .copy_from_slice(&bytes[RECORD_PREFIX..RECORD_PREFIX + frame_length]);
+        let message = Message::<PrepareHeader>::try_from(owned)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != frame_length
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        Ok((header, length, message.into_frozen()))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            ..self.state
+        };
+        for (&op, entry) in &self.entries {
+            if op <= checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let prepare = self.read_record(entry.position).await?.2;
+            let encoded = encode_record(prepare.as_slice(), generation)?;
+            let length = encoded.len();
+            file.write(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                },
+            );
+            state.length += length as u64;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.poisoned = false;
+        if let Err(error) = self.storage.remove_file(&obsolete).await {

Review Comment:
   warning: a crash after publication or failed unlink leaves obsolete WAL generations permanently, allowing repeated failures to fill the disk. reclaim obsolete generations on reopen and retry failed cleanup.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -4143,6 +4476,9 @@ where
             }
         };
 
+        if !self.submit_prepare_persistence(&frozen_for_forward, header.operation) {

Review Comment:
   warning: WAL backpressure leaves the memory journal ahead of the sequencer; a successful retry acknowledges without advancing it, so the next operation fails the gap check. keep both in sync across failed admission and retries.



##########
core/integration/tests/data_integrity/storage_compat.rs:
##########
@@ -1012,7 +1012,7 @@ fn data_topic_options() -> TopicCreateOptions {
             MAX_TOPIC_SIZE_BYTES,
         ))),
         segment_size: Some(IggyByteSize::from(SEGMENT_SIZE_BYTES)),
-        enforce_fsync: Some(true),
+        durability: iggy_common::Durability::Persisted,

Review Comment:
   warning: the fixture sends unsupported options and config to the baseline, then reuses its incompatible config for the replacement; upgrade assertions never run. seed with the baseline schema and translate config when swapping binaries.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -4631,7 +4983,11 @@ where
         if std::mem::take(&mut self.injected_commit_failure) {
             return Err(IggyError::CannotSaveMessagesToSegment);
         }
-        self.commit_messages_inner(config, false).await
+        self.commit_messages_inner(
+            config,
+            self.consensus.replica_count() == 1 && self.durability().is_persisted(),

Review Comment:
   critical: this pre-existing gap lets singleton persisted replies precede durable publication of rotated segment names, so power loss can erase acknowledged messages. sync the partition directory before replying.



##########
core/bench/src/args/common.rs:
##########
@@ -101,15 +101,15 @@ pub struct IggyBenchArgs {
     #[arg(long, default_value_t = false)]
     pub reuse_streams: bool,
 
-    /// Fsync each journal flush on the benchmark topic. Flush timing stays
-    /// governed by `--messages-required-to-save` (server default: 1024), so
-    /// acks are durability-gated only with `--messages-required-to-save 1`.
-    /// Topic option at creation, so it has no effect with `--reuse-streams`.
-    #[arg(long, default_value_t = false)]
-    pub enforce_fsync: bool,
+    /// Message completion policy for newly created benchmark topics.

Review Comment:
   warning: the performance suite helper still emits the removed fsync flag, so those benchmark variants exit during argument parsing. update `construct_bench_command` to set `durability` to `persisted`.



##########
core/common/src/types/options/mod.rs:
##########
@@ -800,8 +823,11 @@ impl TopicCreateOptions {
                     let size = parse_byte_size(entry, key)?;
                     parsed.segment_size = (size != 0).then_some(IggyByteSize::from(size));
                 }
-                topic_option_keys::ENFORCE_FSYNC => {
-                    parsed.enforce_fsync = Some(parse_bool(entry, key)?);
+                topic_option_keys::DURABILITY => {

Review Comment:
   critical: existing `enforce_fsync=true` topic metadata silently becomes `Durability::Replicated` after config migration, disabling fsync on reopened writers. explicitly migrate the stored policy or reject it before opening writers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3982697140


##########
core/shard/src/lib.rs:
##########
@@ -7381,6 +7416,24 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();
+        for namespace in namespace_scratch.iter() {

Review Comment:
   I’ve added a [proposed fix](https://github.com/diegomrsantos/iggy/commit/f48a26aca19cef48d4858973ac31417801892dc8) alongside the [regression](https://github.com/diegomrsantos/iggy/commit/76248cf515e9523c4e746bba9d9ded627e306c80), both on top of `7343be420`.
   
   The fix withholds acknowledgments at the shared partition send function and stops persistence processing after fencing. Checkpoint preparation and queued request resumption now return fatal failures directly to the tick.
   
   The regression now passes on Linux and macOS. Additional coverage includes a real checkpoint index write failure while the WAL remains healthy, plus healthy primary and backup acknowledgment paths. The partition and shard unit tests pass on both platforms.
   
   The two commits are intended to be reviewed and applied together, since the regression fails on its own. Would you prefer to cherry-pick the pair, or would a small PR targeting `topic_durability` be more convenient? Happy to adjust the approach.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3986620245


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   thanks for the repro, this is fixed locally in `c1e808f`. the handler pins the numeric stream and topic ids captured with the durability policy before waiting on the session gate, and keeps the incarnation check afterward. renames can’t redirect the write anymore. the routing and policy tests pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983524204


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   I've published the reproducer in [7a229f9ba](https://github.com/diegomrsantos/iggy/commit/7a229f9baf4eeda6f5ea0d7cb2995bdfed96b362), on `test/http-durability-topic-identity` in my fork. It adds only the test and its imports, on top of `4a38798a5`.
   
   To run it:
   
   ```sh
   cargo test --locked -p server --all-features --lib named_produce_attests_the_dispatched_topic
   ```
   
   It deliberately fails on that baseline with actual `Persisted`, expected `Replicated`. I verified this on Linux; the existing `completed_produce_checks_the_stored_topic_incarnation` test passes, and Clippy passes for the server with all features and targets.
   
   This isolates the current metadata and policy helper sequence. It does not run a full HTTP request. If the fix binds the target earlier, the regression should move to that request boundary so it tests the resulting behavior. Happy to adapt it to the chosen approach.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983528149


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   very good catch! i'll check this tomorrow



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "numinnex (via GitHub)" <gi...@apache.org>.
numinnex commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3978817339


##########
core/simulator/src/storage/tests.rs:
##########
@@ -0,0 +1,1574 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use super::{
+    Crash, DurableFile, DurableStorage, FaultMode, OpenMode, SimStorage, StorageOperation,
+};
+use crate::packet::PacketSimulatorOptions;
+use consensus::MetadataHandle;
+use futures::{executor::block_on, poll};
+use iggy_binary_protocol::batch::{BATCH_HEADER_SIZE, BatchHeader};
+use iggy_binary_protocol::{Command, Operation, PrepareHeader};
+use journal::partition_journal::{PARTITION_WAL_BLOCK_SIZE, SegmentPosition, SegmentReference};
+use journal::{DurableAppend, PartitionPrepareJournal};
+use partitions::{PartitionPersistence, install_backup};
+use server_common::{Message, iobuf::Owned};
+use std::io;
+use std::path::Path;
+use std::rc::Rc;
+use twox_hash::XxHash3_64;
+
+const DIRECTORY: &str = "/partition";
+const WAL: &str = "/partition/wal";
+const OWNED_BATCH_BYTES: usize = 12 * 1024;
+const MATERIALIZED_FILES: &[&str] = &[
+    "/partition/0.log",
+    "/partition/0.index",
+    "/partition/offsets/consumers/1",
+    "/partition/offsets/groups/9",
+    "/partition/superblock.a",
+];
+
+#[derive(Clone, Copy, Debug)]
+enum Mutation {
+    Append,
+    CertifyView,
+    Checkpoint,
+    Truncate,
+    Reset,
+    Purge,
+}
+
+#[test]
+fn process_crash_preserves_completed_writes_but_power_loss_requires_file_and_directory_sync() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        storage
+            .create_directories(Path::new(DIRECTORY))
+            .await
+            .unwrap();
+        storage.sync_directory(Path::new("/")).await.unwrap();
+        let path = Path::new("/partition/value");
+        let mut file = storage.open(path, OpenMode::Create).await.unwrap();
+        file.write(0, b"buffered".to_vec()).await.unwrap();
+        storage.crash(Crash::Process);
+        assert_eq!(
+            storage
+                .open(path, OpenMode::Read)
+                .await
+                .unwrap()
+                .read(0, 8)
+                .await
+                .unwrap(),
+            b"buffered"
+        );
+        storage.crash(Crash::PowerLoss);
+        assert!(!storage.exists(path).await.unwrap());
+        let mut file = storage.open(path, OpenMode::Create).await.unwrap();
+        file.write(0, b"synced".to_vec()).await.unwrap();
+        file.sync().await.unwrap();
+        storage.crash(Crash::PowerLoss);
+        assert!(
+            !storage.exists(path).await.unwrap(),
+            "file sync must not imply directory sync"
+        );
+        replace(&storage, path, b"durable").await.unwrap();
+        storage.crash(Crash::PowerLoss);
+        assert_eq!(
+            storage
+                .open(path, OpenMode::Read)
+                .await
+                .unwrap()
+                .read(0, 7)
+                .await
+                .unwrap(),
+            b"durable"
+        );
+        assert!(
+            file.sync().await.is_err(),
+            "an old process cannot complete into the new one"
+        );
+    });
+}
+
+#[test]
+fn wal_fault_sweep_preserves_acknowledged_history_at_every_io_boundary() {
+    block_on(async {
+        let mut cases = 0;
+        for mutation in [
+            Mutation::Append,
+            Mutation::CertifyView,
+            Mutation::Checkpoint,
+            Mutation::Truncate,
+            Mutation::Reset,
+            Mutation::Purge,
+        ] {
+            let (storage, mut journal) = baseline().await;
+            storage.clear_trace();
+            mutate(&storage, &mut journal, mutation).await.unwrap();
+            let trace = storage.trace();
+            for (cut, operation) in trace.iter().enumerate() {
+                for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                    for crash in [Crash::Process, Crash::PowerLoss] {
+                        for writeback in [false, true] {
+                            let (storage, mut journal) = baseline().await;
+                            storage.fail_at(cut, mode);
+                            let completed = mutate(&storage, &mut journal, mutation).await.is_ok();
+                            drop(journal);
+                            if writeback {
+                                storage.writeback();
+                            }
+                            storage.crash(crash);
+                            let recovered = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage.clone()).await.unwrap_or_else(|error| {
+                                panic!("{mutation:?} cut {cut} {operation:?} {mode:?} {crash:?} writeback={writeback}: {error}");
+                            });
+                            assert_recovery(&storage, &recovered, mutation, completed).await;
+                            cases += 1;
+                        }
+                    }
+                }
+            }
+        }
+        eprintln!("partition WAL fault cases: {cases}");
+    });
+}
+
+#[test]
+fn referenced_wal_fault_sweep_preserves_bodies_through_publication_and_reclamation() {
+    block_on(async {
+        let mut cases = 0;
+        for mutation in [
+            Mutation::Append,
+            Mutation::CertifyView,
+            Mutation::Checkpoint,
+            Mutation::Truncate,
+            Mutation::Reset,
+            Mutation::Purge,
+        ] {
+            let (storage, mut journal) = referenced_baseline().await;
+            storage.clear_trace();
+            mutate_referenced(&storage, &mut journal, mutation)
+                .await
+                .unwrap();
+            let trace = storage.trace();
+            for (cut, operation) in trace.iter().enumerate() {
+                for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                    for crash in [Crash::Process, Crash::PowerLoss] {
+                        for writeback in [false, true] {
+                            let (storage, mut journal) = referenced_baseline().await;
+                            storage.fail_at(cut, mode);
+                            let completed = mutate_referenced(&storage, &mut journal, mutation)
+                                .await
+                                .is_ok();
+                            drop(journal);
+                            if writeback {
+                                storage.writeback();
+                            }
+                            storage.crash(crash);
+                            let context = format!(
+                                "{mutation:?} cut {cut} {operation:?} {mode:?} {crash:?} writeback={writeback}"
+                            );
+                            let recovered = PartitionPrepareJournal::open_with_storage(
+                                Path::new(WAL),
+                                42,
+                                7,
+                                storage.clone(),
+                            )
+                            .await
+                            .unwrap_or_else(|error| panic!("{context}: {error}"));
+                            assert_referenced_recovery(&recovered, mutation, completed, &context)
+                                .await;
+                            cases += 1;
+                        }
+                    }
+                }
+            }
+        }
+        eprintln!("referenced partition WAL fault cases: {cases}");
+    });
+}
+
+#[test]
+fn transfer_fault_sweep_restores_one_complete_materialization_including_the_wal() {
+    block_on(async {
+        let (storage, mut journal) = baseline().await;
+        storage.clear_trace();
+        install(&storage, &mut journal).await.unwrap();
+        let trace = storage.trace();
+        let mut cases = 0;
+        for (cut, operation) in trace.iter().enumerate() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                for crash in [Crash::Process, Crash::PowerLoss] {
+                    let (storage, mut journal) = baseline().await;
+                    storage.fail_at(cut, mode);
+                    let completed = install(&storage, &mut journal).await.is_ok();
+                    drop(journal);
+                    storage.crash(crash);
+                    install_backup::recover_with_storage(Path::new(DIRECTORY), &storage)
+                        .await
+                        .unwrap_or_else(|error| {
+                            panic!("install cut {cut} {operation:?} {mode:?} {crash:?}: {error}")
+                        });
+                    let recovered = PartitionPrepareJournal::open_with_storage(
+                        Path::new(WAL),
+                        42,
+                        7,
+                        storage.clone(),
+                    )
+                    .await
+                    .unwrap();
+                    let value = storage
+                        .open(Path::new("/partition/state"), OpenMode::Read)
+                        .await
+                        .unwrap()
+                        .read(0, 3)
+                        .await
+                        .unwrap();
+                    match recovered.checkpoint_op() {
+                        0 => {
+                            assert!(!completed);
+                            assert_eq!(value, b"old");
+                            assert_eq!(recovered.head(), 3);
+                        }
+                        7 => {
+                            assert_eq!(value, b"new");
+                            assert_eq!(recovered.head(), 7);
+                        }
+                        other => panic!("mixed installed state at {other}"),
+                    }
+                    let expected: &[u8] = if recovered.checkpoint_op() == 0 {
+                        b"old"
+                    } else {
+                        b"new"
+                    };
+                    for path in MATERIALIZED_FILES {
+                        assert_eq!(
+                            storage
+                                .open(Path::new(path), OpenMode::Read)
+                                .await
+                                .unwrap()
+                                .read(0, 3)
+                                .await
+                                .unwrap(),
+                            expected
+                        );
+                    }
+                    cases += 1;
+                }
+            }
+        }
+        eprintln!("partition transfer fault cases: {cases}");
+    });
+}
+
+#[test]
+fn durable_quorum_covers_buffered_predecessors_and_losing_unsynced_replicas() {
+    block_on(async {
+        for replicas in [1, 2, 3, 5, 7] {
+            let sim = crate::Simulator::new(
+                replicas,
+                std::iter::empty(),
+                PacketSimulatorOptions::default(),
+            );
+            let quorum = sim.replicas[0].shards[0]
+                .plane
+                .metadata()
+                .consensus
+                .as_ref()
+                .unwrap()
+                .quorum_replication();
+            let first = prepare(1, 0);
+            let second = prepare(2, first.header().checksum);
+            let mut disks = Vec::new();
+            for replica in 0..replicas {
+                let storage = storage_for_partition().await;
+                let mut journal = PartitionPrepareJournal::open_with_storage(
+                    Path::new(WAL),
+                    42,
+                    7,
+                    storage.clone(),
+                )
+                .await
+                .unwrap();
+                journal
+                    .append_buffered(first.clone().into_frozen())
+                    .await
+                    .unwrap();
+                if replica < quorum {
+                    journal.append(second.clone().into_frozen()).await.unwrap();
+                } else {
+                    journal
+                        .append_buffered(second.clone().into_frozen())
+                        .await
+                        .unwrap();
+                }
+                disks.push(storage);
+            }
+            let mut survivors = 0;
+            for storage in disks {
+                storage.crash(Crash::PowerLoss);
+                let journal =
+                    PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                        .await
+                        .unwrap();
+                if journal.head() == 2 {
+                    assert!(journal.contains(first.header()));
+                    assert!(journal.contains(second.header()));
+                    survivors += 1;
+                } else {
+                    assert_eq!(journal.head(), 0);
+                }
+            }
+            assert_eq!(survivors, quorum);
+        }
+    });
+}
+
+#[test]
+fn stalled_writer_does_not_release_acks_or_block_another_partition() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (persistence, _) =
+            PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        let first = prepare(1, 0);
+        persistence
+            .append(first.clone().into_frozen(), true)
+            .unwrap();
+        storage.pause_writes();
+        assert!(persistence.start());
+        let mut writer = Box::pin(Rc::clone(&persistence).run());
+        assert!(poll!(&mut writer).is_pending());
+        assert!(!persistence.is_durable(first.header()));
+        let independent = storage_for_partition().await;
+        let mut journal =
+            PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, independent)
+                .await
+                .unwrap();
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        assert!(journal.contains(first.header()));
+        persistence.truncate_from(1);
+        let replacement = prepare_with_payload(1, 0, b"replacement");
+        persistence
+            .append(replacement.clone().into_frozen(), true)
+            .unwrap();
+        storage.resume_writes();
+        writer.await;
+        assert!(!persistence.is_durable(first.header()));
+        assert!(persistence.is_durable(replacement.header()));
+        storage.crash(Crash::PowerLoss);
+        let journal = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+            .await
+            .unwrap();
+        assert!(journal.contains(replacement.header()));
+    });
+}
+
+#[test]
+fn queue_capacity_and_retirement_withhold_unpersisted_acknowledgments() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (persistence, _) =
+            PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        let mut parent = 0;
+        let mut accepted = 0;
+        loop {
+            let prepare = prepare_with_payload(accepted + 1, parent, b"queued");
+            parent = prepare.header().checksum;
+            match persistence.append(prepare.into_frozen(), true) {
+                Ok(()) => accepted += 1,
+                Err(error) => {
+                    assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
+                    break;
+                }
+            }
+        }
+        assert!(accepted > 0);
+        assert!(!persistence.is_durable_through(accepted));
+        persistence.retire();
+        assert!(!persistence.start());
+        storage.crash(Crash::PowerLoss);
+        let journal = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 0);
+    });
+}
+
+#[test]
+fn interrupted_rollback_can_itself_restart_at_every_io_boundary() {
+    block_on(async {
+        let storage = interrupted_install().await;
+        storage.clear_trace();
+        install_backup::recover_with_storage(Path::new(DIRECTORY), &storage)
+            .await
+            .unwrap();
+        let trace = storage.trace();
+        let mut cases = 0;
+        for (cut, operation) in trace.iter().enumerate() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                for crash in [Crash::Process, Crash::PowerLoss] {
+                    let storage = interrupted_install().await;
+                    storage.fail_at(cut, mode);
+                    let _ =
+                        install_backup::recover_with_storage(Path::new(DIRECTORY), &storage).await;
+                    storage.crash(crash);
+                    install_backup::recover_with_storage(Path::new(DIRECTORY), &storage)
+                        .await
+                        .unwrap_or_else(|error| {
+                            panic!("rollback cut {cut} {operation:?} {mode:?} {crash:?}: {error}")
+                        });
+                    let journal = PartitionPrepareJournal::open_with_storage(
+                        Path::new(WAL),
+                        42,
+                        7,
+                        storage.clone(),
+                    )
+                    .await
+                    .unwrap();
+                    assert_eq!(journal.head(), 3);
+                    assert_eq!(journal.checkpoint_op(), 0);
+                    assert_eq!(
+                        storage
+                            .open(Path::new("/partition/state"), OpenMode::Read)
+                            .await
+                            .unwrap()
+                            .read(0, 3)
+                            .await
+                            .unwrap(),
+                        b"old"
+                    );
+                    cases += 1;
+                }
+            }
+        }
+        eprintln!("partition rollback fault cases: {cases}");
+    });
+}
+
+#[test]
+fn failed_durable_completion_never_releases_a_prepare_ack() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (persistence, _) =
+            PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        let first = prepare(1, 0);
+        persistence
+            .append(first.clone().into_frozen(), true)
+            .unwrap();
+        storage.clear_trace();
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        let trace = storage.trace();
+        for cut in 0..trace.len() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                let storage = storage_for_partition().await;
+                let (persistence, _) =
+                    PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                        .await
+                        .unwrap();
+                persistence
+                    .append(first.clone().into_frozen(), true)
+                    .unwrap();
+                storage.fail_at(cut, mode);
+                assert!(persistence.start());
+                Rc::clone(&persistence).run().await;
+                assert!(persistence.failure().is_some());
+                assert!(!persistence.is_durable(first.header()));
+                assert!(!persistence.is_durable_through(1));
+            }
+        }
+    });
+}
+
+#[test]
+fn synchronized_corruption_in_any_record_block_is_refused() {

Review Comment:
   warning: `synchronized_corruption_in_any_record_block_is_refused` flips bits only in `/partition/wal/prepares-0.wal`, and builds from `baseline()` rather than `owned_segment_baseline()`, so segment storage is not even enabled in this case. No test corrupts or shortens a `segment-*.log`.
   That is the one damage class this design created and the only shape no length check can catch: `read_exact_at` errors on a short file, and the owned fault sweep covers torn writes at I/O boundaries, not a same-length bit flip in an already-durable body. With `checksum_body == 0` the body has no journal-level check, so a bit-rotted or zero-filled body is accepted by `read_record` in every simulated case.
   Fix: extend the sweep over `segment-*.log` with bit-flip and short-file cases. This is the test that would have caught the missing body checksum and should land with its fix.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {

Review Comment:
   nit: `write_segment_body` builds `SegmentPosition { length: reference.position, next_offset: reference.start_offset }`, which violates the type's own `valid()` (`:496-499`: `(length == 0) == (next_offset == start_offset)`) for every `position > 0`.
   Harmless today — `open_segment_file` reads only `generation`, `position.start_offset` and `position.length`, and never calls `valid()` — but it makes the stated invariant untrue at a call site, which is how the next reader loses it. Note `length` is load-bearing at `:451` (`cursor.position.length > 0` selects the hard-link branch), so the fix is to pass the three fields `open_segment_file` actually reads, not to make the fake cursor valid.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))

Review Comment:
   warning: the deliberately-terminal ENOENT behaviour here stays correct on its own terms, but segment ownership changes what it implies: the WAL now unlinks offset-named files (`segments.rs:428`) that `persistence_checkpoint_files` still lists, because the skip guard (`iggy_partition.rs:993-1000`) keys on `log.segments()` membership rather than file existence.
   After that sweep the next flush re-marks the segment dirty (`iggy_partition.rs:5613-5615`), it is still in `log.segments()`, both its paths are listed, this `open` gets ENOENT, and the partition can never reclaim WAL coverage again.
   Fail-closed is right; the new work manufactured the condition. Fixing the sweep with the skip-names variant kills this too, which is a reason to prefer that variant.
   Fix: exclude paths the WAL swept, or have the sweep retire the matching segments.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -4301,6 +4959,29 @@ where
         }
     }
 
+    fn drain_persistable_commits(&self) -> Vec<PipelineEntry> {
+        let Some(persistence) = &self.persistence else {
+            return drain_committable_prefix(self.consensus());
+        };
+        self.persist_repaired_prefix();
+        let through = self.consensus.commit_max().min(persistence.head());
+        let mut drained = Vec::new();
+        self.consensus.with_pipeline_mut(|pipeline| {
+            let mut next = self.consensus.commit_min() + 1;

Review Comment:
   warning: this merge resolution carries master's `head_op != next -> break` hole gate (#4073) but drops the `report_uncommittable_head` call that accompanies it on the non-persisted path (`core/consensus/src/plane_helpers.rs:497`, `:553`).
   Gate semantics match master and are correct, so no behavioural wedge was introduced. But `plane_helpers.rs:583-589` documents the head-below-floor state as legitimately reachable — `complete_repair`'s `set_commit_floor` raises `commit_min` past a live pipeline without `clear_pipeline`, so "nothing pops a head below the floor" until a view change clears it — and warns on it. The persisted path now reaches that identical permanent stall with ZERO log output, which is exactly the diagnostic #4073 added.
   Fix: call `report_uncommittable_head` from the persisted drain too. One call.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,
+    retired_offset_files: RefCell<Vec<S::File>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    certified_log_view: Cell<Option<u32>>,
+    requested_log_view: Cell<Option<(u32, u64, u128)>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    checkpoint_needed: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    retained_bytes: Cell<u64>,
+    segment_checkpoint: Cell<Option<SegmentPosition>>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    writer_active: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct WriterLease {
+    key: PathBuf,
+    id: u64,
+    retired: AtomicBool,
+    running: AtomicBool,
+    waiters: Mutex<Vec<std::task::Waker>>,
+}
+
+struct WriterRegistration {
+    id: u64,
+    writer: Weak<WriterLease>,
+    interrupted: bool,
+}
+
+static WRITERS: LazyLock<Mutex<HashMap<PathBuf, WriterRegistration>>> =
+    LazyLock::new(|| Mutex::new(HashMap::new()));
+
+impl WriterLease {
+    async fn acquire(key: PathBuf) -> io::Result<Arc<Self>> {
+        loop {
+            let previous = {
+                let mut writers = WRITERS
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if writers
+                    .get(&key)
+                    .is_some_and(|registration| registration.interrupted)
+                {
+                    return Err(io::Error::other(
+                        "interrupted partition WAL writer requires process restart",
+                    ));
+                }
+                if let Some(previous) = writers
+                    .get(&key)
+                    .and_then(|registration| registration.writer.upgrade())
+                {
+                    drop(writers);
+                    Some(previous)
+                } else {
+                    let lease = Arc::new(Self {
+                        key: key.clone(),
+                        id: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+                        retired: AtomicBool::new(false),
+                        running: AtomicBool::new(false),
+                        waiters: Mutex::new(Vec::new()),
+                    });
+                    writers.insert(
+                        key.clone(),
+                        WriterRegistration {
+                            id: lease.id,
+                            writer: Arc::downgrade(&lease),
+                            interrupted: false,
+                        },
+                    );
+                    drop(writers);
+                    return Ok(lease);
+                }
+            };
+            let Some(previous) = previous else { continue };
+            if !previous.retired.load(Ordering::Acquire) {
+                return Err(io::Error::new(
+                    io::ErrorKind::AlreadyExists,
+                    "partition WAL already has an active writer",
+                ));
+            }
+            compio::runtime::time::timeout(
+                PERSISTENCE_DRAIN_TIMEOUT,
+                futures::future::poll_fn(|context| {
+                    let mut waiters = previous
+                        .waiters
+                        .lock()
+                        .unwrap_or_else(std::sync::PoisonError::into_inner);
+                    if !previous.running.load(Ordering::Acquire) {
+                        return std::task::Poll::Ready(());
+                    }
+                    if !waiters
+                        .iter()
+                        .any(|waiter| waiter.will_wake(context.waker()))
+                    {
+                        waiters.push(context.waker().clone());
+                    }
+                    std::task::Poll::Pending
+                }),
+            )
+            .await
+            .map_err(|_| {
+                io::Error::new(
+                    io::ErrorKind::TimedOut,
+                    "retired partition WAL writer did not stop",
+                )
+            })?;
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if writers
+                .get(&key)
+                .is_some_and(|registration| registration.id == previous.id)
+            {
+                writers.remove(&key);
+            }
+        }
+    }
+
+    fn finish(&self) {
+        self.running.store(false, Ordering::Release);
+        for waiter in self
+            .waiters
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .drain(..)
+        {
+            waiter.wake();
+        }
+    }
+}
+
+impl Drop for WriterLease {
+    fn drop(&mut self) {
+        let mut writers = WRITERS
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if writers
+            .get(&self.key)
+            .is_some_and(|registration| registration.id == self.id && !registration.interrupted)
+        {
+            writers.remove(&self.key);
+        }
+    }
+}
+
+struct WriterTicket<S: DurableStorage> {
+    owner: Rc<PartitionPersistence<S>>,
+    started: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterTicket<S> {
+    fn drop(&mut self) {
+        if self.started {
+            return;
+        }
+        self.owner.fail(io::Error::new(
+            io::ErrorKind::Interrupted,
+            "partition WAL writer was dropped before polling",
+        ));
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct WriterGuard<'a, S: DurableStorage> {
+    owner: &'a PartitionPersistence<S>,
+    journal: Option<PartitionPrepareJournal<S>>,
+    complete: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterGuard<'_, S> {
+    fn drop(&mut self) {
+        *self.owner.journal.borrow_mut() = self.journal.take();
+        self.owner.in_flight_bytes.set(0);
+        self.owner.checkpoint_running.set(false);
+        if !self.complete
+            && let Some(lease) = &self.owner.lease
+        {
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if let Some(registration) = writers.get_mut(&lease.key)
+                && registration.id == lease.id
+            {
+                registration.interrupted = true;
+            }
+        }
+        if !self.complete && self.owner.failure.borrow().is_none() {
+            *self.owner.failure.borrow_mut() = Some(Arc::new(io::Error::new(
+                io::ErrorKind::Interrupted,
+                "partition WAL writer stopped during a mutation",
+            )));
+        }
+        self.owner.writer_active.set(false);
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation<S: DurableStorage> {
+    EnableSegments {
+        epoch: u64,
+        initial: SegmentPosition,
+        max_size: u64,
+    },
+    CertifyView {
+        epoch: u64,
+        view: u32,
+        op: u64,
+        checksum: u128,
+    },
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+        offset_files: Vec<S::File>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        let lease = if let Some(key) = storage.writer_identity(directory)? {

Review Comment:
   warning: the `WriterLease` key is `<partition_dir>/prepares-<created_revision>`, but this change extends the journal's write domain into the shared PARENT directory: `segments.rs:461`/`:468` unlink and relink `{offset:020}.log`, `:405` truncates that inode, `:428` unlinks `{offset}.log`/`.index`. Two incarnations of the same partition therefore take different keys and `WriterLease::acquire` never waits — so last round's fencing fix no longer covers the journal's write domain.
   Narrowing the writes is not possible (the public offset name is inherently shared), so widening the key is the only direction. Live overlap is unproven — `retire()` clears the queue promptly, so the window is narrow — but the invariant regression is provable from the code.
   Fix: key the lease on the partition directory, paired with a check that the reconciler's retire path drops the old `PartitionPersistence` before the new revision opens, or the rebuild deadlocks instead of racing.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();

Review Comment:
   nit: `reset_with_segment_checkpoint` calls `segment_files.clear()` here, before `sync_segment_files()` at `:253`, and `mark_purge` does the same at `partition_journal.rs:505` — dropping writing handles without syncing them. That contradicts the barrier rationale stated at `:330-332` ("Keep the writing handle: reopening after an errseq writeback error could turn a failed body barrier into a successful acknowledgment").
   Safe as the code stands, because every body write is followed by `sync_segment_files()` inside `write_segment_bodies` (`:296`) before its record lands — so the handles dropped here are always already synced. The coupling is accidental and undocumented.
   This becomes critical if the per-batch barrier at `:296` is ever made conditional or deferred, so it is the prerequisite for that optimization.
   Fix: sync before every `clear()`, and before any `publish` that can name an unsynced body.



##########
core/server/config.toml:
##########
@@ -1005,6 +844,68 @@ clients_table_max = 8192
 # plane), a pipeline exists per partition, so raising this multiplies pinned
 # request-buffer memory by the partition count. Keep it modest.
 [partition]
+# Retention is per topic, set at CreateTopic and readable on GetTopic:
+#   max_topic_size   - delete oldest sealed segments past this size
+#                      ("unlimited" when unset)
+#   message_expiry   - delete sealed segments older than this ("none" when unset)
+# Both policies can be active at once. The active segment is never touched.
+# Call GET /options/topic (or the SDK's describe_options) for the full catalog
+# with this server's defaults.
+
+# Topic durability and flush scheduling are set at creation and returned by GetTopic.
+# durability controls message completion. consumer_offset_durability controls explicit offset stores and deletes.
+# Both independently default to "replicated". Neither inherits the other.
+# In replicated groups, either persisted policy enables the prepare WAL for full message bodies.

Review Comment:
   warning: "either persisted policy enables the prepare WAL for full message bodies" is wrong for exactly the case this change altered. Message-persisted topics now journal a 32-byte reference; only offset-persisted-with-replicated-messages still journals full bodies inline (`iggy_partition.rs:797` gates `enable_segment_storage` on `durability().is_persisted()` alone).
   `:859` stays true as written, since capacity accounting still charges the full body.
   Fix: drop "either" and split the two policies explicitly.



##########
core/server/src/responses.rs:
##########
@@ -1063,11 +1063,16 @@ fn topic_option_descriptors() -> Result<Vec<OptionDescriptor>, IggyError> {
             ),
         },
         OptionDescriptor {
-            key: WireName::new(topic_option_keys::ENFORCE_FSYNC)
-                .map_err(|_| IggyError::InvalidFormat)?,
-            kind: HeaderKind::Bool.as_code(),
-            default_value: Bytes::copy_from_slice(&[u8::from(iggy_common::DEFAULT_ENFORCE_FSYNC)]),
-            description: "Whether writes to this topic's partitions fsync".to_string(),
+            key: WireName::new(topic_option_keys::DURABILITY).map_err(|_| IggyError::InvalidFormat)?,
+            kind: HeaderKind::String.as_code(),
+            default_value: Bytes::from_static(b"replicated"),
+            description: "Message completion: replicated or persisted. Independently defaults to replicated. A singleton quorum has one copy. In replicated groups, either persisted policy enables a WAL containing full message bodies and spends partition.wal_bytes_max on those bodies.".to_string(),

Review Comment:
   warning: this description says a persisted-message topic "enables a WAL containing full message bodies and spends `partition.wal_bytes_max` on those bodies". The WAL now records a 32-byte `SegmentReference`; `iggy_partition.rs:797` enables segment storage for every message-persisted topic and `partition_journal.rs:618` sizes the record at `REFERENCED_PREPARE_BYTES`.
   An operator sizing disk from `GET /options/topic` therefore budgets the segment bytes twice, when the actual extra is zero (hard links). The budget sentence is still correct — `partition_journal.rs:619`/`:634` charge the full `body_bytes` to capacity — so only the physical-layout claim is wrong. Leave `:1075` alone: `durability()` is message-only, so replicated-messages + persisted-offsets does still journal bodies inline.
   Fix: state that the WAL records a reference to the segment file holding the body, retains that inode by hard link until the WAL reclaims the operation, and still charges the full body size against `partition.wal_bytes_max`.



##########
core/server/src/segment_recovery.rs:
##########
@@ -3335,6 +3375,59 @@ mod tests {
     /// an anchor must not launder an overlap either. Reachable because each end

Review Comment:
   warning: this doc block ("No re-anchor plants a segment whose range a predecessor already covers...") was written for `given_overlapping_segments_when_recovering_should_refuse_even_when_anchored`, which the newly inserted test pushed down to `:3432`. The block now documents the new test instead.
   Fix: move the new test below the one this block describes, or give it its own doc.



##########
core/bench/src/utils/mod.rs:
##########
@@ -321,14 +330,15 @@ fn add_infrastructure_arguments(parts: &mut Vec<String>, args: &IggyBenchArgs) {
         parts.push(format!("--max-topic-size \'{max_topic_size}\'"));

Review Comment:
   warning: the recorded reproduce-command (built in this function, see `:311-318`) emits `--partitions 0` for `pinned-consumer` and `balanced-consumer-group`, which declare no `--partitions` flag. `PinnedConsumerArgs::partitions()` and `BalancedConsumerGroupArgs::partitions()` return 0 while `default_partitions` resolves to 1 and 24, so `0 != default` pushes the flag.
   `bench_command` lands in `BenchmarkParams` and is published as the run's reproduce line, so the published command fails to parse. The new round-trip test only exercises `pinned-producer`.
   Fix: skip the flag for kinds whose args do not declare it.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;

Review Comment:
   nit: `reference.validate(header, header.size as usize)` passes `header.size` as `frame_length`, making `validate`'s own `header.size as usize != frame_length` test (`:1344`) a self-comparison. On the append path (`:615`) `frame_length` is `prepare.len()` and the clause bites; on recovery it is dead.
   Consequently `record_length` is never cross-checked for a `SEGMENT_RECORD` — the `INLINE_RECORD` arm at `:965` is the only size cross-check — so a header claiming up to `PREPARE_BYTES_MAX` drives `Owned::zeroed` and a segment read with no envelope agreement. Bounded by `:1345-1347`, so no over-allocation, but the framing check the inline path gets is absent here.
   Fix: pass the record's real `frame_length`, and validate `record_length(header.size)` for the reference form too.



##########
core/server/src/server_error.rs:
##########
@@ -572,7 +572,7 @@ impl std::fmt::Display for PartitionRecoveryRefusal {
                 durable_position,
             } => write!(
                 f,
-                "segment {start_offset} runs under enforce_fsync with {entry_count} sparse \
+                "segment {start_offset} runs under persisted durability with {entry_count} sparse \
                  index entries, and the byte-0 rebuild proved its log only through byte \
                  {walked_position}, short of byte {durable_position} which the last \
                  entry's own fdatasync ordering proves the log had already made durable; \

Review Comment:
   warning: `StorageSizeMismatch`'s text says "file length {on_disk_bytes} ... at writer open", but `segment_recovery.rs:288` passes `bounds.messages_size` — the bytes a byte-0 walk proved — not the file length, and `raw_messages_size` may be far larger. For a torn or shortened persisted body, which is this change's signature failure mode, the operator is handed an actively wrong number.
   The doc at `:469-470` ("A writer reopening over recovered bounds") is now false for both `segment_recovery.rs:253` and `:288`. Paired with the non-self-healing refusal at `segment_recovery.rs:283-293`, the wrong number reappears on every boot forever.
   Fix: add a separate refusal variant for a checkpointed prefix the walk cannot prove, and fix both call sites together.



##########
core/bench/src/utils/mod.rs:
##########
@@ -321,14 +330,15 @@ fn add_infrastructure_arguments(parts: &mut Vec<String>, args: &IggyBenchArgs) {
         parts.push(format!("--max-topic-size \'{max_topic_size}\'"));
     }

Review Comment:
   warning: the default table in this function (see `:300-306` and `:311-317`) omits `EndToEndProducingConsumerGroup`, so the `_` arm supplies 6 streams and 1 partition while that kind's own clap defaults are 1 and 24. An explicit `-s 6` therefore compares equal to the assumed default and is dropped from the recorded command, and the reproduced run silently uses 1 stream.
   Silent non-equivalence is worse than a parse error: the published line runs, with different geometry.
   Fix: read the defaults from the kind's own args rather than a parallel table.



##########
core/server_common/src/fs_utils.rs:
##########
@@ -44,6 +48,58 @@ impl DirEntry {
     }
 }
 
+/// Reserve segment space without changing its contents or logical length.
+/// Unsupported or failed reservations fall back to buffered allocation.
+#[cfg(target_os = "linux")]
+pub fn preallocate_file(file: &fs::File, file_path: &Path, len: u64) {
+    let Ok(len) = i64::try_from(len) else {
+        warn!(
+            target: "iggy.partitions.storage",
+            file = %file_path.display(),
+            preallocate_len = len,
+            "file preallocation size is unsupported, using buffered allocation"
+        );
+        return;
+    };
+
+    // Runs INLINE on the shard thread, deliberately. `server_common::executor`

Review Comment:
   warning: this 17-line rationale was relocated into a generic fs utility, where it asserts a caller-context invariant `fs_utils` cannot enforce and states a motive the operator docs contradict: it says preallocation is "opt-in per topic at creation for that reason" (the shard-pool panic), while `config.toml`'s `preallocate_segments` block and `responses.rs:1105-1119` both give disk consumption as the reason.
   Its cost argument is also now stale: it justifies the inline `fallocate` as boot-and-rotation only, but `partition_journal.rs:372` -> `segments.rs:406-408` puts it on the per-view-change truncation path. The untested microsecond claim, the NFS/FUSE/extent-tree walkthrough, the quoted compio panic string, and four lines about macOS inside a `#[cfg(target_os = "linux")]` arm it itself calls "Linux-only regardless" all cut against the repo's comment rules.
   Fix: reduce to the one load-bearing constraint ("no blocking pool exists, so this runs inline"), and state the shard-thread claim at the call sites, which is also where the new view-change reachability belongs.



##########
core/server_common/src/segment_storage/mod.rs:
##########
@@ -39,6 +42,49 @@ pub struct SegmentStorage {
 }
 
 impl SegmentStorage {
+    /// The WAL owns message writes; this storage exposes only their committed prefix.
+    pub async fn with_read_only_messages(

Review Comment:
   warning: the two sibling constructors disagree on positional slot 3, both `u64`: `new(messages_path, index_path, messages_size, indexes_size, file_exists)` versus `with_read_only_messages(messages_path, index_path, indexes_size, file_exists, preallocate_size)` at `:88-92`.
   Slots 4 and 5 are type-guarded (`bool`, `Option<u64>`); slot 3 is not, so swapping `messages_size` and `indexes_size` between the two compiles silently. Live call sites already pass different things into that position: `segment_recovery.rs:402` passes `plan.index_size`, `iggy_partition.rs:6883` passes `0`.
   Fix: one constructor with an explicit mode, or a named-parameters struct.



##########
core/bench/src/args/defaults.rs:
##########
@@ -35,15 +35,15 @@ pub const DEFAULT_MESSAGE_BATCHES: NonZeroU32 = u32!(1000);
 pub const DEFAULT_MESSAGE_SIZE: NonZeroU32 = u32!(1000);
 pub const DEFAULT_TOTAL_MESSAGES_SIZE: IggyByteSize = IggyByteSize::new(8_000_000);
 
-pub const DEFAULT_PINNED_NUMBER_OF_STREAMS: NonZeroU32 = u32!(8);
+pub const DEFAULT_PINNED_NUMBER_OF_STREAMS: NonZeroU32 = u32!(6);

Review Comment:
   nit: `DEFAULT_PINNED_NUMBER_OF_STREAMS` is read by no pinned kind — only `end_to_end/producing_consumer.rs:34` and the reproducer table. All three pinned kinds take `streams: Option<NonZeroU32>` and fall back to their actor count.
   So the 8 -> 6 edit changed `end-to-end-producing-consumer`'s default, while the README sentence added alongside it describes pinned workloads that never read this constant, and never mentions that `end-to-end-producing-consumer-group` still defaults to 1 stream. It also invalidates comparison against previously recorded `performance_results/`.
   Fix: rename to the kind it actually governs, or give the e2e kinds their own constant.



##########
core/server/config.toml:
##########
@@ -1005,6 +844,68 @@ clients_table_max = 8192
 # plane), a pipeline exists per partition, so raising this multiplies pinned
 # request-buffer memory by the partition count. Keep it modest.
 [partition]
+# Retention is per topic, set at CreateTopic and readable on GetTopic:
+#   max_topic_size   - delete oldest sealed segments past this size

Review Comment:
   nit: the retention text still reads as an immediate cap, but persisted topics now defer segment deletion until the WAL checkpoint passes: `iggy_partition.rs:6731-6736` calls `request_checkpoint()` and `break`s for a sealed segment whose `end_offset >= checkpoint.next_offset`.
   So `max_topic_size` and `message_expiry` overshoot is now bounded by checkpoint cadence — itself driven by `retained_bytes >= capacity/2`, i.e. WAL pressure — not by the cap.
   Fix: say retention can lag on persisted topics, and what bounds the lag.



##########
core/metadata/src/stm/stream.rs:
##########
@@ -2820,11 +2819,21 @@ mod tests {
         assert_eq!(topic.compression_algorithm, CompressionAlgorithm::None);
 
         // partitions_count is create-consumed, never persisted.
-        assert_eq!(topic.options.len(), 3);
+        assert_eq!(topic.options.len(), 5);
         let expiry_key = HeaderKey::from_str(topic_option_keys::MESSAGE_EXPIRY).unwrap();
         let expiry = topic.options.get(&expiry_key).unwrap();
         assert!(expiry.explicit, "client-sent key keeps its provenance");
         assert_eq!(expiry.value.kind(), HeaderKind::Uint64);

Review Comment:
   nit: this test asserts explicit provenance for durability keys the real admission path strips when unsupplied. The request is encoded with `explicit.to_wire()` at `:2804`, which always emits both durability keys, so `assert!(option.explicit)` passes for keys the client never sent, and `options.len() == 5` pins the pre-strip shape.
   Production admission (`core/metadata/src/impls/metadata.rs:3469`) uses `to_explicit_wire(|key| supplied..)`, which removes them (`core/common/src/types/options/mod.rs:741-755`). The test would pass identically if that call were reverted.
   Fix: build the block with `to_explicit_wire`, or assert derived provenance for the unsupplied keys.



##########
core/bench/src/args/kinds/pinned/consumer.rs:
##########
@@ -16,7 +16,7 @@
 // under the License.

Review Comment:
   nit: three `validate()` messages in the bench arg kinds state the inverse of the rule they enforce, each telling the operator to do the thing that just failed: `streams > consumers` is refused with "must be equal to" (this file, `:77`), `cg_number < streams` with "must be less than or equal to the number of streams", and `partitions < consumers` with "Consumer number must be greater than the number of partitions" (`balanced/producer_and_consumer_group.rs:110`, `:121`). `end_to_end/producing_consumer_group.rs` repeats the same inversion.
   Fix: state the enforced relation in each message.



##########
core/bench/src/args/examples.rs:
##########
@@ -15,176 +15,220 @@
 // specific language governing permissions and limitations
 // under the License.
 
-const EXAMPLES: &str = r#"EXAMPLES:
+const EXAMPLES: &str = r"EXAMPLES:
 
-1) Pinned Mode Benchmarking:
+Start iggy-server separately. The benchmark connects to a running server.
+Global options precede the kind, kind options precede the transport, and
+transport options precede the optional output subcommand.
 
-    Run benchmarks with pinned producers and consumers. This mode pins specific producers
-    and consumers to specific streams and partitions (one to one):
+Default producer and consumer counts are six. Pinned workloads default to six streams.
+
+1) All benchmark kinds and aliases:
+
+    Pinned producer (pp), consumer (pc), and producer/consumer (ppc):
 
     $ cargo r -r --bin iggy-bench -- pinned-producer --streams 10 --producers 10 tcp
     $ cargo r -r --bin iggy-bench -- pinned-consumer --streams 10 --consumers 10 tcp
     $ cargo r -r --bin iggy-bench -- pinned-producer-and-consumer --streams 10 --producers 10 --consumers 10 tcp
-    $ cargo r -r --bin iggy-bench -- -T 10GB pp --producers 5 tcp
-
-2) Balanced Mode Benchmarking:
 
-    Run benchmarks with balanced distribution of producers and consumers. This mode
-    automatically balances the load across streams and consumer groups:
+    Balanced producer (bp), consumer group (bcg), and producer/consumer group (bpcg):
 
     $ cargo r -r --bin iggy-bench -- balanced-producer --partitions 24 --producers 6 tcp
     $ cargo r -r --bin iggy-bench -- balanced-consumer-group --consumers 6 tcp
     $ cargo r -r --bin iggy-bench -- balanced-producer-and-consumer-group --partitions 24 --producers 6 --consumers 6 tcp
-    $ cargo r -r --bin iggy-bench -- -T 10GB bpc tcp
-
-    Durability-matched run, where every produce ack waits for an fsync
-    (--partitions 1 routes every producer straight to that partition):
-
-    $ cargo r -r --bin iggy-bench -- --enforce-fsync --messages-required-to-save 1 \
-        balanced-producer --partitions 1 --producers 8 tcp
-
-3) End-to-End Benchmarking:
-
-    Run end-to-end benchmarks that measure performance for a producer that is also a consumer:
-
-    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer --producers 12 --streams 12 tcp
-    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer-group --partitions 24 --producers 6 tcp
-
-4) Advanced Configuration:
-
-    You can customize various parameters for any benchmark mode:
-
-    Global options (before the benchmark command):
-    --messages-per-batch (-P): Number of messages per batch [default: 1000]
-                               For random batch sizes, use range format: "100..1000"
-    --message-batches (-b): Total number of batches [default: 1000]
-    --total-messages-size (-T): Total size of messages to send (e.g., "1GB", "500MB")
-                                Mutually exclusive with --message-batches
-    --message-size (-m): Message size in bytes [default: 1000]
-                        For random sizes, use range format: "100..1000"
-    --rate-limit (-r): Optional throughput limit per producer (e.g., "50KB", "10MB")
-    --warmup-time (-w): Warmup duration [default: 0s]
-    --sampling-time (-t): Metrics sampling interval [default: 10ms]
-    --moving-average-window (-W): Window size for moving average [default: 20]
-    --username (-u): Username for server authentication [default: iggy]
-    --password (-p): Password for server authentication [default: iggy]
-    --reuse-streams: Reuse existing bench streams instead of deleting them
-
-    Benchmark-specific options (after the benchmark command):
-    --streams (-s): Number of streams
-    --partitions (-a): Number of partitions
-    --producers (-c): Number of producers
-    --consumers (-c): Number of consumers
-    --max-topic-size (-T): Max topic size (e.g., "1GiB")
-    --message-expiry (-e): Topic message expiry time (e.g., "1s", "5min", "1h")
-
-    Examples with detailed configuration:
-
-    # Fixed message and batch sizes:
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size 1000 \
-        --messages-per-batch 100 \
-        --message-batches 1000 \
-        --rate-limit "100MB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-    # Random message sizes (100-1000 bytes):
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size "100..1000" \
-        --messages-per-batch 100 \
-        --total-messages-size "1GB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-    # Random batch sizes (10-100 messages per batch):
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size 1000 \
-        --messages-per-batch "10..100" \
-        --total-messages-size "500MB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-    # Random message and batch sizes with rate limiting:
-    $ cargo r -r --bin iggy-bench -- \
-        --message-size "500..2000" \
-        --messages-per-batch "50..200" \
-        --total-messages-size "2GB" \
-        --rate-limit "50MB" \
-        balanced-producer \
-        --streams 5 \
-        --producers 5 \
-        tcp
-
-5) Remote Server Benchmarking:
-
-    To benchmark a remote server, specify the server address in the transport subcommand.
-    Both IP addresses and hostnames are supported:
-
-    $ cargo r -r --bin iggy-bench -- pinned-producer \
-        --streams 5 --producers 5 \
-        tcp --server-address 192.168.1.100:8090
-    $ cargo r -r --bin iggy-bench -- pinned-producer \
-        --streams 5 --producers 5 \
-        tcp --server-address localhost:8090
-
-    With custom credentials:
-
-    $ cargo r -r --bin iggy-bench -- \
-        --username admin --password secret \
-        pinned-producer --streams 5 --producers 5 \
-        tcp --server-address 192.168.1.100:8090
-
-6) Output Data and Results:
-
-    The benchmark tool can store detailed results for analysis and comparison:
-
-    # Basic result storage (results will be stored in ./performance_results):
-    $ cargo r -r --bin iggy-bench -- pinned-producer --streams 10 --producers 10 tcp output
-
-
-    # Organized benchmarking with metadata:
-    $ cargo r -r --bin iggy-bench -- balanced-producer --partitions 24 --producers 6 tcp \
-        output \
-        --identifier "prod-test-$(date +%Y%m%d)" \
-        --remark "production-config" \
-        --gitref "$(git rev-parse --short HEAD)" \
-        --gitref-date "$(git show -s --format=%cI HEAD)"
-
-    # Quick result visualization:
-    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer --producers 12 --streams 12 tcp \
-        output --open-charts
-
-    Output configuration options:
-    --open-charts (-c)  : Open charts after the benchmark
-    --output-dir (-o)   : Directory for storing results [default: performance_results]
-    --identifier        : Benchmark run ID (if not provided defaults to hostname)
-    --remark            : Additional context (e.g., "production-config")
-    --extra-info        : Custom metadata for future analysis, currently unused
-
-7) Help and Documentation:
-
-    For more details on available options:
-
-    # General help
-    $ cargo r -r --bin iggy-bench -- --help
+    $ cargo r -r --bin iggy-bench -- --total-data 10GiB bpcg tcp
 
-    # Specific benchmark help
-    $ cargo r -r --bin iggy-bench -- pinned-producer --help
+    End-to-end producing consumer (e2e) and producing consumer group (e2ecg):
 
-    # Protocol help
-    $ cargo r -r --bin iggy-bench -- pinned-producer tcp --help
+    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer --producing-consumers 12 --streams 12 tcp
+    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer-group --partitions 24 --producers 6 --consumers 6 tcp
+
+2) All transports:
+
+    $ cargo r -r --bin iggy-bench -- pinned-producer tcp --server-address 127.0.0.1:8090
+    $ cargo r -r --bin iggy-bench -- pinned-producer quic --server-address 127.0.0.1:8080
+    $ cargo r -r --bin iggy-bench -- pinned-producer http --server-address 127.0.0.1:3000
+    $ cargo r -r --bin iggy-bench -- pinned-producer websocket --server-address 127.0.0.1:8092
+
+3) Topic durability:
+
+    --durability controls message completion.
+    --consumer-offset-durability controls explicit offset-store/delete completion.
+    Both independently default to replicated. Neither inherits the other.
+    Both policies normally write to disk. Persisted additionally waits for
+    recoverable stable storage on the required VSR quorum, or the single replica.
+
+    Both replicated (the default):
+    $ cargo r -r --bin iggy-bench -- balanced-producer-and-consumer-group tcp
+
+    Persisted messages, replicated offsets:
+    $ cargo r -r --bin iggy-bench -- --durability persisted balanced-producer-and-consumer-group tcp
+
+    Replicated messages, persisted offsets:
+    $ cargo r -r --bin iggy-bench -- --consumer-offset-durability persisted balanced-producer-and-consumer-group tcp
+
+    Both persisted:
+    $ cargo r -r --bin iggy-bench -- --durability persisted --consumer-offset-durability persisted balanced-producer-and-consumer-group tcp
+
+    These options apply when topics are created. They do not modify topics
+    with --reuse-streams. Consumer polling with auto-commit remains asynchronous.
+    Its poll latency is not an acknowledged offset-store latency measurement.
+    In replicated groups, either persisted policy enables a WAL that also retains
+    message predecessors, even when message durability is replicated.
+
+4) Topic flush cadence and retention:
+
+    --messages-required-to-save is a global create-time topic option.
+    It controls segment flush cadence, not the acknowledgment guarantee.
+    --max-topic-size and --message-expiry are kind-specific topic options.
+    These flags do not change existing topics with --reuse-streams.
+
+    Persisted messages without forcing a segment flush for every message:
+    $ cargo r -r --bin iggy-bench -- --durability persisted --messages-required-to-save 1024 balanced-producer --partitions 1 --producers 8 tcp
 
-    # Output help
+    Replicated acknowledgments with eager segment flushing:
+    $ cargo r -r --bin iggy-bench -- --messages-required-to-save 1 balanced-producer tcp
+
+    Retention can delete data during a long run. Use matching policies when comparing:
+    $ cargo r -r --bin iggy-bench -- balanced-producer --max-topic-size 10GiB --message-expiry 1h tcp
+
+5) Workload configuration:
+
+    --messages-per-batch (-P): Messages per batch, or a range such as 100..1000.
+    --message-batches (-b): Batches per actor, mutually exclusive with --total-data.
+    --total-data (-T): Total message bytes across actors, such as 10GiB.
+    --message-size (-m): Message bytes, or a range such as 100..1000.
+    --rate-limit (-r): Aggregate throughput limit across actors, such as 100MB.
+    --warmup-time (-w): Warmup duration, such as 10s.
+    --sampling-time (-t): Metrics sampling interval.
+    --moving-average-window (-W): Moving-average window size.
+
+    Fixed message and batch sizes:
+    $ cargo r -r --bin iggy-bench -- --message-size 1000 --messages-per-batch 100 --message-batches 1000 --rate-limit 100MB balanced-producer --streams 5 --producers 5 tcp
+
+    Random message sizes:
+    $ cargo r -r --bin iggy-bench -- --message-size 100..1000 --messages-per-batch 100 --total-data 1GiB balanced-producer --streams 5 --producers 5 tcp
+
+    Random batch sizes:
+    $ cargo r -r --bin iggy-bench -- --message-size 1000 --messages-per-batch 10..100 --total-data 500MiB balanced-producer tcp
+
+    Random message and batch sizes with a warmup and aggregate rate limit:
+    $ cargo r -r --bin iggy-bench -- --message-size 500..2000 --messages-per-batch 50..200 --total-data 2GiB --warmup-time 10s --rate-limit 50MB balanced-producer tcp
+
+6) Remote server and output:
+
+    $ cargo r -r --bin iggy-bench -- pinned-producer --streams 5 --producers 5 tcp --server-address localhost:8090
+    $ cargo r -r --bin iggy-bench -- --username admin --password secret pinned-producer tcp --server-address 192.168.1.100:8090
+    $ cargo r -r --bin iggy-bench -- pinned-producer tcp output
+    $ cargo r -r --bin iggy-bench -- --durability persisted balanced-producer tcp output --identifier dedicated-host --remark persisted-messages --gitref abc123
+    $ cargo r -r --bin iggy-bench -- end-to-end-producing-consumer tcp output --open-charts
+
+    Output options include --output-dir (-o), --identifier, --remark, --gitref,
+    --gitref-date, --extra-info, and --open-charts (-c).
+    Record both durability policies, CPU allocation, host tuning, and storage.
+    See core/bench/README.md and https://iggy.apache.org/docs/server/linux-tuning.
+
+7) Help:
+
+    $ cargo r -r --bin iggy-bench -- --help
+    $ cargo r -r --bin iggy-bench -- pinned-producer --help
+    $ cargo r -r --bin iggy-bench -- pinned-producer tcp --help
     $ cargo r -r --bin iggy-bench -- pinned-producer tcp output --help
-"#;
+";
 
 pub fn print_examples() {
     println!("{EXAMPLES}");
 }
+
+#[cfg(test)]
+mod tests {
+    use super::EXAMPLES;
+    use crate::args::common::IggyBenchArgs;
+    use clap::{CommandFactory, Parser, error::ErrorKind};
+    use iggy::prelude::Durability;
+    use std::collections::BTreeSet;
+
+    #[test]
+    fn published_examples_parse_and_cover_every_kind_and_transport() {

Review Comment:
   nit: this coverage test proves clap parsing only — `try_get_matches_from` skips `IggyBenchArgs::validate()` and the per-kind `validate()`, which `exit()` on conflict. A published example such as `balanced-consumer-group --consumers 6 --streams 2` would pass this test and die at runtime.
   Every current example was checked by hand against its kind's `validate()` and none is broken, so the gap is latent, not live.
   Fix: extract validation into a `Result`-returning function and assert on it here.



##########
core/server/config.toml:
##########
@@ -1005,6 +844,68 @@ clients_table_max = 8192
 # plane), a pipeline exists per partition, so raising this multiplies pinned
 # request-buffer memory by the partition count. Keep it modest.
 [partition]
+# Retention is per topic, set at CreateTopic and readable on GetTopic:
+#   max_topic_size   - delete oldest sealed segments past this size
+#                      ("unlimited" when unset)
+#   message_expiry   - delete sealed segments older than this ("none" when unset)
+# Both policies can be active at once. The active segment is never touched.
+# Call GET /options/topic (or the SDK's describe_options) for the full catalog
+# with this server's defaults.
+
+# Topic durability and flush scheduling are set at creation and returned by GetTopic.
+# durability controls message completion. consumer_offset_durability controls explicit offset stores and deletes.
+# Both independently default to "replicated". Neither inherits the other.
+# In replicated groups, either persisted policy enables the prepare WAL for full message bodies.
+# Persisted offsets with replicated messages still consume wal_bytes_max for message payloads.
+# Their barriers can also persist co-batched messages. Only replicated/replicated stays off this WAL.
+# Persisted prepares are limited to 64 MiB including the consensus header. Oversized operations are rejected permanently.
+# Both policies write data to storage. "replicated" waits for VSR commit and application without an additional stable-storage barrier.
+# "persisted" also requires recoverable stable-storage copies at the replication quorum before explicit success.
+# A singleton quorum is one replica. Its persisted completion follows recoverable local persistence.
+# Poll auto-commit remains asynchronous. A successful poll does not confirm that its submitted offset operation committed or became durable.
+# HTTP ack=none returns dispatch acceptance with Iggy-Durability: none, even for persisted topics.
+# messages_required_to_save defaults to 1024 and size_of_messages_required_to_save defaults to 1 MiB.
+# These thresholds schedule ordinary segment writes. Required persistence, capacity pressure and lifecycle operations can flush sooner.
+
+# Segment storage
+# Segment size is per topic, set at CreateTopic as `segment_size` (1 GiB when
+# unset). It is a soft limit: a segment may close one whole batch past it.
+# Bounds are enforced at creation - a 512 B multiple, at least 1 MiB, and no
+# larger than 1 GiB.
+#
+# `preallocate_segments` is per topic too: it reserves exactly `segment_size`
+# up front where the filesystem supports it. Off unless a topic asks for it --
+# with the default 1 GiB segment size it costs 1 GiB of real disk per
+# partition at creation.
+
+# Recovery behavior
+# Recovery validates message batches against their checksums and partition identity before serving data.

Review Comment:
   warning: "Recovery validates message batches against their checksums and partition identity before serving data" is false for a body the partition WAL reaches by reference: `partition_journal.rs:885-893` gates the only check on `checksum_body != 0`, which `core/consensus/src/impls.rs:4061-4068` never sets for a partition prepare.
   The asymmetry is visible to operators: the same bytes ARE checksum-verified when polled (`:889` still holds for the poll path) and unverified when replayed.
   Fix: while the gap stands, say that a WAL-referenced body is covered by no checksum on the replay path; delete that sentence when the `batch_checksum` recompute lands.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors

Review Comment:
   nit: the `# Errors` section omits the terminal refusal this function actually returns when segment storage is already enabled with a different `max_size` — `"segment size differs from the durable WAL layout"` at `:69-71` — which "inconsistent boundaries or a failed storage barrier" does not cover.
   That line is now the only warning an operator gets that `max_size` is a durable, immutable part of the WAL layout with no reconciliation path.
   Fix: list it.



##########
core/server/config.toml:
##########
@@ -1005,6 +844,68 @@ clients_table_max = 8192
 # plane), a pipeline exists per partition, so raising this multiplies pinned
 # request-buffer memory by the partition count. Keep it modest.
 [partition]
+# Retention is per topic, set at CreateTopic and readable on GetTopic:
+#   max_topic_size   - delete oldest sealed segments past this size
+#                      ("unlimited" when unset)
+#   message_expiry   - delete sealed segments older than this ("none" when unset)
+# Both policies can be active at once. The active segment is never touched.
+# Call GET /options/topic (or the SDK's describe_options) for the full catalog
+# with this server's defaults.
+
+# Topic durability and flush scheduling are set at creation and returned by GetTopic.
+# durability controls message completion. consumer_offset_durability controls explicit offset stores and deletes.
+# Both independently default to "replicated". Neither inherits the other.
+# In replicated groups, either persisted policy enables the prepare WAL for full message bodies.
+# Persisted offsets with replicated messages still consume wal_bytes_max for message payloads.
+# Their barriers can also persist co-batched messages. Only replicated/replicated stays off this WAL.
+# Persisted prepares are limited to 64 MiB including the consensus header. Oversized operations are rejected permanently.
+# Both policies write data to storage. "replicated" waits for VSR commit and application without an additional stable-storage barrier.
+# "persisted" also requires recoverable stable-storage copies at the replication quorum before explicit success.
+# A singleton quorum is one replica. Its persisted completion follows recoverable local persistence.
+# Poll auto-commit remains asynchronous. A successful poll does not confirm that its submitted offset operation committed or became durable.
+# HTTP ack=none returns dispatch acceptance with Iggy-Durability: none, even for persisted topics.
+# messages_required_to_save defaults to 1024 and size_of_messages_required_to_save defaults to 1 MiB.
+# These thresholds schedule ordinary segment writes. Required persistence, capacity pressure and lifecycle operations can flush sooner.
+
+# Segment storage
+# Segment size is per topic, set at CreateTopic as `segment_size` (1 GiB when
+# unset). It is a soft limit: a segment may close one whole batch past it.
+# Bounds are enforced at creation - a 512 B multiple, at least 1 MiB, and no
+# larger than 1 GiB.
+#
+# `preallocate_segments` is per topic too: it reserves exactly `segment_size`
+# up front where the filesystem supports it. Off unless a topic asks for it --
+# with the default 1 GiB segment size it costs 1 GiB of real disk per
+# partition at creation.
+
+# Recovery behavior
+# Recovery validates message batches against their checksums and partition identity before serving data.
+# A genuinely incomplete tail can be truncated. Interior damage or valid records after a damaged range require refusal or repair, never blind truncation.
+# A sparse index that contradicts the message log is rebuilt only when the discrepancy fits the storage guarantee.
+# With message durability = "replicated", background writeback can preserve later pages before earlier ones, so recovery checks the log from byte zero.
+# With message durability = "persisted", completed durable segment flushes constrain the incomplete tail and permit the established index-anchored recovery path.
+# Durable prepares can still reside in the partition WAL rather than segments. Recovery reconciles that history with the materialized state before serving.
+# Index reconstruction and validation can take time across many segments. A slow recovery is not by itself evidence of a stalled server.
+# Unrecoverable local segment data is fenced and repaired from peers when available. A singleton cannot fetch a missing copy from another replica.
+# Fenced files remain available for diagnosis. Recovery must not replace an acknowledged durable history with an empty healthy partition.
+# Metadata and partition journals verify their own integrity and recovery frontiers independently of sparse indexes.
+
+# Per-partition active WAL and queued/in-flight prepare budget when either
+# topic policy is persisted. A 4 KiB multiple, from 128 MiB + 8 KiB to 4 GiB.
+# The minimum accommodates the retained commit-point prepare and a maximum-size successor.
+# Checkpointing begins at half the byte budget or 1024 dirty files.

Review Comment:
   warning: this block promises "The HTTP metrics endpoint exposes per-shard `partition_wal_*` byte gauges" directly beneath `wal_bytes_max` and the "Checkpointing begins at half the byte budget" line, but the published gauge no longer tracks the budget: `core/shard/src/metrics.rs:324-325` feeds `partition_wal_disk_bytes` from `disk_bytes` (WAL file length) while admission and checkpoint cadence gate on `retained_bytes` (full body bytes).
   With references that is a ratio of roughly 12.8x for small bodies and far more for large ones, so a 256 MiB budget can be exhausted at a ~0.4 MiB gauge reading.
   Fix: export `retained_bytes` and correct this text to name the quantity that actually throttles.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));

Review Comment:
   warning: this refusal — `invalid("segment lost durably published bytes")` — is the terminal outcome of the `ensure_initial_segment` truncation bug, and it is not diagnosable. `invalid()` (`partition_journal.rs:1422-1424`) builds an `io::Error` with a bare message: no path, no offset, no generation, no expected/actual length. It surfaces as one `warn!` plus `IggyError::CannotReadFile` (`partition_helpers.rs:865-868`).
   That `?` returns BEFORE `load_persisted_segments_with_checkpoint`, so nothing is fenced: the fence-and-repair-from-peers path `config.toml:890-891` documents is short-circuited, and on a singleton there is no peer copy at all. The only remedy the PR's own test uses is `restart_node_from_clean_slate` (`core/integration/src/harness/orchestrator/harness.rs:405`), which is harness-only and documented nowhere for operators.
   Fix: carry the path, offset, generation and both lengths in the error, and route the refusal through the documented fence path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio merged PR #4092:
URL: https://github.com/apache/iggy/pull/4092


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983323151


##########
core/partitions/src/state_transfer.rs:
##########
@@ -3194,6 +3465,9 @@ where
         minted_next_offset: u64,
         staged_was_empty: bool,
     ) -> Result<(), iggy_common::IggyError> {
+        if let Some(persistence) = &self.persistence {

Review Comment:
   removed the unreachable retained-offset branch.



##########
core/partitions/src/offset_storage.rs:
##########
@@ -121,15 +121,43 @@ pub fn decode_offset_record(bytes: &[u8]) -> OffsetRecord {
 ///
 /// # Errors
 /// [`IggyError`] when the directory, file, or write cannot be created or completed.
-pub async fn persist_offset(path: &str, offset: u64, enforce_fsync: bool) -> Result<(), IggyError> {
+pub async fn persist_offset(path: &str, offset: u64, persisted: bool) -> Result<(), IggyError> {
     let record = encode_offset_record(offset);
-    if enforce_fsync {
+    if persisted {
         replace_file(path, record, true, false).await
     } else {
         write_in_place(path, record).await
     }
 }
 
+/// Keep the original writer open so checkpoint observes its writeback errors.

Review Comment:
   documented the barriers required before wal reclamation.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -2139,10 +2669,53 @@ where
         Ok(())
     }
 
+    async fn write_consumer_offset(
+        &self,
+        path: &str,
+        offset: u64,
+        persisted: bool,
+    ) -> Result<(), IggyError> {
+        if let Some(persistence) = &self.persistence {
+            let file = crate::offset_storage::persist_offset_retained(
+                path,
+                offset,
+                persistence.take_offset_file(path),
+            )
+            .await
+            .inspect_err(|error| {
+                persistence.fail(std::io::Error::other(error.to_string()));
+            })?;
+            persistence.retain_offset_file(path.to_owned(), file);
+            Ok(())
+        } else {
+            persist_offset(path, offset, persisted).await
+        }
+    }
+
+    async fn write_cold_consumer_offset(
+        &self,
+        path: &str,
+        offset: u64,
+        persisted: bool,
+    ) -> Result<(u64, bool), IggyError> {
+        if self.persistence.is_some() {
+            let result = crate::offset_storage::read_offset_max(path, offset).await?;

Review Comment:
   fixed; covered cold-offset writes are skipped.



##########
core/server/src/http/reads.rs:
##########
@@ -404,6 +404,78 @@ pub(in crate::http) fn authorize_data_plane(
         .authorize(|permissioner| rule(permissioner, user_id, stream_id, topic_id))
 }
 
+static DURABILITY_KEY: std::sync::LazyLock<iggy_common::HeaderKey> =
+    std::sync::LazyLock::new(|| "durability".parse().expect("catalog key is valid"));
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(in crate::http) struct TopicDurability {
+    stream_id: usize,
+    topic_id: usize,
+    created_revision: u64,
+    pub durability: iggy_common::Durability,
+}
+
+impl TopicDurability {
+    pub fn confirmed_policy(self, state: &HttpInner) -> iggy_common::Durability {
+        state
+            .shard
+            .plane
+            .metadata()
+            .mux_stm
+            .streams()
+            .read(|inner| self.confirmed_policy_in(inner))
+    }
+
+    fn confirmed_policy_in(

Review Comment:
   durability is create-only; the revision check protects replacement.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {

Review Comment:
   documented why reset can install a new layout size.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "spetz (via GitHub)" <gi...@apache.org>.
spetz commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5585723474

   /ready


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "spetz (via GitHub)" <gi...@apache.org>.
spetz commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5588563212

   /ready


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "numinnex (via GitHub)" <gi...@apache.org>.
numinnex commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3957531916


##########
core/partitions/src/state_transfer.rs:
##########
@@ -389,30 +378,26 @@ impl ConsumerOffsetsWire {
         let mut cursor = LeCursor::new(content);
         let magic = cursor.take(CONSUMER_OFFSETS_MAGIC.len())?;
         let version = cursor.u8()?;
-        let carries_dedup = if magic == CONSUMER_OFFSETS_MAGIC {
-            if version != CONSUMER_OFFSETS_VERSION {
-                return Err(ConsumerOffsetsWireError::UnsupportedVersion { version });
-            }
-            true
-        } else if magic == CONSUMER_OFFSETS_MAGIC_V1 {
-            if version != CONSUMER_OFFSETS_VERSION_V1 {
-                return Err(ConsumerOffsetsWireError::UnsupportedVersion { version });
-            }
-            false
-        } else {
+        if magic != CONSUMER_OFFSETS_MAGIC {

Review Comment:
   critical: dropping the ICO1/ICO2 decode paths breaks rolling upgrade in BOTH directions, not one. A replica below the repair floor cannot rejoin an un-upgraded peer, and the deleted test's comment said so ("An un-upgraded primary still ships ICO1"). `prepare_checksum` is appended-and-optional (`:397` decodes `0 => None`), so an ICO2-tolerant decode is available and is not lax: `:2458` refuses `None` only when the receiver has persistence, so tolerance still fails closed for persisted topics.
   Fix: keep ICO2 decode yielding `prepare_checksum: None`, and name the expected version in the `:565` error.



##########
core/common/src/types/options/mod.rs:
##########
@@ -909,11 +936,21 @@ impl TopicCreateOptions {
                 OptionValue::explicit(HeaderValue::from(segment_size.as_bytes_u64())),
             );
         }
-        if let Some(enforce_fsync) = self.enforce_fsync {
+        for (key, policy) in [
+            (topic_option_keys::DURABILITY, self.durability),
+            (
+                topic_option_keys::CONSUMER_OFFSET_DURABILITY,
+                self.consumer_offset_durability,
+            ),
+        ] {
+            if let Some(raw) = self.raw.get(key)
+                && raw.parse::<Durability>().ok() != Some(policy)
+            {
+                return Err(IggyError::InvalidOptionValue(key.to_owned()));
+            }
             options.insert(

Review Comment:
   critical: both durability keys are inserted `OptionValue::explicit` unconditionally, and the clients call `to_wire()`/`to_string_options()` (`traits/binary_impls/topics.rs:99`, `sdk/src/http/topics.rs:88`), never `to_explicit_wire`. So the supplied-set filters (`metadata.rs:3469`, `http/handlers.rs:975`) record them client-supplied and `derived_block` never records the derived default -- `GetTopic` can no longer tell "asked for replicated" from "server default". The bug is pinned by a shipped assertion: `tests/sdk/options.rs:87` expects explicit==true for a key the fixture never sets, three lines above `:90` stating the opposite contract.
   Fix: `Option<Durability>` in `TopicCreateOptions`. A non-`Option` `Copy + Default` field leaves no was-set predicate to pass, so routing through `to_explicit_wire` cannot work -- it would drop the key and downgrade to replicated. Same change also fixes `:946`, where a raw `--set durability=persisted` is a hard `InvalidOptionValue` while Go/Java/C# honor it.



##########
core/server/src/partition_helpers.rs:
##########
@@ -989,10 +977,8 @@ async fn recover_partition_segments(
     let segment_size = runtime_options
         .segment_size
         .unwrap_or_else(|| IggyByteSize::from(iggy_common::DEFAULT_SEGMENT_SIZE));
-    let enforce_fsync = runtime_options
-        .enforce_fsync
-        .unwrap_or(iggy_common::DEFAULT_ENFORCE_FSYNC);
-    load_persisted_segments(config, namespace, segment_size, enforce_fsync, stats)
+    let persisted = runtime_options.durability.is_persisted();

Review Comment:
   critical: a topic created before this PR with `enforce_fsync = true` silently resolves to `Durability::Replicated`, losing segment fdatasync here and at `:1012`, plus `durable_segments` in recovery, which `segment_recovery.rs:174` calls "hides previously durable data loss". Path: the committed key hits `absorb_strict`, which has no `ENFORCE_FSYNC` arm, so `options/mod.rs:849` errors and `:1149` discards by design. No repair exists: `UPDATABLE_TOPIC_OPTION_KEYS` excludes both durability keys, and there is no CHANGELOG/UPGRADE file. `GetTopic` keeps advertising `enforce_fsync: true` while the runtime ignores it.
   Fix: map a stored `enforce_fsync = true` to `durability = Persisted` on read; prefer that over refuse-to-load, which would fence every legacy topic at boot.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {
+            self.storage
+                .open(path, OpenMode::Read)
+                .await?
+                .sync()
+                .await?;
+        }
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.state.anchor_known = checksum.is_some();
+        self.rewrite(op, checksum.unwrap_or(0), Some(0)).await
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation <= self.state.purge_generation {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short WAL prepare"))?,
+        )
+        .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+        if self
+            .entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+        {
+            return Ok(());
+        }
+        if header.op
+            != self
+                .state
+                .head
+                .checked_add(1)
+                .ok_or_else(|| invalid("WAL op exhausted"))?
+            || (self.state.anchor_known && header.parent != self.state.head_checksum)
+            || header.group != self.state.group
+        {
+            return Err(invalid("partition WAL append does not extend its history"));
+        }
+        let encoded = encode_record(prepare.as_slice(), self.state.generation)?;
+        let length = encoded.len();
+        if self.state.length + length as u64 > self.capacity {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL requires checkpoint",
+            ));
+        }
+        self.poisoned = true;
+        self.file.write(self.state.length, encoded).await?;
+        let state = JournalState {
+            length: self.state.length + length as u64,
+            head: header.op,
+            head_checksum: header.checksum,
+            checkpoint_checksum: if self.state.anchor_known {
+                self.state.checkpoint_checksum
+            } else {
+                header.parent
+            },
+            anchor_known: true,
+            ..self.state
+        };
+        self.entries.insert(
+            header.op,
+            StoredPrepare {
+                position: self.state.length,
+                length,
+                checksum: header.checksum,
+            },
+        );
+        self.state = state;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory)? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(&self, position: u64) -> io::Result<(PrepareHeader, usize, Frozen<4096>)> {
+        let prefix = self.file.read(position, RECORD_PREFIX).await?;
+        let frame_length = u32::from_le_bytes(
+            prefix[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut bytes = self.file.read(position, length).await?;
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let mut owned = Owned::<4096>::zeroed(frame_length);
+        owned
+            .as_mut_slice()
+            .copy_from_slice(&bytes[RECORD_PREFIX..RECORD_PREFIX + frame_length]);
+        let message = Message::<PrepareHeader>::try_from(owned)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != frame_length
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        Ok((header, length, message.into_frozen()))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            ..self.state
+        };
+        for (&op, entry) in &self.entries {
+            if op <= checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let prepare = self.read_record(entry.position).await?.2;
+            let encoded = encode_record(prepare.as_slice(), generation)?;
+            let length = encoded.len();
+            file.write(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                },
+            );
+            state.length += length as u64;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.poisoned = false;
+        if let Err(error) = self.storage.remove_file(&obsolete).await {
+            tracing::warn!(%error, "failed to remove superseded partition WAL file");
+        }
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(STATE_MAGIC);
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);
+        bytes[8..16].copy_from_slice(&checksum.to_le_bytes());
+        bytes
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != PARTITION_WAL_BLOCK_SIZE || &bytes[..8] != STATE_MAGIC {
+            return Err(invalid("unknown partition WAL frontier format"));
+        }
+        let read_u64 = |offset| -> io::Result<u64> {
+            Ok(u64::from_le_bytes(
+                bytes[offset..offset + 8]
+                    .try_into()
+                    .map_err(|_| invalid("invalid WAL frontier field"))?,
+            ))
+        };
+        if read_u64(8)? != XxHash3_64::oneshot(&bytes[16..]) {
+            return Err(invalid("partition WAL frontier checksum mismatch"));
+        }
+        let state = Self {
+            group: read_u64(16)?,
+            incarnation: read_u64(24)?,
+            generation: read_u64(32)?,
+            length: read_u64(40)?,
+            checkpoint: read_u64(48)?,
+            head: read_u64(72)?,
+            anchor_known: match bytes[96] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid WAL anchor flag")),
+            },
+            purge_generation: read_u64(104)?,
+            purge_floor: read_u64(112)?,
+            checkpoint_checksum: u128::from_le_bytes(
+                bytes[56..72]
+                    .try_into()
+                    .map_err(|_| invalid("invalid checkpoint checksum"))?,
+            ),
+            head_checksum: u128::from_le_bytes(
+                bytes[80..96]
+                    .try_into()
+                    .map_err(|_| invalid("invalid head checksum"))?,
+            ),
+        };
+        if state.length > PARTITION_WAL_CAPACITY_MAX
+            || !state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+            || state.head < state.checkpoint
+            || (!state.anchor_known && state.head != state.checkpoint)
+        {
+            return Err(invalid("invalid partition WAL frontier bounds"));
+        }
+        Ok(state)
+    }
+}
+
+/// Padded size of a prepare record, including its envelope.
+///
+/// # Errors
+/// Returns an error for a frame outside the protocol size bounds.
+pub fn record_length(frame_length: usize) -> io::Result<usize> {
+    if !(size_of::<PrepareHeader>()..=PREPARE_BYTES_MAX).contains(&frame_length) {

Review Comment:
   critical: `PREPARE_BYTES_MAX` (64 MiB) equals the shipped `message_bus.max_message_size` (`config.toml:1051`), but `has_capacity` is called with the whole prepare frame including the 256-byte `PrepareHeader` -- so a maximum-sized legally admitted batch overflows by the header at the default, with no operator change. `record_length` Err collapses into `has_capacity` false (`persistence.rs:258`), and `iggy_partition.rs:3740` answers `TransientNotAccepted`: a permanent size refusal reported as backpressure that no checkpoint can ever clear, naming neither the batch size nor the ceiling.
   Fix: return a permanent, size-naming error, and cross-check `max_message_size` + `http.max_request_size` against `PREPARE_BYTES_MAX - size_of::<PrepareHeader>()` in `PartitionConfig::validate`.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {
+            self.storage
+                .open(path, OpenMode::Read)
+                .await?
+                .sync()
+                .await?;
+        }
+        for path in directories {

Review Comment:
   warning: `checkpoint_files` serially opens and fsyncs every dirty path, one `await` each. The dirty-offset set grows one entry per distinct consumer per offset commit and is unbounded between checkpoints, because the only trigger is `capacity/2` bytes (`persistence.rs:434`). 10k consumers means 10k serial openat+fsync while this partition's ack (`iggy_partition.rs:4570`), `commit_journal` (`:4612`) and retention (`:6263`) all early-return -- a partition-wide freeze lasting O(distinct consumers touched) fsyncs.
   Fix: fan the fsyncs out in chunks like the superblock pre-pass, and trigger the checkpoint on dirty-file count as well as bytes. The count trigger also stops a low-occupancy WAL from never checkpointing.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {

Review Comment:
   warning: this loop fsyncs every ancestor directory up to the filesystem root, once per persisted partition open. Only `directory.parent()` is load-bearing after `create_directories`. At the default relative `path = "local_data"` that is 7 directory fsyncs per partition, 6 redundant, repeatedly re-syncing the same shared parents -- 7000 fsyncs at 1000 partitions; an absolute data root adds 4 more plus a fsync of `/` per partition.
   Also a narrow failure mode: `sync_directory` opens O_RDONLY, which needs `r` while traversal needs only `x`, so a mode-0711 ancestor gives EACCES and the partition never loads.
   Fix: sync the parent only.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {
+            self.storage
+                .open(path, OpenMode::Read)
+                .await?
+                .sync()
+                .await?;
+        }
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.state.anchor_known = checksum.is_some();
+        self.rewrite(op, checksum.unwrap_or(0), Some(0)).await
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation <= self.state.purge_generation {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short WAL prepare"))?,
+        )
+        .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+        if self
+            .entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+        {
+            return Ok(());
+        }
+        if header.op
+            != self
+                .state
+                .head
+                .checked_add(1)
+                .ok_or_else(|| invalid("WAL op exhausted"))?
+            || (self.state.anchor_known && header.parent != self.state.head_checksum)
+            || header.group != self.state.group
+        {
+            return Err(invalid("partition WAL append does not extend its history"));
+        }
+        let encoded = encode_record(prepare.as_slice(), self.state.generation)?;
+        let length = encoded.len();
+        if self.state.length + length as u64 > self.capacity {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL requires checkpoint",
+            ));
+        }
+        self.poisoned = true;
+        self.file.write(self.state.length, encoded).await?;
+        let state = JournalState {
+            length: self.state.length + length as u64,
+            head: header.op,
+            head_checksum: header.checksum,
+            checkpoint_checksum: if self.state.anchor_known {
+                self.state.checkpoint_checksum
+            } else {
+                header.parent
+            },
+            anchor_known: true,
+            ..self.state
+        };
+        self.entries.insert(
+            header.op,
+            StoredPrepare {
+                position: self.state.length,
+                length,
+                checksum: header.checksum,
+            },
+        );
+        self.state = state;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory)? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(&self, position: u64) -> io::Result<(PrepareHeader, usize, Frozen<4096>)> {
+        let prefix = self.file.read(position, RECORD_PREFIX).await?;

Review Comment:
   warning: recovery costs 2 io_uring reads per record (the 32-byte prefix here, the full record at `:506`, so the first 32 bytes are read twice), 2 zeroed `vec![0; n]` in `durable_storage.rs:164`, an `Owned::zeroed` + `copy_from_slice` at `:518`, and then `iggy_partition.rs:771` copies each record AGAIN into a fresh `Owned::zeroed` -- 4 allocations and 2 full copies per record, 32768 records at the 256 MiB default. `read_record` already holds a `Message<PrepareHeader>` before `into_frozen()`.
   This is the rejoin-to-quorum path, so recovery time is the SLO. Fix: one aligned read, return the `Message` already built, drop the second copy.



##########
core/journal/src/durable_storage.rs:
##########
@@ -0,0 +1,190 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use compio::fs::{File, OpenOptions};
+use compio::io::{AsyncReadAtExt, AsyncWriteAtExt};
+use std::ffi::OsString;
+use std::io;
+use std::path::Path;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OpenMode {
+    Read,
+    ReadWrite,
+    Create,
+}
+
+pub struct StorageEntry {
+    pub name: OsString,
+    pub directory: bool,
+}
+
+/// Filesystem operations whose completion and persistence order affect recovery.
+/// Implementations must preserve open file identity across rename and unlink.
+pub trait DurableStorage {
+    type File: DurableFile;
+
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn open(&self, path: &Path, mode: OpenMode) -> impl Future<Output = io::Result<Self::File>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn create_directories(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn sync_directory(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn rename(&self, source: &Path, target: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn remove_file(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn hard_link(&self, source: &Path, target: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn exists(&self, path: &Path) -> io::Result<bool>;

Review Comment:
   warning: `exists`, `entries` and `remove_tree` are declared sync in the trait and the impls use `try_exists`, `std::fs::read_dir` and `std::fs::remove_dir_all` (`:125`, `:129`, `:148`) -- blocking syscalls on a shard executor that has no blocking pool, locked in by the trait signature for every future caller. `partition_helpers.rs:576` already adds an unconditional per-partition blocking `stat` at boot via `install_backup::recover`, and a recursive `remove_dir_all` over a partition tree is an unbounded shard stall.
   Fix: make `exists` and `remove_tree` async over compio ops (`compio::fs::metadata` is a real io_uring `PathStat`; `remove_file`/`remove_dir` are async). `read_dir` has no async form in compio 0.12 -- keep it sync but restrict it to boot.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +720,292 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for prepare in prepares {
+            let mut owned = server_common::iobuf::Owned::<4096>::zeroed(prepare.len());
+            owned.as_mut_slice().copy_from_slice(prepare.as_slice());
+            let message =
+                Message::<PrepareHeader>::try_from(owned).map_err(|_| IggyError::InvalidCommand)?;
+            let header = *message.header();
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min();
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let directories = [
+            &self.partition_dir,
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        .map(std::path::PathBuf::from)
+        .collect();
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        let pending = std::mem::take(&mut *self.pending_persisted_acks.borrow_mut());
+        for header in pending.into_values() {
+            if self
+                .log
+                .journal()
+                .inner
+                .header_by_op(header.op)
+                .is_some_and(|current| current.checksum == header.checksum)
+            {
+                self.send_prepare_ok(&header).await;
+            }
+        }
+    }
+
+    const fn requires_persistence(&self, operation: Operation) -> bool {
+        match operation {
+            Operation::SendMessages => self.durability().is_persisted(),
+            Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset => {
+                self.consumer_offset_durability().is_persisted()
+            }
+            _ => false,
+        }
+    }
+
+    fn submit_prepare_persistence(&self, prepare: &Frozen<4096>, operation: Operation) -> bool {
+        let Some(persistence) = &self.persistence else {
+            return self.consensus.replica_count() == 1 || !self.requires_persistence(operation);
+        };
+        if let Err(error) =
+            persistence.append(prepare.clone(), self.requires_persistence(operation))
+        {
+            warn!(%error, namespace_raw = self.namespace().inner(), "partition WAL refused prepare");
+            return false;
+        }
+        self.start_persistence();
+        true
+    }
+
+    fn persist_repaired_prefix(&self) {
+        let Some(persistence) = &self.persistence else {
+            return;
+        };
+        while let Some(op) = persistence.head().checked_add(1) {
+            let Some(prepare) = self.log.journal().inner.repair_entry(op) else {
+                break;
+            };
+            if !persistence.has_capacity(prepare.len()) {

Review Comment:
   warning: `repair_entry` can hand back `Some(<zero-length Frozen>)` where its own doc promises `None` -- `journal.rs:268`/`:274` return `Owned::<4096>::zeroed(0)` on an `offset_to_index` miss. This break then treats it as capacity pressure: `has_capacity(0)` -> `record_length(0)` Err (0 < `size_of::<PrepareHeader>()`) -> silent truncation of the repair prefix at that op.
   That opens a permanent chain gap at LOW WAL occupancy, so unlike the capacity-rejection case already flagged at `:844`, `needs_checkpoint()` never fires and no fence follows -- the partition sits un-acked and un-fenced behind a single `warn!`. The sentinel is pre-existing (`journal.rs` is untouched here); this is the first consumer that makes it load-bearing.
   Fix: return `None` on a miss, and assert non-empty here rather than folding it into the capacity break.



##########
core/shard/src/lib.rs:
##########
@@ -4131,8 +4152,18 @@ where
             stats,
             consensus,
             partitions.config().segment_size,
-            partitions.config().consumer_offset_enforce_fsync,
         );
+        let runtime_options = self.plane.metadata().mux_stm.streams().read(|inner| {

Review Comment:
   warning: this materialisation reads `TopicRuntimeOptions` including `durability` but never calls `open_persistence*`, so a multi-replica persisted topic gets `persistence == None`: `submit_prepare_persistence` returns false, `send_prepare_ok` parks the ack in `pending_persisted_acks`, and `drive_persistence` returns early on `None` and never drains it -- a silent permanent wedge with no `fatal` and no log.
   Same root closes a coverage gap: `open_persistence*` has exactly two callers repo-wide, both in `partition_helpers.rs`, so everything above `PartitionPersistence` (ack parking, the drain, `accepts_completion`, router delivery, multi-replica quorum) is unreachable from the simulator, not merely untested -- which is the band the chain-forwarding and fencing defects live in. The 983 new lines in `simulator/src/storage/tests.rs` do cover the layer below.
   Fix: wire `PartitionPersistence<SimStorage>` into `init_partition`, or hard-reject `Durability::Persisted` there so the wedge becomes loud.



##########
core/simulator/src/storage.rs:
##########
@@ -0,0 +1,496 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Deterministic filesystem model for persistence ordering and power-loss tests.
+
+#![allow(clippy::future_not_send)]
+
+use journal::durable_storage::{DurableFile, DurableStorage, OpenMode, StorageEntry};
+use std::cell::RefCell;
+use std::collections::BTreeMap;
+use std::ffi::OsString;
+use std::io;
+use std::path::{Component, Path};
+use std::rc::Rc;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Crash {
+    Process,
+    PowerLoss,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FaultMode {
+    Before,
+    After,
+    TornWrite,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StorageOperation {
+    Open,
+    Create,
+    Read,
+    Write,
+    Length,
+    Truncate,
+    FileSync,
+    CreateDirectory,
+    DirectorySync,
+    Rename,
+    Unlink,
+    Link,
+    Exists,
+    List,
+    RemoveTree,
+}
+
+#[derive(Clone, Default)]
+pub struct SimStorage {
+    state: Rc<RefCell<State>>,
+}
+
+pub struct SimFile {
+    storage: SimStorage,
+    inode: usize,
+    epoch: u64,
+}
+
+#[derive(Clone)]
+enum Inode {
+    File {
+        buffered: Vec<u8>,
+        stable: Vec<u8>,
+    },
+    Directory {
+        entries: BTreeMap<OsString, usize>,
+        stable: BTreeMap<OsString, usize>,
+    },
+}
+
+#[derive(Clone)]
+struct State {
+    inodes: Vec<Inode>,
+    epoch: u64,
+    trace: Vec<StorageOperation>,
+    fault: Option<(usize, FaultMode)>,
+    paused: bool,
+    waiters: Vec<std::task::Waker>,
+}
+
+impl SimStorage {
+    #[must_use]
+    pub fn trace(&self) -> Vec<StorageOperation> {
+        self.state.borrow().trace.clone()
+    }
+
+    pub fn clear_trace(&self) {
+        let mut state = self.state.borrow_mut();
+        state.trace.clear();
+        state.fault = None;
+    }
+
+    pub fn fail_at(&self, operation: usize, mode: FaultMode) {
+        let mut state = self.state.borrow_mut();
+        state.trace.clear();
+        state.fault = Some((operation, mode));
+    }
+
+    /// A process restart preserves the OS cache. Power loss discards it.
+    /// Every restart invalidates open handles owned by the old process.
+    pub fn crash(&self, crash: Crash) {
+        let mut state = self.state.borrow_mut();
+        state.epoch += 1;
+        if crash == Crash::PowerLoss {
+            for inode in &mut state.inodes {
+                match inode {
+                    Inode::File { buffered, stable } => buffered.clone_from(stable),
+                    Inode::Directory { entries, stable } => entries.clone_from(stable),
+                }
+            }
+        }
+        state.trace.clear();
+        state.fault = None;
+    }
+
+    /// Model background writeback without attributing a durability barrier to it.
+    pub fn writeback(&self) {
+        for inode in &mut self.state.borrow_mut().inodes {
+            match inode {
+                Inode::File { buffered, stable } => stable.clone_from(buffered),
+                Inode::Directory { entries, stable } => stable.clone_from(entries),
+            }
+        }
+    }
+
+    pub fn pause_writes(&self) {
+        self.state.borrow_mut().paused = true;
+    }
+
+    pub fn resume_writes(&self) {
+        let waiters = {
+            let mut state = self.state.borrow_mut();
+            state.paused = false;
+            std::mem::take(&mut state.waiters)
+        };
+        for waiter in waiters {
+            waiter.wake();
+        }
+    }
+
+    async fn wait_for_write(&self) {
+        futures::future::poll_fn(|context| {
+            let mut state = self.state.borrow_mut();
+            if !state.paused {
+                return std::task::Poll::Ready(());
+            }
+            if !state
+                .waiters
+                .iter()
+                .any(|waiter| waiter.will_wake(context.waker()))
+            {
+                state.waiters.push(context.waker().clone());
+            }
+            std::task::Poll::Pending
+        })
+        .await;
+    }
+
+    fn perform<T>(
+        &self,
+        operation: StorageOperation,
+        action: impl FnOnce(&mut State, bool) -> io::Result<T>,
+    ) -> io::Result<T> {
+        let mut state = self.state.borrow_mut();
+        let index = state.trace.len();
+        state.trace.push(operation);
+        let mode = state
+            .fault
+            .filter(|(at, _)| *at == index)
+            .map(|(_, mode)| mode);
+        if state.fault.is_some_and(|(at, _)| index > at) || mode == Some(FaultMode::Before) {
+            return Err(io::Error::other("injected storage failure"));
+        }
+        let result = action(&mut state, mode == Some(FaultMode::TornWrite))?;
+        if mode.is_some() {
+            return Err(io::Error::other("injected failure after storage effect"));
+        }
+        Ok(result)
+    }
+}
+
+impl DurableStorage for SimStorage {
+    type File = SimFile;
+
+    async fn open(&self, path: &Path, mode: OpenMode) -> io::Result<SimFile> {
+        let operation = if mode == OpenMode::Create {
+            StorageOperation::Create
+        } else {
+            StorageOperation::Open
+        };
+        let (inode, epoch) = self.perform(operation, |state, _| {
+            let inode = if mode == OpenMode::Create {
+                let (parent, name) = state.parent(path)?;
+                if let Some(&inode) = state.directory(parent)?.get(&name) {
+                    match &mut state.inodes[inode] {
+                        Inode::File { buffered, .. } => buffered.clear(),
+                        Inode::Directory { .. } => {
+                            return Err(invalid("cannot truncate directory"));
+                        }
+                    }
+                    inode
+                } else {
+                    let inode = state.inodes.len();
+                    state.inodes.push(Inode::File {
+                        buffered: Vec::new(),
+                        stable: Vec::new(),
+                    });
+                    state.directory_mut(parent)?.insert(name, inode);
+                    inode
+                }
+            } else {
+                state.lookup(path)?
+            };
+            Ok((inode, state.epoch))
+        })?;
+        Ok(SimFile {
+            storage: self.clone(),
+            inode,
+            epoch,
+        })
+    }
+
+    async fn create_directories(&self, path: &Path) -> io::Result<()> {
+        self.perform(StorageOperation::CreateDirectory, |state, _| {
+            let mut parent = 0;
+            for name in components(path)? {
+                parent = if let Some(&inode) = state.directory(parent)?.get(&name) {
+                    inode
+                } else {
+                    let inode = state.inodes.len();
+                    state.inodes.push(Inode::directory());
+                    state.directory_mut(parent)?.insert(name, inode);
+                    inode
+                };
+                state.directory(parent)?;
+            }
+            Ok(())
+        })
+    }
+
+    async fn sync_directory(&self, path: &Path) -> io::Result<()> {
+        self.perform(StorageOperation::DirectorySync, |state, _| {
+            let inode = state.lookup(path)?;
+            match &mut state.inodes[inode] {
+                Inode::Directory { entries, stable } => stable.clone_from(entries),
+                Inode::File { .. } => return Err(invalid("directory sync on a file")),
+            }
+            Ok(())
+        })
+    }
+
+    async fn rename(&self, source: &Path, target: &Path) -> io::Result<()> {

Review Comment:
   warning: the model is more permissive than `DiskStorage` on exactly the operations `install_backup` commits with. `rename` inserts over an existing target unconditionally, where real `rename(2)` returns ENOTEMPTY onto a non-empty directory -- precisely the BACKUP->RETIRED rename with a leftover RETIRED, which succeeds in the model and fails on disk. `remove_tree` at `:328` unlinks a subtree in one atomic map edit where `remove_dir_all` can fail partway, the state `recover_with_storage` must be idempotent over, and `SimFile::sync` models fsync while `DiskStorage` uses `sync_data`, so a missing directory barrier reads as durable.
   With the fault schedule at `:185` also unable to express a transient EIO/ENOSPC followed by success, `install_backup` has no faithful crash coverage on either axis. Fix: reject directory-onto-nonempty-directory renames, model partial `remove_tree` failure, distinguish `sync_data`, and make the injected fault one-shot.



##########
core/configs/src/configs_impl/file_provider.rs:
##########
@@ -30,12 +30,9 @@ const DISPLAY_CONFIG_ENV: &str = "IGGY_DISPLAY_CONFIG";
 
 /// A config key that no longer exists, and what took over from it.
 ///
-/// Nothing else catches such a key. Its struct field is gone and no config
-/// table sets `deny_unknown_fields`, so figment drops an unrecognized key
-/// without a word from either source: a server still carrying
-/// `enforce_fsync = true` would boot reporting success and run without fsync.
-/// Every relocated key used to change behavior, so the boot is refused rather
-/// than warned about.
+/// Reject obsolete keys explicitly, including environment variables that the
+/// typed provider would otherwise ignore. These entries are rejection rules,
+/// never accepted mappings or compatibility aliases.
 #[derive(Debug, Clone, Copy)]
 pub struct RelocatedKey {

Review Comment:
   warning: `RelocatedKey` has no moved-to-root variant, so the flatten migration's only operator message is "the feature it configured was removed". An operator with `[system] path = "/data"` is told the data-path feature is gone, when it was relocated to root `path`. Same for the encryption key and the sharding table.
   Fix: add a `MovedTo(&'static str)` arm and name the new root key per relocated table, so the message says where the setting went.



##########
core/server/src/responses.rs:
##########
@@ -1063,11 +1063,16 @@ fn topic_option_descriptors() -> Result<Vec<OptionDescriptor>, IggyError> {
             ),
         },
         OptionDescriptor {
-            key: WireName::new(topic_option_keys::ENFORCE_FSYNC)
-                .map_err(|_| IggyError::InvalidFormat)?,
-            kind: HeaderKind::Bool.as_code(),
-            default_value: Bytes::copy_from_slice(&[u8::from(iggy_common::DEFAULT_ENFORCE_FSYNC)]),
-            description: "Whether writes to this topic's partitions fsync".to_string(),
+            key: WireName::new(topic_option_keys::DURABILITY).map_err(|_| IggyError::InvalidFormat)?,
+            kind: HeaderKind::String.as_code(),
+            default_value: Bytes::from_static(b"replicated"),
+            description: "Message completion: replicated or persisted. Independently defaults to replicated. A singleton quorum has one copy.".to_string(),
+        },
+        OptionDescriptor {
+            key: WireName::new(topic_option_keys::CONSUMER_OFFSET_DURABILITY).map_err(|_| IggyError::InvalidFormat)?,
+            kind: HeaderKind::String.as_code(),
+            default_value: Bytes::from_static(b"replicated"),

Review Comment:
   warning: these two descriptions say only "Independently defaults to replicated", and they are what `iggy options topic`, `GET /options/topic` and every SDK `describe_options` actually serve -- so this is the doc surface an operator reads, ahead of `config.toml`.
   Missing from both: selecting `persisted` for the offset policy alone engages the message WAL for full message bodies, spending `wal_bytes_max` on payloads. An operator currently reads offset-sized records and gets batch-sized ones.
   Fix: state the pairing's cost in both descriptions.



##########
scripts/performance/run-standard-performance-suite.sh:
##########
@@ -68,21 +68,21 @@ get_env_vars() {
 
     # Specific env vars based on bench type
     case "$bench_type" in
-    # fsync is a topic creation option (`enforce_fsync`) now, not server config,
-    # so the bench command carries `--enforce-fsync` (added by
+    # Durability is a topic creation option, so the bench command carries
+    # `--durability persisted` (added by
     # `construct_bench_command` off the same remark) and only the cache setting
     # is left to the server environment.
     *"no_cache_fsync"*)
-        env_vars+=("IGGY_SYSTEM_CACHE_ENABLED=false")
+        env_vars+=("IGGY_CACHE_ENABLED=false")

Review Comment:
   warning: these renamed variables name config sections that do not exist -- `ServerConfig` has no `cache` or `segment` section -- so `no_cache`, `only_cache`, `no_wait` and `no_cache_fsync` all run with identical defaults and have been publishing baseline numbers, making every cache-mode comparison from this suite meaningless.
   Pre-existing: on the merge base `SegmentConfig` held only `archive_expired` and there was no `cache` section either, so the rename preserved a no-op instead of removing it.
   Fix: delete the dead variables -- there is no live key to repoint them at.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -4143,6 +4476,9 @@ where
             }
         };
 
+        if !self.submit_prepare_persistence(&frozen_for_forward, header.operation) {
+            return;

Review Comment:
   critical: this WAL refusal returns BEFORE `replicate_frozen_to_next_in_chain` at `:4495` (same shape at `:4297`), so one replica's local disk admission withholds the prepare from every replica behind it in the chain -- `plane_helpers.rs:170` is next-hop, not broadcast. `wal_bytes_max` is per-node config and never replicated, so a mid-chain replica at the 64 MiB minimum starves a quorum that did not need it. This contradicts the PR description's "forward prepares before waiting for local persistence", and is distinct from the sequencer-gap comment on the line above.
   Fix: forward first, then gate only the local ack -- `send_prepare_ok`'s `pending_persisted_acks` gate already assumes a forwarded-but-unpersisted prepare. Separately, this arm only `warn!`s where the sibling at `:4425` sets `fatal` for the same reason; on a size refusal the WAL stays under `capacity/2`, so `needs_checkpoint()` never fires and no fence ever arrives.



##########
core/integration/src/harness/config/resolve.rs:
##########
@@ -69,10 +69,7 @@ pub fn resolve_config_paths(
                 env_vars.insert(m.env_name.to_string(), value.clone());
 
                 // Track if encryption key is set (auto-enable encryption)
-                if path == "encryption"
-                    || path == "encryption.key"
-                    || path == "system.encryption.key"
-                {
+                if path == "encryption" || path == "encryption.key" || path == "encryption.key" {

Review Comment:
   warning: the mechanical rename left a duplicated clause -- `path == "encryption.key"` appears twice (the third term was `"system.encryption.key"`).
   This blocks CI: `clippy::nonminimal_bool` is warn-by-default and fires here, and `.github/actions/rust/pre-merge/action.yml:203` runs `cargo clippy --all-targets --all-features -- -D warnings` workspace-wide with no `--exclude`; `core/integration` is a member and carries no `allow`. Verification step 3 fails as submitted.
   Fix: drop the third clause.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {

Review Comment:
   warning: bare `?` on `open(OpenMode::Read)` makes ENOENT terminal -- it latches `PartitionPersistence.failure` (`persistence.rs:560`), `start()` then refuses forever (`:502`), and `drive_persistence` converts that into `fatal` -> node shutdown. A path that no longer exists holds no unsynced bytes, so this fails closed in the wrong direction over one match arm. The `directories` list at `iggy_partition.rs:889` is built from three `Option<String>` with no existence check at all, and `sync_directory` at `:311` has the same bare `?`.
   Fix: tolerate `NotFound` per path, for files and those directories alike.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,774 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableStorage};
+use journal::partition_journal::PARTITION_WAL_BYTES_MAX;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation {
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        let journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+        )
+        .await?;
+        let prepares = journal.prepares().await?;
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare_header(prepare)?;
+            accepted.checksums.push_back(header.checksum);
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.accepted.borrow().checksum(header.op) == Some(header.checksum)
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .disk_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn mark_offset_dirty(&self, kind_index: usize, consumer_id: u32, exists: bool) {
+        let mut offsets = self.dirty_offsets[kind_index].borrow_mut();
+        if exists {
+            offsets.insert(consumer_id);
+        } else {
+            offsets.remove(&consumer_id);
+        }
+    }
+
+    pub fn take_dirty_files(&self) -> (BTreeSet<u64>, [BTreeSet<u32>; 2]) {
+        (
+            std::mem::take(&mut *self.dirty_segments.borrow_mut()),
+            std::array::from_fn(|index| {
+                std::mem::take(&mut *self.dirty_offsets[index].borrow_mut())
+            }),
+        )
+    }
+
+    pub fn checkpoint(&self, through_op: u64) {
+        self.checkpoint_files(through_op, Vec::new(), Vec::new());
+    }
+
+    pub fn checkpoint_files(
+        &self,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    ) {
+        if through_op <= self.checkpoint_requested.get() {
+            return;
+        }
+        self.checkpoint_requested.set(through_op);
+        self.queue.borrow_mut().push_back(Mutation::Checkpoint {
+            epoch: self.epoch.get(),
+            through_op,
+            files,
+            directories,
+        });
+    }
+
+    pub const fn checkpoint_pending(&self) -> bool {
+        self.checkpoint_running.get() || self.checkpoint_requested.get() > self.checkpoint.get()
+    }
+
+    pub fn truncate_from(&self, from_op: u64) {
+        if from_op > self.accepted_head.get() {
+            return;
+        }
+        self.checkpoint_requested.set(self.checkpoint.get());
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        // Retained submissions still precede the replacement history.
+        self.queue
+            .borrow_mut()
+            .retain_mut(|mutation| match mutation {
+                Mutation::Append {
+                    epoch: previous,
+                    prepare,
+                    bytes,
+                    ..
+                } => {
+                    if prepare_header(prepare).is_ok_and(|header| header.op < from_op) {
+                        *previous = epoch;
+                        true
+                    } else {
+                        self.queued_bytes
+                            .set(self.queued_bytes.get().saturating_sub(*bytes));
+                        false
+                    }
+                }
+                Mutation::Checkpoint {
+                    epoch: previous,
+                    through_op,
+                    ..
+                } if *through_op < from_op => {
+                    *previous = epoch;
+                    self.checkpoint_requested
+                        .set(self.checkpoint_requested.get().max(*through_op));
+                    true
+                }
+                _ => false,
+            });
+        self.accepted.borrow_mut().truncate_from(from_op);
+        self.accepted_head.set(from_op.saturating_sub(1));
+        self.durable_head
+            .set(self.durable_head.get().min(from_op.saturating_sub(1)));
+        self.queue
+            .borrow_mut()
+            .push_back(Mutation::Truncate { epoch, from_op });
+    }
+
+    pub fn reset(&self, op: u64, checksum: Option<u128>) {
+        self.checkpoint_requested.set(op);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        self.queue.borrow_mut().clear();
+        self.queued_bytes.set(0);
+        *self.accepted.borrow_mut() = AcceptedPrepares {
+            base: op,
+            checksums: VecDeque::new(),
+        };
+        self.accepted_head.set(op);
+        self.durable_head.set(0);
+        self.queue.borrow_mut().push_back(Mutation::Reset {
+            epoch,
+            op,
+            checksum,
+        });
+    }
+
+    pub fn mark_purge(&self, generation: u64, floor: u64) {
+        self.queue.borrow_mut().push_back(Mutation::Purge {
+            epoch: self.epoch.get(),
+            generation,
+            floor,
+        });
+    }
+
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.purge_generation.get(), self.purge_floor.get())
+    }
+
+    pub const fn needs_checkpoint(&self) -> bool {
+        !self.checkpoint_pending()
+            && self.disk_bytes.get() + self.queued_bytes.get() + self.in_flight_bytes.get()
+                >= self.capacity / 2
+    }
+
+    pub fn take_metrics(&self) -> PersistenceMetrics {
+        PersistenceMetrics {
+            disk_bytes: self.disk_bytes.get(),
+            queued_bytes: self.queued_bytes.get(),
+            in_flight_bytes: self.in_flight_bytes.get(),
+            checkpoints_pending: u64::from(self.checkpoint_pending()),
+            completed_batches: self.completed_batches.replace(0),
+            batched_prepares: self.batched_prepares.replace(0),
+            completed_checkpoints: self.completed_checkpoints.replace(0),
+            failed_writes: self.failed_writes.replace(0),
+        }
+    }
+
+    pub fn failure(&self) -> Option<Arc<io::Error>> {
+        self.failure.borrow().clone()
+    }
+
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.checkpoint.get()
+    }
+
+    pub fn checksum(&self, op: u64) -> Option<u128> {
+        if op == self.checkpoint.get() {
+            self.checkpoint_checksum.get()
+        } else {
+            self.accepted.borrow().checksum(op)
+        }
+    }
+
+    pub const fn head(&self) -> u64 {
+        self.accepted_head.get()
+    }
+
+    pub fn retire(&self) {

Review Comment:
   critical: `retire()` sets the flag and clears the queue, but cannot stop a mutation already dequeued and suspended inside `journal.publish()`'s `file.sync()` -- the journal was moved out at `:508` and is unreachable from `&self`, and `run()` tests `retired` only at each iteration top (`:513`). `Drop` cannot await, and the quarantine rebuild reopens the same `prepares-{created_revision}` with no join. Worse, `rewrite` unlinks the superseded generation (`partition_journal.rs:602`), so the resurrected frontier can name a `.wal` that no longer exists -> `open(.., ReadWrite)` NotFound -> boot refuses the partition. The documented rebuild path becomes the thing that bricks it.
   Fix: a join handle / RAII guard on `run()` that restores `journal` + `running` and wakes waiters on drop. Same primitive closes the `:508` gap.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,980 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use iggy_binary_protocol::{Command, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use std::collections::BTreeMap;
+use std::io;
+use std::path::{Path, PathBuf};
+use twox_hash::XxHash3_64;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 64 * 1024 * 1024 + 4096;
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    purge_generation: u64,
+    purge_floor: u64,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        let mut ancestor = directory;
+        while let Some(parent) = ancestor.parent() {
+            if parent.as_os_str().is_empty() {
+                break;
+            }
+            storage.sync_directory(parent).await?;
+            ancestor = parent;
+        }
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+        };
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, _) = journal.read_record(position).await?;
+            if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            journal.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        Ok(journal)
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Frozen<4096>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+        )
+        .await
+    }
+
+    /// Synchronize materialized files before removing their WAL coverage.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        for path in files {
+            self.storage
+                .open(path, OpenMode::Read)
+                .await?
+                .sync()
+                .await?;
+        }
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.state.anchor_known = checksum.is_some();
+        self.rewrite(op, checksum.unwrap_or(0), Some(0)).await
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation <= self.state.purge_generation {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short WAL prepare"))?,
+        )
+        .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+        if self
+            .entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+        {
+            return Ok(());
+        }
+        if header.op
+            != self
+                .state
+                .head
+                .checked_add(1)
+                .ok_or_else(|| invalid("WAL op exhausted"))?
+            || (self.state.anchor_known && header.parent != self.state.head_checksum)
+            || header.group != self.state.group
+        {
+            return Err(invalid("partition WAL append does not extend its history"));
+        }
+        let encoded = encode_record(prepare.as_slice(), self.state.generation)?;
+        let length = encoded.len();
+        if self.state.length + length as u64 > self.capacity {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL requires checkpoint",
+            ));
+        }
+        self.poisoned = true;
+        self.file.write(self.state.length, encoded).await?;
+        let state = JournalState {
+            length: self.state.length + length as u64,
+            head: header.op,
+            head_checksum: header.checksum,
+            checkpoint_checksum: if self.state.anchor_known {
+                self.state.checkpoint_checksum
+            } else {
+                header.parent
+            },
+            anchor_known: true,
+            ..self.state
+        };
+        self.entries.insert(
+            header.op,
+            StoredPrepare {
+                position: self.state.length,
+                length,
+                checksum: header.checksum,
+            },
+        );
+        self.state = state;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory)? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(&self, position: u64) -> io::Result<(PrepareHeader, usize, Frozen<4096>)> {
+        let prefix = self.file.read(position, RECORD_PREFIX).await?;
+        let frame_length = u32::from_le_bytes(
+            prefix[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut bytes = self.file.read(position, length).await?;
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let mut owned = Owned::<4096>::zeroed(frame_length);
+        owned
+            .as_mut_slice()
+            .copy_from_slice(&bytes[RECORD_PREFIX..RECORD_PREFIX + frame_length]);
+        let message = Message::<PrepareHeader>::try_from(owned)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != frame_length
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        Ok((header, length, message.into_frozen()))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            ..self.state
+        };
+        for (&op, entry) in &self.entries {
+            if op <= checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let prepare = self.read_record(entry.position).await?.2;
+            let encoded = encode_record(prepare.as_slice(), generation)?;
+            let length = encoded.len();
+            file.write(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                },
+            );
+            state.length += length as u64;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.poisoned = false;
+        if let Err(error) = self.storage.remove_file(&obsolete).await {
+            tracing::warn!(%error, "failed to remove superseded partition WAL file");
+        }
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(STATE_MAGIC);
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);
+        bytes[8..16].copy_from_slice(&checksum.to_le_bytes());
+        bytes
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != PARTITION_WAL_BLOCK_SIZE || &bytes[..8] != STATE_MAGIC {
+            return Err(invalid("unknown partition WAL frontier format"));
+        }
+        let read_u64 = |offset| -> io::Result<u64> {
+            Ok(u64::from_le_bytes(
+                bytes[offset..offset + 8]
+                    .try_into()
+                    .map_err(|_| invalid("invalid WAL frontier field"))?,
+            ))
+        };
+        if read_u64(8)? != XxHash3_64::oneshot(&bytes[16..]) {
+            return Err(invalid("partition WAL frontier checksum mismatch"));
+        }
+        let state = Self {
+            group: read_u64(16)?,
+            incarnation: read_u64(24)?,
+            generation: read_u64(32)?,
+            length: read_u64(40)?,
+            checkpoint: read_u64(48)?,
+            head: read_u64(72)?,
+            anchor_known: match bytes[96] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid WAL anchor flag")),
+            },
+            purge_generation: read_u64(104)?,
+            purge_floor: read_u64(112)?,
+            checkpoint_checksum: u128::from_le_bytes(
+                bytes[56..72]
+                    .try_into()
+                    .map_err(|_| invalid("invalid checkpoint checksum"))?,
+            ),
+            head_checksum: u128::from_le_bytes(
+                bytes[80..96]
+                    .try_into()
+                    .map_err(|_| invalid("invalid head checksum"))?,
+            ),
+        };
+        if state.length > PARTITION_WAL_CAPACITY_MAX
+            || !state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+            || state.head < state.checkpoint
+            || (!state.anchor_known && state.head != state.checkpoint)
+        {
+            return Err(invalid("invalid partition WAL frontier bounds"));
+        }
+        Ok(state)
+    }
+}
+
+/// Padded size of a prepare record, including its envelope.
+///
+/// # Errors
+/// Returns an error for a frame outside the protocol size bounds.
+pub fn record_length(frame_length: usize) -> io::Result<usize> {
+    if !(size_of::<PrepareHeader>()..=PREPARE_BYTES_MAX).contains(&frame_length) {
+        return Err(invalid("partition WAL prepare length out of bounds"));
+    }
+    Ok((RECORD_PREFIX + frame_length).next_multiple_of(PARTITION_WAL_BLOCK_SIZE))
+}
+
+fn encode_record(prepare: &[u8], generation: u64) -> io::Result<Vec<u8>> {
+    let mut bytes = vec![0; record_length(prepare.len())?];

Review Comment:
   warning: `encode_record` allocates a plain unaligned `vec![0; ..]` for a WAL that is strictly 4096-aligned, so there is no O_DIRECT path for the Direct I/O backend the PR description names as a design goal. `XxHash3_64::oneshot` at `:713` then hashes the zero padding as well as the record.
   Separately, a ~288-byte `StoreConsumerOffset` prepare occupies a full 4096-byte record, ~14x write amplification per offset commit under `consumer_offset_durability = persisted`.
   Fix: allocate via `Owned<4096>` and hash only the meaningful prefix. Do NOT pack sub-block records -- that would break the `state.length.is_multiple_of(4096)` decode gate at `:686` and make the WAL non-append-only at sector granularity, so one torn block could destroy already-acked data. A multi-op record (N prepares in one aligned record) is the safe way to cut the amplification.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,774 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableStorage};
+use journal::partition_journal::PARTITION_WAL_BYTES_MAX;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation {
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        let journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+        )
+        .await?;
+        let prepares = journal.prepares().await?;
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare_header(prepare)?;
+            accepted.checksums.push_back(header.checksum);
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.accepted.borrow().checksum(header.op) == Some(header.checksum)
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .disk_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn mark_offset_dirty(&self, kind_index: usize, consumer_id: u32, exists: bool) {
+        let mut offsets = self.dirty_offsets[kind_index].borrow_mut();
+        if exists {
+            offsets.insert(consumer_id);
+        } else {
+            offsets.remove(&consumer_id);
+        }
+    }
+
+    pub fn take_dirty_files(&self) -> (BTreeSet<u64>, [BTreeSet<u32>; 2]) {
+        (
+            std::mem::take(&mut *self.dirty_segments.borrow_mut()),
+            std::array::from_fn(|index| {
+                std::mem::take(&mut *self.dirty_offsets[index].borrow_mut())
+            }),
+        )
+    }
+
+    pub fn checkpoint(&self, through_op: u64) {
+        self.checkpoint_files(through_op, Vec::new(), Vec::new());
+    }
+
+    pub fn checkpoint_files(
+        &self,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    ) {
+        if through_op <= self.checkpoint_requested.get() {
+            return;
+        }
+        self.checkpoint_requested.set(through_op);
+        self.queue.borrow_mut().push_back(Mutation::Checkpoint {
+            epoch: self.epoch.get(),
+            through_op,
+            files,
+            directories,
+        });
+    }
+
+    pub const fn checkpoint_pending(&self) -> bool {
+        self.checkpoint_running.get() || self.checkpoint_requested.get() > self.checkpoint.get()
+    }
+
+    pub fn truncate_from(&self, from_op: u64) {
+        if from_op > self.accepted_head.get() {
+            return;
+        }
+        self.checkpoint_requested.set(self.checkpoint.get());
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        // Retained submissions still precede the replacement history.
+        self.queue
+            .borrow_mut()
+            .retain_mut(|mutation| match mutation {
+                Mutation::Append {
+                    epoch: previous,
+                    prepare,
+                    bytes,
+                    ..
+                } => {
+                    if prepare_header(prepare).is_ok_and(|header| header.op < from_op) {
+                        *previous = epoch;
+                        true
+                    } else {
+                        self.queued_bytes
+                            .set(self.queued_bytes.get().saturating_sub(*bytes));
+                        false
+                    }
+                }
+                Mutation::Checkpoint {
+                    epoch: previous,
+                    through_op,
+                    ..
+                } if *through_op < from_op => {
+                    *previous = epoch;
+                    self.checkpoint_requested
+                        .set(self.checkpoint_requested.get().max(*through_op));
+                    true
+                }
+                _ => false,
+            });
+        self.accepted.borrow_mut().truncate_from(from_op);
+        self.accepted_head.set(from_op.saturating_sub(1));
+        self.durable_head
+            .set(self.durable_head.get().min(from_op.saturating_sub(1)));
+        self.queue
+            .borrow_mut()
+            .push_back(Mutation::Truncate { epoch, from_op });
+    }
+
+    pub fn reset(&self, op: u64, checksum: Option<u128>) {
+        self.checkpoint_requested.set(op);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        self.queue.borrow_mut().clear();
+        self.queued_bytes.set(0);
+        *self.accepted.borrow_mut() = AcceptedPrepares {
+            base: op,
+            checksums: VecDeque::new(),
+        };
+        self.accepted_head.set(op);
+        self.durable_head.set(0);
+        self.queue.borrow_mut().push_back(Mutation::Reset {
+            epoch,
+            op,
+            checksum,
+        });
+    }
+
+    pub fn mark_purge(&self, generation: u64, floor: u64) {
+        self.queue.borrow_mut().push_back(Mutation::Purge {
+            epoch: self.epoch.get(),
+            generation,
+            floor,
+        });
+    }
+
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.purge_generation.get(), self.purge_floor.get())
+    }
+
+    pub const fn needs_checkpoint(&self) -> bool {
+        !self.checkpoint_pending()
+            && self.disk_bytes.get() + self.queued_bytes.get() + self.in_flight_bytes.get()
+                >= self.capacity / 2
+    }
+
+    pub fn take_metrics(&self) -> PersistenceMetrics {
+        PersistenceMetrics {
+            disk_bytes: self.disk_bytes.get(),
+            queued_bytes: self.queued_bytes.get(),
+            in_flight_bytes: self.in_flight_bytes.get(),
+            checkpoints_pending: u64::from(self.checkpoint_pending()),
+            completed_batches: self.completed_batches.replace(0),
+            batched_prepares: self.batched_prepares.replace(0),
+            completed_checkpoints: self.completed_checkpoints.replace(0),
+            failed_writes: self.failed_writes.replace(0),
+        }
+    }
+
+    pub fn failure(&self) -> Option<Arc<io::Error>> {
+        self.failure.borrow().clone()
+    }
+
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.checkpoint.get()
+    }
+
+    pub fn checksum(&self, op: u64) -> Option<u128> {
+        if op == self.checkpoint.get() {
+            self.checkpoint_checksum.get()
+        } else {
+            self.accepted.borrow().checksum(op)
+        }
+    }
+
+    pub const fn head(&self) -> u64 {
+        self.accepted_head.get()
+    }
+
+    pub fn retire(&self) {
+        self.retired.set(true);
+        self.queue.borrow_mut().clear();
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn drain(&self) -> io::Result<()> {
+        futures::future::poll_fn(|context| {
+            if let Some(error) = self.failure() {
+                return std::task::Poll::Ready(Err(io::Error::new(error.kind(), error)));
+            }
+            if !self.running.get() && self.queue.borrow().is_empty() {
+                return std::task::Poll::Ready(Ok(()));
+            }
+            let mut waiters = self.waiters.borrow_mut();
+            if !waiters
+                .iter()
+                .any(|waiter| waiter.will_wake(context.waker()))
+            {
+                waiters.push(context.waker().clone());
+            }
+            std::task::Poll::Pending
+        })
+        .await
+    }
+
+    pub fn start(&self) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && !self.queue.borrow().is_empty()
+            && !self.running.replace(true)
+    }
+
+    pub async fn run(self: Rc<Self>) {
+        let Some(mut journal) = self.journal.borrow_mut().take() else {

Review Comment:
   warning: this is the only `run()` exit that clears `running` without waking `waiters` (every other exit wakes at `:587`) -- an unpaired invariant in the one place a stuck caller cannot recover from.
   Separately, `drain()` has no timeout while being awaited under the partition `write_lock` (`iggy_partition.rs:4944`, `:6750`, `state_transfer.rs:2539`), so a stalled device fsync blocks every write path on that partition with none of the watchdog the repo arms for exactly this shape at `shard/router.rs:270`.
   Fix: an RAII/join guard that restores `journal` + `running` and wakes waiters on drop -- the same primitive the `retire()` race needs.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,6 +720,292 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = PartitionPersistence::open_with_capacity(
+            &directory,
+            self.namespace().inner(),
+            self.created_revision,
+            journal::durable_storage::DiskStorage,
+            capacity,
+        )
+        .await
+        .map_err(|error| {
+            warn!(%error, "cannot open partition prepare WAL");
+            IggyError::CannotReadFile
+        })?;
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for prepare in prepares {
+            let mut owned = server_common::iobuf::Owned::<4096>::zeroed(prepare.len());
+            owned.as_mut_slice().copy_from_slice(prepare.as_slice());
+            let message =
+                Message::<PrepareHeader>::try_from(owned).map_err(|_| IggyError::InvalidCommand)?;
+            let header = *message.header();
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min();
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.flush_committed_messages(config).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let directories = [
+            &self.partition_dir,
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        .map(std::path::PathBuf::from)
+        .collect();
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        let pending = std::mem::take(&mut *self.pending_persisted_acks.borrow_mut());
+        for header in pending.into_values() {
+            if self
+                .log
+                .journal()
+                .inner
+                .header_by_op(header.op)
+                .is_some_and(|current| current.checksum == header.checksum)
+            {
+                self.send_prepare_ok(&header).await;
+            }
+        }
+    }
+
+    const fn requires_persistence(&self, operation: Operation) -> bool {
+        match operation {
+            Operation::SendMessages => self.durability().is_persisted(),
+            Operation::StoreConsumerOffset | Operation::DeleteConsumerOffset => {
+                self.consumer_offset_durability().is_persisted()
+            }
+            _ => false,
+        }
+    }
+
+    fn submit_prepare_persistence(&self, prepare: &Frozen<4096>, operation: Operation) -> bool {
+        let Some(persistence) = &self.persistence else {
+            return self.consensus.replica_count() == 1 || !self.requires_persistence(operation);
+        };
+        if let Err(error) =

Review Comment:
   warning: `append` is unconditional whenever persistence exists and only the `durable` sync flag is policy-gated, while persistence opens if EITHER policy is persisted (`:739`). So `durability = replicated` + `consumer_offset_durability = persisted` writes every full message body into the disk WAL and spends the offset policy's `wal_bytes_max` budget on payloads. `append_batch` also ORs `durable` across the batch (`persistence.rs:631`), so one offset store forces a `journal.sync()` over co-batched bodies, and those bodies drive `disk_bytes` toward `capacity/2`.
   The retained bodies are load-bearing (they keep the durable offset frontier from naming unrecoverable messages), so this is an operator-visibility gap, not a design defect: the PR's "replicated topics stay off the disk WAL path" holds only when BOTH policies are replicated. Fix: document the pairing's cost in `config.toml:910` and in both `OptionDescriptor` descriptions.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,774 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableStorage};
+use journal::partition_journal::PARTITION_WAL_BYTES_MAX;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation {
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Frozen<4096>>)> {
+        let journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+        )
+        .await?;
+        let prepares = journal.prepares().await?;
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare_header(prepare)?;
+            accepted.checksums.push_back(header.checksum);
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.accepted.borrow().checksum(header.op) == Some(header.checksum)
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .disk_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn mark_offset_dirty(&self, kind_index: usize, consumer_id: u32, exists: bool) {
+        let mut offsets = self.dirty_offsets[kind_index].borrow_mut();
+        if exists {
+            offsets.insert(consumer_id);
+        } else {
+            offsets.remove(&consumer_id);
+        }
+    }
+
+    pub fn take_dirty_files(&self) -> (BTreeSet<u64>, [BTreeSet<u32>; 2]) {
+        (
+            std::mem::take(&mut *self.dirty_segments.borrow_mut()),
+            std::array::from_fn(|index| {
+                std::mem::take(&mut *self.dirty_offsets[index].borrow_mut())
+            }),
+        )
+    }
+
+    pub fn checkpoint(&self, through_op: u64) {
+        self.checkpoint_files(through_op, Vec::new(), Vec::new());
+    }
+
+    pub fn checkpoint_files(
+        &self,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    ) {
+        if through_op <= self.checkpoint_requested.get() {
+            return;
+        }
+        self.checkpoint_requested.set(through_op);
+        self.queue.borrow_mut().push_back(Mutation::Checkpoint {
+            epoch: self.epoch.get(),
+            through_op,
+            files,
+            directories,
+        });
+    }
+
+    pub const fn checkpoint_pending(&self) -> bool {
+        self.checkpoint_running.get() || self.checkpoint_requested.get() > self.checkpoint.get()
+    }
+
+    pub fn truncate_from(&self, from_op: u64) {
+        if from_op > self.accepted_head.get() {
+            return;
+        }
+        self.checkpoint_requested.set(self.checkpoint.get());
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        // Retained submissions still precede the replacement history.
+        self.queue
+            .borrow_mut()
+            .retain_mut(|mutation| match mutation {
+                Mutation::Append {
+                    epoch: previous,
+                    prepare,
+                    bytes,
+                    ..
+                } => {
+                    if prepare_header(prepare).is_ok_and(|header| header.op < from_op) {
+                        *previous = epoch;
+                        true
+                    } else {
+                        self.queued_bytes
+                            .set(self.queued_bytes.get().saturating_sub(*bytes));
+                        false
+                    }
+                }
+                Mutation::Checkpoint {
+                    epoch: previous,
+                    through_op,
+                    ..
+                } if *through_op < from_op => {
+                    *previous = epoch;
+                    self.checkpoint_requested
+                        .set(self.checkpoint_requested.get().max(*through_op));
+                    true
+                }
+                _ => false,
+            });
+        self.accepted.borrow_mut().truncate_from(from_op);
+        self.accepted_head.set(from_op.saturating_sub(1));
+        self.durable_head
+            .set(self.durable_head.get().min(from_op.saturating_sub(1)));
+        self.queue
+            .borrow_mut()
+            .push_back(Mutation::Truncate { epoch, from_op });
+    }
+
+    pub fn reset(&self, op: u64, checksum: Option<u128>) {
+        self.checkpoint_requested.set(op);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        self.queue.borrow_mut().clear();
+        self.queued_bytes.set(0);
+        *self.accepted.borrow_mut() = AcceptedPrepares {
+            base: op,
+            checksums: VecDeque::new(),
+        };
+        self.accepted_head.set(op);
+        self.durable_head.set(0);
+        self.queue.borrow_mut().push_back(Mutation::Reset {
+            epoch,
+            op,
+            checksum,
+        });
+    }
+
+    pub fn mark_purge(&self, generation: u64, floor: u64) {
+        self.queue.borrow_mut().push_back(Mutation::Purge {
+            epoch: self.epoch.get(),
+            generation,
+            floor,
+        });
+    }
+
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.purge_generation.get(), self.purge_floor.get())
+    }
+
+    pub const fn needs_checkpoint(&self) -> bool {
+        !self.checkpoint_pending()
+            && self.disk_bytes.get() + self.queued_bytes.get() + self.in_flight_bytes.get()
+                >= self.capacity / 2
+    }
+
+    pub fn take_metrics(&self) -> PersistenceMetrics {
+        PersistenceMetrics {
+            disk_bytes: self.disk_bytes.get(),
+            queued_bytes: self.queued_bytes.get(),
+            in_flight_bytes: self.in_flight_bytes.get(),
+            checkpoints_pending: u64::from(self.checkpoint_pending()),
+            completed_batches: self.completed_batches.replace(0),
+            batched_prepares: self.batched_prepares.replace(0),
+            completed_checkpoints: self.completed_checkpoints.replace(0),
+            failed_writes: self.failed_writes.replace(0),
+        }
+    }
+
+    pub fn failure(&self) -> Option<Arc<io::Error>> {
+        self.failure.borrow().clone()
+    }
+
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.checkpoint.get()
+    }
+
+    pub fn checksum(&self, op: u64) -> Option<u128> {
+        if op == self.checkpoint.get() {
+            self.checkpoint_checksum.get()
+        } else {
+            self.accepted.borrow().checksum(op)
+        }
+    }
+
+    pub const fn head(&self) -> u64 {
+        self.accepted_head.get()
+    }
+
+    pub fn retire(&self) {
+        self.retired.set(true);
+        self.queue.borrow_mut().clear();
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn drain(&self) -> io::Result<()> {
+        futures::future::poll_fn(|context| {
+            if let Some(error) = self.failure() {
+                return std::task::Poll::Ready(Err(io::Error::new(error.kind(), error)));
+            }
+            if !self.running.get() && self.queue.borrow().is_empty() {
+                return std::task::Poll::Ready(Ok(()));
+            }
+            let mut waiters = self.waiters.borrow_mut();
+            if !waiters
+                .iter()
+                .any(|waiter| waiter.will_wake(context.waker()))
+            {
+                waiters.push(context.waker().clone());
+            }
+            std::task::Poll::Pending
+        })
+        .await
+    }
+
+    pub fn start(&self) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && !self.queue.borrow().is_empty()
+            && !self.running.replace(true)
+    }
+
+    pub async fn run(self: Rc<Self>) {
+        let Some(mut journal) = self.journal.borrow_mut().take() else {
+            self.running.set(false);
+            return;
+        };
+        loop {
+            if self.retired.get() {
+                break;
+            }
+            let Some(mutation) = self.queue.borrow_mut().pop_front() else {
+                break;
+            };
+            let (epoch, bytes) = match &mutation {
+                Mutation::Append { epoch, bytes, .. } => (*epoch, *bytes),
+                Mutation::Purge { epoch, .. }
+                | Mutation::Truncate { epoch, .. }
+                | Mutation::Checkpoint { epoch, .. }
+                | Mutation::Reset { epoch, .. } => (*epoch, 0),
+            };
+            self.queued_bytes
+                .set(self.queued_bytes.get().saturating_sub(bytes));
+            self.in_flight_bytes.set(bytes);
+            let result = match mutation {
+                Mutation::Purge {
+                    generation, floor, ..
+                } => journal.mark_purge(generation, floor).await,
+                Mutation::Append {
+                    prepare, durable, ..
+                } => {
+                    self.append_batch(&mut journal, prepare, durable, epoch, bytes)
+                        .await
+                }
+                Mutation::Truncate { from_op, .. } => journal.truncate_from(from_op).await,
+                Mutation::Checkpoint {
+                    through_op,
+                    files,
+                    directories,
+                    ..
+                } => {
+                    self.checkpoint_running.set(true);
+                    let result = journal
+                        .checkpoint_files(through_op, &files, &directories)
+                        .await;
+                    self.checkpoint_running.set(false);
+                    if result.is_ok() {
+                        self.completed_checkpoints
+                            .set(self.completed_checkpoints.get() + 1);
+                    }
+                    result
+                }
+                Mutation::Reset { op, checksum, .. } => journal.reset(op, checksum).await,
+            };
+            self.in_flight_bytes.set(0);
+            if let Err(error) = result {
+                self.failed_writes.set(self.failed_writes.get() + 1);
+                *self.failure.borrow_mut() = Some(Arc::new(error));
+                self.notify();
+                break;
+            }
+            if epoch == self.epoch.get() && !self.retired.get() {
+                self.disk_bytes.set(journal.size_bytes());
+                let advanced = journal.durable_op() != self.durable_head.get()
+                    || journal.checkpoint_op() != self.checkpoint.get();
+                self.durable_head.set(journal.durable_op());
+                if journal.checkpoint_op() > self.checkpoint.get() {
+                    self.accepted
+                        .borrow_mut()
+                        .checkpoint(journal.checkpoint_op());
+                }
+                self.checkpoint.set(journal.checkpoint_op());
+                self.checkpoint_checksum.set(journal.checkpoint_checksum());
+                self.purge_generation.set(journal.purge_marker().0);
+                self.purge_floor.set(journal.purge_marker().1);
+                if advanced {
+                    self.notify();
+                }
+            }
+        }
+        *self.journal.borrow_mut() = Some(journal);
+        self.running.set(false);
+        for waiter in self.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+
+    async fn append_batch(
+        &self,
+        journal: &mut PartitionPrepareJournal<S>,
+        first: Frozen<4096>,
+        mut durable: bool,
+        epoch: u64,
+        first_bytes: u64,
+    ) -> io::Result<()> {
+        let mut batch = SmallVec::<[Frozen<4096>; 8]>::new();
+        batch.push(first);
+        let mut bytes = first_bytes;
+        {
+            let mut queue = self.queue.borrow_mut();
+            while batch.len() < APPEND_BATCH_OPS_MAX {
+                let Some(Mutation::Append {
+                    epoch: next_epoch,
+                    bytes: next_bytes,
+                    ..
+                }) = queue.front()
+                else {
+                    break;
+                };
+                if *next_epoch != epoch
+                    || bytes.saturating_add(*next_bytes) > APPEND_BATCH_BYTES_MAX
+                {
+                    break;
+                }
+                let Some(Mutation::Append {
+                    prepare,
+                    durable: requires_sync,
+                    bytes: record_bytes,
+                    ..
+                }) = queue.pop_front()
+                else {
+                    unreachable!("append prefix was checked");
+                };
+                bytes += record_bytes;
+                self.queued_bytes
+                    .set(self.queued_bytes.get().saturating_sub(record_bytes));
+                durable |= requires_sync;
+                batch.push(prepare);
+            }
+        }
+        self.in_flight_bytes.set(bytes);
+        let count = batch.len() as u64;
+        for prepare in batch {

Review Comment:
   warning: the batch loop awaits `append_buffered` per record, and each one issues its own `file.write(self.state.length, ..)` (`partition_journal.rs:433`). The fsync is coalesced but the writes are not: up to `APPEND_BATCH_OPS_MAX` = 64 io_uring write SQEs where one suffices, on every persisted topic's per-prepare path. Offsets are strictly contiguous, so the batch is already a single extent.
   Fix: concatenate the batch into one padded buffer, single write, then `sync()`. Keep the dedup / `head + 1` / `parent` / capacity checks BEFORE building the buffer and update `state`/`entries` only after the write returns, with `poisoned` spanning it.



##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1426,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);

Review Comment:
   warning: HTTP produce resolves topic durability twice per request, here and again in `confirmed_policy` at `:1437`. Each pass is a metadata STM read plus an O(partitions_count) `created_revision` min scan (`http/reads.rs:453`) plus a full `from_resource_options` option-map parse. `confirmed_policy` also heap-allocates two `Identifier`s (`to_le_bytes().to_vec()`) only to convert them straight back to `WireIdentifier::Numeric`, while `TopicDurability` already holds both ids as `usize`. All of it fills one response header, on the default `ack=replicated` path.
   Fix: resolve once and re-check by the stored `usize` ids, with no `Identifier` rebuild.



##########
core/server/src/http/handlers.rs:
##########
@@ -165,12 +165,11 @@ const PONG: &str = "pong";
 const HTTP_READ_CLIENT_ID: u128 = 0;
 
 /// Response header attesting what durability a produce response proves:
-/// [`DURABILITY_REPLICATED_MEMORY`] after an awaited quorum commit,
-/// [`DURABILITY_NONE`] for a `?ack=none` fire-and-forget.
+/// The completed topic policy after an awaited quorum commit. If namespace
+/// replacement prevents attesting its incarnation, report the proven quorum
+/// guarantee. [`DURABILITY_NONE`] means `?ack=none` dispatch acceptance.
 const DURABILITY_HEADER: HeaderName = HeaderName::from_static("iggy-durability");

Review Comment:
   warning: the `Iggy-Durability` value changed from `replicated-memory` to `replicated`/`persisted` -- a public HTTP contract break. An external client switching on `replicated-memory` now silently falls into its else branch. `README.md:236` is the repo's only migration note and does not mention it, and there is no CHANGELOG/UPGRADE file.
   The header also has zero consumers: it appears only here and in `tests/server/http_vsr.rs:47`, and no HTTP SDK reads it.
   Fix: list the rename in the breaking-change note, and surface the header in at least one HTTP SDK so the contract it breaks has a client.



##########
core/partitions/src/install_backup.rs:
##########
@@ -0,0 +1,211 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+use std::io;
+use std::path::Path;
+
+const BACKUP: &str = ".install-backup";
+const BUILDING: &str = ".install-building";
+const RETIRED: &str = ".install-retired";
+
+/// Recover an interrupted install before opening any partition files.
+///
+/// # Errors
+/// Returns an error if the previous materialization cannot be restored durably.
+pub async fn recover(directory: &Path) -> io::Result<()> {
+    recover_with_storage(directory, &DiskStorage).await
+}
+
+/// # Errors
+/// Returns an error when the install transaction cannot complete durably.
+pub async fn recover_with_storage<S: DurableStorage>(
+    directory: &Path,
+    storage: &S,
+) -> io::Result<()> {
+    let backup = directory.join(BACKUP);
+    if !storage.exists(&backup)? {
+        return Ok(());
+    }
+    for entry in storage.entries(directory)? {
+        if entry.name == BACKUP {
+            continue;
+        }
+        storage.remove_tree(&directory.join(&entry.name))?;
+    }
+    link_tree(&backup, directory, false, storage).await?;
+    finish_with_storage(directory, storage).await
+}
+
+/// Freeze the old materialization and WAL together before a destructive install.
+/// The caller drains persistence and holds the partition write lock until finish.
+///
+/// # Errors
+/// Returns an error if the rollback state cannot be made durable.
+/// After any failure the caller must stop serving until recovery.
+pub async fn begin(directory: &Path) -> io::Result<()> {
+    begin_with_storage(directory, &DiskStorage).await
+}
+
+/// # Errors
+/// Returns an error when the install transaction cannot complete durably.
+pub async fn begin_with_storage<S: DurableStorage>(
+    directory: &Path,
+    storage: &S,
+) -> io::Result<()> {
+    if storage.exists(&directory.join(BACKUP))? {
+        return Err(io::Error::other("partition install recovery is pending"));
+    }
+    let building = directory.join(BUILDING);
+    storage.remove_tree(&building)?;
+    storage.remove_tree(&directory.join(RETIRED))?;
+    storage.create_directories(&building).await?;
+    link_tree(directory, &building, true, storage).await?;
+    storage.rename(&building, &directory.join(BACKUP)).await?;
+    storage.sync_directory(directory).await
+}
+
+/// Publish a completed install before the group can resume voting or serving.
+///
+/// # Errors
+/// Returns an error if the installation cannot be published durably.
+pub async fn finish(directory: &Path) -> io::Result<()> {
+    finish_with_storage(directory, &DiskStorage).await
+}
+
+/// # Errors
+/// Returns an error when the install transaction cannot complete durably.
+pub async fn finish_with_storage<S: DurableStorage>(
+    directory: &Path,
+    storage: &S,
+) -> io::Result<()> {
+    let retired = directory.join(RETIRED);
+    storage.rename(&directory.join(BACKUP), &retired).await?;
+    storage.sync_directory(directory).await?;
+    // The durable rename is the commit point. Cleanup never changes recovery.
+    if let Err(error) = storage.remove_tree(&retired) {

Review Comment:
   warning: this RETIRED removal is best-effort `warn!`, and `recover` returns early whenever `.install-backup` is absent (`:41`), so nothing ever sweeps RETIRED or BUILDING -- only `begin_with_storage:74` clears them, i.e. only if a LATER install starts on the same partition. A crash right after a successful install, or one `remove_tree` failure, pins a hardlink tree of the whole pre-install chain. Blocks are shared at first and become unreclaimable as retention and rotation unlink the live names, so segment retention silently stops freeing space on that partition.
   Fix: sweep BUILDING and RETIRED unconditionally at the top of `recover`.



##########
core/configs/src/server_config/server.rs:
##########
@@ -56,37 +60,14 @@ const DEFAULT_CONFIG_PATH: &str = "core/server/config.toml";
 /// enough. The partition knobs matter most: they are create-only options now,
 /// so a topic that boots without one can never be given it afterwards.
 const RELOCATED_CONFIG_KEYS: &[RelocatedKey] = &[

Review Comment:
   warning: this rejection list plus `IGGY_EXTRA*` is all boot rejects; every other unknown `IGGY_*` is silently dropped, and `all_env_var_names()` at `:209` has no production caller -- its only caller repo-wide is the test harness (`integration/src/harness/config/resolve.rs:127`), which does fail loud. So a mistyped or half-migrated `IGGY_ENCRYPTION_*` boots reporting success with encryption off.
   The gap predates this PR, but this PR renames the entire environment surface, which is exactly when it gets exercised.
   Fix: run the harness's `all_env_var_names()` check at boot.



##########
foreign/cpp/include/iggy.hpp:
##########
@@ -403,6 +403,18 @@ inline iggy::ffi::HeaderEntry to_option_entry(const std::string_view key,
  *       partition storage is created. Changing them later could leave existing
  *       and new segments with different storage settings.
  */
+enum class Durability { Replicated, Persisted };

Review Comment:
   warning: `enum class Durability` is inserted directly beneath the Doxygen block written for `class TopicOption` (`:390`-`:405`, "Creates topic option entries for `Client::create_topic(...)` / Each factory encodes one key..."). That block now documents the enum, `TopicOption` at `:418` ships undocumented, and `ConsumerOffsetDurability` at `:445` has no doc at all. Same insertion damage at `foreign/cpp/src/client.rs:486`, where the "`None` is what tells admission..." comment now sits over non-`Option` durability code.
   Fix: move the enum above the block and document the new factory.



##########
core/binary_protocol/src/primitives/options.rs:
##########
@@ -432,39 +432,42 @@ mod tests {
     /// in their own unit tests, and a change to the TLV layout has to break all
     /// of them together instead of leaving one SDK talking to itself.
     ///
-    /// `enforce_fsync=true` (a `Bool`) and `segment_size=1 GiB` (a `Uint64`)
+    /// `preallocate_segments=true` (a `Bool`) and `segment_size=1 GiB` (a `Uint64`)
     /// cover both a one-byte and an eight-byte value. What the vector pins is
     /// the per-entry byte layout, not a key order: these two land sorted only

Review Comment:
   warning: `durability` was appended after `segment_size`, so this golden vector is no longer in BTreeMap order (`'d' < 'p' < 's'`) and no longer matches what the Rust encoder emits -- while all five copies of the comment still say "these two land sorted only because `iggy_common` holds options in a `BTreeMap`". `unsorted_keys_are_accepted` at `:474` now passes trivially.
   The same stale claim is in `foreign/go/contracts/compression_algorithm_test.go:56`, `foreign/java/.../OptionsBlockGoldenVectorTest.java:41`, `foreign/csharp/.../OptionsBlockGoldenVectorTests.cs:34` and `foreign/node/src/wire/options.utils.test.ts:33`.
   Fix: insert `durability` first so the vector is sorted again, or restate all five comments as insertion-order.



##########
core/common/src/types/options/durability.rs:
##########
@@ -0,0 +1,51 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use serde::{Deserialize, Serialize};
+use strum::{AsRefStr, Display, EnumString, IntoStaticStr};
+
+/// Storage guarantee required at explicit operation completion. Both policies persist data.
+#[derive(
+    Debug,
+    Clone,
+    Copy,
+    Default,
+    PartialEq,
+    Eq,
+    Serialize,
+    Deserialize,
+    Display,
+    EnumString,

Review Comment:
   warning: `EnumString` without `ascii_case_insensitive` and without `clap::ValueEnum` means a bad token surfaces as bare strum text with no possible-values list: `--durability Persisted` fails with "invalid value 'Persisted' ... Matching variant not found", and the C++ FFI returns the same string with no key and no valid tokens (`foreign/cpp/src/client.rs:492`).
   The repo already derives `ValueEnum` for `ConsumerKind` (`types/consumer/consumer_kind.rs:45`).
   Fix: derive `ValueEnum`, and map the FFI parse error through `InvalidOptionValue`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983316998


##########
core/bench/src/utils/mod.rs:
##########
@@ -321,14 +330,15 @@ fn add_infrastructure_arguments(parts: &mut Vec<String>, args: &IggyBenchArgs) {
         parts.push(format!("--max-topic-size \'{max_topic_size}\'"));

Review Comment:
   fixed; consumer-only replay no longer adds --partitions.



##########
core/bench/src/utils/mod.rs:
##########
@@ -321,14 +330,15 @@ fn add_infrastructure_arguments(parts: &mut Vec<String>, args: &IggyBenchArgs) {
         parts.push(format!("--max-topic-size \'{max_topic_size}\'"));
     }

Review Comment:
   fixed the group-mode defaults; replay keeps the same geometry.



##########
core/server_common/src/segment_storage/mod.rs:
##########
@@ -39,6 +42,49 @@ pub struct SegmentStorage {
 }
 
 impl SegmentStorage {
+    /// The WAL owns message writes; this storage exposes only their committed prefix.
+    pub async fn with_read_only_messages(

Review Comment:
   the constructors have different contracts; their call sites are correct.



##########
core/server_common/src/fs_utils.rs:
##########
@@ -44,6 +48,58 @@ impl DirEntry {
     }
 }
 
+/// Reserve segment space without changing its contents or logical length.
+/// Unsupported or failed reservations fall back to buffered allocation.
+#[cfg(target_os = "linux")]
+pub fn preallocate_file(file: &fs::File, file_path: &Path, len: u64) {
+    let Ok(len) = i64::try_from(len) else {
+        warn!(
+            target: "iggy.partitions.storage",
+            file = %file_path.display(),
+            preallocate_len = len,
+            "file preallocation size is unsupported, using buffered allocation"
+        );
+        return;
+    };
+
+    // Runs INLINE on the shard thread, deliberately. `server_common::executor`

Review Comment:
   trimmed the comment to why the io has to run inline.



##########
core/bench/src/args/defaults.rs:
##########
@@ -35,15 +35,15 @@ pub const DEFAULT_MESSAGE_BATCHES: NonZeroU32 = u32!(1000);
 pub const DEFAULT_MESSAGE_SIZE: NonZeroU32 = u32!(1000);
 pub const DEFAULT_TOTAL_MESSAGES_SIZE: IggyByteSize = IggyByteSize::new(8_000_000);
 
-pub const DEFAULT_PINNED_NUMBER_OF_STREAMS: NonZeroU32 = u32!(8);
+pub const DEFAULT_PINNED_NUMBER_OF_STREAMS: NonZeroU32 = u32!(6);

Review Comment:
   the e2e mode shares pinned stream assignment, so the default is shared.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3986620245


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   thanks for the repro, this is fixed locally in https://github.com/apache/iggy/pull/4092/commits/c1e808f693f977ae9c63696ba571bb596d0f1aad. the handler pins the numeric stream and topic ids captured with the durability policy before waiting on the session gate, and keeps the incarnation check afterward. renames can’t redirect the write anymore. the routing and policy tests pass.



##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   thanks for the repro, this is fixed in [`c1e808f` (this PR)](https://github.com/apache/iggy/pull/4092/commits/c1e808f693f977ae9c63696ba571bb596d0f1aad). the handler pins the numeric stream and topic ids captured with the durability policy before waiting on the session gate, and keeps the incarnation check afterward. renames can’t redirect the write anymore. the routing and policy tests pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "numinnex (via GitHub)" <gi...@apache.org>.
numinnex commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3978815967


##########
core/server/src/partition_helpers.rs:
##########
@@ -392,19 +382,13 @@ pub async fn ensure_initial_segment(
     // offering peers a segment that claims `[0..N]`.
     let start_offset = partition.mint_frontier();
     let messages_path =
-        config
-            .system
-            .get_messages_file_path(stream_id, topic_id, partition_id, start_offset);
-    let index_path = config
-        .system
-        .get_index_path(stream_id, topic_id, partition_id, start_offset);
+        config.get_messages_file_path(stream_id, topic_id, partition_id, start_offset);
+    let index_path = config.get_index_path(stream_id, topic_id, partition_id, start_offset);
     let runtime = partition.runtime_options();
     let segment_size = runtime
         .segment_size
         .unwrap_or_else(|| IggyByteSize::from(iggy_common::DEFAULT_SEGMENT_SIZE));
-    let enforce_fsync = runtime
-        .enforce_fsync
-        .unwrap_or(iggy_common::DEFAULT_ENFORCE_FSYNC);
+    let persisted = runtime.durability.is_persisted();
     let preallocate_segments = runtime
         .preallocate_segments
         .unwrap_or(iggy_common::DEFAULT_PREALLOCATE_SEGMENTS);

Review Comment:
   critical: `ensure_initial_segment` opens the log at `mint_frontier()` with `SegmentStorage::new(.., file_exists=false)` at `:400`, which truncates (`core/server_common/src/segment_storage/messages_writer.rs:53-55`), and never consults `segment_checkpoint()`. In owned mode that inode holds committed, WAL-referenced bodies.
   Chain: retention may remove the checkpoint's own sealed segment (`iggy_partition.rs:6733` allows it, `end_offset == next_offset-1 < next_offset`) -> the boot filter drops the only survivor (`segment_recovery.rs:227-229`) -> empty chain -> `mint_frontier()` lands on the WAL's tail segment -> truncated to 0 -> next boot refuses `"segment lost durably published bytes"` permanently.
   The new comment at `:395-399` justifies truncation for a stale `.index` at this offset; that case is real but disjoint from the owned-log case, which the truncate destroys.
   Fix: branch on `segment_checkpoint().is_some()` -> `with_read_only_messages`, as `install_empty_segment` already does.



##########
core/shard/src/lib.rs:
##########
@@ -11549,6 +11619,51 @@ async fn dispatch_vsr_actions<B, P, J>(
     }
 }
 
+fn partition_start_view_suffix<B: MessageBus, SB: SuperblockStore>(
+    partition: &IggyPartition<B, SB>,
+    commit: u64,
+    head: u64,
+) -> Vec<PrepareHeader> {
+    // Probe replies and stale-view corrections need the same canonical headers
+    // as election broadcasts before a backup can fetch an uncommitted body.
+    (commit.max(1)..=head)
+        .rev()
+        .take(consensus::DVC_HEADERS_MAX)
+        .map_while(|op| partition.log.journal().inner.repair_header(op))
+        .collect()
+}
+
+#[allow(clippy::future_not_send)]
+async fn dispatch_partition_wire_actions<B, P, J, SB>(
+    consensus: &VsrConsensus<B, P>,
+    partition: &IggyPartition<B, SB>,
+    mut actions: Vec<VsrAction>,
+) where
+    B: MessageBus,
+    P: Pipeline<Entry = consensus::PipelineEntry>,
+    J: JournalHandle,
+    J::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
+    SB: SuperblockStore,
+{
+    if !partition.persist_superblock_if_needed().await {
+        return;
+    }
+    if partition.requires_state_transfer() {
+        actions.retain(|action| matches!(action, VsrAction::SendRequestStartView { .. }));
+    }
+    for action in &mut actions {

Review Comment:
   critical: the suffix backfill fires on every empty-suffix `SendStartView`, including the two paths consensus deliberately emits numbers-only (`core/consensus/src/impls.rs:3200` probe answer, `core/shard/src/lib.rs:10234-10238` stale-view correction). Receiver-side `adopt_start_view_suffix` (`impls.rs:3255-3264`) installs `pending_view_log` iff the suffix is non-empty, so a numbers-only announcement now mutates every backup's view state.
   Chain: one lagging peer's stale heartbeat -> `RespondStartView` broadcasts (`target: None`) the primary's uncommitted tail `[C..H]` -> healthy backups pass every reject gate and adopt -> `build_dvc_suffix:11105-11112` then reports op H as present-from-view and NOT nacked on replicas holding no body for it. Primary dies -> the merge reaches a non-nack quorum for an op only the dead primary held.
   Distinct from the send-cost finding on `:11622`: this is receiver state mutation and a loss of the nack guarantee.
   Fix: pass the suffix only from the merge-concluding site (`start_pending_view`), or gate the backfill on provenance rather than `suffix.is_empty()`.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()

Review Comment:
   critical: no checksum covers a persisted message body any more. This clause gates the only body check on `header.checksum_body != 0`, and `core/consensus/src/impls.rs:4061-4068` sets it to `0` for every non-`METADATA_GROUP` prepare, deliberately, because `stamp_prepare_for_persistence` rewrites bytes inside the sealed range per replica. The record hash at `:938` now covers 256 B of header plus a 32 B reference.
   This is a regression, not a pre-existing gap: before this change `encode_payload_into` hashed `bytes[..RECORD_PREFIX + frame_length]` where `frame_length = 256 + body`, so the record hash did cover the body.
   Worse, the checkpoint prepare is restored unvalidated (`iggy_partition.rs:837-842`) and `state_transfer.rs:2247` ships those bytes to a peer whose gate uses the same dead clause.
   Fix: recompute `BatchHeader.batch_checksum` in `read_record` for referenced records (no new field, no header byte, boot-only) and independently at the state-transfer receive gate. Do NOT seal a hash at reserve time: `impls.rs:4100-4103` seals `checksum` last over `checksum_body`, so that would break `identity_checksum()`, the `parent` chain and pipeline-entry comparison.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {

Review Comment:
   critical: `recover_segment_files` unlinks `{offset}.log` and `{offset}.index` for `offset > tail.start_offset && offset >= tail.next_offset`, and it runs at RUNTIME from `truncate_from` (`partition_journal.rs:372`) on every view-change suffix truncation, not only at boot.
   The partition's `truncate_uncommitted_from` (`iggy_partition.rs:5244-5339`) retires no segment and never calls `invalidate_sealed_read_state`, which `log.rs:286-294` documents as mandatory for exactly this hazard.
   Result: index writes continue through the orphaned inode and `save_indexes` returns `Ok`, while a cached read fd in `sealed_read_state` keeps serving rolled-back bytes and the WAL later recreates `{offset}.log` as a new inode with no index.
   Fix: restrict the runtime sweep to WAL-private `segment-*.log` — the offset-named files are the partition's namespace, not the journal's.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -2440,6 +2574,32 @@ where
             });
         }
         let offsets_wire = ConsumerOffsetsWire::decode(offsets_bytes)?;
+        if self.persistence.is_some()
+            && (offsets_wire.prepare_checksum.is_none()
+                || (commit_op > 0 && offsets_wire.checkpoint_prepare.is_empty()))
+        {
+            return Err(ConsumerOffsetsWireError::MissingPrepareChecksum.into());
+        }
+        if !offsets_wire.checkpoint_prepare.is_empty() {

Review Comment:
   critical: `checkpoint_prepare` validation is unconditional while `prepare_checksum` is optional, so a non-persisted origin ships `prepare_checksum = None` plus a non-empty prepare and `Some(header.checksum) != None` refuses the install.
   Origin with `persistence == None` (multi-replica topic, both durability keys `replicated`): `offsets_wire_snapshot:2260-2275` yields `None` — `header_by_op(commit_op)` is empty once the committed prefix is evicted, the `persistence.checksum` fallback needs a WAL, and the last fallback needs `current_sequence() == commit_op` (false with any in-flight prepare). `:2277-2281` still fills `checkpoint_prepare` from `repair_entry(commit_op)`, and the `:2282-2286` refusal is gated on `persistence.is_some()`, so the artifact ships. Receiver returns `InvalidPrepareChecksum`.
   Being a check-phase failure it grows the re-arm backoff (`:84-95`) instead of rotating peers, so a joining replica starves on a busy in-memory topic.
   Fix: skip the block when `prepare_checksum.is_none() && persistence.is_none()`, or have the sender leave `checkpoint_prepare` empty when it has no checksum for `commit_op`.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {

Review Comment:
   critical: one `write_frozen` per record — K sequential io_uring writes per batch, where the previous `MessagesWriter::write_frozen_chunked` did one `write_vectored_all_at` per IOV_MAX chunk. Each await is a separate submission/completion round trip.
   `reserve` assigns `position = tail.position.length` then advances it (`:536-546`), so every reference in a batch is physically contiguous by construction — a single vectored write is directly available, with a rotation falling out as two writes.
   This is the whole append-path win and it carries zero barrier-ordering risk, unlike making the batch fsync conditional. Land it first.
   Fix: group records by `(generation, start_offset)` and issue one vectored write per group.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,
+    retired_offset_files: RefCell<Vec<S::File>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    certified_log_view: Cell<Option<u32>>,
+    requested_log_view: Cell<Option<(u32, u64, u128)>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    checkpoint_needed: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    retained_bytes: Cell<u64>,
+    segment_checkpoint: Cell<Option<SegmentPosition>>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    writer_active: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct WriterLease {
+    key: PathBuf,
+    id: u64,
+    retired: AtomicBool,
+    running: AtomicBool,
+    waiters: Mutex<Vec<std::task::Waker>>,
+}
+
+struct WriterRegistration {
+    id: u64,
+    writer: Weak<WriterLease>,
+    interrupted: bool,
+}
+
+static WRITERS: LazyLock<Mutex<HashMap<PathBuf, WriterRegistration>>> =
+    LazyLock::new(|| Mutex::new(HashMap::new()));
+
+impl WriterLease {
+    async fn acquire(key: PathBuf) -> io::Result<Arc<Self>> {
+        loop {
+            let previous = {
+                let mut writers = WRITERS
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if writers
+                    .get(&key)
+                    .is_some_and(|registration| registration.interrupted)
+                {
+                    return Err(io::Error::other(
+                        "interrupted partition WAL writer requires process restart",
+                    ));
+                }
+                if let Some(previous) = writers
+                    .get(&key)
+                    .and_then(|registration| registration.writer.upgrade())
+                {
+                    drop(writers);
+                    Some(previous)
+                } else {
+                    let lease = Arc::new(Self {
+                        key: key.clone(),
+                        id: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+                        retired: AtomicBool::new(false),
+                        running: AtomicBool::new(false),
+                        waiters: Mutex::new(Vec::new()),
+                    });
+                    writers.insert(
+                        key.clone(),
+                        WriterRegistration {
+                            id: lease.id,
+                            writer: Arc::downgrade(&lease),
+                            interrupted: false,
+                        },
+                    );
+                    drop(writers);
+                    return Ok(lease);
+                }
+            };
+            let Some(previous) = previous else { continue };
+            if !previous.retired.load(Ordering::Acquire) {
+                return Err(io::Error::new(
+                    io::ErrorKind::AlreadyExists,
+                    "partition WAL already has an active writer",
+                ));
+            }
+            compio::runtime::time::timeout(
+                PERSISTENCE_DRAIN_TIMEOUT,
+                futures::future::poll_fn(|context| {
+                    let mut waiters = previous
+                        .waiters
+                        .lock()
+                        .unwrap_or_else(std::sync::PoisonError::into_inner);
+                    if !previous.running.load(Ordering::Acquire) {
+                        return std::task::Poll::Ready(());
+                    }
+                    if !waiters
+                        .iter()
+                        .any(|waiter| waiter.will_wake(context.waker()))
+                    {
+                        waiters.push(context.waker().clone());
+                    }
+                    std::task::Poll::Pending
+                }),
+            )
+            .await
+            .map_err(|_| {
+                io::Error::new(
+                    io::ErrorKind::TimedOut,
+                    "retired partition WAL writer did not stop",
+                )
+            })?;
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if writers
+                .get(&key)
+                .is_some_and(|registration| registration.id == previous.id)
+            {
+                writers.remove(&key);
+            }
+        }
+    }
+
+    fn finish(&self) {
+        self.running.store(false, Ordering::Release);
+        for waiter in self
+            .waiters
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .drain(..)
+        {
+            waiter.wake();
+        }
+    }
+}
+
+impl Drop for WriterLease {
+    fn drop(&mut self) {
+        let mut writers = WRITERS
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if writers
+            .get(&self.key)
+            .is_some_and(|registration| registration.id == self.id && !registration.interrupted)
+        {
+            writers.remove(&self.key);
+        }
+    }
+}
+
+struct WriterTicket<S: DurableStorage> {
+    owner: Rc<PartitionPersistence<S>>,
+    started: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterTicket<S> {
+    fn drop(&mut self) {
+        if self.started {
+            return;
+        }
+        self.owner.fail(io::Error::new(
+            io::ErrorKind::Interrupted,
+            "partition WAL writer was dropped before polling",
+        ));
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct WriterGuard<'a, S: DurableStorage> {
+    owner: &'a PartitionPersistence<S>,
+    journal: Option<PartitionPrepareJournal<S>>,
+    complete: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterGuard<'_, S> {
+    fn drop(&mut self) {
+        *self.owner.journal.borrow_mut() = self.journal.take();
+        self.owner.in_flight_bytes.set(0);
+        self.owner.checkpoint_running.set(false);
+        if !self.complete
+            && let Some(lease) = &self.owner.lease
+        {
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if let Some(registration) = writers.get_mut(&lease.key)
+                && registration.id == lease.id
+            {
+                registration.interrupted = true;
+            }
+        }
+        if !self.complete && self.owner.failure.borrow().is_none() {
+            *self.owner.failure.borrow_mut() = Some(Arc::new(io::Error::new(
+                io::ErrorKind::Interrupted,
+                "partition WAL writer stopped during a mutation",
+            )));
+        }
+        self.owner.writer_active.set(false);
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation<S: DurableStorage> {
+    EnableSegments {
+        epoch: u64,
+        initial: SegmentPosition,
+        max_size: u64,
+    },
+    CertifyView {
+        epoch: u64,
+        view: u32,
+        op: u64,
+        checksum: u128,
+    },
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+        offset_files: Vec<S::File>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        let lease = if let Some(key) = storage.writer_identity(directory)? {
+            Some(WriterLease::acquire(key).await?)
+        } else {
+            None
+        };
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+            preallocate_segments,
+        )
+        .await?;
+        let prepares = journal.take_recovered_prepares();
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare.header();
+            if header.op > journal.checkpoint_op() {
+                accepted.checksums.push_back(header.checksum);
+            }
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            lease,
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            certified_log_view: Cell::new(journal.certified_log_view()),
+            requested_log_view: Cell::new(None),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            checkpoint_needed: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            retained_bytes: Cell::new(journal.retained_bytes()),
+            segment_checkpoint: Cell::new(journal.segment_checkpoint()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            offset_files: RefCell::new(HashMap::new()),
+            retired_offset_files: RefCell::new(Vec::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            writer_active: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    #[cfg(test)]
+    pub(crate) fn exhaust_capacity_for_test(&self) {
+        self.disk_bytes.set(self.capacity);
+        self.retained_bytes.set(self.capacity);
+    }
+
+    #[cfg(test)]
+    pub(crate) fn release_capacity_for_test(&self) {
+        self.disk_bytes.set(0);
+        self.retained_bytes.set(0);
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.certified_log_view.get()
+    }
+
+    pub fn certify_log_view(&self, view: u32, op: u64, checksum: u128) -> bool {
+        if self.certified_log_view.get() == Some(view) {
+            return true;
+        }
+        if self.retired.get()
+            || self.failure.borrow().is_some()
+            || op > self.head()
+            || !(op == 0 && checksum == 0 || self.checksum(op) == Some(checksum))
+        {
+            return false;
+        }
+        let target = (view, op, checksum);
+        if self
+            .requested_log_view
+            .get()
+            .is_none_or(|(pending, _, _)| pending != view)
+        {
+            self.requested_log_view.set(Some(target));
+            self.queue.borrow_mut().push_back(Mutation::CertifyView {
+                epoch: self.epoch.get(),
+                view,
+                op,
+                checksum,
+            });
+        }
+        false
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.checksum(header.op) == Some(header.checksum)
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        self.segment_checkpoint.get()
+    }
+
+    pub fn enable_segment_storage(&self, initial: SegmentPosition, max_size: u64) {
+        self.queue.borrow_mut().push_back(Mutation::EnableSegments {
+            epoch: self.epoch.get(),
+            initial,
+            max_size,
+        });
+    }
+
+    /// Verify the physical prefix before making its indexes and logical sizes visible.
+    ///
+    /// # Errors
+    /// Returns an error for a failed barrier or a body outside the durable segment range.
+    pub async fn validate_segment_prefix(
+        &self,
+        prepares: &[Frozen<4096>],
+        start_offset: u64,
+        mut position: u64,
+    ) -> io::Result<u64> {
+        self.drain_with_timeout().await?;

Review Comment:
   critical: `validate_segment_prefix` calls `drain_with_timeout()` inside the per-chunk flush loop (`iggy_partition.rs:6437-6447`, inside `while entries.peek()` at `:5464`) while `commit_messages_inner` holds `write_lock` (`:5387`). Produce journaling takes the same lock (`:5124-5125`), so every flush stalls all produce behind the WAL writer's fsyncs, removing the produce/WAL pipelining that existed before this change. On `PERSISTENCE_DRAIN_TIMEOUT` (30 s) it maps to `CannotSyncFile` -> `FatalCommit`: a slow disk becomes a fenced partition instead of backpressure.
   Note the drain exists to reclaim the journal (`run_inner` *takes* it), not to prove durability — `op <= durable_head` does that.
   Fix: mirror `(op -> SegmentReference)` into `PartitionPersistence` state next to `durable_head`, never borrow the journal from the flush path, and when a reference is not yet durable return WITHOUT advancing `segment.size` and retry next cycle — never error, or the timeout fence is traded for a `CannotSyncFile` on every flush that laps the writer.



##########
core/server/src/segment_recovery.rs:
##########
@@ -219,26 +241,56 @@ pub async fn load_persisted_segments(
     let mut planned = Vec::with_capacity(start_offsets.len());
     for start_offset in start_offsets {
         let messages_path =
-            config
-                .system
-                .get_messages_file_path(stream_id, topic_id, partition_id, start_offset);
-        let index_path =
-            config
-                .system
-                .get_index_path(stream_id, topic_id, partition_id, start_offset);
+            config.get_messages_file_path(stream_id, topic_id, partition_id, start_offset);
+        let index_path = config.get_index_path(stream_id, topic_id, partition_id, start_offset);
 
         let raw_messages_size = file_len(&messages_path)?;
-
-        let bounds = recover_segment_bounds(
-            identity,
-            &index_path,
-            &messages_path,
-            start_offset,
-            raw_messages_size,
-            enforce_fsync,
-            &mut scratch,
-        )
-        .await?;
+        let messages_size = checkpoint
+            .filter(|checkpoint| checkpoint.start_offset == start_offset)
+            .map_or(raw_messages_size, |checkpoint| checkpoint.length);
+        if raw_messages_size < messages_size {
+            return Err(
+                identity.refusal(PartitionRecoveryRefusal::StorageSizeMismatch {
+                    start_offset,
+                    on_disk_bytes: raw_messages_size,
+                    expected_bytes: messages_size,
+                }),
+            );
+        }
+        let bounds = if checkpoint.is_some() {

Review Comment:
   warning: with a checkpoint present this branch routes EVERY segment through `recover_by_walking_log` (byte 0, per-batch checksum), not only the one the checkpoint names, and `:248-250` sets `messages_size = raw_messages_size` for the others. `recover_by_walking_log` always returns `rebuilt_index: Some(..)` (`:1596`), so `:395-396` re-stages and installs every `.index` on every boot after reading every byte on disk.
   Correctness half: the exact size check at `:283-293` with `truncate_to` removed for the whole checkpoint path (`:392-394`) makes any deviation on a non-checkpoint segment a permanent, non-self-healing `StorageSizeMismatch` refusal — identical on every subsequent boot. Converse hole: because `messages_size` is the file's own length and the index is unconditionally rebuilt from the log, a sealed segment that LOST its tail now passes, where `recover_segment_bounds` previously caught it off the durable index. Only the cross-segment `Hole` refusal remains.
   Fix: walk only where `checkpoint.start_offset == start_offset` and keep `recover_segment_bounds` (with its `truncate_to`) for the rest. One change resolves both halves.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;

Review Comment:
   critical: the public tail name is rebuilt as unlink-then-`hard_link`, which is not crash-atomic, and the `restore` predicate at `:393-395` is not idempotent across that window.
   Trigger: segment reaches `length >= max_size`, the checkpoint catches up (`tail.next_offset == checkpoint.next_offset`), producer idles. A view change runs `truncate_from` -> `recover_segment_files` -> `remove_segment_name(&public)` lands durably while the `hard_link` does not (no directory fsync until `:431`). Kill -9. Next boot: `length < max_size` false, `next_offset > checkpoint_next` false, `exists(public)` false, so `restore == false` forever.
   The bytes then live only as `prepares-N/segment-{g}-{S}.log`; the recovered chain is short while `checkpoint_end` (`partition_helpers.rs:979`) still claims through `next_offset-1`, so polls of `[S, next_offset)` resolve no segment.
   Fix: `hard_link` to a temp name then `rename` over `public` (atomic, no unlink), or gate `restore` on `exists(retained)` rather than `exists(public)`.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory

Review Comment:
   warning: the sweep unlinks `{offset}.log` at `offset >= tail.next_offset`, but that same `start_offset` is still in `dirty_segments` and still in `self.log.segments()`, so the next `checkpoint_files` (`partition_journal.rs:387-391` via `iggy_partition.rs:1001-1012`) opens a missing path. ENOENT there is deliberately terminal, and `persistence.failure` is never cleared, so WAL reclamation stops for the life of the process.
   Trigger: boot marks EVERY segment dirty (`iggy_partition.rs:861`), including the empty active one at S0. A view change before the first checkpoint rolls the tail back into the previous segment, so `S0 > tail.start_offset && S0 >= tail.next_offset` and `S0.log` is unlinked. The partition then wedges at capacity.
   Fail-closed remains the right decision; this change manufactures its precondition. Distinct from the stale-fd consequence on `:415`.
   Fix: drop the swept `start_offset` from `dirty_segments` and retire the segment, or exempt names the partition still lists.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {
+            return Err(invalid(
+                "message offsets do not extend the physical segment tail",
+            ));
+        }
+        if self.tail.position.length >= self.max_size {
+            self.tail = self.allocate(SegmentPosition {
+                start_offset: batch.base_offset,
+                length: 0,
+                next_offset: batch.base_offset,
+            })?;
+        }
+        let reference = SegmentReference {
+            generation: self.tail.generation,
+            start_offset: self.tail.position.start_offset,
+            position: self.tail.position.length,
+            length: batch.batch_length,
+        };
+        self.tail.position.length = reference
+            .position
+            .checked_add(reference.length)
+            .ok_or_else(|| invalid("segment position exhausted"))?;
+        self.tail.position.next_offset = batch_next_offset(prepare)?;
+        Ok((Some(reference), Some(self.tail.position.next_offset)))
+    }
+
+    pub(super) fn reset_position(&mut self, position: SegmentPosition) -> io::Result<()> {
+        if !position.valid() {
+            return Err(invalid("invalid replacement segment boundary"));
+        }
+        self.tail = self.allocate(position)?;
+        self.checkpoint = self.tail;
+        Ok(())
+    }
+
+    fn allocate(&mut self, position: SegmentPosition) -> io::Result<SegmentCursor> {
+        let generation = self.next_generation;
+        self.next_generation = generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        Ok(SegmentCursor {
+            generation,
+            position,
+        })
+    }
+
+    pub(super) fn encode(self, bytes: &mut [u8]) {
+        let values = [
+            self.max_size,
+            self.next_generation,
+            self.tail.generation,
+            self.tail.position.start_offset,
+            self.tail.position.length,
+            self.tail.position.next_offset,
+            self.checkpoint.generation,
+            self.checkpoint.position.start_offset,
+            self.checkpoint.position.length,
+            self.checkpoint.position.next_offset,
+        ];
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip(values)
+        {
+            *field = value.to_le_bytes();
+        }
+    }
+
+    pub(super) fn decode(bytes: &[u8]) -> io::Result<Self> {
+        let mut values = [0; SEGMENT_STATE_BYTES / size_of::<u64>()];
+        for (value, field) in values
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *value = u64::from_le_bytes(*field);
+        }
+        let [
+            max_size,
+            next_generation,
+            tail_generation,
+            tail_start,
+            tail_length,
+            tail_next,
+            checkpoint_generation,
+            checkpoint_start,
+            checkpoint_length,
+            checkpoint_next,
+        ] = values;
+        let state = Self {
+            max_size,
+            next_generation,
+            tail: SegmentCursor {
+                generation: tail_generation,
+                position: SegmentPosition {
+                    start_offset: tail_start,
+                    length: tail_length,
+                    next_offset: tail_next,
+                },
+            },
+            checkpoint: SegmentCursor {
+                generation: checkpoint_generation,
+                position: SegmentPosition {
+                    start_offset: checkpoint_start,
+                    length: checkpoint_length,
+                    next_offset: checkpoint_next,
+                },
+            },
+        };
+        if max_size == 0

Review Comment:
   warning: `SegmentState::decode` bounds `max_size` only by `!= 0`. That value reaches `fallocate` at `:407` and `:316` with no ceiling, and the only cross-check (`:69-71`, `"segment size differs from the durable WAL layout"`) runs from `iggy_partition.rs:812` AFTER `open_with_storage_and_capacity` already called `recover_segment_files`.
   Trigger: a checksum-consistent frontier carrying `max_size = 512 GiB` on a `preallocate_segments` topic. Boot issues `fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, 512 GiB)` inline on the shard thread — real disk, not sparse — stalling the whole core with no partition-level bound. The same value also makes `restore` at `:393` unconditionally true.
   Fix: clamp `max_size` in `decode` to `MIN_TOPIC_SEGMENT_SIZE..=MAX_TOPIC_SEGMENT_SIZE` and require a 512-byte multiple.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await

Review Comment:
   warning: `sync_segment_files()` runs unconditionally per append batch — including on buffered (`durable = false`) appends that deliberately skip the WAL fsync, and on batches that wrote zero bodies (any non-`SendMessages` prepare; `reserve` returns `(None, None)` at `:520-522`). That is one avoidable fdatasync per `StoreConsumerOffset` on every persisted topic.
   Do NOT move the barrier into `sync()`: `retain_active_segment_file` (`:337-344`) is called at `partition_journal.rs:680`, inside `append_batch_inner` and before any `sync()`, so a batch that rotated mid-append would drop the pre-rotation segment's handle with its bytes still dirty and its reference already in the WAL — the errseq hole the comment at `:330-332` forbids.
   Fix: skip the sync only when the batch wrote zero bodies. Safe standing alone, since any body-carrying batch still syncs before returning. Sequence the `segment_files.clear()` sites (`:173`, `partition_journal.rs:505`) before any further deferral.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;
+            Some(reference)
+        } else {
+            None
+        };
+        Ok((buffer, frame_length, reference))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+        checkpoint_prepare: Option<(Frozen<4096>, Option<SegmentReference>)>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            checkpoint_prepare: false,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            if checkpoint > self.state.checkpoint {
+                segments.checkpoint = self
+                    .segment_boundary(checkpoint)
+                    .ok_or_else(|| invalid("missing segment checkpoint boundary"))?;
+            }
+            if let Some(from_op) = truncate.filter(|from_op| *from_op > 0) {
+                segments.tail = self
+                    .segment_boundary(from_op - 1)
+                    .ok_or_else(|| invalid("missing segment rollback boundary"))?;
+            }
+        }
+        if let Some((prepare, reference)) = checkpoint_prepare {
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let mut encoded = Owned::zeroed(length);
+            encode_record_into(
+                prepare.as_slice(),
+                reference,
+                generation,
+                encoded.as_mut_slice(),
+            )?;
+            let length = encoded.as_slice().len();
+            file.write_aligned(0, encoded).await?;
+            entries.insert(
+                checkpoint,
+                StoredPrepare {
+                    position: 0,
+                    length,
+                    checksum,
+                    reference,
+                    next_offset: None,
+                    retained_bytes: record_length(prepare.len())? as u64,
+                },
+            );
+            state.length = length as u64;
+            state.checkpoint_prepare = true;
+        }
+        let previous_entries: Vec<_> = self
+            .entries
+            .iter()
+            .map(|(&op, &entry)| (op, entry))
+            .collect();
+        for (op, entry) in previous_entries {
+            if op < checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let (record, payload_length, mut reference) =
+                self.read_encoded_record(entry.position).await?;
+            let payload = &record.as_slice()[RECORD_PREFIX..RECORD_PREFIX + payload_length];
+            let mut next_offset = entry.next_offset;
+            let mut converted = false;
+            if reference.is_none()
+                && op > state.purge_floor
+                && let Some(segments) = &mut state.segment_storage
+            {
+                let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                    &payload[..size_of::<PrepareHeader>()],
+                )
+                .map_err(|_| invalid("invalid prepare during segment migration"))?;
+                if header.operation == Operation::SendMessages
+                    && segments::decode_batch(payload)?.base_offset
+                        >= segments.tail.position.next_offset
+                {
+                    (reference, next_offset) = segments.reserve(header, payload)?;
+                    if let Some(reference) = reference {
+                        self.write_segment_body(
+                            reference,
+                            &Frozen::from(Owned::copy_from_slice(payload)),
+                        )
+                        .await?;
+                        converted = true;
+                    }
+                }
+            }
+            let encoded_length = if converted {
+                REFERENCED_PREPARE_BYTES
+            } else {
+                payload_length
+            };
+            let mut encoded = Owned::zeroed(record_length(encoded_length)?);
+            if converted {
+                encode_record_into(payload, reference, generation, encoded.as_mut_slice())?;
+            } else {
+                encode_payload_into(
+                    payload,
+                    if reference.is_some() {
+                        SEGMENT_RECORD
+                    } else {
+                        INLINE_RECORD
+                    },
+                    generation,
+                    encoded.as_mut_slice(),
+                )?;
+            }
+            let length = encoded.as_slice().len();
+            file.write_aligned(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: entry.retained_bytes,
+                },
+            );
+            state.length += length as u64;
+            state.checkpoint_prepare |= op == checkpoint;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        self.sync_segment_files().await?;
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        let retained = self.retained_segment_paths(&entries, state.segment_storage);
+        self.obsolete.extend(
+            self.retained_segment_paths(&self.entries, self.state.segment_storage)
+                .into_iter()
+                .filter(|path| !retained.contains(path)),
+        );
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        self.obsolete.push_back(obsolete);
+        self.cleanup_obsolete().await;
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(if self.segment_references {
+            REFERENCE_STATE_MAGIC
+        } else {
+            STATE_MAGIC
+        });
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[97] = u8::from(self.checkpoint_prepare);
+        bytes[98] = u8::from(self.certified_log_view.is_some());
+        bytes[120..124].copy_from_slice(&self.certified_log_view.unwrap_or(0).to_le_bytes());
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        bytes[segments::SEGMENT_STATE_FLAG] = u8::from(self.segment_storage.is_some());
+        if let Some(segments) = self.segment_storage {
+            segments.encode(
+                &mut bytes[segments::SEGMENT_STATE_OFFSET
+                    ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+            );
+        }
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);
+        bytes[8..16].copy_from_slice(&checksum.to_le_bytes());
+        bytes
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != PARTITION_WAL_BLOCK_SIZE
+            || (&bytes[..8] != STATE_MAGIC && &bytes[..8] != REFERENCE_STATE_MAGIC)
+        {
+            return Err(invalid("unknown partition WAL frontier format"));
+        }
+        let read_u64 = |offset| -> io::Result<u64> {
+            Ok(u64::from_le_bytes(
+                bytes[offset..offset + 8]
+                    .try_into()
+                    .map_err(|_| invalid("invalid WAL frontier field"))?,
+            ))
+        };
+        if read_u64(8)? != XxHash3_64::oneshot(&bytes[16..]) {
+            return Err(invalid("partition WAL frontier checksum mismatch"));
+        }
+        let state = Self {
+            segment_references: &bytes[..8] == REFERENCE_STATE_MAGIC,
+            segment_storage: match bytes[segments::SEGMENT_STATE_FLAG] {
+                0 => None,
+                1 if &bytes[..8] == REFERENCE_STATE_MAGIC => Some(SegmentState::decode(
+                    &bytes[segments::SEGMENT_STATE_OFFSET
+                        ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+                )?),
+                _ => return Err(invalid("invalid segment storage flag")),
+            },
+            group: read_u64(16)?,
+            incarnation: read_u64(24)?,
+            generation: read_u64(32)?,
+            length: read_u64(40)?,
+            checkpoint: read_u64(48)?,
+            head: read_u64(72)?,
+            anchor_known: match bytes[96] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid WAL anchor flag")),
+            },
+            checkpoint_prepare: match bytes[97] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid checkpoint prepare flag")),
+            },
+            certified_log_view: match bytes[98] {
+                0 => None,
+                1 => Some(u32::from_le_bytes(
+                    bytes[120..124]
+                        .try_into()
+                        .map_err(|_| invalid("invalid certified view"))?,
+                )),
+                _ => return Err(invalid("invalid certified view flag")),
+            },
+            purge_generation: read_u64(104)?,
+            purge_floor: read_u64(112)?,
+            checkpoint_checksum: u128::from_le_bytes(
+                bytes[56..72]
+                    .try_into()
+                    .map_err(|_| invalid("invalid checkpoint checksum"))?,
+            ),
+            head_checksum: u128::from_le_bytes(
+                bytes[80..96]
+                    .try_into()
+                    .map_err(|_| invalid("invalid head checksum"))?,
+            ),
+        };
+        if state.length > PARTITION_WAL_CAPACITY_MAX
+            || !state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+            || state.head < state.checkpoint
+            || (!state.anchor_known && state.head != state.checkpoint)
+            || (state.checkpoint_prepare
+                && (state.checkpoint == 0 || state.length == 0 || !state.anchor_known))
+        {
+            return Err(invalid("invalid partition WAL frontier bounds"));
+        }
+        Ok(state)
+    }
+}
+
+/// Padded size of a prepare record, including its envelope.
+///
+/// # Errors
+/// Returns an error for a frame outside the protocol size bounds.
+pub fn record_length(frame_length: usize) -> io::Result<usize> {
+    if !(size_of::<PrepareHeader>()..=PREPARE_BYTES_MAX).contains(&frame_length) {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidInput,
+            format!(
+                "partition prepare size {frame_length} exceeds or falls below the supported range {}..={PREPARE_BYTES_MAX} bytes",
+                size_of::<PrepareHeader>()
+            ),
+        ));
+    }
+    Ok((RECORD_PREFIX + frame_length).next_multiple_of(PARTITION_WAL_BLOCK_SIZE))
+}
+
+fn encode_record_into(
+    prepare: &[u8],
+    reference: Option<SegmentReference>,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    if let Some(reference) = reference {
+        let mut payload = [0; REFERENCED_PREPARE_BYTES];
+        payload[..size_of::<PrepareHeader>()]
+            .copy_from_slice(&prepare[..size_of::<PrepareHeader>()]);
+        reference.encode(&mut payload[size_of::<PrepareHeader>()..]);
+        encode_payload_into(&payload, SEGMENT_RECORD, generation, bytes)
+    } else {
+        encode_payload_into(prepare, INLINE_RECORD, generation, bytes)
+    }
+}
+
+fn encode_payload_into(
+    payload: &[u8],
+    kind: u32,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    let length = u32::try_from(payload.len()).map_err(|_| invalid("oversized prepare"))?;
+    bytes[..4].copy_from_slice(&length.to_le_bytes());
+    bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+        .copy_from_slice(&kind.to_le_bytes());
+    bytes[8..16].copy_from_slice(&generation.to_le_bytes());
+    bytes[RECORD_PREFIX..RECORD_PREFIX + payload.len()].copy_from_slice(payload);
+    let checksum = XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + payload.len()]);
+    bytes[16..24].copy_from_slice(&checksum.to_le_bytes());
+    Ok(())
+}
+
+impl SegmentReference {
+    fn validate(self, header: &PrepareHeader, frame_length: usize) -> io::Result<()> {
+        if header.command != Command::Prepare
+            || header.operation != Operation::SendMessages
+            || header.size as usize != frame_length
+            || !(size_of::<PrepareHeader>() + BATCH_HEADER_SIZE..=PREPARE_BYTES_MAX)
+                .contains(&frame_length)
+            || self.length != (frame_length - size_of::<PrepareHeader>()) as u64
+            || self.position.checked_add(self.length).is_none()
+        {
+            return Err(invalid("invalid partition WAL segment reference"));
+        }
+        Ok(())
+    }
+
+    fn path(self, directory: &Path) -> PathBuf {
+        directory.join(format!(
+            "segment-{}-{}.log",
+            self.generation, self.start_offset
+        ))
+    }
+
+    fn encode(self, bytes: &mut [u8]) {
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip([
+                self.generation,
+                self.start_offset,
+                self.position,
+                self.length,
+            ])
+        {
+            field.copy_from_slice(&value.to_le_bytes());
+        }
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != SEGMENT_REFERENCE_BYTES {
+            return Err(invalid("invalid partition WAL segment reference size"));
+        }
+        let mut fields = [0; SEGMENT_REFERENCE_BYTES / size_of::<u64>()];
+        for (field, bytes) in fields
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *field = u64::from_le_bytes(*bytes);
+        }
+        let [generation, start_offset, position, length] = fields;
+        Ok(Self {
+            generation,
+            start_offset,
+            position,
+            length,
+        })
+    }
+}
+
+fn referenced_segments(
+    entries: &BTreeMap<u64, StoredPrepare>,
+    directory: &Path,

Review Comment:
   warning: `referenced_segments` has no `purge_floor` filter, while the sibling `segment_boundary` (`segments.rs:368`) does. After `mark_purge` every entry at or below the floor is provably dead (commit skips them, `iggy_partition.rs:5507`), yet its `segment-{gen}-{start}.log` link still pins the whole segment inode. `remove_public_segment_files` frees only the public name, and purge never requests a WAL checkpoint.
   Trigger: purge a topic whose WAL spans two rotations, then idle. Up to `2 x segment_size` of purged message bodies survive on disk indefinitely, invisible to retention and to `partition_wal_disk_bytes`. Purge is a deletion operation, so this is data remanence as well as unreclaimed disk.
   Distinct from the cursor/entry consistency issue at `:499`: this is inode pinning by dead references.
   Fix: drop `reference` for ops at or below `purge_floor` in `mark_purge`, or filter `referenced_segments` by the floor.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await

Review Comment:
   warning: `truncate_from` now runs the full `recover_segment_files` on every view-change suffix truncation, putting boot-shaped work on the shard's critical path: `DiskStorage::entries` spawns a fresh OS thread under a process-global `SCANNER` mutex (`durable_storage.rs:213-223`), plus two `sync_directory` fsyncs (`segments.rs:474-475`), an inline blocking `dup`+`ftruncate` (`durable_storage.rs:311-319`), and when opted in a full `max_size` `fallocate` inline (`segments.rs:406-408`). N partitions truncating in one view change means N thread spawns serialized on one global mutex.
   The settled "entries on a dedicated thread" decision was costed as boot-only.
   Fix: skip the sweep only when `rewrite` left `segments.tail` unchanged. Note `tail == checkpoint` is NOT a safe guard — `rewrite`'s `segment_boundary` fallback is `.or(Some(segments.checkpoint))`, so equal cursors are the maximal rollback, the case with the most files above the boundary to sweep.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(

Review Comment:
   warning: the extent buffer is `Owned::zeroed(K * 4096)`, memsetting 4096 B per referenced record to carry ~320 B of content, and the WAL then writes 4096 B per message batch regardless of body size (`record_length`, `:1303`). That is ~12.8x memset and write amplification for bodies under ~3.8 KB, which is where the byte saving from references is already zero.
   Fix: pack multiple referenced records per block, or size the extent from actual content. Note this changes on-disk record framing and the `state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE)` decode gate at `:686`, so it is a design item, not a patch — and sub-block packing must not co-locate an unacked record with an acked one, or one torn block destroys durably acknowledged data.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -2139,10 +2669,53 @@ where
         Ok(())
     }
 
+    async fn write_consumer_offset(
+        &self,
+        path: &str,
+        offset: u64,
+        persisted: bool,
+    ) -> Result<(), IggyError> {
+        if let Some(persistence) = &self.persistence {
+            let file = crate::offset_storage::persist_offset_retained(
+                path,
+                offset,
+                persistence.take_offset_file(path),
+            )
+            .await
+            .inspect_err(|error| {
+                persistence.fail(std::io::Error::other(error.to_string()));

Review Comment:
   critical: `write_consumer_offset` calls `persistence.fail(io::Error::other(error.to_string()))` on every `Err` from `persist_offset_retained` — ENOSPC, EDQUOT, EIO, or a failed open under fd exhaustion. `failure` is set-once with no clearing path (`persistence.rs:96/467/857-860`; `reset_with_segments` does not clear it), so `is_durable` is false forever, `certify_log_view` fails, and `drive_persistence` (`:1067-1076`) raises `FatalCommit` — `shard/src/lib.rs:7534-7541` notes such a partition never ticks again.
   This contradicts the caller's own comment at `:2630-2635` ("the pending entry must remain stageable for retry"), and `io::Error::other` erases the kind so the `!= WouldBlock` discrimination the two sibling `fail()` sites apply is impossible here.
   Composes with the retained-fd bound at `persistence.rs:70-71`: fd exhaustion -> open fails -> partition fenced permanently. The fault is also mislabelled `Operation::SendMessages`.
   Fix: `fail()` only on a non-retryable kind (mirror `:1179`/`:1203`) and return the error for the documented retry otherwise.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,

Review Comment:
   warning: `offset_files` / `retired_offset_files` retain one open fd per consumer-offset path until a checkpoint drains them (`:704-705`, cleared at `:833`), and the only bound is `CHECKPOINT_DIRTY_FILES_MAX = 1024` — which is per partition. 100 partitions x ~1024 exhausts a default `RLIMIT_NOFILE`.
   Composes with `iggy_partition.rs:2686`: once a retained-fd open fails, that error calls `persistence.fail()` and fences the partition permanently.
   Fix: cap the retained-fd map and fall back to open-per-write above the cap.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {

Review Comment:
   warning: `reserve` demands `base_offset == tail.position.next_offset` with no `op > purge_floor` exemption, while both siblings in this area have one (`partition_journal.rs:1079`, `segments.rs:368`).
   The purge is not a log-ordered partition op: `core/shard/src/router.rs:857-869` applies it as `LifecycleFrame::PurgePartition`, fanned out per replica with no fence against partition ops. So two replicas reset at different op boundaries — the backup runs `mark_purge` -> `reset_position` (`tail.next_offset = 0`) while the primary keeps minting from the pre-purge offset space. Op `accepted_head+1` then arrives carrying a pre-purge `base_offset`, clears admission (`persistence.rs:624`) and dies here with `"message offsets do not extend the physical segment tail"`, fencing the partition.
   Pre-change this was harmless: the legacy append path did no offset validation and `purge_floor_op` filtered at flush time. This adds a cross-replica contiguity precondition to an event that is not cross-replica ordered.
   Fix: skip reservation (leave inline, `reference = None`) for `header.op <= state.purge_floor`.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(

Review Comment:
   warning: `retain_segment_inodes` issues one `exists()` statx plus one `format!` + PathBuf allocation per record per batch, on the same path for every record of a batch. A 64-record batch costs 64 statx SQEs and 128 heap allocations for one link.
   Redundant in owned mode: `write_segment_body` -> `open_segment_file` (`segments.rs:437-478`) already guarantees the retained link on all three branches, and `:474-475` already does the directory fsyncs.
   Fix: return early when `state.segment_storage.is_some()`; otherwise dedupe by `(generation, start_offset)`.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {

Review Comment:
   nit: `open_segment_file` calls `file.preallocate(&public, size)` with no already-reserved or `len == 0` guard, unlike `with_read_only_messages` (`core/server_common/src/segment_storage/mod.rs:61-70`).
   Consequences: (1) the initial/installed empty segment is fallocate'd twice on one inode — the partition creates `{0}.log` first, `FALLOC_FL_KEEP_SIZE` leaves length 0, so the first `write_segment_body` takes the hard-link branch and reserves again (on later rotations the WAL creates the file first, so the partition's guard skips and there is only one); (2) it repeats on every reopen after `retain_active_segment_file` drops the handle and on every view-change recovery (`:406-408`); (3) the warn at `fs_utils.rs:83-89` labels `&public` while the fd is the retained `segment-{gen}-{off}.log` link, so a failure names a different filename than the one opened.
   Fix: guard the reserve to the create branch, and log the path of the fd actually passed.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,8 +727,510 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        self.open_persistence_with_recovered(capacity, None).await
+    }
+
+    /// # Errors
+    /// Returns an error if durable history cannot be opened, migrated, or replayed.
+    #[allow(clippy::too_many_lines)]
+    pub async fn open_persistence_with_recovered(
+        &mut self,
+        capacity: u64,
+        recovered: Option<(Rc<PartitionPersistence>, Vec<Message<PrepareHeader>>)>,
+    ) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = if let Some(recovered) = recovered {
+            recovered
+        } else {
+            PartitionPersistence::open_with_capacity(
+                &directory,
+                self.namespace().inner(),
+                self.created_revision,
+                journal::durable_storage::DiskStorage,
+                capacity,
+                self.runtime_options
+                    .preallocate_segments
+                    .unwrap_or(iggy_common::DEFAULT_PREALLOCATE_SEGMENTS),
+            )
+            .await
+            .map_err(|error| {
+                warn!(%error, "cannot open partition prepare WAL");
+                IggyError::CannotReadFile
+            })?
+        };
+        if self.durability().is_persisted() && !self.materialization_missing {
+            let segment = self.log.active_segment();
+            let length = segment.size.as_bytes_u64();
+            let initial = journal::partition_journal::SegmentPosition {
+                start_offset: segment.start_offset,
+                length,
+                next_offset: if length == 0 {
+                    segment.start_offset
+                } else {
+                    segment
+                        .end_offset
+                        .checked_add(1)
+                        .ok_or(IggyError::CannotReadFile)?
+                },
+            };
+            persistence.enable_segment_storage(initial, segment.max_size.as_bytes_u64());
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(&persistence).run());
+            }
+            persistence.drain_with_timeout().await.map_err(|error| {
+                warn!(%error, "cannot enable partition segment persistence");
+                IggyError::CannotSyncFile
+            })?;
+        }
+        self.restore_certified_log_view(&persistence).await?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    async fn restore_certified_log_view(
+        &mut self,
+        persistence: &Rc<PartitionPersistence>,
+    ) -> Result<(), IggyError> {
+        if !self.materialization_missing
+            && self.recovered_log_view.is_none()
+            && persistence.head() == 0
+        {
+            persistence.certify_log_view(self.consensus.log_view(), 0, 0);
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(persistence).run());
+            }
+            persistence
+                .drain_with_timeout()
+                .await
+                .map_err(|_| IggyError::CannotSyncFile)?;
+        }
+        if !self.materialization_missing {
+            match persistence.certified_log_view() {
+                Some(view) if view >= self.consensus.log_view() => {
+                    if view > self.consensus.view() {
+                        self.consensus.set_view(view);
+                    }
+                    self.consensus.set_log_view(view);
+                }
+                _ => {
+                    self.materialization_missing = true;
+                    self.ensure_materialization_recovery();
+                }
+            }
+        }
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.commit_messages_inner(config, true, through_op).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let mut directories = Vec::with_capacity(4);
+        for directory in [
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        {
+            let path = std::path::PathBuf::from(directory);
+            directories.push(path.clone());
+            if let Some(parent) = path.parent()
+                && !directories.iter().any(|existing| existing == parent)
+            {
+                directories.push(parent.to_path_buf());
+            }
+        }
+        if let Some(directory) = &self.partition_dir {
+            directories.push(std::path::PathBuf::from(directory));
+        }
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        if self.materialization_missing || !self.ensure_wal_view() {
+            return;
+        }
+        let durable_op = persistence.durable_op();
+        loop {
+            let ready = self
+                .pending_persisted_acks
+                .borrow()
+                .first_key_value()
+                .is_some_and(|(op, _)| *op <= durable_op);
+            if !ready {
+                break;
+            }
+            let Some((_, header)) = self.pending_persisted_acks.borrow_mut().pop_first() else {

Review Comment:
   critical: `drive_persistence` `pop_first()`s a parked ack before proving the send can happen, and `send_prepare_ok`'s `purge_deferred` fail-closed return re-inserts nothing, so the header is destroyed. The sibling at `:7940-7943` does re-insert.
   Reachability: `drive_persistence` only pops when `op <= durable_op`, so `register_rebuilt_ack` (`:7935`) returns `true` and does not re-park; `purge_deferred` then returns `false` and the header is gone. One parked ack lost per tick for as long as a purge stays deferred (`PurgeError::FrontierNotRecorded`, re-issued by the reconciler).
   On a promoted primary whose whole rebuilt window was parked (`:11750` -> `:1146-1157`) this is unrecoverable: `RetransmitPrepares` to self is a no-op and this plane has no `repair_primary_self_acks` — its own doc says so at `:4744-4747`. `commit_max` pins below that op forever.
   Fix: peek, send, and pop only on a delivered send.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {

Review Comment:
   warning: `migrate_segment_prepares` predicates on `entry.reference.is_none()`, which is permanently true for any retained non-`SendMessages` prepare — those never acquire a reference (`:520-522`) and `rewrite` gates conversion on `Operation::SendMessages` (`partition_journal.rs:1086`). A typical persisted topic retains a consumer-offset prepare above `purge_floor`.
   Called unconditionally at `partition_journal.rs:246` after every open, so every boot runs a full `rewrite` + generation swap + frontier publish that changes nothing, and `rewrite` sets `poisoned = true` first (`:1005`) with no recovery path but reopen.
   Compounding: any legacy inline entry whose `base_offset > segments.tail.position.next_offset` passes the migration guard (`:1086-1088` tests `>=`) but fails `reserve`'s exact equality, so the Err leaves a freshly opened journal poisoned and `:246` repeats it on every retry — an unrecoverable boot loop.
   Fix: predicate on convertibility, and make the boot migration refuse with intact state rather than poison.



##########
core/server_common/src/fs_utils.rs:
##########
@@ -44,6 +48,58 @@ impl DirEntry {
     }
 }
 
+/// Reserve segment space without changing its contents or logical length.
+/// Unsupported or failed reservations fall back to buffered allocation.
+#[cfg(target_os = "linux")]
+pub fn preallocate_file(file: &fs::File, file_path: &Path, len: u64) {
+    let Ok(len) = i64::try_from(len) else {
+        warn!(
+            target: "iggy.partitions.storage",
+            file = %file_path.display(),
+            preallocate_len = len,
+            "file preallocation size is unsupported, using buffered allocation"
+        );
+        return;
+    };
+
+    // Runs INLINE on the shard thread, deliberately. `server_common::executor`
+    // sets `thread_pool_limit(0)` on the shard proactor, so `spawn_blocking`
+    // has no worker to park a task on and compio panics the shard outright with
+    // "the thread pool is needed but no worker thread is running". (That limit
+    // is skipped on macOS, whose polling driver routes fs through the pool, so
+    // the panic is Linux-and-most-targets, not universal. This arm is
+    // Linux-only regardless.)
+    //
+    // The cost is acceptable only because of what this call is: a metadata-only
+    // extent reservation, microseconds on the local filesystems this option
+    // exists for, and an immediate `EOPNOTSUPP` where the filesystem cannot do
+    // it. Where it can genuinely block -- NFSv4.2 `ALLOCATE`, FUSE, a badly
+    // fragmented extent tree forcing a journal commit -- it stalls the whole
+    // core, not one partition, because nothing here yields. Preallocation is
+    // opt-in per topic at creation for that reason; on such a deployment,
+    // create topics without `preallocate_segments` rather than reintroducing a
+    // pool the shard runtime does not have.
+    if let Err(error) = fallocate(file, FallocateFlags::FALLOC_FL_KEEP_SIZE, 0, len) {
+        warn!(
+            target: "iggy.partitions.storage",
+            file = %file_path.display(),
+            preallocate_len = len,
+            %error,
+            "file preallocation failed, using buffered allocation"
+        );
+    }
+}
+
+/// Reserve segment space when supported, without changing its logical length.
+#[cfg(not(target_os = "linux"))]

Review Comment:
   nit: the non-Linux stub warns on every call, not once — per segment creation (`segment_storage/mod.rs:69`, `messages_writer.rs:65`) and now per view-change recovery (`segments.rs:407`). On a many-partition non-Linux host boot emits one WARN per owned partition.
   Fix: guard with a `OnceLock`, or warn once at topic creation when the platform cannot honour `preallocate_segments`.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;

Review Comment:
   warning: `APPEND_BATCH_BYTES_MAX` caps batch coalescing on `record_length(prepare.len())`, i.e. body bytes, while the actual WAL extent under segment storage is 4096 B per record. A 512 KiB batch therefore stops coalescing after two records for an 8 KiB WAL write, keeping the barrier count per record high exactly where references made the write cheap.
   Fix: cap on WAL record bytes when segment storage is on.



##########
core/server_common/src/segment_storage/mod.rs:
##########
@@ -39,6 +42,49 @@ pub struct SegmentStorage {
 }
 
 impl SegmentStorage {
+    /// The WAL owns message writes; this storage exposes only their committed prefix.
+    pub async fn with_read_only_messages(
+        messages_path: &str,
+        index_path: &str,
+        indexes_size: u64,
+        file_exists: bool,
+        preallocate_size: Option<u64>,
+    ) -> Result<Self, IggyError> {
+        let messages_file = compio::fs::OpenOptions::new()

Review Comment:
   nit: `with_read_only_messages` opens the messages file only to statx it, maybe `fallocate`, and then `sync_all()` — a full metadata fsync — before dropping the fd; `MessagesReader::new` at `:82` reopens the same path. The `sync_all` fires even when `preallocate_size` is `None`, where the open accomplished nothing and the WAL has already barriered the inode.
   Fix: skip the open entirely when `preallocate_size` is `None`, and reuse the reader's fd otherwise.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;
+            Some(reference)
+        } else {
+            None
+        };
+        Ok((buffer, frame_length, reference))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+        checkpoint_prepare: Option<(Frozen<4096>, Option<SegmentReference>)>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            checkpoint_prepare: false,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            if checkpoint > self.state.checkpoint {
+                segments.checkpoint = self
+                    .segment_boundary(checkpoint)
+                    .ok_or_else(|| invalid("missing segment checkpoint boundary"))?;
+            }
+            if let Some(from_op) = truncate.filter(|from_op| *from_op > 0) {
+                segments.tail = self
+                    .segment_boundary(from_op - 1)
+                    .ok_or_else(|| invalid("missing segment rollback boundary"))?;
+            }
+        }
+        if let Some((prepare, reference)) = checkpoint_prepare {
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let mut encoded = Owned::zeroed(length);
+            encode_record_into(
+                prepare.as_slice(),
+                reference,
+                generation,
+                encoded.as_mut_slice(),
+            )?;
+            let length = encoded.as_slice().len();
+            file.write_aligned(0, encoded).await?;
+            entries.insert(
+                checkpoint,
+                StoredPrepare {
+                    position: 0,
+                    length,
+                    checksum,
+                    reference,
+                    next_offset: None,
+                    retained_bytes: record_length(prepare.len())? as u64,
+                },
+            );
+            state.length = length as u64;
+            state.checkpoint_prepare = true;
+        }
+        let previous_entries: Vec<_> = self
+            .entries
+            .iter()
+            .map(|(&op, &entry)| (op, entry))
+            .collect();
+        for (op, entry) in previous_entries {
+            if op < checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let (record, payload_length, mut reference) =
+                self.read_encoded_record(entry.position).await?;
+            let payload = &record.as_slice()[RECORD_PREFIX..RECORD_PREFIX + payload_length];
+            let mut next_offset = entry.next_offset;
+            let mut converted = false;
+            if reference.is_none()
+                && op > state.purge_floor
+                && let Some(segments) = &mut state.segment_storage
+            {
+                let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                    &payload[..size_of::<PrepareHeader>()],
+                )
+                .map_err(|_| invalid("invalid prepare during segment migration"))?;
+                if header.operation == Operation::SendMessages
+                    && segments::decode_batch(payload)?.base_offset
+                        >= segments.tail.position.next_offset
+                {
+                    (reference, next_offset) = segments.reserve(header, payload)?;
+                    if let Some(reference) = reference {
+                        self.write_segment_body(
+                            reference,
+                            &Frozen::from(Owned::copy_from_slice(payload)),
+                        )
+                        .await?;
+                        converted = true;
+                    }
+                }
+            }
+            let encoded_length = if converted {
+                REFERENCED_PREPARE_BYTES
+            } else {
+                payload_length
+            };
+            let mut encoded = Owned::zeroed(record_length(encoded_length)?);
+            if converted {
+                encode_record_into(payload, reference, generation, encoded.as_mut_slice())?;
+            } else {
+                encode_payload_into(
+                    payload,
+                    if reference.is_some() {
+                        SEGMENT_RECORD
+                    } else {
+                        INLINE_RECORD
+                    },
+                    generation,
+                    encoded.as_mut_slice(),
+                )?;
+            }
+            let length = encoded.as_slice().len();
+            file.write_aligned(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: entry.retained_bytes,
+                },
+            );
+            state.length += length as u64;
+            state.checkpoint_prepare |= op == checkpoint;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        self.sync_segment_files().await?;
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        let retained = self.retained_segment_paths(&entries, state.segment_storage);
+        self.obsolete.extend(
+            self.retained_segment_paths(&self.entries, self.state.segment_storage)
+                .into_iter()
+                .filter(|path| !retained.contains(path)),
+        );
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        self.obsolete.push_back(obsolete);
+        self.cleanup_obsolete().await;
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(if self.segment_references {
+            REFERENCE_STATE_MAGIC
+        } else {
+            STATE_MAGIC
+        });
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[97] = u8::from(self.checkpoint_prepare);
+        bytes[98] = u8::from(self.certified_log_view.is_some());
+        bytes[120..124].copy_from_slice(&self.certified_log_view.unwrap_or(0).to_le_bytes());
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        bytes[segments::SEGMENT_STATE_FLAG] = u8::from(self.segment_storage.is_some());
+        if let Some(segments) = self.segment_storage {
+            segments.encode(
+                &mut bytes[segments::SEGMENT_STATE_OFFSET
+                    ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+            );
+        }
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);

Review Comment:
   warning: the frontier checksum is `XxHash3_64(&bytes[16..])`, so `bytes[..8]` — the magic — is unauthenticated, and this change made that range decide the record format: `:1229` derives `segment_references` from it and `:1232` decodes the 80-byte `SegmentState` only under `IGGYWAL2`.
   Damage confined to those bytes verifies clean and reinterprets the frontier. The `IGGYWAL1`->`IGGYWAL2` direction is silently accepted (`segment_references = true` with `segment_storage: None`), though it cannot complete into a body misread because `encode_payload_into:1335` spans `RECORD_KIND_OFFSET`. The reachable harm is the reverse: `IGGYWAL2`->`IGGYWAL1` with flag byte 99 == 1 hits `:1236` `Err("invalid segment storage flag")` and leaves the partition permanently unopenable.
   Trigger is narrow — `publish` writes `frontier.tmp`, syncs, then renames atomically, and `'1'`/`'2'` differ by two bits — so this is hardening a newly load-bearing field, not a likely failure.
   Fix: hash `bytes[..8]` together with `bytes[16..]`.



##########
core/shard/src/lib.rs:
##########
@@ -11549,6 +11619,51 @@ async fn dispatch_vsr_actions<B, P, J>(
     }
 }
 
+fn partition_start_view_suffix<B: MessageBus, SB: SuperblockStore>(

Review Comment:
   warning: `partition_start_view_suffix` allocates and copies up to `DVC_HEADERS_MAX` (128) x 256 B = 32 KiB of headers and broadcasts it on the stale-peer correction path (`:4725-4733`), per partition per heartbeat, where the suffix was previously `Vec::new()`. The metadata arm at `:4683` still sends none, so the two planes are asymmetric.
   `CommitOutcome::RespondStartView` fires on every heartbeat from a lagging replica, so this is 128 `repair_header` lookups plus one Vec allocation per fire.
   Fix: bound by actual peer lag, or send headers only when the peer's `op` is below head.



##########
core/journal/src/durable_storage.rs:
##########
@@ -0,0 +1,343 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use compio::buf::{IntoInner, IoBuf};
+use compio::fs::{File, OpenOptions};
+use compio::io::{AsyncReadAtExt, AsyncWriteAtExt};
+use futures::channel::oneshot;
+use futures::lock::Mutex;
+use server_common::iobuf::{Frozen, Owned};
+use std::ffi::OsString;
+use std::io;
+use std::path::Path;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OpenMode {
+    Read,
+    ReadWrite,
+    Create,
+}
+
+pub struct StorageEntry {
+    pub name: OsString,
+    pub directory: bool,
+}
+
+/// Filesystem operations whose completion and persistence order affect recovery.
+/// Implementations must preserve open file identity across rename and unlink.
+pub trait DurableStorage {
+    type File: DurableFile;
+
+    /// Process-local identity for exclusive writer ownership.
+    ///
+    /// # Errors
+    /// Returns an error if the absolute identity cannot be resolved.
+    fn writer_identity(&self, _path: &Path) -> io::Result<Option<std::path::PathBuf>> {
+        Ok(None)
+    }
+
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn open(&self, path: &Path, mode: OpenMode) -> impl Future<Output = io::Result<Self::File>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn create_directories(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn sync_directory(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn rename(&self, source: &Path, target: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn remove_file(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn hard_link(&self, source: &Path, target: &Path) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns the underlying filesystem error.
+    fn exists(&self, path: &Path) -> impl Future<Output = io::Result<bool>>;
+    /// # Errors
+    /// Returns an error for unreadable directories or unsupported file types.
+    fn entries(&self, path: &Path) -> impl Future<Output = io::Result<Vec<StorageEntry>>>;
+    /// # Errors
+    /// Returns the underlying filesystem error. Missing paths are accepted.
+    fn remove_tree(&self, path: &Path) -> impl Future<Output = io::Result<()>>;
+}
+
+pub trait DurableFile {
+    /// Best-effort reservation that must not change bytes or logical length.
+    /// Backends without physical allocation may ignore this hint.
+    fn preallocate(&self, _path: &Path, _length: u64) {}
+
+    /// # Errors
+    /// Returns an error if the complete range cannot be read.
+    fn read(&self, offset: u64, length: usize) -> impl Future<Output = io::Result<Vec<u8>>>;
+    /// # Errors
+    /// Returns an error if any part of the write fails.
+    fn write(&mut self, offset: u64, bytes: Vec<u8>) -> impl Future<Output = io::Result<()>>;
+    /// # Errors
+    /// Returns an error if the immutable extent cannot be written completely.
+    fn write_frozen(

Review Comment:
   nit: the default `write_frozen` does `bytes.as_slice().to_vec()`, a full body copy, and `SimFile` (`core/simulator/src/storage.rs:376`) does not override it — so every simulated body write allocates and copies the whole batch. Sim-only, but it inflates DST memory pressure, which the deterministic-simulator work tracks.
   Fix: override `write_frozen` on `SimFile`.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,
+    retired_offset_files: RefCell<Vec<S::File>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    certified_log_view: Cell<Option<u32>>,
+    requested_log_view: Cell<Option<(u32, u64, u128)>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    checkpoint_needed: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    retained_bytes: Cell<u64>,
+    segment_checkpoint: Cell<Option<SegmentPosition>>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    writer_active: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct WriterLease {
+    key: PathBuf,
+    id: u64,
+    retired: AtomicBool,
+    running: AtomicBool,
+    waiters: Mutex<Vec<std::task::Waker>>,
+}
+
+struct WriterRegistration {
+    id: u64,
+    writer: Weak<WriterLease>,
+    interrupted: bool,
+}
+
+static WRITERS: LazyLock<Mutex<HashMap<PathBuf, WriterRegistration>>> =
+    LazyLock::new(|| Mutex::new(HashMap::new()));
+
+impl WriterLease {
+    async fn acquire(key: PathBuf) -> io::Result<Arc<Self>> {
+        loop {
+            let previous = {
+                let mut writers = WRITERS
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if writers
+                    .get(&key)
+                    .is_some_and(|registration| registration.interrupted)
+                {
+                    return Err(io::Error::other(
+                        "interrupted partition WAL writer requires process restart",
+                    ));
+                }
+                if let Some(previous) = writers
+                    .get(&key)
+                    .and_then(|registration| registration.writer.upgrade())
+                {
+                    drop(writers);
+                    Some(previous)
+                } else {
+                    let lease = Arc::new(Self {
+                        key: key.clone(),
+                        id: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+                        retired: AtomicBool::new(false),
+                        running: AtomicBool::new(false),
+                        waiters: Mutex::new(Vec::new()),
+                    });
+                    writers.insert(
+                        key.clone(),
+                        WriterRegistration {
+                            id: lease.id,
+                            writer: Arc::downgrade(&lease),
+                            interrupted: false,
+                        },
+                    );
+                    drop(writers);
+                    return Ok(lease);
+                }
+            };
+            let Some(previous) = previous else { continue };
+            if !previous.retired.load(Ordering::Acquire) {
+                return Err(io::Error::new(
+                    io::ErrorKind::AlreadyExists,
+                    "partition WAL already has an active writer",
+                ));
+            }
+            compio::runtime::time::timeout(
+                PERSISTENCE_DRAIN_TIMEOUT,
+                futures::future::poll_fn(|context| {
+                    let mut waiters = previous
+                        .waiters
+                        .lock()
+                        .unwrap_or_else(std::sync::PoisonError::into_inner);
+                    if !previous.running.load(Ordering::Acquire) {
+                        return std::task::Poll::Ready(());
+                    }
+                    if !waiters
+                        .iter()
+                        .any(|waiter| waiter.will_wake(context.waker()))
+                    {
+                        waiters.push(context.waker().clone());
+                    }
+                    std::task::Poll::Pending
+                }),
+            )
+            .await
+            .map_err(|_| {
+                io::Error::new(
+                    io::ErrorKind::TimedOut,
+                    "retired partition WAL writer did not stop",
+                )
+            })?;
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if writers
+                .get(&key)
+                .is_some_and(|registration| registration.id == previous.id)
+            {
+                writers.remove(&key);
+            }
+        }
+    }
+
+    fn finish(&self) {
+        self.running.store(false, Ordering::Release);
+        for waiter in self
+            .waiters
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .drain(..)
+        {
+            waiter.wake();
+        }
+    }
+}
+
+impl Drop for WriterLease {
+    fn drop(&mut self) {
+        let mut writers = WRITERS
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if writers
+            .get(&self.key)
+            .is_some_and(|registration| registration.id == self.id && !registration.interrupted)
+        {
+            writers.remove(&self.key);
+        }
+    }
+}
+
+struct WriterTicket<S: DurableStorage> {
+    owner: Rc<PartitionPersistence<S>>,
+    started: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterTicket<S> {
+    fn drop(&mut self) {
+        if self.started {
+            return;
+        }
+        self.owner.fail(io::Error::new(
+            io::ErrorKind::Interrupted,
+            "partition WAL writer was dropped before polling",
+        ));
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct WriterGuard<'a, S: DurableStorage> {
+    owner: &'a PartitionPersistence<S>,
+    journal: Option<PartitionPrepareJournal<S>>,
+    complete: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterGuard<'_, S> {
+    fn drop(&mut self) {
+        *self.owner.journal.borrow_mut() = self.journal.take();
+        self.owner.in_flight_bytes.set(0);
+        self.owner.checkpoint_running.set(false);
+        if !self.complete
+            && let Some(lease) = &self.owner.lease
+        {
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if let Some(registration) = writers.get_mut(&lease.key)
+                && registration.id == lease.id
+            {
+                registration.interrupted = true;
+            }
+        }
+        if !self.complete && self.owner.failure.borrow().is_none() {
+            *self.owner.failure.borrow_mut() = Some(Arc::new(io::Error::new(
+                io::ErrorKind::Interrupted,
+                "partition WAL writer stopped during a mutation",
+            )));
+        }
+        self.owner.writer_active.set(false);
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation<S: DurableStorage> {
+    EnableSegments {
+        epoch: u64,
+        initial: SegmentPosition,
+        max_size: u64,
+    },
+    CertifyView {
+        epoch: u64,
+        view: u32,
+        op: u64,
+        checksum: u128,
+    },
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+        offset_files: Vec<S::File>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        let lease = if let Some(key) = storage.writer_identity(directory)? {
+            Some(WriterLease::acquire(key).await?)
+        } else {
+            None
+        };
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+            preallocate_segments,
+        )
+        .await?;
+        let prepares = journal.take_recovered_prepares();
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare.header();
+            if header.op > journal.checkpoint_op() {
+                accepted.checksums.push_back(header.checksum);
+            }
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            lease,
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            certified_log_view: Cell::new(journal.certified_log_view()),
+            requested_log_view: Cell::new(None),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            checkpoint_needed: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            retained_bytes: Cell::new(journal.retained_bytes()),
+            segment_checkpoint: Cell::new(journal.segment_checkpoint()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            offset_files: RefCell::new(HashMap::new()),
+            retired_offset_files: RefCell::new(Vec::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            writer_active: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    #[cfg(test)]
+    pub(crate) fn exhaust_capacity_for_test(&self) {
+        self.disk_bytes.set(self.capacity);
+        self.retained_bytes.set(self.capacity);
+    }
+
+    #[cfg(test)]
+    pub(crate) fn release_capacity_for_test(&self) {
+        self.disk_bytes.set(0);
+        self.retained_bytes.set(0);
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.certified_log_view.get()
+    }
+
+    pub fn certify_log_view(&self, view: u32, op: u64, checksum: u128) -> bool {
+        if self.certified_log_view.get() == Some(view) {
+            return true;
+        }
+        if self.retired.get()
+            || self.failure.borrow().is_some()
+            || op > self.head()
+            || !(op == 0 && checksum == 0 || self.checksum(op) == Some(checksum))
+        {
+            return false;
+        }
+        let target = (view, op, checksum);
+        if self
+            .requested_log_view
+            .get()
+            .is_none_or(|(pending, _, _)| pending != view)
+        {
+            self.requested_log_view.set(Some(target));
+            self.queue.borrow_mut().push_back(Mutation::CertifyView {
+                epoch: self.epoch.get(),
+                view,
+                op,
+                checksum,
+            });
+        }
+        false
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.checksum(header.op) == Some(header.checksum)
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        self.segment_checkpoint.get()
+    }
+
+    pub fn enable_segment_storage(&self, initial: SegmentPosition, max_size: u64) {
+        self.queue.borrow_mut().push_back(Mutation::EnableSegments {
+            epoch: self.epoch.get(),
+            initial,
+            max_size,
+        });
+    }
+
+    /// Verify the physical prefix before making its indexes and logical sizes visible.
+    ///
+    /// # Errors
+    /// Returns an error for a failed barrier or a body outside the durable segment range.
+    pub async fn validate_segment_prefix(
+        &self,
+        prepares: &[Frozen<4096>],
+        start_offset: u64,
+        mut position: u64,
+    ) -> io::Result<u64> {
+        self.drain_with_timeout().await?;
+        let journal = self.journal.borrow();
+        let journal = journal
+            .as_ref()
+            .ok_or_else(|| io::Error::other("segment writer has no journal"))?;
+        let initial = position;
+        for prepare in prepares {
+            let header = prepare_header(prepare)?;
+            let reference: SegmentReference = journal
+                .segment_reference(header)
+                .ok_or_else(|| io::Error::other("committed prepare has no durable segment body"))?;
+            if reference.start_offset != start_offset
+                || reference.position != position
+                || reference.length != (prepare.len() - size_of::<PrepareHeader>()) as u64
+            {
+                return Err(io::Error::other(
+                    "committed prepare differs from its segment position",
+                ));
+            }
+            position = position
+                .checked_add(reference.length)
+                .ok_or_else(|| io::Error::other("segment prefix overflow"))?;
+        }
+        Ok(position - initial)
+    }
+
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head.get()
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .retained_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn take_offset_file(&self, path: &str) -> Option<S::File> {
+        self.offset_files.borrow_mut().remove(path)
+    }
+
+    /// # Panics
+    /// Panics if the previous writer was not taken before replacement.
+    pub fn retain_offset_file(&self, path: String, file: S::File) {
+        assert!(self.offset_files.borrow_mut().insert(path, file).is_none());
+    }
+
+    pub fn retire_offset_file(&self, path: &str) {
+        if let Some(file) = self.take_offset_file(path) {
+            self.retired_offset_files.borrow_mut().push(file);
+        }
+    }
+
+    pub fn mark_offset_dirty(&self, kind_index: usize, consumer_id: u32, exists: bool) {
+        let mut offsets = self.dirty_offsets[kind_index].borrow_mut();
+        if exists {
+            offsets.insert(consumer_id);
+        } else {
+            offsets.remove(&consumer_id);
+        }
+    }
+
+    pub fn retire_offset_files(&self) {
+        self.retired_offset_files
+            .borrow_mut()
+            .extend(self.offset_files.borrow_mut().drain().map(|(_, file)| file));
+    }
+
+    pub fn take_dirty_files(&self) -> (BTreeSet<u64>, [BTreeSet<u32>; 2]) {
+        (
+            std::mem::take(&mut *self.dirty_segments.borrow_mut()),
+            std::array::from_fn(|index| {
+                std::mem::take(&mut *self.dirty_offsets[index].borrow_mut())
+            }),
+        )
+    }
+
+    pub fn checkpoint(&self, through_op: u64) {
+        self.checkpoint_files(through_op, Vec::new(), Vec::new());
+    }
+
+    pub fn checkpoint_files(
+        &self,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    ) {
+        if through_op <= self.checkpoint_requested.get() {
+            return;
+        }
+        self.checkpoint_requested.set(through_op);
+        self.checkpoint_needed.set(false);
+        let mut offset_files = std::mem::take(&mut *self.retired_offset_files.borrow_mut());
+        offset_files.extend(self.offset_files.borrow_mut().drain().map(|(_, file)| file));
+        self.queue.borrow_mut().push_back(Mutation::Checkpoint {
+            epoch: self.epoch.get(),
+            through_op,
+            files,
+            directories,
+            offset_files,
+        });
+    }
+
+    pub const fn checkpoint_pending(&self) -> bool {
+        self.checkpoint_running.get() || self.checkpoint_requested.get() > self.checkpoint.get()
+    }
+
+    pub fn request_checkpoint(&self) {
+        self.checkpoint_needed.set(true);
+    }
+
+    pub fn truncate_from(&self, from_op: u64) {
+        if from_op > self.accepted_head.get() {
+            return;
+        }
+        self.checkpoint_requested.set(self.checkpoint.get());
+        self.certified_log_view.set(None);
+        self.requested_log_view.set(None);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        // Retained submissions still precede the replacement history.
+        self.queue
+            .borrow_mut()
+            .retain_mut(|mutation| match mutation {
+                Mutation::Append {
+                    epoch: previous,
+                    prepare,
+                    bytes,
+                    ..
+                } => {
+                    if prepare_header(prepare).is_ok_and(|header| header.op < from_op) {
+                        *previous = epoch;
+                        true
+                    } else {
+                        self.queued_bytes
+                            .set(self.queued_bytes.get().saturating_sub(*bytes));
+                        false
+                    }
+                }
+                Mutation::Checkpoint {
+                    epoch: previous,
+                    through_op,
+                    ..
+                } if *through_op < from_op => {
+                    *previous = epoch;
+                    self.checkpoint_requested
+                        .set(self.checkpoint_requested.get().max(*through_op));
+                    true
+                }
+                _ => false,
+            });
+        self.accepted.borrow_mut().truncate_from(from_op);
+        self.accepted_head.set(from_op.saturating_sub(1));
+        self.durable_head
+            .set(self.durable_head.get().min(from_op.saturating_sub(1)));
+        self.queue
+            .borrow_mut()
+            .push_back(Mutation::Truncate { epoch, from_op });
+    }
+
+    pub fn reset(&self, op: u64, checksum: Option<u128>) {
+        self.reset_with_prepare(op, checksum, None);
+    }
+
+    pub fn reset_with_prepare(
+        &self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+    ) {
+        self.reset_with_segments(op, checksum, prepare, None);
+    }
+
+    pub fn reset_with_segments(
+        &self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    ) {
+        self.offset_files.borrow_mut().clear();
+        self.retired_offset_files.borrow_mut().clear();
+        self.certified_log_view.set(None);
+        self.requested_log_view.set(None);
+        self.checkpoint_requested.set(op);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        self.queue.borrow_mut().clear();
+        self.queued_bytes.set(0);
+        *self.accepted.borrow_mut() = AcceptedPrepares {
+            base: op,
+            checksums: VecDeque::new(),
+        };
+        self.accepted_head.set(op);
+        self.durable_head.set(0);
+        self.queue.borrow_mut().push_back(Mutation::Reset {
+            epoch,
+            op,
+            checksum,
+            prepare,
+            segments,
+        });
+    }
+
+    pub fn mark_purge(&self, generation: u64, floor: u64) {
+        self.queue.borrow_mut().push_back(Mutation::Purge {
+            epoch: self.epoch.get(),
+            generation,
+            floor,
+        });
+    }
+
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.purge_generation.get(), self.purge_floor.get())
+    }
+
+    pub fn needs_checkpoint(&self) -> bool {
+        !self.checkpoint_pending()
+            && (self.checkpoint_needed.get()
+                || self.retained_bytes.get() + self.queued_bytes.get() + self.in_flight_bytes.get()
+                    >= self.capacity / 2
+                || self.retired_offset_files.borrow().len() >= CHECKPOINT_DIRTY_FILES_MAX
+                || self.dirty_segments.borrow().len() * 2
+                    + self
+                        .dirty_offsets
+                        .iter()
+                        .map(|offsets| offsets.borrow().len())
+                        .sum::<usize>()
+                    >= CHECKPOINT_DIRTY_FILES_MAX)
+    }
+
+    pub fn take_metrics(&self) -> PersistenceMetrics {
+        PersistenceMetrics {
+            disk_bytes: self.disk_bytes.get(),
+            queued_bytes: self.queued_bytes.get(),
+            in_flight_bytes: self.in_flight_bytes.get(),
+            checkpoints_pending: u64::from(self.checkpoint_pending()),
+            completed_batches: self.completed_batches.replace(0),
+            batched_prepares: self.batched_prepares.replace(0),
+            completed_checkpoints: self.completed_checkpoints.replace(0),
+            failed_writes: self.failed_writes.replace(0),
+        }
+    }
+
+    pub fn fail(&self, error: io::Error) {
+        self.failed_writes.set(self.failed_writes.get() + 1);
+        *self.failure.borrow_mut() = Some(Arc::new(error));
+        self.notify();
+    }
+
+    pub fn failure(&self) -> Option<Arc<io::Error>> {
+        self.failure.borrow().clone()
+    }
+
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.checkpoint.get()
+    }
+
+    pub fn checksum(&self, op: u64) -> Option<u128> {
+        if op == self.checkpoint.get() {
+            self.checkpoint_checksum.get()
+        } else {
+            self.accepted.borrow().checksum(op)
+        }
+    }
+
+    pub const fn head(&self) -> u64 {
+        self.accepted_head.get()
+    }
+
+    pub fn retire(&self) {
+        self.retired.set(true);
+        if let Some(lease) = &self.lease {
+            lease.retired.store(true, Ordering::Release);
+        }
+        self.queue.borrow_mut().clear();
+        self.queued_bytes.set(0);
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn drain(&self) -> io::Result<()> {
+        futures::future::poll_fn(|context| {
+            if !self.running.get()
+                && let Some(error) = self.failure()
+            {
+                return std::task::Poll::Ready(Err(io::Error::new(error.kind(), error)));
+            }
+            if !self.running.get() && self.queue.borrow().is_empty() {
+                return std::task::Poll::Ready(Ok(()));
+            }
+            let mut waiters = self.waiters.borrow_mut();
+            if !waiters
+                .iter()
+                .any(|waiter| waiter.will_wake(context.waker()))
+            {
+                waiters.push(context.waker().clone());
+            }
+            std::task::Poll::Pending
+        })
+        .await
+    }
+
+    /// # Errors
+    /// Returns a storage failure or a timeout without allowing a second writer.
+    pub async fn drain_with_timeout(&self) -> io::Result<()> {
+        compio::runtime::time::timeout(PERSISTENCE_DRAIN_TIMEOUT, self.drain())
+            .await
+            .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "partition WAL drain timed out"))?
+    }
+
+    pub fn start(&self) -> bool {
+        let start = !self.retired.get()
+            && self.failure.borrow().is_none()
+            && !self.queue.borrow().is_empty()
+            && !self.running.replace(true);
+        if start && let Some(lease) = &self.lease {
+            lease.running.store(true, Ordering::Release);
+        }
+        start
+    }
+
+    pub fn run(self: Rc<Self>) -> impl Future<Output = ()> {
+        let mut ticket = WriterTicket {
+            owner: self,
+            started: false,
+        };
+        async move {
+            ticket.started = true;
+            Rc::clone(&ticket.owner).run_inner().await;
+        }
+    }
+
+    async fn run_inner(self: Rc<Self>) {
+        if self.writer_active.replace(true) {
+            self.fail(io::Error::other("partition WAL writer was started twice"));
+            return;
+        }
+        self.running.set(true);
+        if let Some(lease) = &self.lease {
+            lease.running.store(true, Ordering::Release);
+        }
+        let journal = self.journal.borrow_mut().take();
+        let mut guard = WriterGuard {
+            owner: &self,
+            journal,
+            complete: false,
+        };
+        let Some(journal) = guard.journal.as_mut() else {
+            self.fail(io::Error::other("partition WAL writer has no journal"));
+            guard.complete = true;
+            return;
+        };
+        loop {
+            if self.retired.get() {
+                break;
+            }
+            let Some(mutation) = self.queue.borrow_mut().pop_front() else {
+                break;
+            };
+            let (epoch, bytes) = match &mutation {
+                Mutation::Append { epoch, bytes, .. } => (*epoch, *bytes),
+                Mutation::CertifyView { epoch, .. }
+                | Mutation::EnableSegments { epoch, .. }
+                | Mutation::Purge { epoch, .. }
+                | Mutation::Truncate { epoch, .. }
+                | Mutation::Checkpoint { epoch, .. }
+                | Mutation::Reset { epoch, .. } => (*epoch, 0),
+            };
+            self.queued_bytes
+                .set(self.queued_bytes.get().saturating_sub(bytes));
+            self.in_flight_bytes.set(bytes);
+            let result = self.apply_mutation(journal, mutation, epoch, bytes).await;
+            self.in_flight_bytes.set(0);
+            if let Err(error) = result {
+                self.failed_writes.set(self.failed_writes.get() + 1);
+                *self.failure.borrow_mut() = Some(Arc::new(error));
+                self.notify();
+                break;
+            }
+            if epoch == self.epoch.get() && !self.retired.get() {
+                self.disk_bytes.set(journal.size_bytes());
+                self.retained_bytes.set(journal.retained_bytes());
+                self.segment_checkpoint.set(journal.segment_checkpoint());
+                let advanced = journal.durable_op() != self.durable_head.get()
+                    || journal.checkpoint_op() != self.checkpoint.get()
+                    || journal.certified_log_view() != self.certified_log_view.get();
+                self.certified_log_view.set(journal.certified_log_view());
+                if self
+                    .requested_log_view
+                    .get()
+                    .is_some_and(|(view, _, _)| Some(view) == self.certified_log_view.get())
+                {
+                    self.requested_log_view.set(None);
+                }
+                self.durable_head.set(journal.durable_op());
+                if journal.checkpoint_op() > self.checkpoint.get() {
+                    self.accepted
+                        .borrow_mut()
+                        .checkpoint(journal.checkpoint_op());
+                }
+                self.checkpoint.set(journal.checkpoint_op());
+                self.checkpoint_checksum.set(journal.checkpoint_checksum());
+                self.purge_generation.set(journal.purge_marker().0);
+                self.purge_floor.set(journal.purge_marker().1);
+                if advanced {
+                    self.notify();
+                }
+            }
+        }
+        guard.complete = true;
+    }
+
+    async fn apply_mutation(
+        &self,
+        journal: &mut PartitionPrepareJournal<S>,
+        mutation: Mutation<S>,
+        epoch: u64,
+        bytes: u64,
+    ) -> io::Result<()> {
+        match mutation {
+            Mutation::EnableSegments {
+                initial, max_size, ..
+            } => journal.enable_segment_storage(initial, max_size).await,
+            Mutation::CertifyView {
+                view, op, checksum, ..
+            } => journal.certify_log_view(view, op, checksum).await,
+            Mutation::Purge {
+                generation, floor, ..
+            } => journal.mark_purge(generation, floor).await,
+            Mutation::Append {
+                prepare, durable, ..
+            } => {
+                self.append_batch(journal, prepare, durable, epoch, bytes)
+                    .await
+            }
+            Mutation::Truncate { from_op, .. } => journal.truncate_from(from_op).await,
+            Mutation::Checkpoint {
+                through_op,
+                files,
+                directories,
+                offset_files,
+                ..
+            } => {
+                self.checkpoint_running.set(true);
+                let result = async {
+                    futures::stream::iter(offset_files.iter().map(Ok::<_, io::Error>))

Review Comment:
   nit: each dirty consumer-offset file is fsynced twice per checkpoint — once through the retained fd here, once via a fresh `open(path, Read)` in `checkpoint_files` (`partition_journal.rs:387-391`), the same path from the same `persisted_offset_path`. Up to 1024 extra open+fsync+close per checkpoint.
   Do NOT drop the second open: it IS the existence proof the deliberately-terminal ENOENT behaviour rests on. Excluding those paths would delete the proof.
   Fix: keep the `open(Read)`, skip the redundant `sync()` for paths already synced through a retained fd.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,
+    retired_offset_files: RefCell<Vec<S::File>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    certified_log_view: Cell<Option<u32>>,
+    requested_log_view: Cell<Option<(u32, u64, u128)>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    checkpoint_needed: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    retained_bytes: Cell<u64>,
+    segment_checkpoint: Cell<Option<SegmentPosition>>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    writer_active: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct WriterLease {
+    key: PathBuf,
+    id: u64,
+    retired: AtomicBool,
+    running: AtomicBool,
+    waiters: Mutex<Vec<std::task::Waker>>,
+}
+
+struct WriterRegistration {
+    id: u64,
+    writer: Weak<WriterLease>,
+    interrupted: bool,
+}
+
+static WRITERS: LazyLock<Mutex<HashMap<PathBuf, WriterRegistration>>> =
+    LazyLock::new(|| Mutex::new(HashMap::new()));
+
+impl WriterLease {
+    async fn acquire(key: PathBuf) -> io::Result<Arc<Self>> {
+        loop {
+            let previous = {
+                let mut writers = WRITERS
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if writers
+                    .get(&key)
+                    .is_some_and(|registration| registration.interrupted)
+                {
+                    return Err(io::Error::other(
+                        "interrupted partition WAL writer requires process restart",
+                    ));
+                }
+                if let Some(previous) = writers
+                    .get(&key)
+                    .and_then(|registration| registration.writer.upgrade())
+                {
+                    drop(writers);
+                    Some(previous)
+                } else {
+                    let lease = Arc::new(Self {
+                        key: key.clone(),
+                        id: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+                        retired: AtomicBool::new(false),
+                        running: AtomicBool::new(false),
+                        waiters: Mutex::new(Vec::new()),
+                    });
+                    writers.insert(
+                        key.clone(),
+                        WriterRegistration {
+                            id: lease.id,
+                            writer: Arc::downgrade(&lease),
+                            interrupted: false,
+                        },
+                    );
+                    drop(writers);
+                    return Ok(lease);
+                }
+            };
+            let Some(previous) = previous else { continue };
+            if !previous.retired.load(Ordering::Acquire) {
+                return Err(io::Error::new(
+                    io::ErrorKind::AlreadyExists,
+                    "partition WAL already has an active writer",
+                ));
+            }
+            compio::runtime::time::timeout(
+                PERSISTENCE_DRAIN_TIMEOUT,
+                futures::future::poll_fn(|context| {
+                    let mut waiters = previous
+                        .waiters
+                        .lock()
+                        .unwrap_or_else(std::sync::PoisonError::into_inner);
+                    if !previous.running.load(Ordering::Acquire) {
+                        return std::task::Poll::Ready(());
+                    }
+                    if !waiters
+                        .iter()
+                        .any(|waiter| waiter.will_wake(context.waker()))
+                    {
+                        waiters.push(context.waker().clone());
+                    }
+                    std::task::Poll::Pending
+                }),
+            )
+            .await
+            .map_err(|_| {
+                io::Error::new(
+                    io::ErrorKind::TimedOut,
+                    "retired partition WAL writer did not stop",
+                )
+            })?;
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if writers
+                .get(&key)
+                .is_some_and(|registration| registration.id == previous.id)
+            {
+                writers.remove(&key);
+            }
+        }
+    }
+
+    fn finish(&self) {
+        self.running.store(false, Ordering::Release);
+        for waiter in self
+            .waiters
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .drain(..)
+        {
+            waiter.wake();
+        }
+    }
+}
+
+impl Drop for WriterLease {
+    fn drop(&mut self) {
+        let mut writers = WRITERS
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if writers
+            .get(&self.key)
+            .is_some_and(|registration| registration.id == self.id && !registration.interrupted)
+        {
+            writers.remove(&self.key);
+        }
+    }
+}
+
+struct WriterTicket<S: DurableStorage> {
+    owner: Rc<PartitionPersistence<S>>,
+    started: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterTicket<S> {
+    fn drop(&mut self) {
+        if self.started {
+            return;
+        }
+        self.owner.fail(io::Error::new(
+            io::ErrorKind::Interrupted,
+            "partition WAL writer was dropped before polling",
+        ));
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct WriterGuard<'a, S: DurableStorage> {
+    owner: &'a PartitionPersistence<S>,
+    journal: Option<PartitionPrepareJournal<S>>,
+    complete: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterGuard<'_, S> {
+    fn drop(&mut self) {
+        *self.owner.journal.borrow_mut() = self.journal.take();
+        self.owner.in_flight_bytes.set(0);
+        self.owner.checkpoint_running.set(false);
+        if !self.complete
+            && let Some(lease) = &self.owner.lease
+        {
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if let Some(registration) = writers.get_mut(&lease.key)
+                && registration.id == lease.id
+            {
+                registration.interrupted = true;
+            }
+        }
+        if !self.complete && self.owner.failure.borrow().is_none() {
+            *self.owner.failure.borrow_mut() = Some(Arc::new(io::Error::new(
+                io::ErrorKind::Interrupted,
+                "partition WAL writer stopped during a mutation",
+            )));
+        }
+        self.owner.writer_active.set(false);
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation<S: DurableStorage> {
+    EnableSegments {
+        epoch: u64,
+        initial: SegmentPosition,
+        max_size: u64,
+    },
+    CertifyView {
+        epoch: u64,
+        view: u32,
+        op: u64,
+        checksum: u128,
+    },
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+        offset_files: Vec<S::File>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        let lease = if let Some(key) = storage.writer_identity(directory)? {
+            Some(WriterLease::acquire(key).await?)
+        } else {
+            None
+        };
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+            preallocate_segments,
+        )
+        .await?;
+        let prepares = journal.take_recovered_prepares();
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare.header();
+            if header.op > journal.checkpoint_op() {
+                accepted.checksums.push_back(header.checksum);
+            }
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            lease,
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            certified_log_view: Cell::new(journal.certified_log_view()),
+            requested_log_view: Cell::new(None),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            checkpoint_needed: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            retained_bytes: Cell::new(journal.retained_bytes()),
+            segment_checkpoint: Cell::new(journal.segment_checkpoint()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            offset_files: RefCell::new(HashMap::new()),
+            retired_offset_files: RefCell::new(Vec::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            writer_active: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    #[cfg(test)]
+    pub(crate) fn exhaust_capacity_for_test(&self) {
+        self.disk_bytes.set(self.capacity);
+        self.retained_bytes.set(self.capacity);
+    }
+
+    #[cfg(test)]
+    pub(crate) fn release_capacity_for_test(&self) {
+        self.disk_bytes.set(0);
+        self.retained_bytes.set(0);
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.certified_log_view.get()
+    }
+
+    pub fn certify_log_view(&self, view: u32, op: u64, checksum: u128) -> bool {
+        if self.certified_log_view.get() == Some(view) {
+            return true;
+        }
+        if self.retired.get()
+            || self.failure.borrow().is_some()
+            || op > self.head()
+            || !(op == 0 && checksum == 0 || self.checksum(op) == Some(checksum))
+        {
+            return false;
+        }
+        let target = (view, op, checksum);
+        if self
+            .requested_log_view
+            .get()
+            .is_none_or(|(pending, _, _)| pending != view)
+        {
+            self.requested_log_view.set(Some(target));
+            self.queue.borrow_mut().push_back(Mutation::CertifyView {
+                epoch: self.epoch.get(),
+                view,
+                op,
+                checksum,
+            });
+        }
+        false
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.checksum(header.op) == Some(header.checksum)
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        self.segment_checkpoint.get()
+    }
+
+    pub fn enable_segment_storage(&self, initial: SegmentPosition, max_size: u64) {
+        self.queue.borrow_mut().push_back(Mutation::EnableSegments {
+            epoch: self.epoch.get(),
+            initial,
+            max_size,
+        });
+    }
+
+    /// Verify the physical prefix before making its indexes and logical sizes visible.
+    ///
+    /// # Errors
+    /// Returns an error for a failed barrier or a body outside the durable segment range.
+    pub async fn validate_segment_prefix(
+        &self,
+        prepares: &[Frozen<4096>],
+        start_offset: u64,
+        mut position: u64,
+    ) -> io::Result<u64> {
+        self.drain_with_timeout().await?;
+        let journal = self.journal.borrow();
+        let journal = journal
+            .as_ref()
+            .ok_or_else(|| io::Error::other("segment writer has no journal"))?;
+        let initial = position;
+        for prepare in prepares {
+            let header = prepare_header(prepare)?;
+            let reference: SegmentReference = journal
+                .segment_reference(header)
+                .ok_or_else(|| io::Error::other("committed prepare has no durable segment body"))?;
+            if reference.start_offset != start_offset
+                || reference.position != position
+                || reference.length != (prepare.len() - size_of::<PrepareHeader>()) as u64
+            {
+                return Err(io::Error::other(
+                    "committed prepare differs from its segment position",
+                ));
+            }
+            position = position
+                .checked_add(reference.length)
+                .ok_or_else(|| io::Error::other("segment prefix overflow"))?;
+        }
+        Ok(position - initial)
+    }
+
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head.get()
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .retained_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn take_offset_file(&self, path: &str) -> Option<S::File> {
+        self.offset_files.borrow_mut().remove(path)
+    }
+
+    /// # Panics
+    /// Panics if the previous writer was not taken before replacement.
+    pub fn retain_offset_file(&self, path: String, file: S::File) {
+        assert!(self.offset_files.borrow_mut().insert(path, file).is_none());
+    }
+
+    pub fn retire_offset_file(&self, path: &str) {
+        if let Some(file) = self.take_offset_file(path) {
+            self.retired_offset_files.borrow_mut().push(file);
+        }
+    }
+
+    pub fn mark_offset_dirty(&self, kind_index: usize, consumer_id: u32, exists: bool) {
+        let mut offsets = self.dirty_offsets[kind_index].borrow_mut();
+        if exists {
+            offsets.insert(consumer_id);
+        } else {
+            offsets.remove(&consumer_id);
+        }
+    }
+
+    pub fn retire_offset_files(&self) {
+        self.retired_offset_files
+            .borrow_mut()
+            .extend(self.offset_files.borrow_mut().drain().map(|(_, file)| file));
+    }
+
+    pub fn take_dirty_files(&self) -> (BTreeSet<u64>, [BTreeSet<u32>; 2]) {
+        (
+            std::mem::take(&mut *self.dirty_segments.borrow_mut()),
+            std::array::from_fn(|index| {
+                std::mem::take(&mut *self.dirty_offsets[index].borrow_mut())
+            }),
+        )
+    }
+
+    pub fn checkpoint(&self, through_op: u64) {
+        self.checkpoint_files(through_op, Vec::new(), Vec::new());
+    }
+
+    pub fn checkpoint_files(
+        &self,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+    ) {
+        if through_op <= self.checkpoint_requested.get() {
+            return;
+        }
+        self.checkpoint_requested.set(through_op);
+        self.checkpoint_needed.set(false);
+        let mut offset_files = std::mem::take(&mut *self.retired_offset_files.borrow_mut());
+        offset_files.extend(self.offset_files.borrow_mut().drain().map(|(_, file)| file));
+        self.queue.borrow_mut().push_back(Mutation::Checkpoint {
+            epoch: self.epoch.get(),
+            through_op,
+            files,
+            directories,
+            offset_files,
+        });
+    }
+
+    pub const fn checkpoint_pending(&self) -> bool {
+        self.checkpoint_running.get() || self.checkpoint_requested.get() > self.checkpoint.get()
+    }
+
+    pub fn request_checkpoint(&self) {
+        self.checkpoint_needed.set(true);
+    }
+
+    pub fn truncate_from(&self, from_op: u64) {
+        if from_op > self.accepted_head.get() {
+            return;
+        }
+        self.checkpoint_requested.set(self.checkpoint.get());
+        self.certified_log_view.set(None);
+        self.requested_log_view.set(None);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        // Retained submissions still precede the replacement history.
+        self.queue
+            .borrow_mut()
+            .retain_mut(|mutation| match mutation {
+                Mutation::Append {
+                    epoch: previous,
+                    prepare,
+                    bytes,
+                    ..
+                } => {
+                    if prepare_header(prepare).is_ok_and(|header| header.op < from_op) {
+                        *previous = epoch;
+                        true
+                    } else {
+                        self.queued_bytes
+                            .set(self.queued_bytes.get().saturating_sub(*bytes));
+                        false
+                    }
+                }
+                Mutation::Checkpoint {
+                    epoch: previous,
+                    through_op,
+                    ..
+                } if *through_op < from_op => {
+                    *previous = epoch;
+                    self.checkpoint_requested
+                        .set(self.checkpoint_requested.get().max(*through_op));
+                    true
+                }
+                _ => false,
+            });
+        self.accepted.borrow_mut().truncate_from(from_op);
+        self.accepted_head.set(from_op.saturating_sub(1));
+        self.durable_head
+            .set(self.durable_head.get().min(from_op.saturating_sub(1)));
+        self.queue
+            .borrow_mut()
+            .push_back(Mutation::Truncate { epoch, from_op });
+    }
+
+    pub fn reset(&self, op: u64, checksum: Option<u128>) {
+        self.reset_with_prepare(op, checksum, None);
+    }
+
+    pub fn reset_with_prepare(
+        &self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+    ) {
+        self.reset_with_segments(op, checksum, prepare, None);
+    }
+
+    pub fn reset_with_segments(
+        &self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    ) {
+        self.offset_files.borrow_mut().clear();
+        self.retired_offset_files.borrow_mut().clear();
+        self.certified_log_view.set(None);
+        self.requested_log_view.set(None);
+        self.checkpoint_requested.set(op);
+        let epoch = self.epoch.get().wrapping_add(1);
+        self.epoch.set(epoch);
+        self.queue.borrow_mut().clear();
+        self.queued_bytes.set(0);
+        *self.accepted.borrow_mut() = AcceptedPrepares {
+            base: op,
+            checksums: VecDeque::new(),
+        };
+        self.accepted_head.set(op);
+        self.durable_head.set(0);
+        self.queue.borrow_mut().push_back(Mutation::Reset {
+            epoch,
+            op,
+            checksum,
+            prepare,
+            segments,
+        });
+    }
+
+    pub fn mark_purge(&self, generation: u64, floor: u64) {
+        self.queue.borrow_mut().push_back(Mutation::Purge {
+            epoch: self.epoch.get(),
+            generation,
+            floor,
+        });
+    }
+
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.purge_generation.get(), self.purge_floor.get())
+    }
+
+    pub fn needs_checkpoint(&self) -> bool {
+        !self.checkpoint_pending()
+            && (self.checkpoint_needed.get()
+                || self.retained_bytes.get() + self.queued_bytes.get() + self.in_flight_bytes.get()
+                    >= self.capacity / 2
+                || self.retired_offset_files.borrow().len() >= CHECKPOINT_DIRTY_FILES_MAX
+                || self.dirty_segments.borrow().len() * 2
+                    + self
+                        .dirty_offsets
+                        .iter()
+                        .map(|offsets| offsets.borrow().len())
+                        .sum::<usize>()
+                    >= CHECKPOINT_DIRTY_FILES_MAX)
+    }
+
+    pub fn take_metrics(&self) -> PersistenceMetrics {

Review Comment:
   warning: `take_metrics` exports `disk_bytes` (the WAL file length) but not `retained_bytes`, while admission (`:601-607`) and the checkpoint trigger (`:831`) both gate on `retained_bytes`. `core/shard/src/metrics.rs:324-325` feeds `partition_wal_disk_bytes` from the former.
   With references the gauge is 4096 B per record while the budget consumed is the full body, so a 256 MiB `wal_bytes_max` can be exhausted at a ~0.4 MiB gauge reading. An operator watching the published gauge sees a near-idle WAL while produce returns `WouldBlock` / "partition WAL capacity exhausted".
   Fix: export `retained_bytes` (keep `disk_bytes` too) and correct the `config.toml` sentence that promises these gauges track the budget.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {

Review Comment:
   nit: this makes `max_size` a durable, immutable part of the WAL layout with a terminal `Err("segment size differs from the durable WAL layout")` and no reconciliation path, while two independent lookups must agree forever: `partition_helpers.rs:388`/`:1040`/`:1087` use `runtime_options.segment_size.unwrap_or(DEFAULT_SEGMENT_SIZE)` and `iggy_partition.rs:2468-2472` uses `.unwrap_or(config.segment_size)`.
   Unreachable today — `boot/recovery.rs:150`/`:697` hard-wire `PartitionsConfig::segment_size` to the constant and `derived_block` materializes the key — so `config.segment_size` in `effective_segment_size` is dead code that reads like a live second source. Making it configurable turns a cosmetic non-uniformity into a permanent boot failure.
   Fix: derive both from one accessor and delete the dead fallback.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.

Review Comment:
   nit: "Physical tails may exceed the checkpoint boundary but cannot be polled yet" is false, and it sits on the wrong type. The poll bound is the partition's `segment.size` (`iggy_partition.rs:3589` sets `DiskSegment.persisted` from it; `poll_plan.rs:580-597` reads only `while position < persisted`), and `segment.size` advances at `commit_max` (`iggy_partition.rs:5429`, `:6464-6466`) while `segments.checkpoint` advances only at `commit_min` (`:957`). So the readable prefix routinely exceeds `checkpoint` in the `(commit_min, commit_max]` window.
   No read-visibility violation — those bytes are fsynced before their record and `validate_segment_prefix` proves `op <= durable_head` — but the sentence names the wrong cursor as the bound, and `segment_recovery.rs:227-229` acts on that wrong cursor as the recovery bound (see the `partition_helpers.rs` critical).
   Fix: restate on `SegmentState` as `checkpoint.length <= segment.size <= tail.length`, with the poll bound being the partition's `segment.size`.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -2831,7 +3051,7 @@ where
                     source,
                 })?;
         } else {
-            let enforce_fsync = self.effective_enforce_fsync(config);
+            let persisted = self.durability().is_persisted();
             let segment_size = self.effective_segment_size(config);
             let preallocate_segments = self.effective_preallocate_segments(config);
             let last = self.log.segments().len() - 1;

Review Comment:
   warning: the post-install chain is rebuilt with `SegmentStorage::new` at `:3009` — a real `MessagesWriter` on the segment inode — even in owned mode, and the last-segment writer reopen at `:3059-3064` is gated on all four of `messages_reader`/`index_reader`/`messages_writer`/`index_writer` being `Some`, so it is skipped exactly where owned mode needs it, dropping the INDEX writer too. `hydrate_partition_log` (`partition_helpers.rs:1101-1115`) has the dedicated `messages_writer.is_none()` arm this path lacks.
   Reachability: a partition that booted with `materialization_missing` never ran `enable_segment_storage` (`iggy_partition.rs:797`), yet `:3369` keys `reset_with_segment_checkpoint` on `durability().is_persisted()` alone, so the install turns ownership on as a side effect while every segment carries a writer the WAL knows nothing about — two write-capable handles on one inode, and `:6456-6463` then advances a writer cursor for bytes it never wrote.
   Fix: pick the constructor from `segment_checkpoint().is_some()`, and gate the reopen on `index_writer` alone.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {

Review Comment:
   warning: `open_segment_file`'s create branch calls `remove_segment_name(&public)` and then relinks, unlinking the public offset name before anything proves that inode expendable. `reset_with_segment_checkpoint` verifies the installed length only afterwards (`:176-187`), so the check validates the replacement rather than the thing replaced.
   Trigger: a state-transfer install with `initial.length == 0` at a `start_offset` whose `{S}.log` is non-empty. `:451`'s `cursor.position.length > 0` branch is skipped, `:455-459`'s `length() == 0` fails, so the create branch fires, `remove_segment_name` destroys the installed file, and the `0 == 0` assertion at `:182` cannot fire on the case it exists for.
   Fix: verify the existing public file's length against the cursor BEFORE unlinking, and refuse instead of replacing.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {

Review Comment:
   nit: `mark_purge` resets both cursors to zero but leaves `self.entries` — and their pre-purge references and `next_offset`s — intact, while `publish` (`:984-993`) validates no cursor ordering and only `decode` (`segments.rs:638`) rejects `tail_next < checkpoint_next`.
   With a `floor < head` window, a later `checkpoint(through_op)` can pick `segment_boundary` from a surviving pre-purge entry (`segments.rs:360-381` filters only `op > purge_floor`), publishing `checkpoint.next_offset` far above the reset `tail.next_offset == 0`. The write succeeds and the very next `open` fails `decode` forever.
   Reachability is low (`iggy_partition.rs:7220` passes `current_sequence()` and `:489-491` fails closed above `head`), but the asymmetric validation is the real defect.
   Fix: assert the cursor ordering in `publish`, not only in `decode`, and drop or de-reference entries above the new floor in `mark_purge`.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -6049,6 +6843,7 @@ where
         config: &PartitionsConfig,

Review Comment:
   warning: the doc block immediately above (`:6830-6837`) asserts "Both files are opened through `SegmentStorage::new` with `file_exists = false`, which TRUNCATES them. That is load-bearing, not incidental" — but the persisted branch at `:6880-6892` uses `with_read_only_messages`, which sets `.truncate(false)`. Non-truncation is now the load-bearing behaviour, because the file legitimately holds the WAL's physical tail.
   This is the comment that would lead a future reader to "restore" the truncate in `ensure_initial_segment` and reintroduce the destroy-committed-bodies bug.
   Fix: rewrite the doc to say the log must NOT be truncated and why, keeping the index-truncation rationale, and fix it together with `partition_helpers.rs:400`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "numinnex (via GitHub)" <gi...@apache.org>.
numinnex commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3978831180


##########
core/shard/src/lib.rs:
##########
@@ -7553,6 +7606,14 @@ where
                         walk_cursor.get_or_insert(namespace);
                     }
                 }
+                if partition.needs_persistence_checkpoint() {

Review Comment:
   warning: this merge-inserted `checkpoint_persistence().await` can fence the partition (`core/partitions/src/iggy_partition.rs:961-968` sets `self.fatal`) with no `partition.fatal()` re-read afterwards, unlike the sibling walk at `:7867-7879`, which does exactly that after `commit_journal().await` and explains why: "reporting the stale verdict would let the pump keep serving a divergent replica until the next tick noticed."
   Same failure mode here: the sweep goes on to run repair arming, the gap detector and transfer retries on a fenced partition, and `tick_partitions` returns `None` for that sweep, delaying node shutdown by a full tick.
   Fix: copy the `:7874-7879` re-read block after the checkpoint await.



##########
core/simulator/src/replica.rs:
##########
@@ -379,8 +379,7 @@ pub fn new_shard(
     let partitions_config = PartitionsConfig {
         messages_required_to_save: 1000,
         size_of_messages_required_to_save: IggyByteSize::from(4 * 1024 * 1024),
-        enforce_fsync: false, //Disable fsync for simulation
-        consumer_offset_enforce_fsync: false,
+
         validate_checksum: true,
         segment_size: IggyByteSize::from(1024 * 1024 * 1024),

Review Comment:
   nit: `segment_size` is hard-coded here as `IggyByteSize::from(1024 * 1024 * 1024)` rather than referencing `iggy_common::DEFAULT_SEGMENT_SIZE` (`core/common/src/types/options/mod.rs:247`).
   Numerically equal today, so the deterministic simulator also cannot expose the two-fallback `segment_size` divergence — and one edit to the constant makes that divergence live in the simulator with no test naming the coupling.
   Fix: reference the constant.



##########
core/shard/src/lib.rs:
##########
@@ -8501,11 +8562,10 @@ where
     /// disk as they complete, so this bounds corruption, not memory.
     const PARTITION_TRANSFER_TOTAL_LEN_MAX: u64 = 1 << 40;
 
-    /// Alloc cap for the `CONSUMER_OFFSETS` artifact, which accumulates whole
-    /// in `ArtifactProgress::buf` before decode can reject it. Its decoder
-    /// ceilings imply ~24 MiB (two sections of 2^20 12-byte entries); this
-    /// leaves headroom without letting a hostile manifest stage gigabytes.
-    const CONSUMER_OFFSETS_ARTIFACT_LEN_MAX: u64 = 32 << 20;
+    /// Bound the buffered offset and dedup state plus one maximum-sized

Review Comment:
   warning: `CONSUMER_OFFSETS_ARTIFACT_LEN_MAX` went from `32 << 20` to `(32 << 20) + PREPARE_BYTES_MAX + 4` = 96 MiB, tripling an attacker-declared staging allocation, and the rewrite deleted the sentence that constrained it ("this leaves headroom without letting a hostile manifest stage gigabytes").
   One artifact buffers whole in memory (`:9209-9219`), and `PARTITION_TRANSFERS_INFLIGHT_MAX = 4` (`:8574`) makes that 384 MiB per shard, up from 128 MiB — gigabytes across a multi-core node. The 64 MiB addend is the global prepare ceiling; a real consumer-offset `checkpoint_prepare` is orders of magnitude smaller.
   Fix: bound the addend by the effective `messages_size_max` or the WAL record size actually reachable, not by `PREPARE_BYTES_MAX`.



##########
core/shard/src/lib.rs:
##########
@@ -11549,6 +11619,51 @@ async fn dispatch_vsr_actions<B, P, J>(
     }
 }
 
+fn partition_start_view_suffix<B: MessageBus, SB: SuperblockStore>(
+    partition: &IggyPartition<B, SB>,
+    commit: u64,
+    head: u64,
+) -> Vec<PrepareHeader> {
+    // Probe replies and stale-view corrections need the same canonical headers
+    // as election broadcasts before a backup can fetch an uncommitted body.
+    (commit.max(1)..=head)
+        .rev()
+        .take(consensus::DVC_HEADERS_MAX)
+        .map_while(|op| partition.log.journal().inner.repair_header(op))

Review Comment:
   warning: `map_while` stops at the first hole, where the sibling `build_dvc_suffix` (`:11113`) blank-fills it. A partial suffix still feeds the un-nack path (`view_header_at:11326-11334` is a per-op lookup with no coverage test) while silencing the repair detector, since `pending_covers_suffix` (`:10978-10995`) demands contiguous coverage of `(commit_max, head]` AND `pending.op_head == head`.
   So the backup un-nacks whichever ops the partial suffix names while `partition_missing_suffix_through` (`:10902-10923`) returns `None` — the one detector that would fetch the missing bodies stays off. Once a live prepare raises the backup's head past `pending.op_head`, `pending_covers_suffix` fails permanently and only the un-nack survives.
   Fix: build the window with `repair_headers_in` and `dvc_blank` for misses, as `build_dvc_suffix` does.



##########
core/shard/src/lib.rs:
##########
@@ -11549,6 +11619,51 @@ async fn dispatch_vsr_actions<B, P, J>(
     }
 }
 
+fn partition_start_view_suffix<B: MessageBus, SB: SuperblockStore>(
+    partition: &IggyPartition<B, SB>,
+    commit: u64,
+    head: u64,
+) -> Vec<PrepareHeader> {
+    // Probe replies and stale-view corrections need the same canonical headers
+    // as election broadcasts before a backup can fetch an uncommitted body.
+    (commit.max(1)..=head)

Review Comment:
   nit: per-op `repair_header` probing here is what the neighbouring function's comment at `:10369-10371` explicitly forbids: "probing `repair_header` per op is two linear scans each, up to `DVC_HEADERS_MAX` of them." `refresh_partition_dvc_suffix` materializes the window once with `repair_headers_in`.
   Distinct from the send-cost finding at `:11622`, which measures wire bytes: this is the O(128 x journal) scan the sibling was rewritten to avoid, running on the pump.
   Fix: use `repair_headers_in` here too.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,8 +727,510 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        self.open_persistence_with_recovered(capacity, None).await
+    }
+
+    /// # Errors
+    /// Returns an error if durable history cannot be opened, migrated, or replayed.
+    #[allow(clippy::too_many_lines)]
+    pub async fn open_persistence_with_recovered(
+        &mut self,
+        capacity: u64,
+        recovered: Option<(Rc<PartitionPersistence>, Vec<Message<PrepareHeader>>)>,
+    ) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = if let Some(recovered) = recovered {
+            recovered
+        } else {
+            PartitionPersistence::open_with_capacity(
+                &directory,
+                self.namespace().inner(),
+                self.created_revision,
+                journal::durable_storage::DiskStorage,
+                capacity,
+                self.runtime_options
+                    .preallocate_segments
+                    .unwrap_or(iggy_common::DEFAULT_PREALLOCATE_SEGMENTS),
+            )
+            .await
+            .map_err(|error| {
+                warn!(%error, "cannot open partition prepare WAL");
+                IggyError::CannotReadFile
+            })?
+        };
+        if self.durability().is_persisted() && !self.materialization_missing {
+            let segment = self.log.active_segment();
+            let length = segment.size.as_bytes_u64();
+            let initial = journal::partition_journal::SegmentPosition {
+                start_offset: segment.start_offset,
+                length,
+                next_offset: if length == 0 {
+                    segment.start_offset
+                } else {
+                    segment
+                        .end_offset
+                        .checked_add(1)
+                        .ok_or(IggyError::CannotReadFile)?
+                },
+            };
+            persistence.enable_segment_storage(initial, segment.max_size.as_bytes_u64());
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(&persistence).run());
+            }
+            persistence.drain_with_timeout().await.map_err(|error| {
+                warn!(%error, "cannot enable partition segment persistence");
+                IggyError::CannotSyncFile
+            })?;
+        }
+        self.restore_certified_log_view(&persistence).await?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    async fn restore_certified_log_view(
+        &mut self,
+        persistence: &Rc<PartitionPersistence>,
+    ) -> Result<(), IggyError> {
+        if !self.materialization_missing
+            && self.recovered_log_view.is_none()
+            && persistence.head() == 0
+        {
+            persistence.certify_log_view(self.consensus.log_view(), 0, 0);
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(persistence).run());
+            }
+            persistence
+                .drain_with_timeout()
+                .await
+                .map_err(|_| IggyError::CannotSyncFile)?;
+        }
+        if !self.materialization_missing {
+            match persistence.certified_log_view() {
+                Some(view) if view >= self.consensus.log_view() => {
+                    if view > self.consensus.view() {
+                        self.consensus.set_view(view);
+                    }
+                    self.consensus.set_log_view(view);
+                }
+                _ => {
+                    self.materialization_missing = true;
+                    self.ensure_materialization_recovery();
+                }
+            }
+        }
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.commit_messages_inner(config, true, through_op).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {

Review Comment:
   nit: `self.fatal = Some(..)` is unconditional here, while `drive_persistence` (`:1069`) guards with `if self.fatal.is_none()`. A checkpoint failure therefore clobbers the root-cause fault the pump would otherwise have reported.
   Fix: apply the same `is_none()` guard.



##########
core/shard/src/router.rs:
##########
@@ -285,6 +286,15 @@ where
             Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
         M: RestorableMetadataStm,
     {

Review Comment:
   nit: `let _ = sender.try_send(..PartitionPersistenceCompleted..)` drops the wake with no `record_frame_drop`, unlike every other droppable producer in this file (`METADATA_COMMIT_TICK` / `UNROUTABLE` at `:765`).
   Benign for correctness — `on_persistence_completed` is only a wake, and the pump's per-tick `drive_persistence` re-drives each parked header through a checksum-exact `is_durable`, so an ack is deferred by one 10 ms tick and never lost — but wake starvation under main-lane pressure is invisible to operators.
   Fix: add a drop variant and count it.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -711,8 +727,510 @@ where
         partition
     }
 
+    pub fn set_persistence_notifier(&self, notifier: PersistenceNotifier) {
+        if let Some(persistence) = &self.persistence {
+            persistence.set_notifier(notifier);
+        }
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence(&mut self) -> Result<(), IggyError> {
+        self.open_persistence_with_capacity(journal::partition_journal::PARTITION_WAL_BYTES_MAX)
+            .await
+    }
+
+    /// # Errors
+    /// Returns an error if durable prepare history cannot be opened or replayed.
+    pub async fn open_persistence_with_capacity(&mut self, capacity: u64) -> Result<(), IggyError> {
+        self.open_persistence_with_recovered(capacity, None).await
+    }
+
+    /// # Errors
+    /// Returns an error if durable history cannot be opened, migrated, or replayed.
+    #[allow(clippy::too_many_lines)]
+    pub async fn open_persistence_with_recovered(
+        &mut self,
+        capacity: u64,
+        recovered: Option<(Rc<PartitionPersistence>, Vec<Message<PrepareHeader>>)>,
+    ) -> Result<(), IggyError> {
+        if self.consensus.replica_count() > 1
+            && let Some(directory) = &self.partition_dir
+        {
+            self.materialization_missing =
+                crate::state_transfer::materialization_is_missing(directory, self.created_revision)
+                    .await
+                    .map_err(|_| IggyError::CannotReadFile)?;
+            self.ensure_materialization_recovery();
+        }
+        if self.consensus.replica_count() == 1
+            || !(self.durability().is_persisted()
+                || self.consumer_offset_durability().is_persisted())
+        {
+            return Ok(());
+        }
+        let directory = self
+            .partition_dir
+            .as_ref()
+            .ok_or(IggyError::CannotReadFile)?;
+        let directory =
+            std::path::Path::new(directory).join(format!("prepares-{}", self.created_revision));
+        let (persistence, prepares) = if let Some(recovered) = recovered {
+            recovered
+        } else {
+            PartitionPersistence::open_with_capacity(
+                &directory,
+                self.namespace().inner(),
+                self.created_revision,
+                journal::durable_storage::DiskStorage,
+                capacity,
+                self.runtime_options
+                    .preallocate_segments
+                    .unwrap_or(iggy_common::DEFAULT_PREALLOCATE_SEGMENTS),
+            )
+            .await
+            .map_err(|error| {
+                warn!(%error, "cannot open partition prepare WAL");
+                IggyError::CannotReadFile
+            })?
+        };
+        if self.durability().is_persisted() && !self.materialization_missing {
+            let segment = self.log.active_segment();
+            let length = segment.size.as_bytes_u64();
+            let initial = journal::partition_journal::SegmentPosition {
+                start_offset: segment.start_offset,
+                length,
+                next_offset: if length == 0 {
+                    segment.start_offset
+                } else {
+                    segment
+                        .end_offset
+                        .checked_add(1)
+                        .ok_or(IggyError::CannotReadFile)?
+                },
+            };
+            persistence.enable_segment_storage(initial, segment.max_size.as_bytes_u64());
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(&persistence).run());
+            }
+            persistence.drain_with_timeout().await.map_err(|error| {
+                warn!(%error, "cannot enable partition segment persistence");
+                IggyError::CannotSyncFile
+            })?;
+        }
+        self.restore_certified_log_view(&persistence).await?;
+        if self.materialization_missing {
+            self.persistence = Some(persistence);
+            return Ok(());
+        }
+        let (purge_generation, purge_floor) = persistence.purge_marker();
+        if purge_generation <= self.applied_purge_generation {
+            self.purge_floor_op = self.purge_floor_op.max(purge_floor);
+        }
+        let checkpoint = persistence.checkpoint_op();
+        let head = persistence.head();
+        let mut commit = checkpoint;
+        for message in prepares {
+            let header = *message.header();
+            if header.op == checkpoint {
+                self.log
+                    .journal()
+                    .inner
+                    .restore_checkpoint_prepare(checkpoint, message.into_frozen());
+                continue;
+            }
+            commit = commit.max(header.commit.min(head));
+            if header.operation == Operation::SendMessages {
+                self.append_repaired_send_messages(message).await?;
+            } else {
+                self.apply_replicated_operation(message).await?;
+            }
+        }
+        if head > 0 {
+            self.consensus.sequencer().set_sequence(head);
+            if let Some(checksum) = persistence.checksum(head) {
+                self.consensus.set_last_prepare_checksum(checksum);
+            }
+            self.consensus.restore_commit_state(checkpoint, commit);
+        }
+        // Recovery can reuse completed writes whose last barrier was interrupted.
+        // Include them once before reclaiming any recovered WAL history.
+        for segment in self.log.segments() {
+            persistence.mark_segment_dirty(segment.start_offset);
+        }
+        for kind in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup] {
+            self.durable_consumer_offsets.with_entries(kind, |entries| {
+                for consumer_id in entries.keys() {
+                    persistence.mark_offset_dirty(
+                        crate::state_transfer::consumer_kind_index(kind),
+                        *consumer_id,
+                        true,
+                    );
+                }
+            });
+        }
+        self.persistence = Some(persistence);
+        Ok(())
+    }
+
+    async fn restore_certified_log_view(
+        &mut self,
+        persistence: &Rc<PartitionPersistence>,
+    ) -> Result<(), IggyError> {
+        if !self.materialization_missing
+            && self.recovered_log_view.is_none()
+            && persistence.head() == 0
+        {
+            persistence.certify_log_view(self.consensus.log_view(), 0, 0);
+            if persistence.start() {
+                self.consensus
+                    .message_bus()
+                    .spawn(Rc::clone(persistence).run());
+            }
+            persistence
+                .drain_with_timeout()
+                .await
+                .map_err(|_| IggyError::CannotSyncFile)?;
+        }
+        if !self.materialization_missing {
+            match persistence.certified_log_view() {
+                Some(view) if view >= self.consensus.log_view() => {
+                    if view > self.consensus.view() {
+                        self.consensus.set_view(view);
+                    }
+                    self.consensus.set_log_view(view);
+                }
+                _ => {
+                    self.materialization_missing = true;
+                    self.ensure_materialization_recovery();
+                }
+            }
+        }
+        Ok(())
+    }
+
+    pub const fn requires_state_transfer(&self) -> bool {
+        self.materialization_missing
+    }
+
+    pub fn ensure_materialization_recovery(&self) {
+        if self.materialization_missing
+            && (self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle
+                || self.consensus.status() == consensus::Status::ViewChange)
+        {
+            self.consensus.begin_view_probe();
+            if self.consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
+                self.consensus.begin_state_transfer_await();
+            }
+        }
+    }
+
+    pub async fn on_persistence_completed(&mut self, completion: PersistenceCompletion) {
+        if !self
+            .persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.accepts_completion(completion))
+        {
+            return;
+        }
+        self.drive_persistence().await;
+    }
+
+    pub fn needs_persistence_checkpoint(&self) -> bool {
+        self.persistence.as_ref().is_some_and(|persistence| {
+            persistence.needs_checkpoint()
+                && self.consensus.commit_min().min(persistence.head()) > persistence.checkpoint_op()
+        })
+    }
+
+    pub async fn checkpoint_persistence(&mut self, config: &PartitionsConfig) {
+        let Some(persistence) = self
+            .persistence
+            .as_ref()
+            .filter(|persistence| persistence.needs_checkpoint())
+            .cloned()
+        else {
+            return;
+        };
+        let through_op = self.consensus.commit_min().min(persistence.head());
+        if through_op <= persistence.checkpoint_op() {
+            return;
+        }
+        if let Err(error) = self.commit_messages_inner(config, true, through_op).await {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition checkpoint failed");
+            self.fatal = Some(FatalCommit {
+                namespace_raw: self.namespace().inner(),
+                op: through_op,
+                operation: Operation::SendMessages,
+            });
+            return;
+        }
+        let (files, directories) = self.persistence_checkpoint_files(config);
+        persistence.checkpoint_files(through_op, files, directories);
+        self.start_persistence();
+    }
+
+    fn persistence_checkpoint_files(
+        &self,
+        config: &PartitionsConfig,
+    ) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
+        let namespace = self.namespace();
+        let Some(persistence) = &self.persistence else {
+            return (Vec::new(), Vec::new());
+        };
+        let (segments, offsets) = persistence.take_dirty_files();
+        let mut paths = Vec::with_capacity(
+            segments.len() * 2
+                + offsets
+                    .iter()
+                    .map(std::collections::BTreeSet::len)
+                    .sum::<usize>(),
+        );
+        for start_offset in segments {
+            // Retention may already have removed a dirty sealed segment.
+            if self
+                .log
+                .segments()
+                .binary_search_by_key(&start_offset, |segment| segment.start_offset)
+                .is_err()
+            {
+                continue;
+            }
+            paths.push(config.get_messages_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+            paths.push(config.get_index_path(
+                namespace.stream_id(),
+                namespace.topic_id(),
+                namespace.partition_id(),
+                start_offset,
+            ));
+        }
+        for (kind, consumers) in [ConsumerKind::Consumer, ConsumerKind::ConsumerGroup]
+            .into_iter()
+            .zip(offsets)
+        {
+            for consumer_id in consumers {
+                if self.durable_consumer_offsets.contains(kind, consumer_id)
+                    && let Some(path) = self.persisted_offset_path(kind, consumer_id)
+                {
+                    paths.push(path);
+                }
+            }
+        }
+        let mut directories = Vec::with_capacity(4);
+        for directory in [
+            &self.consumer_offsets_path,
+            &self.consumer_group_offsets_path,
+        ]
+        .into_iter()
+        .flatten()
+        {
+            let path = std::path::PathBuf::from(directory);
+            directories.push(path.clone());
+            if let Some(parent) = path.parent()
+                && !directories.iter().any(|existing| existing == parent)
+            {
+                directories.push(parent.to_path_buf());
+            }
+        }
+        if let Some(directory) = &self.partition_dir {
+            directories.push(std::path::PathBuf::from(directory));
+        }
+        (
+            paths.into_iter().map(std::path::PathBuf::from).collect(),
+            directories,
+        )
+    }
+
+    pub fn take_persistence_metrics(&self) -> Option<crate::persistence::PersistenceMetrics> {
+        self.persistence
+            .as_ref()
+            .map(|persistence| persistence.take_metrics())
+    }
+
+    fn persistence_checkpoint_pending(&self) -> bool {
+        self.persistence
+            .as_ref()
+            .is_some_and(|persistence| persistence.checkpoint_pending())
+    }
+
+    pub async fn drive_persistence(&mut self) {
+        let Some(persistence) = self.persistence.as_ref() else {
+            return;
+        };
+        if let Some(error) = persistence.failure() {
+            error!(%error, namespace_raw = self.namespace().inner(), "partition prepare persistence failed");
+            if self.fatal.is_none() {
+                self.fatal = Some(FatalCommit {
+                    namespace_raw: self.namespace().inner(),
+                    op: persistence.head(),
+                    operation: Operation::SendMessages,
+                });
+            }
+            return;
+        }
+        if self.materialization_missing || !self.ensure_wal_view() {
+            return;
+        }
+        let durable_op = persistence.durable_op();
+        loop {
+            let ready = self
+                .pending_persisted_acks
+                .borrow()
+                .first_key_value()
+                .is_some_and(|(op, _)| *op <= durable_op);
+            if !ready {
+                break;
+            }
+            let Some((_, header)) = self.pending_persisted_acks.borrow_mut().pop_first() else {
+                break;
+            };
+            if persistence.checksum(header.op) == Some(header.checksum)

Review Comment:
   warning: `send_prepare_ok` returns `true` on three paths where `send_prepare_ok_common` (`core/consensus/src/plane_helpers.rs:924-945`) silently sent nothing — `status != Normal`, `is_transferring()`, and `header.op > current_sequence()` — so `drive_persistence` counts a dropped ack as delivered and pops it.
   `ensure_wal_view` short-circuits `true` when `certified_log_view() == log_view()`, so the drain proceeds during a view change before `log_view` bumps, and the loop drains the whole parked map without a `break` while every frame is discarded at the status gate.
   Fix: propagate the common helper's verdict, or re-park on a no-op send.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -56,26 +60,9 @@ use std::path::{Path, PathBuf};
 use std::rc::Rc;
 use std::sync::atomic::Ordering;
 
-/// Framing marker for the consumer-offsets wire artifact, "ICO2". Bumped with
-/// the version when the dedup section was appended, so the magic alone tells
-/// the two layouts apart.
-pub(crate) const CONSUMER_OFFSETS_MAGIC: [u8; 4] = *b"ICO2";
-
-/// Version byte following the magic.
-///
-/// Any layout change bumps this, INCLUDING appended fields: the decoder
-/// deliberately fails closed on unknown versions and on trailing bytes,
-/// because a v2 field can change the meaning of fields v1 already read.
-pub(crate) const CONSUMER_OFFSETS_VERSION: u8 = 2;
-
-/// The previous framing, "ICO1" at version 1: the same layout without the
-/// dedup section. Still decoded so a rolling upgrade works in both orders --
-/// an upgraded replica rejoining behind the repair floor of an un-upgraded
-/// primary installs its artifact with an empty slice (dedup for that window
-/// degrades to at-least-once, exactly the pre-dedup behaviour) instead of
-/// refusing it and re-pulling forever.
-pub(crate) const CONSUMER_OFFSETS_MAGIC_V1: [u8; 4] = *b"ICO1";
-const CONSUMER_OFFSETS_VERSION_V1: u8 = 1;
+/// Current state-transfer offsets format, including the prepare-chain anchor.
+pub(crate) const CONSUMER_OFFSETS_MAGIC: [u8; 4] = *b"ICO1";

Review Comment:
   warning: the artifact magic/version moved from ICO3/3 back to ICO1/1 while the format GAINED `prepare_length` + `checkpoint_prepare`. Master ships `CONSUMER_OFFSETS_MAGIC = ICO2` with `CONSUMER_OFFSETS_MAGIC_V1 = ICO1` decoded as `carries_dedup = false`, so ICO1/v1 now names two different layouts, each with a valid trailer checksum — and the trailer cannot separate them.
   The guard test was also rewritten from `for magic in [b"ICO1", b"ICO2"]` to `[b"BAD1", b"ICO9"]`, so it no longer covers either real prior magic. The cases walked here misparse (`Truncated` / `TooManyEntries`) rather than silently corrupting, hence warning.
   Fix: pick an unused magic (ICO4) or restore a real V1 branch, and test the actually-colliding magics.



##########
core/shard/src/lib.rs:
##########
@@ -7381,6 +7416,24 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();
+        for namespace in namespace_scratch.iter() {

Review Comment:
   warning: the `drive_persistence` pre-pass runs ahead of the fence check at `:7536`, and `drive_persistence` (`core/partitions/src/iggy_partition.rs:1063-1099`) guards only on `persistence.failure()`, never on `self.fatal`. A partition fenced by `checkpoint_persistence` — whose fault came from `commit_messages_inner`, not the WAL writer — therefore still emits `PrepareOk`.
   Sequence: tick N sets `fatal` while `persistence.failure()` is still `None`; tick N+1's pre-pass certifies the log view, spawns the writer, drains, and sends `PrepareOk`, so a fenced and divergent replica vouches for ops over the wire before `:7536` reports the fault.
   Fix: skip the pre-pass when `partition.fatal().is_some()`.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -2152,7 +2254,39 @@ where
         // must resume minting at N either way.
         let next_offset = self.offset_frontier();
         let dedup = self.dedup().watermarks_sorted();
+        let commit_op = self.consensus().commit_min();
+        let prepare_checksum = if commit_op == 0 {
+            Some(0)
+        } else {
+            self.log
+                .journal()
+                .inner
+                .header_by_op(commit_op)

Review Comment:
   warning: `prepare_checksum` and `checkpoint_prepare` are read from two different stores and never cross-checked before shipping. `:2264` uses `header_by_op(commit_op)`, which reads resident headers only; `:2280` uses `repair_entry(commit_op)`, which reads resident OR the evicted ring.
   `core/partitions/src/journal.rs:374-386` documents this exact trap: "NOT `header_by_op`, which reads the resident headers alone ... the committed prefix is evicted from those the moment its bytes reach a segment." Any disagreement between the WAL's accepted-checksum deque and the memory journal's entry at that op surfaces only on the receiver, as `InvalidPrepareChecksum`, which reads as peer corruption and feeds the failure backoff instead of a peer rotation.
   Fix: use `repair_header(commit_op)` as that doc prescribes, and assert `header.checksum == prepare_checksum` on the sender.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -3194,6 +3465,9 @@ where
         minted_next_offset: u64,
         staged_was_empty: bool,
     ) -> Result<(), iggy_common::IggyError> {
+        if let Some(persistence) = &self.persistence {

Review Comment:
   nit: this `retire_offset_files()` is unreachable. `converge_to_empty_after_failed_install` runs only when `persistence.is_none()`, because its sole call site at `:2778` sits after the `if self.persistence.is_some() { fence_install_failure(..); return outcome; }` early return at `:2762-2766`.
   Misleading as written: it suggests converge handles the owned-mode case, which it deliberately does not.
   Fix: drop it.



##########
core/partitions/src/offset_storage.rs:
##########
@@ -121,15 +121,43 @@ pub fn decode_offset_record(bytes: &[u8]) -> OffsetRecord {
 ///
 /// # Errors
 /// [`IggyError`] when the directory, file, or write cannot be created or completed.
-pub async fn persist_offset(path: &str, offset: u64, enforce_fsync: bool) -> Result<(), IggyError> {
+pub async fn persist_offset(path: &str, offset: u64, persisted: bool) -> Result<(), IggyError> {
     let record = encode_offset_record(offset);
-    if enforce_fsync {
+    if persisted {
         replace_file(path, record, true, false).await
     } else {
         write_in_place(path, record).await
     }
 }
 
+/// Keep the original writer open so checkpoint observes its writeback errors.

Review Comment:
   nit: `persist_offset_retained` silently drops the consumer-offset durability policy and its doc never says so. `persist_offset(persisted=true)` (`:110-129`) goes through `replace_file` — sibling inode, `sync_data`, atomic rename, "so a failed write leaves the prior cursor intact". With persistence attached, `persist_consumer_offset_commit` (`iggy_partition.rs:2718`) forces `persisted = false` and `write_consumer_offset` (`:2678`) takes this retained-fd path: a bare in-place `write_all_at(.., 0)`, i.e. the `OffsetRecord::Torn` path documented at `:56-58` as "the default path while `consumer_offset_persisted` is off" — now also the path when it is ON.
   The ordering is in fact sound (the checkpoint fsyncs the retained fds before the WAL advances, `persistence.rs:1055-1065`), which is exactly why it needs stating.
   Fix: document that the WAL checkpoint is the durability barrier here and that `persisted` does not apply.



##########
core/server/src/consumer_group.rs:
##########
@@ -117,7 +117,7 @@ async fn gather_in_flight<B, MJ, S, SB>(
     stream_id: &WireIdentifier,

Review Comment:
   warning: one partition awaiting state transfer now fails every `JoinConsumerGroup` on the topic, because `core/server/src/dispatch/partition.rs:108-116` answers every `PartitionRead` with `Rejected(TransientNotAccepted)` while `requires_state_transfer()`, and `gather_in_flight`'s early return at `:172-174` aborts the whole join on the first such partition — for the duration of a multi-GiB transfer.
   The doc above this function (`:107-113`) still states the opposite contract: "a partition that does not answer is treated as not-in-flight (eager handoff) ... a misclassification here just redelivers the uncommitted range to the new owner, which is correct under at-least-once." The new code chose the other trade without changing the stated rationale.
   Fix: treat `Rejected(TransientNotAccepted)` as not-in-flight, or fail only for the assigned partitions, and update the doc.



##########
core/shard/src/lib.rs:
##########
@@ -7381,6 +7416,24 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();

Review Comment:
   warning: this is the only per-partition walk in `tick_partitions` with no `PARTITION_WALKS_PER_TICK_MAX` budget and no cursor, and it runs serially.
   `register_rebuilt_ack` now parks up to a 128-op window per partition, so a cluster-wide view change makes this pass run `persist_repaired_prefix` + `certify_log_view` + N x `send_prepare_ok` for every group on the core — the exact hazard the concurrent superblock pre-pass 20 lines below (`:7442-7470`, `SUPERBLOCK_FAN_OUT` chunks) was written to avoid.
   Fix: budget it like the sibling walks, or fan it out.



##########
core/server/src/consumer_group.rs:
##########
@@ -169,6 +169,9 @@ where
     let mut in_flight = Vec::new();
     let mut stale_clears = Vec::new();
     for (partition_id, ns, reply) in results {
+        if let Some(PartitionReadReply::Rejected(error)) = reply {

Review Comment:
   warning: this early return drops the already-queued `stale_clears` futures un-polled, so `ClearGroupLastPolled` is never even sent. `partition_read` is an `async fn` (`core/shard/src/lib.rs:2003-2020`), so the `try_send` happens on first poll; `stale_clears.push(..)` at `:190` stores unpolled futures and the `return Err` here drops the Vec before `join_all` at `:199`.
   Stale `last_polled` marks from removed members therefore survive, and the next join in the same restart misclassifies those partitions as in-flight — precisely what the comment at `:186-188` says the clear prevents.
   Fix: collect the rejection, run `join_all(stale_clears)`, then return.



##########
core/partitions/src/iggy_partition.rs:
##########
@@ -2139,10 +2669,53 @@ where
         Ok(())
     }
 
+    async fn write_consumer_offset(
+        &self,
+        path: &str,
+        offset: u64,
+        persisted: bool,
+    ) -> Result<(), IggyError> {
+        if let Some(persistence) = &self.persistence {
+            let file = crate::offset_storage::persist_offset_retained(
+                path,
+                offset,
+                persistence.take_offset_file(path),
+            )
+            .await
+            .inspect_err(|error| {
+                persistence.fail(std::io::Error::other(error.to_string()));
+            })?;
+            persistence.retain_offset_file(path.to_owned(), file);
+            Ok(())
+        } else {
+            persist_offset(path, offset, persisted).await
+        }
+    }
+
+    async fn write_cold_consumer_offset(
+        &self,
+        path: &str,
+        offset: u64,
+        persisted: bool,
+    ) -> Result<(u64, bool), IggyError> {
+        if self.persistence.is_some() {
+            let result = crate::offset_storage::read_offset_max(path, offset).await?;

Review Comment:
   nit: `write_cold_consumer_offset` discards `read_offset_max`'s `written` result and rewrites unconditionally, then reports `written = true`. The rework split `persist_offset_max` into read + write precisely to skip already-covered offsets (`offset_storage.rs:277-295`), and the persistence branch throws that away — one extra 16-byte write plus retained-fd churn per cold key.
   Harmless today only because `persisted` is false on that branch, so the `written && persisted` dirty-dir mark at `:2761` never reads the lie.
   Fix: skip the write when the read proves it covered, and return `result.written`.



##########
core/server/src/http/reads.rs:
##########
@@ -404,6 +404,78 @@ pub(in crate::http) fn authorize_data_plane(
         .authorize(|permissioner| rule(permissioner, user_id, stream_id, topic_id))
 }
 
+static DURABILITY_KEY: std::sync::LazyLock<iggy_common::HeaderKey> =
+    std::sync::LazyLock::new(|| "durability".parse().expect("catalog key is valid"));
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(in crate::http) struct TopicDurability {
+    stream_id: usize,
+    topic_id: usize,
+    created_revision: u64,
+    pub durability: iggy_common::Durability,
+}
+
+impl TopicDurability {
+    pub fn confirmed_policy(self, state: &HttpInner) -> iggy_common::Durability {
+        state
+            .shard
+            .plane
+            .metadata()
+            .mux_stm
+            .streams()
+            .read(|inner| self.confirmed_policy_in(inner))
+    }
+
+    fn confirmed_policy_in(

Review Comment:
   nit: `confirmed_policy_in` dropped the durability-field comparison and the rationale comment with it — only `created_revision` is checked now. The previous `confirmed_policy_for` compared the whole `TopicDurability` including `durability` and degraded to `Replicated` on any difference, with the comment "Every successful partition reply proves quorum commit even when namespace replacement prevents attesting the stronger guarantee."
   Defensible, since a live partition keeps its build-time `runtime_options` — but that comment was the only record of the trade, and a produce whose topic durability changed mid-flight now reports the admission-time policy.
   Fix: state why the captured policy wins, or compare the stored durability again.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {

Review Comment:
   nit: `reset_with_segment_checkpoint` silently adopts a new durable `max_size` where `enable_segment_storage` refuses a differing one with a terminal error (`:68-73`). The install builds a fresh `SegmentState { max_size, .. }` from the receiver's `self.log.active_segment().max_size` (`state_transfer.rs:3378`) with no comparison against the recorded layout.
   Unreachable while `effective_segment_size` resolves to one constant, so nit only — but it is a second, inconsistent policy for the same durable field.
   Fix: apply the same refusal on the install path.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -1532,6 +1553,80 @@ fn segment_dir_entries(partition_dir: &str) -> std::io::Result<Vec<PathBuf>> {
         .collect())
 }
 
+/// Remove physical tails outside the logical segment list after draining the WAL.
+/// The caller holds the write lock and has published a purge or install backup.
+pub(crate) async fn remove_public_segment_files(partition_dir: &str) -> std::io::Result<()> {

Review Comment:
   warning: `remove_public_segment_files` is a new client-reachable `DurableStorage::entries` call site (also `iggy_partition.rs:7283`), and `core/journal/src/durable_storage.rs:213-223` serializes every `entries()` on a process-global `Mutex` while spawning one OS thread per call.
   So one purge costs one thread spawn plus one global-mutex acquisition per partition, ahead of every other shard's directory work — and `purge_stream` on a many-partition stream is repeatable by any client with purge rights. The view-change `truncate_from` path was the only trigger noted before; this one is client-driven.
   Fix: reuse the listing the purge loop already walked, or pass the known paths.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {

Review Comment:
   nit: `write_segment_bodies` returns `Ok(())` when `segment_storage.is_none()` even though `records` may carry references, so the WAL would publish `SEGMENT_RECORD`s pointing at bytes nobody wrote.
   Unreachable in production — `append_batch_referenced_buffered` has test-only callers — but it is a silent-success path for a state the type system permits.
   Fix: return `Err(invalid(..))` when any record carries a reference and segment storage is off.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {
+            return Err(invalid(
+                "message offsets do not extend the physical segment tail",
+            ));
+        }
+        if self.tail.position.length >= self.max_size {
+            self.tail = self.allocate(SegmentPosition {
+                start_offset: batch.base_offset,
+                length: 0,
+                next_offset: batch.base_offset,
+            })?;
+        }
+        let reference = SegmentReference {
+            generation: self.tail.generation,
+            start_offset: self.tail.position.start_offset,
+            position: self.tail.position.length,
+            length: batch.batch_length,
+        };
+        self.tail.position.length = reference
+            .position
+            .checked_add(reference.length)
+            .ok_or_else(|| invalid("segment position exhausted"))?;
+        self.tail.position.next_offset = batch_next_offset(prepare)?;
+        Ok((Some(reference), Some(self.tail.position.next_offset)))
+    }
+
+    pub(super) fn reset_position(&mut self, position: SegmentPosition) -> io::Result<()> {
+        if !position.valid() {
+            return Err(invalid("invalid replacement segment boundary"));
+        }
+        self.tail = self.allocate(position)?;
+        self.checkpoint = self.tail;
+        Ok(())
+    }
+
+    fn allocate(&mut self, position: SegmentPosition) -> io::Result<SegmentCursor> {
+        let generation = self.next_generation;
+        self.next_generation = generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        Ok(SegmentCursor {
+            generation,
+            position,
+        })
+    }
+
+    pub(super) fn encode(self, bytes: &mut [u8]) {
+        let values = [
+            self.max_size,
+            self.next_generation,
+            self.tail.generation,
+            self.tail.position.start_offset,
+            self.tail.position.length,
+            self.tail.position.next_offset,
+            self.checkpoint.generation,
+            self.checkpoint.position.start_offset,
+            self.checkpoint.position.length,
+            self.checkpoint.position.next_offset,
+        ];
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip(values)
+        {
+            *field = value.to_le_bytes();
+        }
+    }
+
+    pub(super) fn decode(bytes: &[u8]) -> io::Result<Self> {
+        let mut values = [0; SEGMENT_STATE_BYTES / size_of::<u64>()];
+        for (value, field) in values
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *value = u64::from_le_bytes(*field);
+        }
+        let [
+            max_size,
+            next_generation,
+            tail_generation,
+            tail_start,
+            tail_length,
+            tail_next,
+            checkpoint_generation,
+            checkpoint_start,
+            checkpoint_length,
+            checkpoint_next,
+        ] = values;
+        let state = Self {
+            max_size,
+            next_generation,
+            tail: SegmentCursor {
+                generation: tail_generation,
+                position: SegmentPosition {
+                    start_offset: tail_start,
+                    length: tail_length,
+                    next_offset: tail_next,
+                },
+            },
+            checkpoint: SegmentCursor {
+                generation: checkpoint_generation,
+                position: SegmentPosition {
+                    start_offset: checkpoint_start,
+                    length: checkpoint_length,
+                    next_offset: checkpoint_next,
+                },
+            },
+        };
+        if max_size == 0
+            || tail_generation >= next_generation
+            || checkpoint_generation >= next_generation
+            || !state.tail.position.valid()
+            || !state.checkpoint.position.valid()

Review Comment:
   nit: `decode` puts no ceiling on `next_generation`. A frontier near `u64::MAX` makes `allocate` (`:561`) `checked_add` fail, so every rotation returns "segment generation exhausted" and every append fails permanently with no repair path.
   Fix: bound `next_generation` in `decode` alongside the other field validation.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))

Review Comment:
   nit: the generation bump is unkilled by mutation — replacing `.map_or(Some(0), |g| g.checked_add(1))` with generation REUSE leaves all three suites green, because no test enables ownership on a journal that already holds references (`owned_segments_migrate_only_unmaterialized_legacy_prepares` discards `write_segment`'s reference).
   So the retained-path collision guard is unverified, on a field whose whole purpose is preventing a stale generation from resolving to a live file.
   Fix: add an upgrade test asserting the tail generation exceeds every existing reference generation.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {
+            return Err(invalid(
+                "message offsets do not extend the physical segment tail",
+            ));
+        }
+        if self.tail.position.length >= self.max_size {
+            self.tail = self.allocate(SegmentPosition {
+                start_offset: batch.base_offset,
+                length: 0,
+                next_offset: batch.base_offset,
+            })?;
+        }
+        let reference = SegmentReference {
+            generation: self.tail.generation,
+            start_offset: self.tail.position.start_offset,
+            position: self.tail.position.length,
+            length: batch.batch_length,
+        };
+        self.tail.position.length = reference
+            .position
+            .checked_add(reference.length)
+            .ok_or_else(|| invalid("segment position exhausted"))?;
+        self.tail.position.next_offset = batch_next_offset(prepare)?;
+        Ok((Some(reference), Some(self.tail.position.next_offset)))
+    }
+
+    pub(super) fn reset_position(&mut self, position: SegmentPosition) -> io::Result<()> {
+        if !position.valid() {
+            return Err(invalid("invalid replacement segment boundary"));
+        }
+        self.tail = self.allocate(position)?;
+        self.checkpoint = self.tail;
+        Ok(())
+    }
+
+    fn allocate(&mut self, position: SegmentPosition) -> io::Result<SegmentCursor> {
+        let generation = self.next_generation;
+        self.next_generation = generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        Ok(SegmentCursor {
+            generation,
+            position,
+        })
+    }
+
+    pub(super) fn encode(self, bytes: &mut [u8]) {
+        let values = [
+            self.max_size,
+            self.next_generation,
+            self.tail.generation,
+            self.tail.position.start_offset,
+            self.tail.position.length,
+            self.tail.position.next_offset,
+            self.checkpoint.generation,
+            self.checkpoint.position.start_offset,
+            self.checkpoint.position.length,
+            self.checkpoint.position.next_offset,
+        ];
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip(values)
+        {
+            *field = value.to_le_bytes();
+        }
+    }
+
+    pub(super) fn decode(bytes: &[u8]) -> io::Result<Self> {
+        let mut values = [0; SEGMENT_STATE_BYTES / size_of::<u64>()];
+        for (value, field) in values
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *value = u64::from_le_bytes(*field);
+        }
+        let [
+            max_size,
+            next_generation,
+            tail_generation,
+            tail_start,
+            tail_length,
+            tail_next,
+            checkpoint_generation,
+            checkpoint_start,
+            checkpoint_length,
+            checkpoint_next,
+        ] = values;
+        let state = Self {
+            max_size,
+            next_generation,
+            tail: SegmentCursor {
+                generation: tail_generation,
+                position: SegmentPosition {
+                    start_offset: tail_start,
+                    length: tail_length,
+                    next_offset: tail_next,
+                },
+            },
+            checkpoint: SegmentCursor {
+                generation: checkpoint_generation,
+                position: SegmentPosition {
+                    start_offset: checkpoint_start,
+                    length: checkpoint_length,
+                    next_offset: checkpoint_next,
+                },
+            },
+        };

Review Comment:
   warning: no test exercises any `SegmentState::decode` guard. Neutering `tail_next < checkpoint_next`, `tail_generation >= next_generation`, and `max_size == 0` each individually leaves `cargo test -p journal` at 76/76 and `-p simulator` at 120/120 green.
   So the torn or hostile 80-byte `SegmentState` block is entirely unverified, which pairs with the unauthenticated frontier magic at `partition_journal.rs:1207`.
   Fix: add a decode table test covering each rejection.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;
+            Some(reference)
+        } else {
+            None
+        };
+        Ok((buffer, frame_length, reference))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+        checkpoint_prepare: Option<(Frozen<4096>, Option<SegmentReference>)>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            checkpoint_prepare: false,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            if checkpoint > self.state.checkpoint {
+                segments.checkpoint = self
+                    .segment_boundary(checkpoint)
+                    .ok_or_else(|| invalid("missing segment checkpoint boundary"))?;
+            }
+            if let Some(from_op) = truncate.filter(|from_op| *from_op > 0) {
+                segments.tail = self
+                    .segment_boundary(from_op - 1)
+                    .ok_or_else(|| invalid("missing segment rollback boundary"))?;
+            }
+        }
+        if let Some((prepare, reference)) = checkpoint_prepare {
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let mut encoded = Owned::zeroed(length);
+            encode_record_into(
+                prepare.as_slice(),
+                reference,
+                generation,
+                encoded.as_mut_slice(),
+            )?;
+            let length = encoded.as_slice().len();
+            file.write_aligned(0, encoded).await?;
+            entries.insert(
+                checkpoint,
+                StoredPrepare {
+                    position: 0,
+                    length,
+                    checksum,
+                    reference,
+                    next_offset: None,
+                    retained_bytes: record_length(prepare.len())? as u64,
+                },
+            );
+            state.length = length as u64;
+            state.checkpoint_prepare = true;
+        }
+        let previous_entries: Vec<_> = self
+            .entries
+            .iter()
+            .map(|(&op, &entry)| (op, entry))
+            .collect();
+        for (op, entry) in previous_entries {
+            if op < checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let (record, payload_length, mut reference) =
+                self.read_encoded_record(entry.position).await?;
+            let payload = &record.as_slice()[RECORD_PREFIX..RECORD_PREFIX + payload_length];
+            let mut next_offset = entry.next_offset;
+            let mut converted = false;
+            if reference.is_none()
+                && op > state.purge_floor
+                && let Some(segments) = &mut state.segment_storage
+            {
+                let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                    &payload[..size_of::<PrepareHeader>()],
+                )
+                .map_err(|_| invalid("invalid prepare during segment migration"))?;
+                if header.operation == Operation::SendMessages
+                    && segments::decode_batch(payload)?.base_offset
+                        >= segments.tail.position.next_offset
+                {
+                    (reference, next_offset) = segments.reserve(header, payload)?;
+                    if let Some(reference) = reference {
+                        self.write_segment_body(
+                            reference,
+                            &Frozen::from(Owned::copy_from_slice(payload)),
+                        )
+                        .await?;
+                        converted = true;
+                    }
+                }
+            }
+            let encoded_length = if converted {
+                REFERENCED_PREPARE_BYTES
+            } else {
+                payload_length
+            };
+            let mut encoded = Owned::zeroed(record_length(encoded_length)?);
+            if converted {
+                encode_record_into(payload, reference, generation, encoded.as_mut_slice())?;
+            } else {
+                encode_payload_into(
+                    payload,
+                    if reference.is_some() {
+                        SEGMENT_RECORD
+                    } else {
+                        INLINE_RECORD
+                    },
+                    generation,
+                    encoded.as_mut_slice(),
+                )?;
+            }
+            let length = encoded.as_slice().len();
+            file.write_aligned(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: entry.retained_bytes,
+                },
+            );
+            state.length += length as u64;
+            state.checkpoint_prepare |= op == checkpoint;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        self.sync_segment_files().await?;
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        let retained = self.retained_segment_paths(&entries, state.segment_storage);
+        self.obsolete.extend(
+            self.retained_segment_paths(&self.entries, self.state.segment_storage)
+                .into_iter()
+                .filter(|path| !retained.contains(path)),
+        );
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        self.obsolete.push_back(obsolete);
+        self.cleanup_obsolete().await;
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(if self.segment_references {
+            REFERENCE_STATE_MAGIC
+        } else {
+            STATE_MAGIC
+        });
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[97] = u8::from(self.checkpoint_prepare);
+        bytes[98] = u8::from(self.certified_log_view.is_some());
+        bytes[120..124].copy_from_slice(&self.certified_log_view.unwrap_or(0).to_le_bytes());
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        bytes[segments::SEGMENT_STATE_FLAG] = u8::from(self.segment_storage.is_some());
+        if let Some(segments) = self.segment_storage {
+            segments.encode(
+                &mut bytes[segments::SEGMENT_STATE_OFFSET
+                    ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+            );
+        }
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);
+        bytes[8..16].copy_from_slice(&checksum.to_le_bytes());
+        bytes
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != PARTITION_WAL_BLOCK_SIZE
+            || (&bytes[..8] != STATE_MAGIC && &bytes[..8] != REFERENCE_STATE_MAGIC)
+        {
+            return Err(invalid("unknown partition WAL frontier format"));
+        }
+        let read_u64 = |offset| -> io::Result<u64> {
+            Ok(u64::from_le_bytes(
+                bytes[offset..offset + 8]
+                    .try_into()
+                    .map_err(|_| invalid("invalid WAL frontier field"))?,
+            ))
+        };
+        if read_u64(8)? != XxHash3_64::oneshot(&bytes[16..]) {
+            return Err(invalid("partition WAL frontier checksum mismatch"));
+        }
+        let state = Self {
+            segment_references: &bytes[..8] == REFERENCE_STATE_MAGIC,
+            segment_storage: match bytes[segments::SEGMENT_STATE_FLAG] {
+                0 => None,
+                1 if &bytes[..8] == REFERENCE_STATE_MAGIC => Some(SegmentState::decode(
+                    &bytes[segments::SEGMENT_STATE_OFFSET
+                        ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+                )?),
+                _ => return Err(invalid("invalid segment storage flag")),
+            },
+            group: read_u64(16)?,
+            incarnation: read_u64(24)?,
+            generation: read_u64(32)?,
+            length: read_u64(40)?,
+            checkpoint: read_u64(48)?,
+            head: read_u64(72)?,
+            anchor_known: match bytes[96] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid WAL anchor flag")),
+            },
+            checkpoint_prepare: match bytes[97] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid checkpoint prepare flag")),
+            },
+            certified_log_view: match bytes[98] {
+                0 => None,
+                1 => Some(u32::from_le_bytes(
+                    bytes[120..124]
+                        .try_into()
+                        .map_err(|_| invalid("invalid certified view"))?,
+                )),
+                _ => return Err(invalid("invalid certified view flag")),
+            },
+            purge_generation: read_u64(104)?,
+            purge_floor: read_u64(112)?,
+            checkpoint_checksum: u128::from_le_bytes(
+                bytes[56..72]
+                    .try_into()
+                    .map_err(|_| invalid("invalid checkpoint checksum"))?,
+            ),
+            head_checksum: u128::from_le_bytes(
+                bytes[80..96]
+                    .try_into()
+                    .map_err(|_| invalid("invalid head checksum"))?,
+            ),
+        };
+        if state.length > PARTITION_WAL_CAPACITY_MAX
+            || !state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+            || state.head < state.checkpoint
+            || (!state.anchor_known && state.head != state.checkpoint)
+            || (state.checkpoint_prepare
+                && (state.checkpoint == 0 || state.length == 0 || !state.anchor_known))
+        {
+            return Err(invalid("invalid partition WAL frontier bounds"));
+        }
+        Ok(state)
+    }
+}
+
+/// Padded size of a prepare record, including its envelope.
+///
+/// # Errors
+/// Returns an error for a frame outside the protocol size bounds.
+pub fn record_length(frame_length: usize) -> io::Result<usize> {
+    if !(size_of::<PrepareHeader>()..=PREPARE_BYTES_MAX).contains(&frame_length) {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidInput,
+            format!(
+                "partition prepare size {frame_length} exceeds or falls below the supported range {}..={PREPARE_BYTES_MAX} bytes",
+                size_of::<PrepareHeader>()
+            ),
+        ));
+    }
+    Ok((RECORD_PREFIX + frame_length).next_multiple_of(PARTITION_WAL_BLOCK_SIZE))
+}
+
+fn encode_record_into(
+    prepare: &[u8],
+    reference: Option<SegmentReference>,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    if let Some(reference) = reference {
+        let mut payload = [0; REFERENCED_PREPARE_BYTES];
+        payload[..size_of::<PrepareHeader>()]
+            .copy_from_slice(&prepare[..size_of::<PrepareHeader>()]);
+        reference.encode(&mut payload[size_of::<PrepareHeader>()..]);
+        encode_payload_into(&payload, SEGMENT_RECORD, generation, bytes)
+    } else {
+        encode_payload_into(prepare, INLINE_RECORD, generation, bytes)
+    }
+}
+
+fn encode_payload_into(
+    payload: &[u8],
+    kind: u32,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    let length = u32::try_from(payload.len()).map_err(|_| invalid("oversized prepare"))?;
+    bytes[..4].copy_from_slice(&length.to_le_bytes());
+    bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+        .copy_from_slice(&kind.to_le_bytes());
+    bytes[8..16].copy_from_slice(&generation.to_le_bytes());
+    bytes[RECORD_PREFIX..RECORD_PREFIX + payload.len()].copy_from_slice(payload);
+    let checksum = XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + payload.len()]);
+    bytes[16..24].copy_from_slice(&checksum.to_le_bytes());
+    Ok(())
+}
+
+impl SegmentReference {
+    fn validate(self, header: &PrepareHeader, frame_length: usize) -> io::Result<()> {
+        if header.command != Command::Prepare
+            || header.operation != Operation::SendMessages
+            || header.size as usize != frame_length
+            || !(size_of::<PrepareHeader>() + BATCH_HEADER_SIZE..=PREPARE_BYTES_MAX)
+                .contains(&frame_length)
+            || self.length != (frame_length - size_of::<PrepareHeader>()) as u64
+            || self.position.checked_add(self.length).is_none()
+        {
+            return Err(invalid("invalid partition WAL segment reference"));
+        }
+        Ok(())
+    }
+
+    fn path(self, directory: &Path) -> PathBuf {
+        directory.join(format!(
+            "segment-{}-{}.log",
+            self.generation, self.start_offset
+        ))
+    }
+
+    fn encode(self, bytes: &mut [u8]) {
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip([
+                self.generation,
+                self.start_offset,
+                self.position,
+                self.length,
+            ])
+        {
+            field.copy_from_slice(&value.to_le_bytes());
+        }
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != SEGMENT_REFERENCE_BYTES {
+            return Err(invalid("invalid partition WAL segment reference size"));
+        }
+        let mut fields = [0; SEGMENT_REFERENCE_BYTES / size_of::<u64>()];
+        for (field, bytes) in fields
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *field = u64::from_le_bytes(*bytes);
+        }
+        let [generation, start_offset, position, length] = fields;
+        Ok(Self {
+            generation,
+            start_offset,
+            position,
+            length,
+        })
+    }
+}
+
+fn referenced_segments(
+    entries: &BTreeMap<u64, StoredPrepare>,
+    directory: &Path,
+) -> BTreeSet<PathBuf> {
+    entries
+        .values()
+        .filter_map(|entry| entry.reference.map(|reference| reference.path(directory)))
+        .collect()
+}
+
+fn is_retained_segment_name(name: &str) -> bool {
+    name.strip_prefix("segment-")
+        .and_then(|name| name.strip_suffix(".log"))
+        .and_then(|name| name.split_once('-'))
+        .is_some_and(|(generation, start_offset)| {
+            generation.parse::<u64>().is_ok() && start_offset.parse::<u64>().is_ok()
+        })
+}
+
+fn data_path(directory: &Path, generation: u64) -> PathBuf {
+    directory.join(format!("prepares-{generation}.wal"))
+}
+
+fn invalid(message: &'static str) -> io::Error {
+    io::Error::new(io::ErrorKind::InvalidData, message)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use compio::fs::File;
+    use compio::io::AsyncWriteAtExt;
+    use iggy_binary_protocol::Operation;
+    use iggy_binary_protocol::batch::BatchHeader;
+    use tempfile::tempdir;
+
+    #[cfg(target_os = "linux")]
+    use std::os::unix::fs::MetadataExt;
+
+    const REFERENCE_TEST_BODY_BYTES: usize = 1024 * 1024;
+    #[cfg(target_os = "linux")]
+    const FILE_BLOCK_BYTES: u64 = 512;
+
+    #[compio::test]
+    async fn referenced_bodies_survive_retention_and_checkpoint_without_wal_copies() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        let second_reference = write_segment(partition.path(), 0, 1, &second).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen(), second.clone().into_frozen()],
+                &[Some(first_reference), Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        assert!(!journal.contains(second.header()));
+        journal.sync().await.unwrap();
+        assert_eq!(journal.size_bytes(), 2 * PARTITION_WAL_BLOCK_SIZE as u64);
+        for offset in [0, 1] {
+            DiskStorage
+                .remove_file(&partition.path().join(format!("{offset:020}.log")))
+                .await
+                .unwrap();
+        }
+        DiskStorage.sync_directory(partition.path()).await.unwrap();
+        drop(journal);
+
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), second.as_slice());
+        journal.checkpoint(2).await.unwrap();
+        assert_eq!(journal.size_bytes(), PARTITION_WAL_BLOCK_SIZE as u64);
+        assert!(!first_reference.path(&directory).exists());
+        assert!(second_reference.path(&directory).exists());
+        drop(journal);
+
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered.len(), 1);
+        assert_eq!(recovered[0].as_slice(), second.as_slice());
+    }
+
+    #[compio::test]
+    async fn truncating_a_reference_keeps_the_shared_segment_for_its_retained_prefix() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        let mut segment = DiskStorage
+            .open(
+                &partition.path().join("00000000000000000000.log"),
+                OpenMode::ReadWrite,
+            )
+            .await
+            .unwrap();
+        DurableFile::write(
+            &mut segment,
+            first_reference.length,
+            second.as_slice()[size_of::<PrepareHeader>()..].to_vec(),
+        )
+        .await
+        .unwrap();
+        DurableFile::sync(&segment).await.unwrap();
+        let second_reference = SegmentReference {
+            position: first_reference.length,
+            ..first_reference
+        };
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen(), second.into_frozen()],
+                &[Some(first_reference), Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        journal.truncate_from(2).await.unwrap();
+        assert!(first_reference.path(&directory).exists());
+        DurableFile::truncate(&segment, first_reference.length)
+            .await
+            .unwrap();
+        let replacement = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + BATCH_HEADER_SIZE,
+        );
+        DurableFile::write(
+            &mut segment,
+            first_reference.length,
+            replacement.as_slice()[size_of::<PrepareHeader>()..].to_vec(),
+        )
+        .await
+        .unwrap();
+        DurableFile::sync(&segment).await.unwrap();
+        journal
+            .append_batch_referenced_buffered(
+                &[replacement.clone().into_frozen()],
+                &[Some(SegmentReference {
+                    length: BATCH_HEADER_SIZE as u64,
+                    ..second_reference
+                })],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+    }
+
+    #[compio::test]
+    async fn references_coexist_with_legacy_records_and_survive_purge_name_reuse() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let legacy = prepare(1, 0);
+        journal.append(legacy.clone().into_frozen()).await.unwrap();
+        assert_eq!(
+            &std::fs::read(directory.join("frontier")).unwrap()[..8],
+            STATE_MAGIC
+        );
+        let first = sized_prepare(
+            2,
+            legacy.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen()],
+                &[Some(first_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        assert_eq!(
+            &std::fs::read(directory.join("frontier")).unwrap()[..8],
+            REFERENCE_STATE_MAGIC
+        );
+        journal.mark_purge(1, 2).await.unwrap();
+        DiskStorage
+            .remove_file(&partition.path().join("00000000000000000000.log"))
+            .await
+            .unwrap();
+        let second = sized_prepare(
+            3,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + BATCH_HEADER_SIZE,
+        );
+        let second_reference = write_segment(partition.path(), 1, 0, &second).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[second.clone().into_frozen()],
+                &[Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        drop(journal);
+
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), legacy.as_slice());
+        assert_eq!(recovered[1].as_slice(), first.as_slice());
+        assert_eq!(recovered[2].as_slice(), second.as_slice());
+        assert_eq!(journal.purge_marker(), (1, 2));
+        journal.truncate_from(3).await.unwrap();
+        assert!(first_reference.path(&directory).exists());
+        assert!(!second_reference.path(&directory).exists());
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(
+            journal.prepares().await.unwrap()[1].as_slice(),
+            first.as_slice()
+        );
+    }
+
+    #[compio::test]
+    async fn recovery_sweeps_unpublished_references_and_keeps_the_durable_prefix() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let reference = write_segment(partition.path(), 0, 0, &second).await;
+        journal
+            .append_batch_referenced_buffered(&[second.into_frozen()], &[Some(reference)])
+            .await
+            .unwrap();
+        assert!(reference.path(&directory).exists());
+        drop(journal);
+
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 1);
+        assert_eq!(
+            journal.prepares().await.unwrap()[0].as_slice(),
+            first.as_slice()
+        );
+        assert!(!reference.path(&directory).exists());
+    }
+
+    #[compio::test]
+    async fn recovery_refuses_missing_torn_or_corrupt_referenced_bodies_without_rewriting_evidence()

Review Comment:
   warning: this test's `"corrupt"` arm passes only because its fixture `sized_prepare` (`:2513`) stamps `checksum_body`. Production zeroes that field for every non-metadata prepare (`core/consensus/src/impls.rs:4061-4068`), so the `:887` clause the test exercises is inert in the real system.
   Proven by mutation: setting `checksum_body = 0` in the fixture makes this test panic at `:1719` while 75 of 76 other journal tests are unaffected.
   So a test now certifies the missing-body-checksum hole as closed. That is worse than no test.
   Fix: build the header in production shape and assert the read-side `BatchHeader.batch_checksum` recompute instead.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,
+    retired_offset_files: RefCell<Vec<S::File>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    certified_log_view: Cell<Option<u32>>,
+    requested_log_view: Cell<Option<(u32, u64, u128)>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    checkpoint_needed: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    retained_bytes: Cell<u64>,
+    segment_checkpoint: Cell<Option<SegmentPosition>>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    writer_active: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct WriterLease {
+    key: PathBuf,
+    id: u64,
+    retired: AtomicBool,
+    running: AtomicBool,
+    waiters: Mutex<Vec<std::task::Waker>>,
+}
+
+struct WriterRegistration {
+    id: u64,
+    writer: Weak<WriterLease>,
+    interrupted: bool,
+}
+
+static WRITERS: LazyLock<Mutex<HashMap<PathBuf, WriterRegistration>>> =
+    LazyLock::new(|| Mutex::new(HashMap::new()));
+
+impl WriterLease {
+    async fn acquire(key: PathBuf) -> io::Result<Arc<Self>> {
+        loop {
+            let previous = {
+                let mut writers = WRITERS
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if writers
+                    .get(&key)
+                    .is_some_and(|registration| registration.interrupted)
+                {
+                    return Err(io::Error::other(
+                        "interrupted partition WAL writer requires process restart",
+                    ));
+                }
+                if let Some(previous) = writers
+                    .get(&key)
+                    .and_then(|registration| registration.writer.upgrade())
+                {
+                    drop(writers);
+                    Some(previous)
+                } else {
+                    let lease = Arc::new(Self {
+                        key: key.clone(),
+                        id: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+                        retired: AtomicBool::new(false),
+                        running: AtomicBool::new(false),
+                        waiters: Mutex::new(Vec::new()),
+                    });
+                    writers.insert(
+                        key.clone(),
+                        WriterRegistration {
+                            id: lease.id,
+                            writer: Arc::downgrade(&lease),
+                            interrupted: false,
+                        },
+                    );
+                    drop(writers);
+                    return Ok(lease);
+                }
+            };
+            let Some(previous) = previous else { continue };
+            if !previous.retired.load(Ordering::Acquire) {
+                return Err(io::Error::new(
+                    io::ErrorKind::AlreadyExists,
+                    "partition WAL already has an active writer",
+                ));
+            }
+            compio::runtime::time::timeout(
+                PERSISTENCE_DRAIN_TIMEOUT,
+                futures::future::poll_fn(|context| {
+                    let mut waiters = previous
+                        .waiters
+                        .lock()
+                        .unwrap_or_else(std::sync::PoisonError::into_inner);
+                    if !previous.running.load(Ordering::Acquire) {
+                        return std::task::Poll::Ready(());
+                    }
+                    if !waiters
+                        .iter()
+                        .any(|waiter| waiter.will_wake(context.waker()))
+                    {
+                        waiters.push(context.waker().clone());
+                    }
+                    std::task::Poll::Pending
+                }),
+            )
+            .await
+            .map_err(|_| {
+                io::Error::new(
+                    io::ErrorKind::TimedOut,
+                    "retired partition WAL writer did not stop",
+                )
+            })?;
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if writers
+                .get(&key)
+                .is_some_and(|registration| registration.id == previous.id)
+            {
+                writers.remove(&key);
+            }
+        }
+    }
+
+    fn finish(&self) {
+        self.running.store(false, Ordering::Release);
+        for waiter in self
+            .waiters
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .drain(..)
+        {
+            waiter.wake();
+        }
+    }
+}
+
+impl Drop for WriterLease {
+    fn drop(&mut self) {
+        let mut writers = WRITERS
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if writers
+            .get(&self.key)
+            .is_some_and(|registration| registration.id == self.id && !registration.interrupted)
+        {
+            writers.remove(&self.key);
+        }
+    }
+}
+
+struct WriterTicket<S: DurableStorage> {
+    owner: Rc<PartitionPersistence<S>>,
+    started: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterTicket<S> {
+    fn drop(&mut self) {
+        if self.started {
+            return;
+        }
+        self.owner.fail(io::Error::new(
+            io::ErrorKind::Interrupted,
+            "partition WAL writer was dropped before polling",
+        ));
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct WriterGuard<'a, S: DurableStorage> {
+    owner: &'a PartitionPersistence<S>,
+    journal: Option<PartitionPrepareJournal<S>>,
+    complete: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterGuard<'_, S> {
+    fn drop(&mut self) {
+        *self.owner.journal.borrow_mut() = self.journal.take();
+        self.owner.in_flight_bytes.set(0);
+        self.owner.checkpoint_running.set(false);
+        if !self.complete
+            && let Some(lease) = &self.owner.lease
+        {
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if let Some(registration) = writers.get_mut(&lease.key)
+                && registration.id == lease.id
+            {
+                registration.interrupted = true;
+            }
+        }
+        if !self.complete && self.owner.failure.borrow().is_none() {
+            *self.owner.failure.borrow_mut() = Some(Arc::new(io::Error::new(
+                io::ErrorKind::Interrupted,
+                "partition WAL writer stopped during a mutation",
+            )));
+        }
+        self.owner.writer_active.set(false);
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation<S: DurableStorage> {
+    EnableSegments {
+        epoch: u64,
+        initial: SegmentPosition,
+        max_size: u64,
+    },
+    CertifyView {
+        epoch: u64,
+        view: u32,
+        op: u64,
+        checksum: u128,
+    },
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+        offset_files: Vec<S::File>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        let lease = if let Some(key) = storage.writer_identity(directory)? {
+            Some(WriterLease::acquire(key).await?)
+        } else {
+            None
+        };
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+            preallocate_segments,
+        )
+        .await?;
+        let prepares = journal.take_recovered_prepares();
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare.header();
+            if header.op > journal.checkpoint_op() {
+                accepted.checksums.push_back(header.checksum);
+            }
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            lease,
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            certified_log_view: Cell::new(journal.certified_log_view()),
+            requested_log_view: Cell::new(None),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            checkpoint_needed: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            retained_bytes: Cell::new(journal.retained_bytes()),
+            segment_checkpoint: Cell::new(journal.segment_checkpoint()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            offset_files: RefCell::new(HashMap::new()),
+            retired_offset_files: RefCell::new(Vec::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            writer_active: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    #[cfg(test)]
+    pub(crate) fn exhaust_capacity_for_test(&self) {
+        self.disk_bytes.set(self.capacity);
+        self.retained_bytes.set(self.capacity);
+    }
+
+    #[cfg(test)]
+    pub(crate) fn release_capacity_for_test(&self) {
+        self.disk_bytes.set(0);
+        self.retained_bytes.set(0);
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.certified_log_view.get()
+    }
+
+    pub fn certify_log_view(&self, view: u32, op: u64, checksum: u128) -> bool {
+        if self.certified_log_view.get() == Some(view) {
+            return true;
+        }
+        if self.retired.get()
+            || self.failure.borrow().is_some()
+            || op > self.head()
+            || !(op == 0 && checksum == 0 || self.checksum(op) == Some(checksum))
+        {
+            return false;
+        }
+        let target = (view, op, checksum);
+        if self
+            .requested_log_view
+            .get()
+            .is_none_or(|(pending, _, _)| pending != view)
+        {
+            self.requested_log_view.set(Some(target));
+            self.queue.borrow_mut().push_back(Mutation::CertifyView {
+                epoch: self.epoch.get(),
+                view,
+                op,
+                checksum,
+            });
+        }
+        false
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.checksum(header.op) == Some(header.checksum)
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        self.segment_checkpoint.get()
+    }
+
+    pub fn enable_segment_storage(&self, initial: SegmentPosition, max_size: u64) {
+        self.queue.borrow_mut().push_back(Mutation::EnableSegments {
+            epoch: self.epoch.get(),
+            initial,
+            max_size,
+        });
+    }
+
+    /// Verify the physical prefix before making its indexes and logical sizes visible.
+    ///
+    /// # Errors
+    /// Returns an error for a failed barrier or a body outside the durable segment range.
+    pub async fn validate_segment_prefix(
+        &self,
+        prepares: &[Frozen<4096>],
+        start_offset: u64,
+        mut position: u64,
+    ) -> io::Result<u64> {
+        self.drain_with_timeout().await?;
+        let journal = self.journal.borrow();
+        let journal = journal
+            .as_ref()
+            .ok_or_else(|| io::Error::other("segment writer has no journal"))?;
+        let initial = position;
+        for prepare in prepares {
+            let header = prepare_header(prepare)?;
+            let reference: SegmentReference = journal
+                .segment_reference(header)
+                .ok_or_else(|| io::Error::other("committed prepare has no durable segment body"))?;
+            if reference.start_offset != start_offset
+                || reference.position != position
+                || reference.length != (prepare.len() - size_of::<PrepareHeader>()) as u64
+            {
+                return Err(io::Error::other(
+                    "committed prepare differs from its segment position",
+                ));
+            }
+            position = position
+                .checked_add(reference.length)
+                .ok_or_else(|| io::Error::other("segment prefix overflow"))?;
+        }
+        Ok(position - initial)
+    }
+
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head.get()
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .retained_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn take_offset_file(&self, path: &str) -> Option<S::File> {
+        self.offset_files.borrow_mut().remove(path)
+    }
+
+    /// # Panics
+    /// Panics if the previous writer was not taken before replacement.
+    pub fn retain_offset_file(&self, path: String, file: S::File) {
+        assert!(self.offset_files.borrow_mut().insert(path, file).is_none());

Review Comment:
   nit: `assert!` in non-test shard code. A broken invariant here panics the shard thread and takes the whole core down, not one partition, and the repo forbids `unwrap`/`expect` on external I/O for the same reason.
   Reachability unproven — `commit_consumer_offset_entry` (`iggy_partition.rs:6368`) holds `write_lock` and `&mut self`, so no same-path overlap exists today.
   Fix: push the displaced handle into `retired_offset_files` instead, or downgrade to `debug_assert!`.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)

Review Comment:
   nit: the boundary-monotonicity clause `next_offset >= segments.checkpoint.position.next_offset` is unkilled by mutation — replacing it with a tautology leaves all three suites green. Either checkpoint regression is untested, or the clause is dead.
   Fix: add a case with a below-checkpoint entry, or delete the clause.



##########
core/simulator/src/storage/tests.rs:
##########
@@ -0,0 +1,1574 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use super::{
+    Crash, DurableFile, DurableStorage, FaultMode, OpenMode, SimStorage, StorageOperation,
+};
+use crate::packet::PacketSimulatorOptions;
+use consensus::MetadataHandle;
+use futures::{executor::block_on, poll};
+use iggy_binary_protocol::batch::{BATCH_HEADER_SIZE, BatchHeader};
+use iggy_binary_protocol::{Command, Operation, PrepareHeader};
+use journal::partition_journal::{PARTITION_WAL_BLOCK_SIZE, SegmentPosition, SegmentReference};
+use journal::{DurableAppend, PartitionPrepareJournal};
+use partitions::{PartitionPersistence, install_backup};
+use server_common::{Message, iobuf::Owned};
+use std::io;
+use std::path::Path;
+use std::rc::Rc;
+use twox_hash::XxHash3_64;
+
+const DIRECTORY: &str = "/partition";
+const WAL: &str = "/partition/wal";
+const OWNED_BATCH_BYTES: usize = 12 * 1024;
+const MATERIALIZED_FILES: &[&str] = &[
+    "/partition/0.log",
+    "/partition/0.index",
+    "/partition/offsets/consumers/1",
+    "/partition/offsets/groups/9",
+    "/partition/superblock.a",
+];
+
+#[derive(Clone, Copy, Debug)]
+enum Mutation {
+    Append,
+    CertifyView,
+    Checkpoint,
+    Truncate,
+    Reset,
+    Purge,
+}
+
+#[test]
+fn process_crash_preserves_completed_writes_but_power_loss_requires_file_and_directory_sync() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        storage
+            .create_directories(Path::new(DIRECTORY))
+            .await
+            .unwrap();
+        storage.sync_directory(Path::new("/")).await.unwrap();
+        let path = Path::new("/partition/value");
+        let mut file = storage.open(path, OpenMode::Create).await.unwrap();
+        file.write(0, b"buffered".to_vec()).await.unwrap();
+        storage.crash(Crash::Process);
+        assert_eq!(
+            storage
+                .open(path, OpenMode::Read)
+                .await
+                .unwrap()
+                .read(0, 8)
+                .await
+                .unwrap(),
+            b"buffered"
+        );
+        storage.crash(Crash::PowerLoss);
+        assert!(!storage.exists(path).await.unwrap());
+        let mut file = storage.open(path, OpenMode::Create).await.unwrap();
+        file.write(0, b"synced".to_vec()).await.unwrap();
+        file.sync().await.unwrap();
+        storage.crash(Crash::PowerLoss);
+        assert!(
+            !storage.exists(path).await.unwrap(),
+            "file sync must not imply directory sync"
+        );
+        replace(&storage, path, b"durable").await.unwrap();
+        storage.crash(Crash::PowerLoss);
+        assert_eq!(
+            storage
+                .open(path, OpenMode::Read)
+                .await
+                .unwrap()
+                .read(0, 7)
+                .await
+                .unwrap(),
+            b"durable"
+        );
+        assert!(
+            file.sync().await.is_err(),
+            "an old process cannot complete into the new one"
+        );
+    });
+}
+
+#[test]
+fn wal_fault_sweep_preserves_acknowledged_history_at_every_io_boundary() {
+    block_on(async {
+        let mut cases = 0;
+        for mutation in [
+            Mutation::Append,
+            Mutation::CertifyView,
+            Mutation::Checkpoint,
+            Mutation::Truncate,
+            Mutation::Reset,
+            Mutation::Purge,
+        ] {
+            let (storage, mut journal) = baseline().await;
+            storage.clear_trace();
+            mutate(&storage, &mut journal, mutation).await.unwrap();
+            let trace = storage.trace();
+            for (cut, operation) in trace.iter().enumerate() {
+                for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                    for crash in [Crash::Process, Crash::PowerLoss] {
+                        for writeback in [false, true] {
+                            let (storage, mut journal) = baseline().await;
+                            storage.fail_at(cut, mode);
+                            let completed = mutate(&storage, &mut journal, mutation).await.is_ok();
+                            drop(journal);
+                            if writeback {
+                                storage.writeback();
+                            }
+                            storage.crash(crash);
+                            let recovered = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage.clone()).await.unwrap_or_else(|error| {
+                                panic!("{mutation:?} cut {cut} {operation:?} {mode:?} {crash:?} writeback={writeback}: {error}");
+                            });
+                            assert_recovery(&storage, &recovered, mutation, completed).await;
+                            cases += 1;
+                        }
+                    }
+                }
+            }
+        }
+        eprintln!("partition WAL fault cases: {cases}");
+    });
+}
+
+#[test]
+fn referenced_wal_fault_sweep_preserves_bodies_through_publication_and_reclamation() {
+    block_on(async {
+        let mut cases = 0;
+        for mutation in [
+            Mutation::Append,
+            Mutation::CertifyView,
+            Mutation::Checkpoint,
+            Mutation::Truncate,
+            Mutation::Reset,
+            Mutation::Purge,
+        ] {
+            let (storage, mut journal) = referenced_baseline().await;
+            storage.clear_trace();
+            mutate_referenced(&storage, &mut journal, mutation)
+                .await
+                .unwrap();
+            let trace = storage.trace();
+            for (cut, operation) in trace.iter().enumerate() {
+                for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                    for crash in [Crash::Process, Crash::PowerLoss] {
+                        for writeback in [false, true] {
+                            let (storage, mut journal) = referenced_baseline().await;
+                            storage.fail_at(cut, mode);
+                            let completed = mutate_referenced(&storage, &mut journal, mutation)
+                                .await
+                                .is_ok();
+                            drop(journal);
+                            if writeback {
+                                storage.writeback();
+                            }
+                            storage.crash(crash);
+                            let context = format!(
+                                "{mutation:?} cut {cut} {operation:?} {mode:?} {crash:?} writeback={writeback}"
+                            );
+                            let recovered = PartitionPrepareJournal::open_with_storage(
+                                Path::new(WAL),
+                                42,
+                                7,
+                                storage.clone(),
+                            )
+                            .await
+                            .unwrap_or_else(|error| panic!("{context}: {error}"));
+                            assert_referenced_recovery(&recovered, mutation, completed, &context)
+                                .await;
+                            cases += 1;
+                        }
+                    }
+                }
+            }
+        }
+        eprintln!("referenced partition WAL fault cases: {cases}");
+    });
+}
+
+#[test]
+fn transfer_fault_sweep_restores_one_complete_materialization_including_the_wal() {
+    block_on(async {
+        let (storage, mut journal) = baseline().await;
+        storage.clear_trace();
+        install(&storage, &mut journal).await.unwrap();
+        let trace = storage.trace();
+        let mut cases = 0;
+        for (cut, operation) in trace.iter().enumerate() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                for crash in [Crash::Process, Crash::PowerLoss] {
+                    let (storage, mut journal) = baseline().await;
+                    storage.fail_at(cut, mode);
+                    let completed = install(&storage, &mut journal).await.is_ok();
+                    drop(journal);
+                    storage.crash(crash);
+                    install_backup::recover_with_storage(Path::new(DIRECTORY), &storage)
+                        .await
+                        .unwrap_or_else(|error| {
+                            panic!("install cut {cut} {operation:?} {mode:?} {crash:?}: {error}")
+                        });
+                    let recovered = PartitionPrepareJournal::open_with_storage(
+                        Path::new(WAL),
+                        42,
+                        7,
+                        storage.clone(),
+                    )
+                    .await
+                    .unwrap();
+                    let value = storage
+                        .open(Path::new("/partition/state"), OpenMode::Read)
+                        .await
+                        .unwrap()
+                        .read(0, 3)
+                        .await
+                        .unwrap();
+                    match recovered.checkpoint_op() {
+                        0 => {
+                            assert!(!completed);
+                            assert_eq!(value, b"old");
+                            assert_eq!(recovered.head(), 3);
+                        }
+                        7 => {
+                            assert_eq!(value, b"new");
+                            assert_eq!(recovered.head(), 7);
+                        }
+                        other => panic!("mixed installed state at {other}"),
+                    }
+                    let expected: &[u8] = if recovered.checkpoint_op() == 0 {
+                        b"old"
+                    } else {
+                        b"new"
+                    };
+                    for path in MATERIALIZED_FILES {
+                        assert_eq!(
+                            storage
+                                .open(Path::new(path), OpenMode::Read)
+                                .await
+                                .unwrap()
+                                .read(0, 3)
+                                .await
+                                .unwrap(),
+                            expected
+                        );
+                    }
+                    cases += 1;
+                }
+            }
+        }
+        eprintln!("partition transfer fault cases: {cases}");
+    });
+}
+
+#[test]
+fn durable_quorum_covers_buffered_predecessors_and_losing_unsynced_replicas() {
+    block_on(async {
+        for replicas in [1, 2, 3, 5, 7] {
+            let sim = crate::Simulator::new(
+                replicas,
+                std::iter::empty(),
+                PacketSimulatorOptions::default(),
+            );
+            let quorum = sim.replicas[0].shards[0]
+                .plane
+                .metadata()
+                .consensus
+                .as_ref()
+                .unwrap()
+                .quorum_replication();
+            let first = prepare(1, 0);
+            let second = prepare(2, first.header().checksum);
+            let mut disks = Vec::new();
+            for replica in 0..replicas {
+                let storage = storage_for_partition().await;
+                let mut journal = PartitionPrepareJournal::open_with_storage(
+                    Path::new(WAL),
+                    42,
+                    7,
+                    storage.clone(),
+                )
+                .await
+                .unwrap();
+                journal
+                    .append_buffered(first.clone().into_frozen())
+                    .await
+                    .unwrap();
+                if replica < quorum {
+                    journal.append(second.clone().into_frozen()).await.unwrap();
+                } else {
+                    journal
+                        .append_buffered(second.clone().into_frozen())
+                        .await
+                        .unwrap();
+                }
+                disks.push(storage);
+            }
+            let mut survivors = 0;
+            for storage in disks {
+                storage.crash(Crash::PowerLoss);
+                let journal =
+                    PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                        .await
+                        .unwrap();
+                if journal.head() == 2 {
+                    assert!(journal.contains(first.header()));
+                    assert!(journal.contains(second.header()));
+                    survivors += 1;
+                } else {
+                    assert_eq!(journal.head(), 0);
+                }
+            }
+            assert_eq!(survivors, quorum);
+        }
+    });
+}
+
+#[test]
+fn stalled_writer_does_not_release_acks_or_block_another_partition() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (persistence, _) =
+            PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        let first = prepare(1, 0);
+        persistence
+            .append(first.clone().into_frozen(), true)
+            .unwrap();
+        storage.pause_writes();
+        assert!(persistence.start());
+        let mut writer = Box::pin(Rc::clone(&persistence).run());
+        assert!(poll!(&mut writer).is_pending());
+        assert!(!persistence.is_durable(first.header()));
+        let independent = storage_for_partition().await;
+        let mut journal =
+            PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, independent)
+                .await
+                .unwrap();
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        assert!(journal.contains(first.header()));
+        persistence.truncate_from(1);
+        let replacement = prepare_with_payload(1, 0, b"replacement");
+        persistence
+            .append(replacement.clone().into_frozen(), true)
+            .unwrap();
+        storage.resume_writes();
+        writer.await;
+        assert!(!persistence.is_durable(first.header()));
+        assert!(persistence.is_durable(replacement.header()));
+        storage.crash(Crash::PowerLoss);
+        let journal = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+            .await
+            .unwrap();
+        assert!(journal.contains(replacement.header()));
+    });
+}
+
+#[test]
+fn queue_capacity_and_retirement_withhold_unpersisted_acknowledgments() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (persistence, _) =
+            PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        let mut parent = 0;
+        let mut accepted = 0;
+        loop {
+            let prepare = prepare_with_payload(accepted + 1, parent, b"queued");
+            parent = prepare.header().checksum;
+            match persistence.append(prepare.into_frozen(), true) {
+                Ok(()) => accepted += 1,
+                Err(error) => {
+                    assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
+                    break;
+                }
+            }
+        }
+        assert!(accepted > 0);
+        assert!(!persistence.is_durable_through(accepted));
+        persistence.retire();
+        assert!(!persistence.start());
+        storage.crash(Crash::PowerLoss);
+        let journal = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 0);
+    });
+}
+
+#[test]
+fn interrupted_rollback_can_itself_restart_at_every_io_boundary() {
+    block_on(async {
+        let storage = interrupted_install().await;
+        storage.clear_trace();
+        install_backup::recover_with_storage(Path::new(DIRECTORY), &storage)
+            .await
+            .unwrap();
+        let trace = storage.trace();
+        let mut cases = 0;
+        for (cut, operation) in trace.iter().enumerate() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                for crash in [Crash::Process, Crash::PowerLoss] {
+                    let storage = interrupted_install().await;
+                    storage.fail_at(cut, mode);
+                    let _ =
+                        install_backup::recover_with_storage(Path::new(DIRECTORY), &storage).await;
+                    storage.crash(crash);
+                    install_backup::recover_with_storage(Path::new(DIRECTORY), &storage)
+                        .await
+                        .unwrap_or_else(|error| {
+                            panic!("rollback cut {cut} {operation:?} {mode:?} {crash:?}: {error}")
+                        });
+                    let journal = PartitionPrepareJournal::open_with_storage(
+                        Path::new(WAL),
+                        42,
+                        7,
+                        storage.clone(),
+                    )
+                    .await
+                    .unwrap();
+                    assert_eq!(journal.head(), 3);
+                    assert_eq!(journal.checkpoint_op(), 0);
+                    assert_eq!(
+                        storage
+                            .open(Path::new("/partition/state"), OpenMode::Read)
+                            .await
+                            .unwrap()
+                            .read(0, 3)
+                            .await
+                            .unwrap(),
+                        b"old"
+                    );
+                    cases += 1;
+                }
+            }
+        }
+        eprintln!("partition rollback fault cases: {cases}");
+    });
+}
+
+#[test]
+fn failed_durable_completion_never_releases_a_prepare_ack() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (persistence, _) =
+            PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        let first = prepare(1, 0);
+        persistence
+            .append(first.clone().into_frozen(), true)
+            .unwrap();
+        storage.clear_trace();
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        let trace = storage.trace();
+        for cut in 0..trace.len() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                let storage = storage_for_partition().await;
+                let (persistence, _) =
+                    PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                        .await
+                        .unwrap();
+                persistence
+                    .append(first.clone().into_frozen(), true)
+                    .unwrap();
+                storage.fail_at(cut, mode);
+                assert!(persistence.start());
+                Rc::clone(&persistence).run().await;
+                assert!(persistence.failure().is_some());
+                assert!(!persistence.is_durable(first.header()));
+                assert!(!persistence.is_durable_through(1));
+            }
+        }
+    });
+}
+
+#[test]
+fn synchronized_corruption_in_any_record_block_is_refused() {
+    block_on(async {
+        for block in 0..8 {
+            let (storage, journal) = baseline().await;
+            drop(journal);
+            let mut file = storage
+                .open(
+                    Path::new("/partition/wal/prepares-0.wal"),
+                    OpenMode::ReadWrite,
+                )
+                .await
+                .unwrap();
+            let offset = block * 4096 + 40;
+            let mut byte = file.read(offset, 1).await.unwrap();
+            byte[0] ^= 1;
+            file.write(offset, byte).await.unwrap();
+            file.sync().await.unwrap();
+            storage.crash(Crash::PowerLoss);
+            assert!(
+                PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                    .await
+                    .is_err()
+            );
+        }
+    });
+}
+
+async fn interrupted_install() -> SimStorage {
+    let (storage, mut journal) = baseline().await;
+    install_backup::begin_with_storage(Path::new(DIRECTORY), &storage)
+        .await
+        .unwrap();
+    replace(&storage, Path::new("/partition/state"), b"new")
+        .await
+        .unwrap();
+    journal.reset(7, None).await.unwrap();
+    drop(journal);
+    storage.crash(Crash::PowerLoss);
+    storage
+}
+
+#[test]
+fn lost_frontier_cannot_turn_a_durable_journal_into_an_empty_one() {
+    block_on(async {
+        let (storage, journal) = baseline().await;
+        drop(journal);
+        storage
+            .remove_file(Path::new("/partition/wal/frontier"))
+            .await
+            .unwrap();
+        storage.sync_directory(Path::new(WAL)).await.unwrap();
+        storage.crash(Crash::PowerLoss);
+        assert!(
+            PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                .await
+                .is_err()
+        );
+    });
+}
+
+#[test]
+fn first_open_recovers_after_each_initialization_fault() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+            .await
+            .unwrap();
+        let trace = storage.trace();
+        for (cut, operation) in trace.iter().enumerate() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                for crash in [Crash::Process, Crash::PowerLoss] {
+                    let storage = storage_for_partition().await;
+                    storage.fail_at(cut, mode);
+                    let _ = PartitionPrepareJournal::open_with_storage(
+                        Path::new(WAL),
+                        42,
+                        7,
+                        storage.clone(),
+                    )
+                    .await;
+                    storage.crash(crash);
+                    let journal =
+                        PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                            .await
+                            .unwrap_or_else(|error| {
+                                panic!(
+                                    "first open cut {cut} {operation:?} {mode:?} {crash:?}: {error}"
+                                )
+                            });
+                    assert_eq!(journal.head(), 0);
+                }
+            }
+        }
+        eprintln!(
+            "partition WAL initialization fault cases: {}",
+            trace.len() * 6
+        );
+    });
+}
+
+#[test]
+fn deleting_and_recreating_a_partition_fences_an_old_writer_completion() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        let (old, _) = PartitionPersistence::open_with_storage(
+            Path::new("/partition/prepares-7"),
+            42,
+            7,
+            storage.clone(),
+        )
+        .await
+        .unwrap();
+        let original = prepare(1, 0);
+        old.append(original.clone().into_frozen(), true).unwrap();
+        storage.pause_writes();
+        assert!(old.start());
+        let mut writer = Box::pin(Rc::clone(&old).run());
+        assert!(poll!(&mut writer).is_pending());
+        old.retire();
+        storage.remove_tree(Path::new(DIRECTORY)).await.unwrap();
+        storage.sync_directory(Path::new("/")).await.unwrap();
+        storage.resume_writes();
+        storage
+            .create_directories(Path::new(DIRECTORY))
+            .await
+            .unwrap();
+        storage.sync_directory(Path::new("/")).await.unwrap();
+        let (new, _) = PartitionPersistence::open_with_storage(
+            Path::new("/partition/prepares-8"),
+            42,
+            8,
+            storage.clone(),
+        )
+        .await
+        .unwrap();
+        writer.await;
+        assert!(!old.is_durable(original.header()));
+        let replacement = prepare_with_payload(1, 0, b"new incarnation");
+        new.append(replacement.clone().into_frozen(), true).unwrap();
+        assert!(new.start());
+        Rc::clone(&new).run().await;
+        assert!(new.is_durable(replacement.header()));
+        storage.crash(Crash::PowerLoss);
+        let recovered = PartitionPrepareJournal::open_with_storage(
+            Path::new("/partition/prepares-8"),
+            42,
+            8,
+            storage,
+        )
+        .await
+        .unwrap();
+        assert!(recovered.contains(replacement.header()));
+        assert!(!recovered.contains(original.header()));
+    });
+}
+
+#[test]
+fn independent_message_and_offset_barriers_cover_the_required_prefix() {
+    block_on(async {
+        for message_policy in [
+            iggy_common::Durability::Replicated,
+            iggy_common::Durability::Persisted,
+        ] {
+            for offset_policy in [
+                iggy_common::Durability::Replicated,
+                iggy_common::Durability::Persisted,
+            ] {
+                let storage = storage_for_partition().await;
+                let (persistence, _) =
+                    PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                        .await
+                        .unwrap();
+                let first = prepare(1, 0);
+                let store = prepare(2, first.header().checksum).transmute_header(
+                    |old, header: &mut PrepareHeader| {
+                        *header = old;
+                        header.operation = Operation::StoreConsumerOffset;
+                        header.checksum = header.identity_checksum();
+                    },
+                );
+                let delete = prepare(3, store.header().checksum).transmute_header(
+                    |old, header: &mut PrepareHeader| {
+                        *header = old;
+                        header.operation = Operation::DeleteConsumerOffset;
+                        header.checksum = header.identity_checksum();
+                    },
+                );
+                persistence
+                    .append(first.into_frozen(), message_policy.is_persisted())
+                    .unwrap();
+                persistence
+                    .append(store.into_frozen(), offset_policy.is_persisted())
+                    .unwrap();
+                persistence
+                    .append(delete.into_frozen(), offset_policy.is_persisted())
+                    .unwrap();
+                assert!(persistence.start());
+                Rc::clone(&persistence).run().await;
+                storage.crash(Crash::PowerLoss);
+                let recovered =
+                    PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                        .await
+                        .unwrap();
+                // A shared barrier may persist weaker successors in the same batch.
+                let expected = if offset_policy.is_persisted() || message_policy.is_persisted() {
+                    3
+                } else {
+                    0
+                };
+                assert_eq!(recovered.head(), expected);
+                assert_eq!(recovered.prepares().await.unwrap().len() as u64, expected);
+            }
+        }
+    });
+}
+
+#[test]
+fn queued_prepares_share_a_barrier_and_survive_power_loss_together() {
+    block_on(async {
+        let (storage, persistence) = queued_batch(65).await;
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        assert!(persistence.failure().is_none());
+        let trace = storage.trace();
+        assert_eq!(
+            trace
+                .iter()
+                .filter(|operation| **operation == StorageOperation::FileSync)
+                .count(),
+            4
+        );
+        assert_eq!(
+            trace
+                .iter()
+                .filter(|operation| **operation == StorageOperation::DirectorySync)
+                .count(),
+            2
+        );
+        assert_eq!(
+            trace
+                .iter()
+                .filter(|operation| **operation == StorageOperation::Write)
+                .count(),
+            4
+        );
+        assert!(persistence.is_durable_through(65));
+        storage.crash(Crash::PowerLoss);
+        let recovered = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+            .await
+            .unwrap();
+        assert_eq!(recovered.prepares().await.unwrap().len(), 65);
+    });
+}
+
+#[test]
+fn failed_group_barrier_never_acknowledges_a_partial_batch() {
+    block_on(async {
+        let (storage, persistence) = queued_batch(4).await;
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        let trace = storage.trace();
+        for cut in 0..trace.len() {
+            for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                let (storage, persistence) = queued_batch(4).await;
+                storage.fail_at(cut, mode);
+                assert!(persistence.start());
+                Rc::clone(&persistence).run().await;
+                let acknowledged = persistence.is_durable_through(4);
+                if persistence.failure().is_some() {
+                    assert!(!acknowledged);
+                }
+                storage.crash(Crash::PowerLoss);
+                let recovered =
+                    PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                        .await
+                        .unwrap();
+                assert!(matches!(recovered.head(), 0 | 4));
+                if acknowledged {
+                    assert_eq!(recovered.head(), 4);
+                }
+            }
+        }
+    });
+}
+
+#[test]
+fn checkpoint_syncs_the_retained_writer_before_reclaiming_its_history() {
+    block_on(async {
+        let (storage, persistence) = queued_batch(4).await;
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        let path = Path::new("/partition/offset");
+        let mut file = storage.open(path, OpenMode::Create).await.unwrap();
+        file.write(0, b"offset".to_vec()).await.unwrap();
+        persistence.retain_offset_file(path.to_string_lossy().into_owned(), file);
+        storage.remove_file(path).await.unwrap();
+        persistence.retire_offset_file(path.to_str().unwrap());
+        persistence.checkpoint_files(4, Vec::new(), vec![Path::new(DIRECTORY).to_path_buf()]);
+        storage.fail_at(0, FaultMode::Before);
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        assert!(persistence.failure().is_some());
+        assert_eq!(persistence.checkpoint_op(), 0);
+        storage.crash(Crash::PowerLoss);
+        let recovered = PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+            .await
+            .unwrap();
+        assert_eq!(recovered.checkpoint_op(), 0);
+        assert_eq!(recovered.head(), 4);
+    });
+}
+
+#[test]
+fn checkpoint_barriers_complete_before_wal_reclamation() {
+    block_on(async {
+        let (storage, persistence) = queued_batch(4).await;
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        let path = Path::new("/partition/materialized");
+        storage
+            .create_directories(Path::new(DIRECTORY))
+            .await
+            .unwrap();
+        let mut file = storage.open(path, OpenMode::Create).await.unwrap();
+        file.write(0, b"committed".to_vec()).await.unwrap();
+        persistence.checkpoint_files(
+            4,
+            vec![path.to_path_buf()],
+            vec![Path::new(DIRECTORY).to_path_buf()],
+        );
+        assert!(persistence.checkpoint_pending());
+        assert!(!persistence.needs_checkpoint());
+        assert!(persistence.start());
+        Rc::clone(&persistence).run().await;
+        assert!(!persistence.checkpoint_pending());
+        assert_eq!(persistence.checkpoint_op(), 4);
+        storage.crash(Crash::PowerLoss);
+        let recovered =
+            PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+                .await
+                .unwrap();
+        assert_eq!(recovered.checkpoint_op(), 4);
+        assert_eq!(
+            storage
+                .open(path, OpenMode::Read)
+                .await
+                .unwrap()
+                .read(0, 9)
+                .await
+                .unwrap(),
+            b"committed"
+        );
+    });
+}
+
+#[test]
+fn failed_materialization_keeps_wal_coverage_and_fences_completion() {
+    block_on(async {
+        for missing_directory in [false, true] {
+            let (storage, persistence) = queued_batch(4).await;
+            assert!(persistence.start());
+            Rc::clone(&persistence).run().await;
+            let missing = vec![Path::new("/partition/missing").to_path_buf()];
+            let (files, directories) = if missing_directory {
+                (Vec::new(), missing)
+            } else {
+                (missing, Vec::new())
+            };
+            persistence.checkpoint_files(4, files, directories);
+            assert!(persistence.start());
+            Rc::clone(&persistence).run().await;
+            assert_eq!(
+                persistence.failure().unwrap().kind(),
+                io::ErrorKind::NotFound
+            );
+            assert_eq!(persistence.checkpoint_op(), 0);
+            storage.crash(Crash::PowerLoss);
+            let recovered =
+                PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage)
+                    .await
+                    .unwrap();
+            assert_eq!(recovered.head(), 4);
+            assert_eq!(recovered.prepares().await.unwrap().len(), 4);
+        }
+    });
+}
+
+#[test]
+fn obsolete_wal_generations_are_reclaimed_after_restart_and_failed_unlink() {
+    block_on(async {
+        let (storage, mut journal) = baseline().await;
+        storage.clear_trace();
+        journal.checkpoint(2).await.unwrap();
+        let unlink = storage
+            .trace()
+            .iter()
+            .position(|operation| *operation == StorageOperation::Unlink)
+            .unwrap();
+        for restart in [false, true] {
+            let (storage, mut journal) = baseline().await;
+            storage.fail_at(unlink, FaultMode::Before);
+            journal.checkpoint(2).await.unwrap();
+            storage.clear_trace();
+            let obsolete = Path::new("/partition/wal/prepares-0.wal");
+            assert!(storage.exists(obsolete).await.unwrap());
+            if restart {
+                drop(journal);
+                storage.crash(Crash::PowerLoss);
+                journal = PartitionPrepareJournal::open_with_storage(
+                    Path::new(WAL),
+                    42,
+                    7,
+                    storage.clone(),
+                )
+                .await
+                .unwrap();
+            } else {
+                let parent = journal
+                    .prepares()
+                    .await
+                    .unwrap()
+                    .last()
+                    .map(|prepare| {
+                        bytemuck::checked::from_bytes::<PrepareHeader>(
+                            &prepare.as_slice()[..size_of::<PrepareHeader>()],
+                        )
+                        .checksum
+                    })
+                    .unwrap();
+                journal
+                    .append(prepare(4, parent).into_frozen())
+                    .await
+                    .unwrap();
+            }
+            assert!(!storage.exists(obsolete).await.unwrap());
+            assert_eq!(journal.checkpoint_op(), 2);
+            assert!(journal.prepares().await.unwrap().iter().any(|prepare| {
+                bytemuck::checked::from_bytes::<PrepareHeader>(
+                    &prepare.as_slice()[..size_of::<PrepareHeader>()],
+                )
+                .op == 2
+            }));
+        }
+    });
+}
+
+#[test]
+fn dropping_a_stalled_writer_restores_ownership_and_releases_drain_waiters() {
+    block_on(async {
+        let (storage, persistence) = queued_batch(1).await;
+        storage.pause_writes();
+        assert!(persistence.start());
+        let mut writer = Box::pin(Rc::clone(&persistence).run());
+        assert!(poll!(&mut writer).is_pending());
+        let mut drain = Box::pin(persistence.drain());
+        assert!(poll!(&mut drain).is_pending());
+        drop(writer);
+        assert_eq!(drain.await.unwrap_err().kind(), io::ErrorKind::Interrupted);
+        assert!(!persistence.start());
+    });
+}
+
+#[test]
+fn rename_rejects_a_nonempty_directory_and_a_fault_is_transient() {
+    block_on(async {
+        let storage = storage_for_partition().await;
+        storage
+            .create_directories(Path::new("/source"))
+            .await
+            .unwrap();
+        storage
+            .create_directories(Path::new("/target/child"))
+            .await
+            .unwrap();
+        assert_eq!(
+            storage
+                .rename(Path::new("/source"), Path::new("/target"))
+                .await
+                .unwrap_err()
+                .kind(),
+            io::ErrorKind::DirectoryNotEmpty
+        );
+        assert!(storage.exists(Path::new("/source")).await.unwrap());
+        storage.fail_at(0, FaultMode::Before);
+        assert!(storage.remove_tree(Path::new("/target")).await.is_err());
+        storage.remove_tree(Path::new("/target")).await.unwrap();
+        assert!(!storage.exists(Path::new("/target")).await.unwrap());
+    });
+}
+
+async fn storage_for_partition() -> SimStorage {
+    let storage = SimStorage::default();
+    storage
+        .create_directories(Path::new(DIRECTORY))
+        .await
+        .unwrap();
+    storage.sync_directory(Path::new("/")).await.unwrap();
+    storage.clear_trace();
+    storage
+}
+
+async fn queued_batch(count: u64) -> (SimStorage, Rc<PartitionPersistence<SimStorage>>) {
+    let storage = storage_for_partition().await;
+    let (persistence, _) =
+        PartitionPersistence::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+            .await
+            .unwrap();
+    let mut parent = 0;
+    for op in 1..=count {
+        let prepare = prepare(op, parent);
+        parent = prepare.header().checksum;
+        persistence.append(prepare.into_frozen(), true).unwrap();
+    }
+    storage.clear_trace();
+    (storage, persistence)
+}
+
+async fn baseline() -> (SimStorage, PartitionPrepareJournal<SimStorage>) {
+    let storage = storage_for_partition().await;
+    let mut journal =
+        PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+            .await
+            .unwrap();
+    let mut parent = 0;
+    for op in 1..=3 {
+        let prepare = prepare(op, parent);
+        parent = prepare.header().checksum;
+        journal.append(prepare.into_frozen()).await.unwrap();
+    }
+    replace(&storage, Path::new("/partition/state"), b"old")
+        .await
+        .unwrap();
+    for path in MATERIALIZED_FILES {
+        let path = Path::new(path);
+        storage
+            .create_directories(path.parent().unwrap())
+            .await
+            .unwrap();
+        replace(&storage, path, b"old").await.unwrap();
+    }
+    storage
+        .sync_directory(Path::new("/partition/offsets"))
+        .await
+        .unwrap();
+    storage.sync_directory(Path::new(DIRECTORY)).await.unwrap();
+    (storage, journal)
+}
+
+#[test]
+fn owned_segment_fault_sweep_preserves_acknowledged_bodies_and_checkpoint_bounds() {
+    block_on(async {
+        let mut cases = 0;
+        for mutation in [
+            Mutation::Append,
+            Mutation::Checkpoint,
+            Mutation::Truncate,
+            Mutation::Purge,
+        ] {
+            let (storage, mut journal) = owned_segment_baseline().await;
+            storage.clear_trace();
+            mutate_owned_segments(&mut journal, mutation).await.unwrap();
+            let trace = storage.trace();
+            for (cut, operation) in trace.iter().enumerate() {
+                for mode in [FaultMode::Before, FaultMode::After, FaultMode::TornWrite] {
+                    for crash in [Crash::Process, Crash::PowerLoss] {
+                        for writeback in [false, true] {
+                            let (storage, mut journal) = owned_segment_baseline().await;
+                            storage.fail_at(cut, mode);
+                            let completed =
+                                mutate_owned_segments(&mut journal, mutation).await.is_ok();
+                            drop(journal);
+                            if writeback {
+                                storage.writeback();
+                            }
+                            storage.crash(crash);
+                            let context = format!(
+                                "{mutation:?} cut {cut} {operation:?} {mode:?} {crash:?} writeback={writeback}"
+                            );
+                            let recovered = PartitionPrepareJournal::open_with_storage(
+                                Path::new(WAL),
+                                42,
+                                7,
+                                storage,
+                            )
+                            .await
+                            .unwrap_or_else(|error| panic!("{context}: {error}"));
+                            assert_owned_segments(&recovered, mutation, completed, &context).await;
+                            cases += 1;
+                        }
+                    }
+                }
+            }
+        }
+        println!("owned segment fault cases: {cases}");
+    });
+}
+
+async fn owned_segment_baseline() -> (SimStorage, PartitionPrepareJournal<SimStorage>) {
+    let storage = storage_for_partition().await;
+    let mut journal =
+        PartitionPrepareJournal::open_with_storage(Path::new(WAL), 42, 7, storage.clone())
+            .await
+            .unwrap();
+    journal
+        .enable_segment_storage(SegmentPosition::default(), (2 * OWNED_BATCH_BYTES) as u64)
+        .await
+        .unwrap();
+    let first = owned_prepare(1, 0, 0);
+    let second = owned_prepare(2, first.header().checksum, 1);
+    journal.append(first.into_frozen()).await.unwrap();
+    journal.append(second.into_frozen()).await.unwrap();
+    journal.checkpoint(1).await.unwrap();
+    (storage, journal)
+}
+
+async fn mutate_owned_segments(
+    journal: &mut PartitionPrepareJournal<SimStorage>,
+    mutation: Mutation,
+) -> io::Result<()> {
+    let first = owned_prepare(1, 0, 0);
+    let second = owned_prepare(2, first.header().checksum, 1);
+    match mutation {
+        Mutation::Append => {
+            journal
+                .append(owned_prepare(3, second.header().checksum, 2).into_frozen())
+                .await
+        }
+        Mutation::Checkpoint => journal.checkpoint(2).await,
+        Mutation::Truncate => journal.truncate_from(2).await,
+        Mutation::Purge => {
+            journal.mark_purge(1, 2).await?;
+            journal
+                .append(owned_prepare(3, second.header().checksum, 0).into_frozen())
+                .await
+        }
+        Mutation::CertifyView | Mutation::Reset => unreachable!("not part of this sweep"),

Review Comment:
   nit: the owned sweep excludes `Reset` and `CertifyView` behind `unreachable!("not part of this sweep")`, so its 912 cases cover Append / Checkpoint / Truncate / Purge only.
   No fault case therefore reaches `reset_with_segment_checkpoint` or the state-transfer install in owned mode — which is exactly the path of the install defects at `segments.rs:463` and `state_transfer.rs:3057`.
   Fix: add `Reset` to the owned mutation list.



##########
core/journal/src/partition_journal.rs:
##########
@@ -0,0 +1,2517 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![allow(clippy::future_not_send)]
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::batch::BATCH_HEADER_SIZE;
+use iggy_binary_protocol::{Command, ConsensusHeader, Operation, PrepareHeader};
+use server_common::{
+    Message,
+    iobuf::{Frozen, Owned},
+};
+use twox_hash::XxHash3_64;
+
+use crate::durable_storage::{DiskStorage, DurableFile, DurableStorage, OpenMode};
+
+mod segments;
+pub use segments::SegmentPosition;
+use segments::SegmentState;
+
+pub const PARTITION_WAL_BLOCK_SIZE: usize = 4096;
+pub const PARTITION_WAL_BYTES_MAX: u64 = 256 * 1024 * 1024;
+pub const PARTITION_WAL_CAPACITY_MIN: u64 = 2 * (64 * 1024 * 1024 + 4096);
+pub const PARTITION_WAL_CAPACITY_MAX: u64 = 4 * 1024 * 1024 * 1024;
+const RECORD_PREFIX: usize = 32;
+pub const PREPARE_BYTES_MAX: usize = 64 * 1024 * 1024;
+const STATE_MAGIC: &[u8; 8] = b"IGGYWAL1";
+const REFERENCE_STATE_MAGIC: &[u8; 8] = b"IGGYWAL2";
+const INLINE_RECORD: u32 = 0;
+const SEGMENT_RECORD: u32 = 1;
+const RECORD_KIND_OFFSET: usize = 4;
+const SEGMENT_REFERENCE_BYTES: usize = 4 * size_of::<u64>();
+const REFERENCED_PREPARE_BYTES: usize = size_of::<PrepareHeader>() + SEGMENT_REFERENCE_BYTES;
+
+/// A prepare body in a segment inode retained by the WAL.
+///
+/// The caller assigns a fresh generation whenever an offset-named segment is
+/// replaced, and synchronizes the body through its writing handle before
+/// submitting this reference. Referenced bytes must remain unchanged until the
+/// WAL durably removes their operations.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SegmentReference {
+    pub generation: u64,
+    pub start_offset: u64,
+    pub position: u64,
+    pub length: u64,
+}
+
+pub trait DurableAppend {
+    /// # Errors
+    /// Returns an error if persistence fails or the prepare does not extend the journal.
+    fn append(&mut self, prepare: Frozen<4096>) -> impl Future<Output = io::Result<()>>;
+}
+
+pub struct PartitionPrepareJournal<S: DurableStorage = DiskStorage> {
+    directory: PathBuf,
+    file: S::File,
+    storage: S,
+    capacity: u64,
+    state: JournalState,
+    entries: BTreeMap<u64, StoredPrepare>,
+    poisoned: bool,
+    durable_head: u64,
+    obsolete: VecDeque<PathBuf>,
+    cleanup_directory_dirty: bool,
+    recovered_prepares: Vec<Message<PrepareHeader>>,
+    segment_files: BTreeMap<(u64, u64), S::File>,
+    preallocate_segments: bool,
+    retained_bytes: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+struct JournalState {
+    group: u64,
+    incarnation: u64,
+    generation: u64,
+    length: u64,
+    checkpoint: u64,
+    checkpoint_checksum: u128,
+    head: u64,
+    head_checksum: u128,
+    anchor_known: bool,
+    checkpoint_prepare: bool,
+    certified_log_view: Option<u32>,
+    purge_generation: u64,
+    purge_floor: u64,
+    segment_references: bool,
+    segment_storage: Option<SegmentState>,
+}
+
+#[derive(Clone, Copy)]
+struct StoredPrepare {
+    position: u64,
+    length: usize,
+    checksum: u128,
+    reference: Option<SegmentReference>,
+    next_offset: Option<u64>,
+    retained_bytes: u64,
+}
+
+impl PartitionPrepareJournal {
+    /// # Errors
+    /// Returns an error on I/O failure or invalid durable history.
+    pub async fn open(directory: &Path, group: u64, incarnation: u64) -> io::Result<Self> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Open and verify the durably published partition history.
+    /// The caller must first durably materialize the parent directory.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<Self> {
+        Self::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// Open history independently of the current admission capacity.
+    ///
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_storage_and_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<Self> {
+        if !(PARTITION_WAL_CAPACITY_MIN..=PARTITION_WAL_CAPACITY_MAX).contains(&capacity)
+            || !capacity.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+        {
+            return Err(invalid(
+                "partition WAL capacity is out of bounds or unaligned",
+            ));
+        }
+        let parent = directory
+            .parent()
+            .filter(|parent| !parent.as_os_str().is_empty())
+            .unwrap_or_else(|| Path::new("."));
+        if !storage.exists(parent).await? {
+            return Err(invalid(
+                "partition WAL parent must already be durably materialized",
+            ));
+        }
+        storage.create_directories(directory).await?;
+        storage.sync_directory(parent).await?;
+        let state_path = directory.join("frontier");
+        let existing = match storage.open(&state_path, OpenMode::Read).await {
+            Ok(file) => {
+                let bytes = file.read(0, PARTITION_WAL_BLOCK_SIZE).await?;
+                let state = JournalState::decode(&bytes)?;
+                if state.group != group || state.incarnation != incarnation {
+                    return Err(invalid("partition WAL identity mismatch"));
+                }
+                Some(state)
+            }
+            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
+            Err(error) => return Err(error),
+        };
+        if existing.is_none() {
+            Self::validate_unpublished_history(&storage, directory).await?;
+        }
+        let state = existing.unwrap_or_else(|| JournalState {
+            group,
+            incarnation,
+            certified_log_view: Some(0),
+            ..JournalState::default()
+        });
+        let mode = if existing.is_none() {
+            OpenMode::Create
+        } else {
+            OpenMode::ReadWrite
+        };
+        let file = storage
+            .open(&data_path(directory, state.generation), mode)
+            .await?;
+        if file.length().await? < state.length {
+            return Err(invalid("partition WAL lost acknowledged bytes"));
+        }
+        let mut journal = Self {
+            directory: directory.to_path_buf(),
+            file,
+            storage,
+            capacity,
+            state,
+            entries: BTreeMap::new(),
+            poisoned: false,
+            durable_head: state.head,
+            obsolete: VecDeque::new(),
+            cleanup_directory_dirty: false,
+            recovered_prepares: Vec::new(),
+            segment_files: BTreeMap::new(),
+            preallocate_segments,
+            retained_bytes: 0,
+        };
+        journal.recover_entries().await?;
+        // Only bytes covered by the durable frontier could have released an ack.
+        journal.file.truncate(state.length).await?;
+        journal.file.sync().await?;
+        journal.storage.sync_directory(directory).await?;
+        if existing.is_none() {
+            journal.publish(state).await?;
+        }
+        journal.discover_obsolete().await?;
+        loop {
+            let remaining = journal.obsolete.len();
+            journal.cleanup_obsolete().await;
+            if journal.obsolete.is_empty() || journal.obsolete.len() == remaining {
+                break;
+            }
+        }
+        journal.recover_segment_files().await?;
+        journal.migrate_segment_prepares().await?;
+        Ok(journal)
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.state.certified_log_view
+    }
+
+    /// Publish a complete canonical view only after its required head is durable.
+    ///
+    /// # Errors
+    /// Returns an error if the expected history is absent or persistence fails.
+    pub async fn certify_log_view(&mut self, view: u32, op: u64, checksum: u128) -> io::Result<()> {
+        self.ensure_healthy()?;
+        let matches = if op == self.state.checkpoint {
+            (op == 0 && checksum == 0) || self.state.checkpoint_checksum == checksum
+        } else {
+            self.entries
+                .get(&op)
+                .is_some_and(|entry| entry.checksum == checksum)
+        };
+        if op > self.state.head || !matches {
+            return Err(invalid("view certificate does not match WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let state = JournalState {
+            certified_log_view: Some(view),
+            ..self.state
+        };
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    #[must_use]
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head
+    }
+
+    #[must_use]
+    pub const fn head(&self) -> u64 {
+        self.state.head
+    }
+
+    #[must_use]
+    pub const fn checkpoint_op(&self) -> u64 {
+        self.state.checkpoint
+    }
+
+    #[must_use]
+    pub const fn checkpoint_checksum(&self) -> Option<u128> {
+        if self.state.anchor_known {
+            Some(self.state.checkpoint_checksum)
+        } else {
+            None
+        }
+    }
+
+    #[must_use]
+    pub const fn generation(&self) -> u64 {
+        self.state.generation
+    }
+
+    #[must_use]
+    pub const fn size_bytes(&self) -> u64 {
+        self.state.length
+    }
+
+    /// Admission includes retained body bytes, even when the WAL stores references.
+    pub const fn retained_bytes(&self) -> u64 {
+        self.retained_bytes
+    }
+
+    #[must_use]
+    pub fn contains(&self, header: &PrepareHeader) -> bool {
+        if header.op > self.durable_head {
+            return false;
+        }
+        self.entries
+            .get(&header.op)
+            .is_some_and(|entry| entry.checksum == header.checksum)
+    }
+
+    pub fn take_recovered_prepares(&mut self) -> Vec<Message<PrepareHeader>> {
+        std::mem::take(&mut self.recovered_prepares)
+    }
+
+    /// Read the retained prepares in operation order.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn prepares(&self) -> io::Result<Vec<Message<PrepareHeader>>> {
+        let mut prepares = Vec::with_capacity(self.entries.len());
+        for entry in self.entries.values() {
+            let (_, length, prepare, _) = self.read_record(entry.position).await?;
+            if length != entry.length {
+                return Err(invalid("partition WAL index length mismatch"));
+            }
+            prepares.push(prepare);
+        }
+        Ok(prepares)
+    }
+
+    /// Durably replace the uncommitted suffix.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn truncate_from(&mut self, from_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if from_op <= self.state.checkpoint {
+            return Err(invalid("cannot truncate checkpointed partition operations"));
+        }
+        if from_op > self.state.head {
+            return Ok(());
+        }
+        self.state.certified_log_view = None;
+        self.rewrite(
+            self.state.checkpoint,
+            self.state.checkpoint_checksum,
+            Some(from_op),
+            None,
+        )
+        .await?;
+        self.recover_segment_files().await
+    }
+
+    /// Synchronize required materialized files before removing their WAL coverage.
+    /// Authorized deletions are excluded by the caller. A missing listed path
+    /// does not prove deletion was authorized and cannot permit WAL reclamation.
+    ///
+    /// # Errors
+    /// Returns an error if any file or directory barrier fails.
+    pub async fn checkpoint_files(
+        &mut self,
+        through_op: u64,
+        files: &[std::path::PathBuf],
+        directories: &[std::path::PathBuf],
+    ) -> io::Result<()> {
+        futures::stream::iter(files.iter().map(Ok::<_, io::Error>))
+            .try_for_each_concurrent(16, |path| async {
+                self.storage.open(path, OpenMode::Read).await?.sync().await
+            })
+            .await?;
+        for path in directories {
+            self.storage.sync_directory(path).await?;
+        }
+        self.checkpoint(through_op).await
+    }
+
+    /// The caller has durably materialized every operation through this point.
+    /// Reclaim a prefix already materialized durably by the caller.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn checkpoint(&mut self, through_op: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if through_op <= self.state.checkpoint {
+            return Ok(());
+        }
+        let checksum = self
+            .entries
+            .get(&through_op)
+            .ok_or_else(|| invalid("unknown WAL checkpoint"))?
+            .checksum;
+        self.state.anchor_known = true;
+        self.rewrite(through_op, checksum, None, None).await
+    }
+
+    /// Install an already durable replacement state, such as a completed transfer.
+    /// Replace the journal with an already durable state-transfer checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error on I/O failure, invalid history, or a poisoned journal.
+    pub async fn reset(&mut self, op: u64, checksum: Option<u128>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), None).await
+    }
+
+    /// Install the committed prepare together with its materialized checkpoint.
+    ///
+    /// # Errors
+    /// Returns an error for an invalid checkpoint prepare or a storage failure.
+    pub async fn reset_with_prepare(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.state.segment_storage.is_some() {
+            return Err(invalid(
+                "segment reset requires the installed body boundary",
+            ));
+        }
+        let header = self.validate_checkpoint_prepare(&prepare)?;
+        self.state.anchor_known = true;
+        self.state.certified_log_view = None;
+        self.rewrite(header.op, header.checksum, Some(0), Some((prepare, None)))
+            .await
+    }
+
+    fn validate_checkpoint_prepare(&self, prepare: &Frozen<4096>) -> io::Result<PrepareHeader> {
+        let header = *bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            prepare
+                .as_slice()
+                .get(..size_of::<PrepareHeader>())
+                .ok_or_else(|| invalid("short checkpoint prepare"))?,
+        )
+        .map_err(|_| invalid("invalid checkpoint prepare"))?;
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || (header.checksum != 0 && header.identity_checksum() != header.checksum)
+            || header.size as usize != prepare.len()
+            || (header.checksum_body != 0
+                && header.checksum_body
+                    != u128::from(XxHash3_64::oneshot(
+                        &prepare.as_slice()[size_of::<PrepareHeader>()..],
+                    )))
+        {
+            return Err(invalid("invalid checkpoint prepare identity or checksum"));
+        }
+        Ok(header)
+    }
+
+    #[must_use]
+    pub const fn purge_marker(&self) -> (u64, u64) {
+        (self.state.purge_generation, self.state.purge_floor)
+    }
+
+    /// # Errors
+    /// Returns an error if the purge marker cannot be published durably.
+    pub async fn mark_purge(&mut self, generation: u64, floor: u64) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if generation < self.state.purge_generation
+            || (generation == self.state.purge_generation && floor <= self.state.purge_floor)
+        {
+            return Ok(());
+        }
+        if floor > self.state.head {
+            return Err(invalid("purge exceeds WAL history"));
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        let mut state = JournalState {
+            purge_generation: generation,
+            purge_floor: floor,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            segments.reset_position(SegmentPosition::default())?;
+        }
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.segment_files.clear();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Make every buffered predecessor recoverable with one frontier publication.
+    ///
+    /// # Errors
+    /// Returns an error unless the buffered prefix and its frontier are durable.
+    pub async fn sync(&mut self) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if self.durable_head == self.state.head {
+            return Ok(());
+        }
+        self.poisoned = true;
+        self.file.sync().await?;
+        self.publish(self.state).await?;
+        self.durable_head = self.state.head;
+        self.poisoned = false;
+        Ok(())
+    }
+
+    /// Append a predecessor without releasing a durable acknowledgment.
+    ///
+    /// # Errors
+    /// Returns an error on write failure, capacity exhaustion, or a history conflict.
+    pub async fn append_buffered(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_batch_buffered(std::slice::from_ref(&prepare))
+            .await
+    }
+
+    /// Append a contiguous extent, validating every operation before allocation or I/O.
+    ///
+    /// # Errors
+    /// Returns an error on invalid history, capacity exhaustion or failed write.
+    pub async fn append_batch_buffered(&mut self, prepares: &[Frozen<4096>]) -> io::Result<()> {
+        self.append_batch_inner(prepares, None).await
+    }
+
+    /// Retain durable segment bodies and append only their headers and locations.
+    /// Non-message operations keep their inline payloads. The caller must first
+    /// synchronize every referenced body through the handle that wrote it.
+    ///
+    /// Segment names in the parent directory remain offset-based. Hard links
+    /// owned by this WAL keep referenced inodes alive across retention and purge.
+    ///
+    /// # Errors
+    /// Returns an error for invalid references, history, capacity, or storage.
+    pub async fn append_batch_referenced_buffered(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: &[Option<SegmentReference>],
+    ) -> io::Result<()> {
+        if references.len() != prepares.len() {
+            return Err(invalid("partition WAL reference count mismatch"));
+        }
+        self.append_batch_inner(prepares, Some(references)).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn append_batch_inner(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        references: Option<&[Option<SegmentReference>]>,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        self.cleanup_obsolete().await;
+        self.recovered_prepares.clear();
+        let mut state = self.state;
+        let mut retained_bytes = self.retained_bytes;
+        let mut records: Vec<(u64, StoredPrepare, usize)> = Vec::with_capacity(prepares.len());
+        for (index, prepare) in prepares.iter().enumerate() {
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                prepare
+                    .as_slice()
+                    .get(..size_of::<PrepareHeader>())
+                    .ok_or_else(|| invalid("short WAL prepare"))?,
+            )
+            .map_err(|_| invalid("invalid WAL prepare alignment"))?;
+            if self
+                .entries
+                .get(&header.op)
+                .is_some_and(|entry| entry.checksum == header.checksum)
+                || records.last().is_some_and(|(op, entry, _)| {
+                    *op == header.op && entry.checksum == header.checksum
+                })
+            {
+                continue;
+            }
+            if header.op
+                != state
+                    .head
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op exhausted"))?
+                || (state.anchor_known && header.parent != state.head_checksum)
+                || header.group != state.group
+            {
+                return Err(invalid("partition WAL append does not extend its history"));
+            }
+            let (reference, next_offset) = if let Some(segments) = &mut state.segment_storage {
+                if references.is_some() {
+                    return Err(invalid(
+                        "externally assigned reference in owned segment storage",
+                    ));
+                }
+                segments.reserve(header, prepare.as_slice())?
+            } else {
+                (references.and_then(|references| references[index]), None)
+            };
+            if let Some(reference) = reference {
+                reference.validate(header, prepare.len())?;
+            }
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let body_bytes = record_length(prepare.len())? as u64;
+            if retained_bytes.saturating_add(body_bytes) > self.capacity {
+                return Err(io::Error::new(
+                    io::ErrorKind::WouldBlock,
+                    "partition WAL requires checkpoint",
+                ));
+            }
+            records.push((
+                header.op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: body_bytes,
+                },
+                index,
+            ));
+            state.length += length as u64;
+            retained_bytes += body_bytes;
+            state.head = header.op;
+            state.head_checksum = header.checksum;
+            state.segment_references |= reference.is_some();
+            if state
+                .certified_log_view
+                .is_some_and(|view| header.view > view)
+            {
+                state.certified_log_view = None;
+            }
+            if !state.anchor_known {
+                state.checkpoint_checksum = header.parent;
+                state.anchor_known = true;
+            }
+        }
+        if records.is_empty() {
+            return Ok(());
+        }
+        let mut extent = Owned::zeroed(
+            usize::try_from(state.length - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?,
+        );
+        for (_, record, index) in &records {
+            let position = usize::try_from(record.position - self.state.length)
+                .map_err(|_| invalid("WAL extent overflow"))?;
+            encode_record_into(
+                prepares[*index].as_slice(),
+                record.reference,
+                state.generation,
+                &mut extent.as_mut_slice()[position..position + record.length],
+            )?;
+        }
+        self.poisoned = true;
+        self.write_segment_bodies(prepares, &records).await?;
+        self.retain_segment_inodes(&records).await?;
+        self.file.write_aligned(self.state.length, extent).await?;
+        for (op, record, _) in records {
+            self.entries.insert(op, record);
+        }
+        self.state = state;
+        self.retained_bytes = retained_bytes;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn retain_segment_inodes(
+        &self,
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        let mut linked = false;
+        for (_, record, _) in records {
+            if let Some(reference) = record.reference {
+                let retained = reference.path(&self.directory);
+                if !self.storage.exists(&retained).await? {
+                    let parent = self
+                        .directory
+                        .parent()
+                        .ok_or_else(|| invalid("referenced segment has no partition directory"))?;
+                    let source = parent.join(format!("{:020}.log", reference.start_offset));
+                    self.storage.hard_link(&source, &retained).await?;
+                    linked = true;
+                }
+            }
+        }
+        if linked {
+            // A visible frontier must never name an inode whose last durable
+            // directory entry a concurrent retention or purge can remove.
+            self.storage.sync_directory(&self.directory).await?;
+        }
+        Ok(())
+    }
+
+    async fn recover_entries(&mut self) -> io::Result<()> {
+        let state = self.state;
+        let mut position = 0;
+        let mut previous = state.checkpoint;
+        let mut checksum = state.checkpoint_checksum;
+        while position < state.length {
+            let (header, length, prepare, reference) = self.read_record(position).await?;
+            let next_offset = if state.segment_storage.is_some() && reference.is_some() {
+                Some(segments::batch_next_offset(prepare.as_slice())?)
+            } else {
+                None
+            };
+            self.recovered_prepares.push(prepare);
+            let checkpoint_prepare = position == 0 && state.checkpoint_prepare;
+            if checkpoint_prepare {
+                if header.op != state.checkpoint || header.checksum != state.checkpoint_checksum {
+                    return Err(invalid("partition WAL checkpoint prepare mismatch"));
+                }
+            } else if header.op
+                != previous
+                    .checked_add(1)
+                    .ok_or_else(|| invalid("WAL op overflow"))?
+                || header.parent != checksum
+            {
+                return Err(invalid("partition WAL prepare chain is broken"));
+            }
+            self.entries.insert(
+                header.op,
+                StoredPrepare {
+                    position,
+                    length,
+                    checksum: header.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: record_length(header.size as usize)? as u64,
+                },
+            );
+            previous = header.op;
+            checksum = header.checksum;
+            position += length as u64;
+        }
+        if position != state.length || previous != state.head || checksum != state.head_checksum {
+            return Err(invalid("partition WAL frontier disagrees with its data"));
+        }
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        Ok(())
+    }
+
+    async fn discover_obsolete(&mut self) -> io::Result<()> {
+        let retained = self.retained_segment_paths(&self.entries, self.state.segment_storage);
+        for entry in self.storage.entries(&self.directory).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let generation = name
+                .strip_prefix("prepares-")
+                .and_then(|name| name.strip_suffix(".wal"))
+                .and_then(|value| value.parse::<u64>().ok());
+            if !entry.directory
+                && (generation.is_some_and(|generation| generation != self.state.generation)
+                    || name == "frontier.tmp"
+                    || (is_retained_segment_name(name)
+                        && !retained.contains(&self.directory.join(&entry.name))))
+            {
+                self.obsolete.push_back(self.directory.join(entry.name));
+            }
+        }
+        Ok(())
+    }
+
+    async fn cleanup_obsolete(&mut self) {
+        let count = self.obsolete.len().min(16);
+        for _ in 0..count {
+            let Some(path) = self.obsolete.pop_front() else {
+                break;
+            };
+            match self.storage.remove_file(&path).await {
+                Ok(()) => self.cleanup_directory_dirty = true,
+                Err(error) if error.kind() == io::ErrorKind::NotFound => {
+                    self.cleanup_directory_dirty = true;
+                }
+                Err(error) => {
+                    tracing::warn!(%error, path = %path.display(), "cannot remove obsolete partition WAL generation");
+                    self.obsolete.push_back(path);
+                }
+            }
+        }
+        if self.cleanup_directory_dirty {
+            match self.storage.sync_directory(&self.directory).await {
+                Ok(()) => self.cleanup_directory_dirty = false,
+                Err(error) => tracing::warn!(%error, "cannot synchronize partition WAL cleanup"),
+            }
+        }
+    }
+
+    async fn validate_unpublished_history(storage: &S, directory: &Path) -> io::Result<()> {
+        for entry in storage.entries(directory).await? {
+            if entry.directory || entry.name == "frontier.tmp" {
+                continue;
+            }
+            // An interrupted first open can leave only its empty generation-zero file.
+            // Any other history without its frontier may contain acknowledged data.
+            if entry.name != "prepares-0.wal"
+                || storage
+                    .open(&directory.join(&entry.name), OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    != 0
+            {
+                return Err(invalid(
+                    "partition WAL history exists without its durable frontier",
+                ));
+            }
+        }
+        Ok(())
+    }
+
+    fn ensure_healthy(&self) -> io::Result<()> {
+        if self.poisoned {
+            Err(invalid(
+                "partition WAL requires recovery after failed mutation",
+            ))
+        } else {
+            Ok(())
+        }
+    }
+
+    async fn read_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(
+        PrepareHeader,
+        usize,
+        Message<PrepareHeader>,
+        Option<SegmentReference>,
+    )> {
+        let (mut buffer, frame_length, reference) = self.read_encoded_record(position).await?;
+        let length = buffer.as_slice().len();
+        if let Some(reference) = reference {
+            let payload = &buffer.as_slice()[RECORD_PREFIX..RECORD_PREFIX + frame_length];
+            let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                &payload[..size_of::<PrepareHeader>()],
+            )
+            .map_err(|_| invalid("invalid referenced prepare header"))?;
+            let mut prepare = Owned::zeroed(header.size as usize);
+            prepare.as_mut_slice()[..size_of::<PrepareHeader>()]
+                .copy_from_slice(&payload[..size_of::<PrepareHeader>()]);
+            buffer = self
+                .storage
+                .open(&reference.path(&self.directory), OpenMode::Read)
+                .await?
+                .read_aligned_tail(reference.position, prepare, size_of::<PrepareHeader>())
+                .await?;
+        } else {
+            buffer
+                .as_mut_slice()
+                .copy_within(RECORD_PREFIX..RECORD_PREFIX + frame_length, 0);
+            buffer.truncate(frame_length);
+        }
+        let message = Message::<PrepareHeader>::try_from(buffer)
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        let header = *message.header();
+        if header.command != Command::Prepare
+            || header.group != self.state.group
+            || header.size as usize != message.as_slice().len()
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        if reference.is_some()
+            && ((header.checksum != 0 && header.identity_checksum() != header.checksum)
+                || (header.checksum_body != 0
+                    && header.checksum_body
+                        != u128::from(XxHash3_64::oneshot(
+                            &message.as_slice()[size_of::<PrepareHeader>()..],
+                        ))))
+        {
+            return Err(invalid("referenced segment prepare checksum mismatch"));
+        }
+        Ok((header, length, message, reference))
+    }
+
+    async fn read_encoded_record(
+        &self,
+        position: u64,
+    ) -> io::Result<(Owned<4096>, usize, Option<SegmentReference>)> {
+        let prefix = self
+            .file
+            .read_aligned(position, PARTITION_WAL_BLOCK_SIZE)
+            .await?;
+        let frame_length = u32::from_le_bytes(
+            prefix.as_slice()[..4]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL prefix"))?,
+        ) as usize;
+        let length = record_length(frame_length)?;
+        if position
+            .checked_add(length as u64)
+            .is_none_or(|end| end > self.state.length)
+        {
+            return Err(invalid("partition WAL record crosses durable frontier"));
+        }
+        let mut buffer = if length == PARTITION_WAL_BLOCK_SIZE {
+            prefix
+        } else {
+            let mut bytes = Owned::zeroed(length);
+            bytes.as_mut_slice()[..PARTITION_WAL_BLOCK_SIZE].copy_from_slice(prefix.as_slice());
+            self.file
+                .read_aligned_tail(
+                    position + PARTITION_WAL_BLOCK_SIZE as u64,
+                    bytes,
+                    PARTITION_WAL_BLOCK_SIZE,
+                )
+                .await?
+        };
+        let bytes = buffer.as_mut_slice();
+        let stored_hash = u64::from_le_bytes(
+            bytes[16..24]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL checksum"))?,
+        );
+        bytes[16..24].fill(0);
+        if XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + frame_length]) != stored_hash {
+            return Err(invalid("partition WAL record checksum mismatch"));
+        }
+        let generation = u64::from_le_bytes(
+            bytes[8..16]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL generation"))?,
+        );
+        if generation != self.state.generation {
+            return Err(invalid("partition WAL stale record generation"));
+        }
+        let kind = u32::from_le_bytes(
+            bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+                .try_into()
+                .map_err(|_| invalid("invalid WAL record kind"))?,
+        );
+        if kind != INLINE_RECORD && (kind != SEGMENT_RECORD || !self.state.segment_references) {
+            return Err(invalid("unknown partition WAL record kind"));
+        }
+        let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+            &bytes[RECORD_PREFIX..RECORD_PREFIX + size_of::<PrepareHeader>()],
+        )
+        .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        header
+            .validate()
+            .map_err(|_| invalid("invalid partition WAL prepare"))?;
+        if header.group != self.state.group
+            || (kind == INLINE_RECORD && header.size as usize != frame_length)
+        {
+            return Err(invalid("partition WAL prepare identity mismatch"));
+        }
+        let reference = if kind == SEGMENT_RECORD {
+            if frame_length != REFERENCED_PREPARE_BYTES {
+                return Err(invalid("invalid segment reference record size"));
+            }
+            let reference = SegmentReference::decode(
+                &bytes[RECORD_PREFIX + size_of::<PrepareHeader>()..RECORD_PREFIX + frame_length],
+            )?;
+            reference.validate(header, header.size as usize)?;
+            Some(reference)
+        } else {
+            None
+        };
+        Ok((buffer, frame_length, reference))
+    }
+
+    async fn publish(&self, state: JournalState) -> io::Result<()> {
+        let temporary = self.directory.join("frontier.tmp");
+        let mut file = self.storage.open(&temporary, OpenMode::Create).await?;
+        file.write(0, state.encode()).await?;
+        file.sync().await?;
+        self.storage
+            .rename(&temporary, &self.directory.join("frontier"))
+            .await?;
+        self.storage.sync_directory(&self.directory).await
+    }
+
+    #[allow(clippy::too_many_lines)]
+    async fn rewrite(
+        &mut self,
+        checkpoint: u64,
+        checksum: u128,
+        truncate: Option<u64>,
+        checkpoint_prepare: Option<(Frozen<4096>, Option<SegmentReference>)>,
+    ) -> io::Result<()> {
+        // A failed publication can leave a newer frontier visible on disk.
+        // Poison until reopen instead of overwriting that possibly durable state.
+        self.poisoned = true;
+        let generation = self
+            .state
+            .generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("WAL generation exhausted"))?;
+        let mut file = self
+            .storage
+            .open(&data_path(&self.directory, generation), OpenMode::Create)
+            .await?;
+        let mut entries = BTreeMap::new();
+        let mut state = JournalState {
+            generation,
+            checkpoint,
+            checkpoint_checksum: checksum,
+            head: checkpoint,
+            head_checksum: checksum,
+            length: 0,
+            checkpoint_prepare: false,
+            ..self.state
+        };
+        if let Some(segments) = &mut state.segment_storage {
+            if checkpoint > self.state.checkpoint {
+                segments.checkpoint = self
+                    .segment_boundary(checkpoint)
+                    .ok_or_else(|| invalid("missing segment checkpoint boundary"))?;
+            }
+            if let Some(from_op) = truncate.filter(|from_op| *from_op > 0) {
+                segments.tail = self
+                    .segment_boundary(from_op - 1)
+                    .ok_or_else(|| invalid("missing segment rollback boundary"))?;
+            }
+        }
+        if let Some((prepare, reference)) = checkpoint_prepare {
+            let length =
+                record_length(reference.map_or(prepare.len(), |_| REFERENCED_PREPARE_BYTES))?;
+            let mut encoded = Owned::zeroed(length);
+            encode_record_into(
+                prepare.as_slice(),
+                reference,
+                generation,
+                encoded.as_mut_slice(),
+            )?;
+            let length = encoded.as_slice().len();
+            file.write_aligned(0, encoded).await?;
+            entries.insert(
+                checkpoint,
+                StoredPrepare {
+                    position: 0,
+                    length,
+                    checksum,
+                    reference,
+                    next_offset: None,
+                    retained_bytes: record_length(prepare.len())? as u64,
+                },
+            );
+            state.length = length as u64;
+            state.checkpoint_prepare = true;
+        }
+        let previous_entries: Vec<_> = self
+            .entries
+            .iter()
+            .map(|(&op, &entry)| (op, entry))
+            .collect();
+        for (op, entry) in previous_entries {
+            if op < checkpoint || truncate.is_some_and(|from| op >= from) {
+                continue;
+            }
+            let (record, payload_length, mut reference) =
+                self.read_encoded_record(entry.position).await?;
+            let payload = &record.as_slice()[RECORD_PREFIX..RECORD_PREFIX + payload_length];
+            let mut next_offset = entry.next_offset;
+            let mut converted = false;
+            if reference.is_none()
+                && op > state.purge_floor
+                && let Some(segments) = &mut state.segment_storage
+            {
+                let header = bytemuck::checked::try_from_bytes::<PrepareHeader>(
+                    &payload[..size_of::<PrepareHeader>()],
+                )
+                .map_err(|_| invalid("invalid prepare during segment migration"))?;
+                if header.operation == Operation::SendMessages
+                    && segments::decode_batch(payload)?.base_offset
+                        >= segments.tail.position.next_offset
+                {
+                    (reference, next_offset) = segments.reserve(header, payload)?;
+                    if let Some(reference) = reference {
+                        self.write_segment_body(
+                            reference,
+                            &Frozen::from(Owned::copy_from_slice(payload)),
+                        )
+                        .await?;
+                        converted = true;
+                    }
+                }
+            }
+            let encoded_length = if converted {
+                REFERENCED_PREPARE_BYTES
+            } else {
+                payload_length
+            };
+            let mut encoded = Owned::zeroed(record_length(encoded_length)?);
+            if converted {
+                encode_record_into(payload, reference, generation, encoded.as_mut_slice())?;
+            } else {
+                encode_payload_into(
+                    payload,
+                    if reference.is_some() {
+                        SEGMENT_RECORD
+                    } else {
+                        INLINE_RECORD
+                    },
+                    generation,
+                    encoded.as_mut_slice(),
+                )?;
+            }
+            let length = encoded.as_slice().len();
+            file.write_aligned(state.length, encoded).await?;
+            entries.insert(
+                op,
+                StoredPrepare {
+                    position: state.length,
+                    length,
+                    checksum: entry.checksum,
+                    reference,
+                    next_offset,
+                    retained_bytes: entry.retained_bytes,
+                },
+            );
+            state.length += length as u64;
+            state.checkpoint_prepare |= op == checkpoint;
+            state.head = op;
+            state.head_checksum = entry.checksum;
+        }
+        self.sync_segment_files().await?;
+        file.sync().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.publish(state).await?;
+        let obsolete = data_path(&self.directory, self.state.generation);
+        let retained = self.retained_segment_paths(&entries, state.segment_storage);
+        self.obsolete.extend(
+            self.retained_segment_paths(&self.entries, self.state.segment_storage)
+                .into_iter()
+                .filter(|path| !retained.contains(path)),
+        );
+        self.file = file;
+        self.state = state;
+        self.durable_head = state.head;
+        self.entries = entries;
+        self.retained_bytes = self
+            .entries
+            .values()
+            .map(|entry| entry.retained_bytes)
+            .sum();
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        self.obsolete.push_back(obsolete);
+        self.cleanup_obsolete().await;
+        Ok(())
+    }
+}
+
+impl<S: DurableStorage> DurableAppend for PartitionPrepareJournal<S> {
+    async fn append(&mut self, prepare: Frozen<4096>) -> io::Result<()> {
+        self.append_buffered(prepare).await?;
+        self.sync().await
+    }
+}
+
+impl JournalState {
+    fn encode(self) -> Vec<u8> {
+        let mut bytes = vec![0; PARTITION_WAL_BLOCK_SIZE];
+        bytes[..8].copy_from_slice(if self.segment_references {
+            REFERENCE_STATE_MAGIC
+        } else {
+            STATE_MAGIC
+        });
+        for (offset, value) in [
+            (16, self.group),
+            (24, self.incarnation),
+            (32, self.generation),
+            (40, self.length),
+            (48, self.checkpoint),
+            (72, self.head),
+        ] {
+            bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
+        }
+        bytes[56..72].copy_from_slice(&self.checkpoint_checksum.to_le_bytes());
+        bytes[80..96].copy_from_slice(&self.head_checksum.to_le_bytes());
+        bytes[96] = u8::from(self.anchor_known);
+        bytes[97] = u8::from(self.checkpoint_prepare);
+        bytes[98] = u8::from(self.certified_log_view.is_some());
+        bytes[120..124].copy_from_slice(&self.certified_log_view.unwrap_or(0).to_le_bytes());
+        bytes[104..112].copy_from_slice(&self.purge_generation.to_le_bytes());
+        bytes[112..120].copy_from_slice(&self.purge_floor.to_le_bytes());
+        bytes[segments::SEGMENT_STATE_FLAG] = u8::from(self.segment_storage.is_some());
+        if let Some(segments) = self.segment_storage {
+            segments.encode(
+                &mut bytes[segments::SEGMENT_STATE_OFFSET
+                    ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+            );
+        }
+        let checksum = XxHash3_64::oneshot(&bytes[16..]);
+        bytes[8..16].copy_from_slice(&checksum.to_le_bytes());
+        bytes
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != PARTITION_WAL_BLOCK_SIZE
+            || (&bytes[..8] != STATE_MAGIC && &bytes[..8] != REFERENCE_STATE_MAGIC)
+        {
+            return Err(invalid("unknown partition WAL frontier format"));
+        }
+        let read_u64 = |offset| -> io::Result<u64> {
+            Ok(u64::from_le_bytes(
+                bytes[offset..offset + 8]
+                    .try_into()
+                    .map_err(|_| invalid("invalid WAL frontier field"))?,
+            ))
+        };
+        if read_u64(8)? != XxHash3_64::oneshot(&bytes[16..]) {
+            return Err(invalid("partition WAL frontier checksum mismatch"));
+        }
+        let state = Self {
+            segment_references: &bytes[..8] == REFERENCE_STATE_MAGIC,
+            segment_storage: match bytes[segments::SEGMENT_STATE_FLAG] {
+                0 => None,
+                1 if &bytes[..8] == REFERENCE_STATE_MAGIC => Some(SegmentState::decode(
+                    &bytes[segments::SEGMENT_STATE_OFFSET
+                        ..segments::SEGMENT_STATE_OFFSET + segments::SEGMENT_STATE_BYTES],
+                )?),
+                _ => return Err(invalid("invalid segment storage flag")),
+            },
+            group: read_u64(16)?,
+            incarnation: read_u64(24)?,
+            generation: read_u64(32)?,
+            length: read_u64(40)?,
+            checkpoint: read_u64(48)?,
+            head: read_u64(72)?,
+            anchor_known: match bytes[96] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid WAL anchor flag")),
+            },
+            checkpoint_prepare: match bytes[97] {
+                0 => false,
+                1 => true,
+                _ => return Err(invalid("invalid checkpoint prepare flag")),
+            },
+            certified_log_view: match bytes[98] {
+                0 => None,
+                1 => Some(u32::from_le_bytes(
+                    bytes[120..124]
+                        .try_into()
+                        .map_err(|_| invalid("invalid certified view"))?,
+                )),
+                _ => return Err(invalid("invalid certified view flag")),
+            },
+            purge_generation: read_u64(104)?,
+            purge_floor: read_u64(112)?,
+            checkpoint_checksum: u128::from_le_bytes(
+                bytes[56..72]
+                    .try_into()
+                    .map_err(|_| invalid("invalid checkpoint checksum"))?,
+            ),
+            head_checksum: u128::from_le_bytes(
+                bytes[80..96]
+                    .try_into()
+                    .map_err(|_| invalid("invalid head checksum"))?,
+            ),
+        };
+        if state.length > PARTITION_WAL_CAPACITY_MAX
+            || !state.length.is_multiple_of(PARTITION_WAL_BLOCK_SIZE as u64)
+            || state.head < state.checkpoint
+            || (!state.anchor_known && state.head != state.checkpoint)
+            || (state.checkpoint_prepare
+                && (state.checkpoint == 0 || state.length == 0 || !state.anchor_known))
+        {
+            return Err(invalid("invalid partition WAL frontier bounds"));
+        }
+        Ok(state)
+    }
+}
+
+/// Padded size of a prepare record, including its envelope.
+///
+/// # Errors
+/// Returns an error for a frame outside the protocol size bounds.
+pub fn record_length(frame_length: usize) -> io::Result<usize> {
+    if !(size_of::<PrepareHeader>()..=PREPARE_BYTES_MAX).contains(&frame_length) {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidInput,
+            format!(
+                "partition prepare size {frame_length} exceeds or falls below the supported range {}..={PREPARE_BYTES_MAX} bytes",
+                size_of::<PrepareHeader>()
+            ),
+        ));
+    }
+    Ok((RECORD_PREFIX + frame_length).next_multiple_of(PARTITION_WAL_BLOCK_SIZE))
+}
+
+fn encode_record_into(
+    prepare: &[u8],
+    reference: Option<SegmentReference>,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    if let Some(reference) = reference {
+        let mut payload = [0; REFERENCED_PREPARE_BYTES];
+        payload[..size_of::<PrepareHeader>()]
+            .copy_from_slice(&prepare[..size_of::<PrepareHeader>()]);
+        reference.encode(&mut payload[size_of::<PrepareHeader>()..]);
+        encode_payload_into(&payload, SEGMENT_RECORD, generation, bytes)
+    } else {
+        encode_payload_into(prepare, INLINE_RECORD, generation, bytes)
+    }
+}
+
+fn encode_payload_into(
+    payload: &[u8],
+    kind: u32,
+    generation: u64,
+    bytes: &mut [u8],
+) -> io::Result<()> {
+    let length = u32::try_from(payload.len()).map_err(|_| invalid("oversized prepare"))?;
+    bytes[..4].copy_from_slice(&length.to_le_bytes());
+    bytes[RECORD_KIND_OFFSET..RECORD_KIND_OFFSET + size_of::<u32>()]
+        .copy_from_slice(&kind.to_le_bytes());
+    bytes[8..16].copy_from_slice(&generation.to_le_bytes());
+    bytes[RECORD_PREFIX..RECORD_PREFIX + payload.len()].copy_from_slice(payload);
+    let checksum = XxHash3_64::oneshot(&bytes[..RECORD_PREFIX + payload.len()]);
+    bytes[16..24].copy_from_slice(&checksum.to_le_bytes());
+    Ok(())
+}
+
+impl SegmentReference {
+    fn validate(self, header: &PrepareHeader, frame_length: usize) -> io::Result<()> {
+        if header.command != Command::Prepare
+            || header.operation != Operation::SendMessages
+            || header.size as usize != frame_length
+            || !(size_of::<PrepareHeader>() + BATCH_HEADER_SIZE..=PREPARE_BYTES_MAX)
+                .contains(&frame_length)
+            || self.length != (frame_length - size_of::<PrepareHeader>()) as u64
+            || self.position.checked_add(self.length).is_none()
+        {
+            return Err(invalid("invalid partition WAL segment reference"));
+        }
+        Ok(())
+    }
+
+    fn path(self, directory: &Path) -> PathBuf {
+        directory.join(format!(
+            "segment-{}-{}.log",
+            self.generation, self.start_offset
+        ))
+    }
+
+    fn encode(self, bytes: &mut [u8]) {
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip([
+                self.generation,
+                self.start_offset,
+                self.position,
+                self.length,
+            ])
+        {
+            field.copy_from_slice(&value.to_le_bytes());
+        }
+    }
+
+    fn decode(bytes: &[u8]) -> io::Result<Self> {
+        if bytes.len() != SEGMENT_REFERENCE_BYTES {
+            return Err(invalid("invalid partition WAL segment reference size"));
+        }
+        let mut fields = [0; SEGMENT_REFERENCE_BYTES / size_of::<u64>()];
+        for (field, bytes) in fields
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *field = u64::from_le_bytes(*bytes);
+        }
+        let [generation, start_offset, position, length] = fields;
+        Ok(Self {
+            generation,
+            start_offset,
+            position,
+            length,
+        })
+    }
+}
+
+fn referenced_segments(
+    entries: &BTreeMap<u64, StoredPrepare>,
+    directory: &Path,
+) -> BTreeSet<PathBuf> {
+    entries
+        .values()
+        .filter_map(|entry| entry.reference.map(|reference| reference.path(directory)))
+        .collect()
+}
+
+fn is_retained_segment_name(name: &str) -> bool {
+    name.strip_prefix("segment-")
+        .and_then(|name| name.strip_suffix(".log"))
+        .and_then(|name| name.split_once('-'))
+        .is_some_and(|(generation, start_offset)| {
+            generation.parse::<u64>().is_ok() && start_offset.parse::<u64>().is_ok()
+        })
+}
+
+fn data_path(directory: &Path, generation: u64) -> PathBuf {
+    directory.join(format!("prepares-{generation}.wal"))
+}
+
+fn invalid(message: &'static str) -> io::Error {
+    io::Error::new(io::ErrorKind::InvalidData, message)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use compio::fs::File;
+    use compio::io::AsyncWriteAtExt;
+    use iggy_binary_protocol::Operation;
+    use iggy_binary_protocol::batch::BatchHeader;
+    use tempfile::tempdir;
+
+    #[cfg(target_os = "linux")]
+    use std::os::unix::fs::MetadataExt;
+
+    const REFERENCE_TEST_BODY_BYTES: usize = 1024 * 1024;
+    #[cfg(target_os = "linux")]
+    const FILE_BLOCK_BYTES: u64 = 512;
+
+    #[compio::test]
+    async fn referenced_bodies_survive_retention_and_checkpoint_without_wal_copies() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        let second_reference = write_segment(partition.path(), 0, 1, &second).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen(), second.clone().into_frozen()],
+                &[Some(first_reference), Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        assert!(!journal.contains(second.header()));
+        journal.sync().await.unwrap();
+        assert_eq!(journal.size_bytes(), 2 * PARTITION_WAL_BLOCK_SIZE as u64);
+        for offset in [0, 1] {
+            DiskStorage
+                .remove_file(&partition.path().join(format!("{offset:020}.log")))
+                .await
+                .unwrap();
+        }
+        DiskStorage.sync_directory(partition.path()).await.unwrap();
+        drop(journal);
+
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), second.as_slice());
+        journal.checkpoint(2).await.unwrap();
+        assert_eq!(journal.size_bytes(), PARTITION_WAL_BLOCK_SIZE as u64);
+        assert!(!first_reference.path(&directory).exists());
+        assert!(second_reference.path(&directory).exists());
+        drop(journal);
+
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered.len(), 1);
+        assert_eq!(recovered[0].as_slice(), second.as_slice());
+    }
+
+    #[compio::test]
+    async fn truncating_a_reference_keeps_the_shared_segment_for_its_retained_prefix() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        let mut segment = DiskStorage
+            .open(
+                &partition.path().join("00000000000000000000.log"),
+                OpenMode::ReadWrite,
+            )
+            .await
+            .unwrap();
+        DurableFile::write(
+            &mut segment,
+            first_reference.length,
+            second.as_slice()[size_of::<PrepareHeader>()..].to_vec(),
+        )
+        .await
+        .unwrap();
+        DurableFile::sync(&segment).await.unwrap();
+        let second_reference = SegmentReference {
+            position: first_reference.length,
+            ..first_reference
+        };
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen(), second.into_frozen()],
+                &[Some(first_reference), Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        journal.truncate_from(2).await.unwrap();
+        assert!(first_reference.path(&directory).exists());
+        DurableFile::truncate(&segment, first_reference.length)
+            .await
+            .unwrap();
+        let replacement = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + BATCH_HEADER_SIZE,
+        );
+        DurableFile::write(
+            &mut segment,
+            first_reference.length,
+            replacement.as_slice()[size_of::<PrepareHeader>()..].to_vec(),
+        )
+        .await
+        .unwrap();
+        DurableFile::sync(&segment).await.unwrap();
+        journal
+            .append_batch_referenced_buffered(
+                &[replacement.clone().into_frozen()],
+                &[Some(SegmentReference {
+                    length: BATCH_HEADER_SIZE as u64,
+                    ..second_reference
+                })],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+    }
+
+    #[compio::test]
+    async fn references_coexist_with_legacy_records_and_survive_purge_name_reuse() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let legacy = prepare(1, 0);
+        journal.append(legacy.clone().into_frozen()).await.unwrap();
+        assert_eq!(
+            &std::fs::read(directory.join("frontier")).unwrap()[..8],
+            STATE_MAGIC
+        );
+        let first = sized_prepare(
+            2,
+            legacy.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let first_reference = write_segment(partition.path(), 0, 0, &first).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[first.clone().into_frozen()],
+                &[Some(first_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        assert_eq!(
+            &std::fs::read(directory.join("frontier")).unwrap()[..8],
+            REFERENCE_STATE_MAGIC
+        );
+        journal.mark_purge(1, 2).await.unwrap();
+        DiskStorage
+            .remove_file(&partition.path().join("00000000000000000000.log"))
+            .await
+            .unwrap();
+        let second = sized_prepare(
+            3,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + BATCH_HEADER_SIZE,
+        );
+        let second_reference = write_segment(partition.path(), 1, 0, &second).await;
+        journal
+            .append_batch_referenced_buffered(
+                &[second.clone().into_frozen()],
+                &[Some(second_reference)],
+            )
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        drop(journal);
+
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), legacy.as_slice());
+        assert_eq!(recovered[1].as_slice(), first.as_slice());
+        assert_eq!(recovered[2].as_slice(), second.as_slice());
+        assert_eq!(journal.purge_marker(), (1, 2));
+        journal.truncate_from(3).await.unwrap();
+        assert!(first_reference.path(&directory).exists());
+        assert!(!second_reference.path(&directory).exists());
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(
+            journal.prepares().await.unwrap()[1].as_slice(),
+            first.as_slice()
+        );
+    }
+
+    #[compio::test]
+    async fn recovery_sweeps_unpublished_references_and_keeps_the_durable_prefix() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        let second = sized_prepare(
+            2,
+            first.header().checksum,
+            size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES,
+        );
+        let reference = write_segment(partition.path(), 0, 0, &second).await;
+        journal
+            .append_batch_referenced_buffered(&[second.into_frozen()], &[Some(reference)])
+            .await
+            .unwrap();
+        assert!(reference.path(&directory).exists());
+        drop(journal);
+
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 1);
+        assert_eq!(
+            journal.prepares().await.unwrap()[0].as_slice(),
+            first.as_slice()
+        );
+        assert!(!reference.path(&directory).exists());
+    }
+
+    #[compio::test]
+    async fn recovery_refuses_missing_torn_or_corrupt_referenced_bodies_without_rewriting_evidence()
+    {
+        for damage in ["missing", "torn", "corrupt"] {
+            let partition = tempdir().unwrap();
+            let directory = partition.path().join("prepares-7");
+            let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+                .await
+                .unwrap();
+            let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES);
+            let reference = write_segment(partition.path(), 0, 0, &first).await;
+            journal
+                .append_batch_referenced_buffered(&[first.into_frozen()], &[Some(reference)])
+                .await
+                .unwrap();
+            journal.sync().await.unwrap();
+            drop(journal);
+            let wal = std::fs::read(data_path(&directory, 0)).unwrap();
+            let frontier = std::fs::read(directory.join("frontier")).unwrap();
+            let retained = reference.path(&directory);
+            if damage == "missing" {
+                DiskStorage.remove_file(&retained).await.unwrap();
+            } else {
+                let mut file = DiskStorage
+                    .open(&retained, OpenMode::ReadWrite)
+                    .await
+                    .unwrap();
+                if damage == "torn" {
+                    DurableFile::truncate(&file, reference.length - 1)
+                        .await
+                        .unwrap();
+                } else {
+                    DurableFile::write(&mut file, reference.length - 1, vec![0])
+                        .await
+                        .unwrap();
+                }
+                DurableFile::sync(&file).await.unwrap();
+            }
+            assert!(
+                PartitionPrepareJournal::open(&directory, 42, 7)
+                    .await
+                    .is_err(),
+                "{damage}"
+            );
+            assert_eq!(
+                std::fs::read(data_path(&directory, 0)).unwrap(),
+                wal,
+                "{damage}"
+            );
+            assert_eq!(
+                std::fs::read(directory.join("frontier")).unwrap(),
+                frontier,
+                "{damage}"
+            );
+        }
+    }
+
+    #[compio::test]
+    async fn invalid_references_are_rejected_before_modifying_history() {
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let first = sized_prepare(1, 0, size_of::<PrepareHeader>() + REFERENCE_TEST_BODY_BYTES)
+            .into_frozen();
+        let reference = SegmentReference {
+            generation: 0,
+            start_offset: 0,
+            position: 0,
+            length: REFERENCE_TEST_BODY_BYTES as u64,
+        };
+        for invalid_reference in [
+            SegmentReference {
+                length: reference.length - 1,
+                ..reference
+            },
+            SegmentReference {
+                position: u64::MAX,
+                ..reference
+            },
+        ] {
+            assert!(
+                journal
+                    .append_batch_referenced_buffered(
+                        std::slice::from_ref(&first),
+                        &[Some(invalid_reference)]
+                    )
+                    .await
+                    .is_err()
+            );
+        }
+        assert!(
+            journal
+                .append_batch_referenced_buffered(&[first], &[])
+                .await
+                .is_err()
+        );
+        assert_eq!(journal.head(), 0);
+        assert_eq!(journal.size_bytes(), 0);
+        assert!(!reference.path(&directory).exists());
+        assert!(!journal.poisoned);
+    }
+
+    async fn write_segment(
+        partition: &Path,
+        generation: u64,
+        start_offset: u64,
+        prepare: &Message<PrepareHeader>,
+    ) -> SegmentReference {
+        let body = &prepare.as_slice()[size_of::<PrepareHeader>()..];
+        let path = partition.join(format!("{start_offset:020}.log"));
+        let mut file = DiskStorage.open(&path, OpenMode::Create).await.unwrap();
+        DurableFile::write(&mut file, 0, body.to_vec())
+            .await
+            .unwrap();
+        DurableFile::sync(&file).await.unwrap();
+        DiskStorage.sync_directory(partition).await.unwrap();
+        SegmentReference {
+            generation,
+            start_offset,
+            position: 0,
+            length: body.len() as u64,
+        }
+    }
+
+    #[compio::test]
+    async fn durable_frontier_recovers_only_covered_prepares() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        journal
+            .append_buffered(second.clone().into_frozen())
+            .await
+            .unwrap();
+        assert!(journal.contains(first.header()));
+        assert!(!journal.contains(second.header()));
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.head(), 1);
+        assert_eq!(
+            journal.prepares().await.unwrap()[0].as_slice(),
+            first.as_slice()
+        );
+        assert_eq!(
+            journal.file.metadata().await.unwrap().len(),
+            journal.size_bytes()
+        );
+    }
+
+    #[compio::test]
+    async fn durable_append_covers_buffered_predecessors() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal
+            .append_buffered(first.clone().into_frozen())
+            .await
+            .unwrap();
+        journal.append(second.clone().into_frozen()).await.unwrap();
+        assert!(journal.contains(first.header()));
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let entries = journal.prepares().await.unwrap();
+        assert_eq!(entries.len(), 2);
+        assert_eq!(entries[1].as_slice(), second.as_slice());
+    }
+
+    #[compio::test]
+    async fn zeroed_interior_record_is_not_an_unwritten_tail() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal.append(first.into_frozen()).await.unwrap();
+        journal.append(second.into_frozen()).await.unwrap();
+        let length = journal.size_bytes();
+        let (result, _) = journal
+            .file
+            .write_all_at(vec![0; PARTITION_WAL_BLOCK_SIZE], 0)
+            .await
+            .into();
+        result.unwrap();
+        journal.file.sync_data().await.unwrap();
+        drop(journal);
+        assert!(
+            PartitionPrepareJournal::open(directory.path(), 42, 7)
+                .await
+                .is_err()
+        );
+        assert_eq!(
+            File::open(data_path(directory.path(), 0))
+                .await
+                .unwrap()
+                .metadata()
+                .await
+                .unwrap()
+                .len(),
+            length
+        );
+    }
+
+    #[compio::test]
+    async fn truncate_and_checkpoint_preserve_the_recoverable_history() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        let third = prepare(3, second.header().checksum);
+        for entry in [&first, &second, &third] {
+            journal.append(entry.clone().into_frozen()).await.unwrap();
+        }
+        journal.truncate_from(3).await.unwrap();
+        journal.checkpoint(1).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.checkpoint_op(), 1);
+        assert_eq!(journal.head(), 2);
+        assert_eq!(journal.prepares().await.unwrap().len(), 2);
+        journal.append(third.into_frozen()).await.unwrap();
+        assert_eq!(journal.head(), 3);
+        assert!(journal.truncate_from(1).await.is_err());
+    }
+
+    #[compio::test]
+    async fn missing_durable_tail_and_wrong_incarnation_are_rejected() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        journal.append(prepare(1, 0).into_frozen()).await.unwrap();
+        assert!(
+            PartitionPrepareJournal::open(directory.path(), 42, 8)
+                .await
+                .is_err()
+        );
+        journal.file.set_len(0).await.unwrap();
+        journal.file.sync_data().await.unwrap();
+        drop(journal);
+        assert!(
+            PartitionPrepareJournal::open(directory.path(), 42, 7)
+                .await
+                .is_err()
+        );
+    }
+
+    #[compio::test]
+    async fn same_generation_purge_retry_persists_the_larger_floor() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let second = prepare(2, first.header().checksum);
+        journal.append(first.into_frozen()).await.unwrap();
+        journal.mark_purge(9, 1).await.unwrap();
+        journal.append(second.into_frozen()).await.unwrap();
+        journal.mark_purge(9, 2).await.unwrap();
+        journal.mark_purge(9, 1).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.purge_marker(), (9, 2));
+    }
+
+    #[compio::test]
+    async fn view_certificate_requires_complete_matching_history() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let first = prepare(1, 0);
+        let checksum = first.header().checksum;
+        assert!(journal.certify_log_view(2, 1, checksum).await.is_err());
+        journal.append(first.into_frozen()).await.unwrap();
+        journal.certify_log_view(2, 1, checksum).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.certified_log_view(), Some(2));
+        journal.truncate_from(1).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.certified_log_view(), None);
+    }
+
+    #[compio::test]
+    async fn transferred_checkpoint_retains_its_prepare_after_restart() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let checkpoint = prepare(7, 1234);
+        let checksum = checkpoint.header().checksum;
+        let expected = checkpoint.as_slice().to_vec();
+        journal
+            .reset_with_prepare(checkpoint.into_frozen())
+            .await
+            .unwrap();
+        journal.certify_log_view(2, 7, checksum).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.checkpoint_op(), 7);
+        assert_eq!(journal.certified_log_view(), Some(2));
+        let prepares = journal.take_recovered_prepares();
+        assert_eq!(prepares.len(), 1);
+        assert_eq!(prepares[0].as_slice(), expected);
+        journal
+            .append(prepare(8, checksum).into_frozen())
+            .await
+            .unwrap();
+    }
+
+    #[compio::test]
+    async fn purge_marker_does_not_promote_the_uncommitted_tail_to_checkpoint() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        journal.append(prepare(1, 0).into_frozen()).await.unwrap();
+        journal.mark_purge(9, 1).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.purge_marker(), (9, 1));
+        assert_eq!(journal.checkpoint_op(), 0);
+        assert_eq!(journal.prepares().await.unwrap().len(), 1);
+    }
+
+    #[compio::test]
+    async fn transferred_checkpoint_binds_the_next_accepted_parent() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        journal.reset(7, None).await.unwrap();
+        let next = prepare(8, 1234);
+        journal.append(next.clone().into_frozen()).await.unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.checkpoint_op(), 7);
+        assert_eq!(journal.head(), 8);
+        assert!(journal.contains(next.header()));
+    }
+
+    #[compio::test]
+    async fn reducing_capacity_recovers_existing_history_and_backpressures_new_appends() {
+        let directory = tempdir().unwrap();
+        let mut journal = PartitionPrepareJournal::open(directory.path(), 42, 7)
+            .await
+            .unwrap();
+        let mut buffer = Owned::<4096>::zeroed(PREPARE_BYTES_MAX);
+        let template = prepare(1, 0);
+        buffer.as_mut_slice()[..size_of::<PrepareHeader>()]
+            .copy_from_slice(&template.as_slice()[..size_of::<PrepareHeader>()]);
+        let checksum_body = XxHash3_64::oneshot(&buffer.as_slice()[size_of::<PrepareHeader>()..]);
+        let header = bytemuck::checked::from_bytes_mut::<PrepareHeader>(
+            &mut buffer.as_mut_slice()[..size_of::<PrepareHeader>()],
+        );
+        header.size = u32::try_from(PREPARE_BYTES_MAX).unwrap();
+        header.checksum_body = u128::from(checksum_body);
+        header.checksum = header.identity_checksum();
+        let first = Message::<PrepareHeader>::try_from(buffer).unwrap();
+        let second = sized_prepare(2, first.header().checksum, PREPARE_BYTES_MAX);
+        let third = prepare(3, second.header().checksum);
+        journal.append_buffered(first.into_frozen()).await.unwrap();
+        let fourth = prepare(4, third.header().checksum);
+        journal.append_buffered(second.into_frozen()).await.unwrap();
+        journal.append(third.into_frozen()).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory.path(),
+            42,
+            7,
+            DiskStorage,
+            PARTITION_WAL_CAPACITY_MIN,
+            false,
+        )
+        .await
+        .unwrap();
+        assert_eq!(journal.head(), 3);
+        assert!(journal.size_bytes() > PARTITION_WAL_CAPACITY_MIN);
+        assert!(journal.append(fourth.clone().into_frozen()).await.is_err());
+        journal.checkpoint(3).await.unwrap();
+        journal.append(fourth.into_frozen()).await.unwrap();
+        assert_eq!(journal.head(), 4);
+    }
+
+    #[test]
+    fn record_padding_and_state_checksums_cover_the_format() {
+        assert_eq!(record_length(256).unwrap(), 4096);
+        assert_eq!(record_length(4096).unwrap(), 8192);
+        assert!(record_length(PREPARE_BYTES_MAX + 1).is_err());
+        let state = JournalState {
+            group: 42,
+            incarnation: 7,
+            ..JournalState::default()
+        };
+        let mut bytes = state.encode();
+        assert_eq!(JournalState::decode(&bytes).unwrap(), state);
+        bytes[24] ^= 1;
+        assert!(JournalState::decode(&bytes).is_err());
+    }
+
+    #[compio::test]
+    async fn owned_segments_rollback_physical_tails_without_advancing_the_checkpoint() {
+        const BODY_BYTES: usize = 8192;
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        journal
+            .enable_segment_storage(SegmentPosition::default(), (2 * BODY_BYTES) as u64)
+            .await
+            .unwrap();
+        let first = segment_prepare(1, 0, 0, BODY_BYTES);
+        let second = segment_prepare(2, first.header().checksum, 1, BODY_BYTES);
+        let third = segment_prepare(3, second.header().checksum, 2, BODY_BYTES);
+        journal
+            .append_batch_buffered(&[
+                first.clone().into_frozen(),
+                second.clone().into_frozen(),
+                third.clone().into_frozen(),
+            ])
+            .await
+            .unwrap();
+        journal.sync().await.unwrap();
+        assert_eq!(journal.size_bytes(), (3 * PARTITION_WAL_BLOCK_SIZE) as u64);
+        assert_eq!(
+            journal.segment_checkpoint(),
+            Some(SegmentPosition::default())
+        );
+        journal.checkpoint(1).await.unwrap();
+        let checkpoint = SegmentPosition {
+            start_offset: 0,
+            length: BODY_BYTES as u64,
+            next_offset: 1,
+        };
+        assert_eq!(journal.segment_checkpoint(), Some(checkpoint));
+        journal.truncate_from(2).await.unwrap();
+        assert_eq!(
+            std::fs::metadata(partition.path().join("00000000000000000000.log"))
+                .unwrap()
+                .len(),
+            BODY_BYTES as u64
+        );
+        assert!(!partition.path().join("00000000000000000002.log").exists());
+        let replacement = segment_prepare(2, first.header().checksum, 1, BODY_BYTES / 2);
+        journal
+            .append(replacement.clone().into_frozen())
+            .await
+            .unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(journal.segment_checkpoint(), Some(checkpoint));
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+    }
+
+    #[compio::test]
+    async fn owned_segments_recover_unpublished_bytes_and_keep_purged_prepare_bodies() {
+        const BODY_BYTES: usize = 8192;
+        let partition = tempdir().unwrap();
+        let directory = partition.path().join("prepares-7");
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        journal
+            .enable_segment_storage(SegmentPosition::default(), (4 * BODY_BYTES) as u64)
+            .await
+            .unwrap();
+        let first = segment_prepare(1, 0, 0, BODY_BYTES);
+        let second = segment_prepare(2, first.header().checksum, 1, BODY_BYTES);
+        journal.append(first.clone().into_frozen()).await.unwrap();
+        journal.append_buffered(second.into_frozen()).await.unwrap();
+        drop(journal);
+        let mut journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        assert_eq!(
+            std::fs::metadata(partition.path().join("00000000000000000000.log"))
+                .unwrap()
+                .len(),
+            BODY_BYTES as u64
+        );
+        journal.mark_purge(1, 1).await.unwrap();
+        let replacement = segment_prepare(2, first.header().checksum, 0, BODY_BYTES / 2);
+        journal
+            .append(replacement.clone().into_frozen())
+            .await
+            .unwrap();
+        drop(journal);
+        let journal = PartitionPrepareJournal::open(&directory, 42, 7)
+            .await
+            .unwrap();
+        let recovered = journal.prepares().await.unwrap();
+        assert_eq!(recovered[0].as_slice(), first.as_slice());
+        assert_eq!(recovered[1].as_slice(), replacement.as_slice());
+        assert_eq!(
+            std::fs::read(partition.path().join("00000000000000000000.log")).unwrap(),
+            replacement.as_slice()[size_of::<PrepareHeader>()..]
+        );
+    }
+
+    #[cfg(target_os = "linux")]
+    #[compio::test]
+    async fn given_preallocated_segments_when_recovering_and_replacing_should_keep_reservations() {
+        const SEGMENT_BYTES: u64 = 1024 * 1024;
+        const BODY_BYTES: usize = 4096;
+
+        for preallocate in [false, true] {
+            let partition = tempdir().unwrap();
+            let directory = partition.path().join("prepares-7");
+            let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+                &directory,
+                42,
+                7,
+                DiskStorage,
+                PARTITION_WAL_BYTES_MAX,
+                preallocate,
+            )
+            .await
+            .unwrap();
+            journal
+                .enable_segment_storage(SegmentPosition::default(), SEGMENT_BYTES)
+                .await
+                .unwrap();
+            let first = segment_prepare(1, 0, 0, usize::try_from(SEGMENT_BYTES).unwrap());
+            let second = segment_prepare(2, first.header().checksum, 1, BODY_BYTES);
+            journal.append(first.clone().into_frozen()).await.unwrap();
+            journal.append(second.clone().into_frozen()).await.unwrap();
+            journal.checkpoint(1).await.unwrap();
+            drop(journal);
+
+            let active = partition.path().join("00000000000000000001.log");
+            std::fs::OpenOptions::new()
+                .write(true)
+                .open(&active)
+                .unwrap()
+                .set_len(SEGMENT_BYTES + BODY_BYTES as u64)
+                .unwrap();
+            let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+                &directory,
+                42,
+                7,
+                DiskStorage,
+                PARTITION_WAL_BYTES_MAX,
+                preallocate,
+            )
+            .await
+            .unwrap();
+            let metadata = std::fs::metadata(&active).unwrap();
+            assert_eq!(metadata.len(), BODY_BYTES as u64);
+            assert_eq!(
+                metadata.blocks() * FILE_BLOCK_BYTES >= SEGMENT_BYTES,

Review Comment:
   nit: this assertion bakes a filesystem promise into an equality — `metadata.blocks() * FILE_BLOCK_BYTES >= SEGMENT_BYTES == preallocate` requires `st_blocks` to reflect `FALLOC_FL_KEEP_SIZE`. Green on tmpfs; on ZFS, NFS or 9p the call either returns `EOPNOTSUPP` or reserves nothing, so the test goes red for reasons unrelated to the code (see also `:2286`).
   Fix: probe reservation support once and skip the block assertion where the filesystem does not reserve.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5620434859

   While looking through #4092 in preparation for rebasing #4119, I noticed that it includes both the durability changes and a broader configuration restructuring. Would it make sense to review those in separate PRs?
   
   Smaller, focused changes would make it easier for me to understand the behavior and contribute useful review feedback. It would also help to understand which parts of #4092 my fix depends on. I may be missing some context around why these changes need to land together.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "diegomrsantos (via GitHub)" <gi...@apache.org>.
diegomrsantos commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983437781


##########
core/server/src/http/handlers.rs:
##########
@@ -1405,17 +1427,18 @@ pub(in crate::http) async fn send_messages(
         .map_err(PartitionWriteError::Rejected)?;
     match query.ack {
         ProduceAck::Replicated => {
+            let policy = topic_durability(&state, &stream_id, &topic_id);
             let (reply, header) = SendWrapper::new(partition_write_replicated(
                 &state,
                 &identity.session,
                 Operation::SendMessages,
                 &body,
             ))
             .await?;
-            let durability = [(
-                DURABILITY_HEADER,
-                HeaderValue::from_static(DURABILITY_REPLICATED_MEMORY),
-            )];
+            let policy = policy.map_or(iggy_common::Durability::Replicated, |policy| {
+                policy.confirmed_policy(&state)

Review Comment:
   I found a separate case from the [earlier policy discussion](https://github.com/apache/iggy/pull/4092#discussion_r3983323849): neither topic's durability changes, but a rename changes which topic the request reaches.
   
   With a caller authorized for both topics:
   
   1. Topic A is named `orders` with `durability=persisted`; topic B is named `fast` with `durability=replicated`.
   2. An awaited produce to `orders` captures A's policy, then waits on the session's data gate.
   3. During that wait, A is renamed to `archived` and B to `orders`.
   4. Dispatch resolves `orders` to B. After B commits, policy confirmation checks A's saved identity and creation revision. A still exists, so the response advertises `persisted` for B's replicated write.
   
   The [reproducer](https://github.com/diegomrsantos/iggy/blob/9e144b843a643bee5dc59c76238bad44114064c7/core/server/src/http/reads.rs#L507) creates the stream and topics and performs both renames through the production metadata handlers. It still fails at the final assertion: the name resolves to B, but confirmation returns `Persisted` from A.
   
   This tests the metadata and policy helpers; it does not execute a full HTTP request. The waiting sequence follows from the handler capturing policy before the data gate and dispatch resolving the name afterward.
   
   Could we retain the policy together with the same resolved topic and incarnation used for dispatch, through to the response?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983324493


##########
core/partitions/src/state_transfer.rs:
##########
@@ -1532,6 +1553,80 @@ fn segment_dir_entries(partition_dir: &str) -> std::io::Result<Vec<PathBuf>> {
         .collect())
 }
 
+/// Remove physical tails outside the logical segment list after draining the WAL.
+/// The caller holds the write lock and has published a purge or install backup.
+pub(crate) async fn remove_public_segment_files(partition_dir: &str) -> std::io::Result<()> {

Review Comment:
   keeping the physical scan; the logical list misses uncommitted tails.



##########
core/partitions/src/persistence.rs:
##########
@@ -0,0 +1,1329 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::TryStreamExt;
+use iggy_binary_protocol::PrepareHeader;
+use journal::PartitionPrepareJournal;
+use journal::durable_storage::{DiskStorage, DurableFile, DurableStorage};
+use journal::partition_journal::{PARTITION_WAL_BYTES_MAX, SegmentPosition, SegmentReference};
+use server_common::Message;
+use server_common::iobuf::Frozen;
+use smallvec::SmallVec;
+use std::cell::{Cell, RefCell};
+use std::collections::{BTreeSet, HashMap, VecDeque};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+const APPEND_BATCH_BYTES_MAX: u64 = 1024 * 1024;
+const APPEND_BATCH_OPS_MAX: usize = 64;
+const CHECKPOINT_DIRTY_FILES_MAX: usize = 1024;
+const PERSISTENCE_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
+
+static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersistenceCompletion {
+    pub group: u64,
+    pub instance: u64,
+    pub epoch: u64,
+}
+
+#[derive(Default)]
+pub struct PersistenceMetrics {
+    pub disk_bytes: u64,
+    pub queued_bytes: u64,
+    pub in_flight_bytes: u64,
+    pub checkpoints_pending: u64,
+    pub completed_batches: u64,
+    pub batched_prepares: u64,
+    pub completed_checkpoints: u64,
+    pub failed_writes: u64,
+}
+
+pub type PersistenceNotifier = Rc<dyn Fn(PersistenceCompletion)>;
+
+pub struct PartitionPersistence<S: DurableStorage = DiskStorage> {
+    group: u64,
+    instance: u64,
+    lease: Option<Arc<WriterLease>>,
+    epoch: Cell<u64>,
+    journal: RefCell<Option<PartitionPrepareJournal<S>>>,
+    queue: RefCell<VecDeque<Mutation<S>>>,
+    offset_files: RefCell<HashMap<String, S::File>>,
+    retired_offset_files: RefCell<Vec<S::File>>,
+    accepted: RefCell<AcceptedPrepares>,
+    accepted_head: Cell<u64>,
+    durable_head: Cell<u64>,
+    checkpoint: Cell<u64>,
+    checkpoint_checksum: Cell<Option<u128>>,
+    certified_log_view: Cell<Option<u32>>,
+    requested_log_view: Cell<Option<(u32, u64, u128)>>,
+    checkpoint_requested: Cell<u64>,
+    checkpoint_running: Cell<bool>,
+    checkpoint_needed: Cell<bool>,
+    dirty_segments: RefCell<BTreeSet<u64>>,
+    dirty_offsets: [RefCell<BTreeSet<u32>>; 2],
+    purge_generation: Cell<u64>,
+    purge_floor: Cell<u64>,
+    capacity: u64,
+    disk_bytes: Cell<u64>,
+    retained_bytes: Cell<u64>,
+    segment_checkpoint: Cell<Option<SegmentPosition>>,
+    queued_bytes: Cell<u64>,
+    in_flight_bytes: Cell<u64>,
+    waiters: RefCell<Vec<std::task::Waker>>,
+    running: Cell<bool>,
+    writer_active: Cell<bool>,
+    retired: Cell<bool>,
+    failure: RefCell<Option<Arc<io::Error>>>,
+    notifier: RefCell<Option<PersistenceNotifier>>,
+    completed_batches: Cell<u64>,
+    batched_prepares: Cell<u64>,
+    completed_checkpoints: Cell<u64>,
+    failed_writes: Cell<u64>,
+}
+
+struct WriterLease {
+    key: PathBuf,
+    id: u64,
+    retired: AtomicBool,
+    running: AtomicBool,
+    waiters: Mutex<Vec<std::task::Waker>>,
+}
+
+struct WriterRegistration {
+    id: u64,
+    writer: Weak<WriterLease>,
+    interrupted: bool,
+}
+
+static WRITERS: LazyLock<Mutex<HashMap<PathBuf, WriterRegistration>>> =
+    LazyLock::new(|| Mutex::new(HashMap::new()));
+
+impl WriterLease {
+    async fn acquire(key: PathBuf) -> io::Result<Arc<Self>> {
+        loop {
+            let previous = {
+                let mut writers = WRITERS
+                    .lock()
+                    .unwrap_or_else(std::sync::PoisonError::into_inner);
+                if writers
+                    .get(&key)
+                    .is_some_and(|registration| registration.interrupted)
+                {
+                    return Err(io::Error::other(
+                        "interrupted partition WAL writer requires process restart",
+                    ));
+                }
+                if let Some(previous) = writers
+                    .get(&key)
+                    .and_then(|registration| registration.writer.upgrade())
+                {
+                    drop(writers);
+                    Some(previous)
+                } else {
+                    let lease = Arc::new(Self {
+                        key: key.clone(),
+                        id: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+                        retired: AtomicBool::new(false),
+                        running: AtomicBool::new(false),
+                        waiters: Mutex::new(Vec::new()),
+                    });
+                    writers.insert(
+                        key.clone(),
+                        WriterRegistration {
+                            id: lease.id,
+                            writer: Arc::downgrade(&lease),
+                            interrupted: false,
+                        },
+                    );
+                    drop(writers);
+                    return Ok(lease);
+                }
+            };
+            let Some(previous) = previous else { continue };
+            if !previous.retired.load(Ordering::Acquire) {
+                return Err(io::Error::new(
+                    io::ErrorKind::AlreadyExists,
+                    "partition WAL already has an active writer",
+                ));
+            }
+            compio::runtime::time::timeout(
+                PERSISTENCE_DRAIN_TIMEOUT,
+                futures::future::poll_fn(|context| {
+                    let mut waiters = previous
+                        .waiters
+                        .lock()
+                        .unwrap_or_else(std::sync::PoisonError::into_inner);
+                    if !previous.running.load(Ordering::Acquire) {
+                        return std::task::Poll::Ready(());
+                    }
+                    if !waiters
+                        .iter()
+                        .any(|waiter| waiter.will_wake(context.waker()))
+                    {
+                        waiters.push(context.waker().clone());
+                    }
+                    std::task::Poll::Pending
+                }),
+            )
+            .await
+            .map_err(|_| {
+                io::Error::new(
+                    io::ErrorKind::TimedOut,
+                    "retired partition WAL writer did not stop",
+                )
+            })?;
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if writers
+                .get(&key)
+                .is_some_and(|registration| registration.id == previous.id)
+            {
+                writers.remove(&key);
+            }
+        }
+    }
+
+    fn finish(&self) {
+        self.running.store(false, Ordering::Release);
+        for waiter in self
+            .waiters
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .drain(..)
+        {
+            waiter.wake();
+        }
+    }
+}
+
+impl Drop for WriterLease {
+    fn drop(&mut self) {
+        let mut writers = WRITERS
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if writers
+            .get(&self.key)
+            .is_some_and(|registration| registration.id == self.id && !registration.interrupted)
+        {
+            writers.remove(&self.key);
+        }
+    }
+}
+
+struct WriterTicket<S: DurableStorage> {
+    owner: Rc<PartitionPersistence<S>>,
+    started: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterTicket<S> {
+    fn drop(&mut self) {
+        if self.started {
+            return;
+        }
+        self.owner.fail(io::Error::new(
+            io::ErrorKind::Interrupted,
+            "partition WAL writer was dropped before polling",
+        ));
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct WriterGuard<'a, S: DurableStorage> {
+    owner: &'a PartitionPersistence<S>,
+    journal: Option<PartitionPrepareJournal<S>>,
+    complete: bool,
+}
+
+impl<S: DurableStorage> Drop for WriterGuard<'_, S> {
+    fn drop(&mut self) {
+        *self.owner.journal.borrow_mut() = self.journal.take();
+        self.owner.in_flight_bytes.set(0);
+        self.owner.checkpoint_running.set(false);
+        if !self.complete
+            && let Some(lease) = &self.owner.lease
+        {
+            let mut writers = WRITERS
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner);
+            if let Some(registration) = writers.get_mut(&lease.key)
+                && registration.id == lease.id
+            {
+                registration.interrupted = true;
+            }
+        }
+        if !self.complete && self.owner.failure.borrow().is_none() {
+            *self.owner.failure.borrow_mut() = Some(Arc::new(io::Error::new(
+                io::ErrorKind::Interrupted,
+                "partition WAL writer stopped during a mutation",
+            )));
+        }
+        self.owner.writer_active.set(false);
+        self.owner.running.set(false);
+        if let Some(lease) = &self.owner.lease {
+            lease.finish();
+        }
+        for waiter in self.owner.waiters.borrow_mut().drain(..) {
+            waiter.wake();
+        }
+    }
+}
+
+struct AcceptedPrepares {
+    base: u64,
+    checksums: VecDeque<u128>,
+}
+
+impl AcceptedPrepares {
+    fn checksum(&self, op: u64) -> Option<u128> {
+        let index = usize::try_from(op.checked_sub(self.base)?.checked_sub(1)?).ok()?;
+        self.checksums.get(index).copied()
+    }
+
+    fn truncate_from(&mut self, op: u64) {
+        let keep =
+            usize::try_from(op.saturating_sub(self.base).saturating_sub(1)).unwrap_or(usize::MAX);
+        self.checksums.truncate(keep);
+    }
+
+    fn checkpoint(&mut self, op: u64) {
+        let count = usize::try_from(op.saturating_sub(self.base))
+            .unwrap_or(usize::MAX)
+            .min(self.checksums.len());
+        self.checksums.drain(..count);
+        self.base = op;
+    }
+}
+
+enum Mutation<S: DurableStorage> {
+    EnableSegments {
+        epoch: u64,
+        initial: SegmentPosition,
+        max_size: u64,
+    },
+    CertifyView {
+        epoch: u64,
+        view: u32,
+        op: u64,
+        checksum: u128,
+    },
+    Purge {
+        epoch: u64,
+        generation: u64,
+        floor: u64,
+    },
+    Append {
+        epoch: u64,
+        prepare: Frozen<4096>,
+        durable: bool,
+        bytes: u64,
+    },
+    Truncate {
+        epoch: u64,
+        from_op: u64,
+    },
+    Checkpoint {
+        epoch: u64,
+        through_op: u64,
+        files: Vec<PathBuf>,
+        directories: Vec<PathBuf>,
+        offset_files: Vec<S::File>,
+    },
+    Reset {
+        epoch: u64,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        segments: Option<(SegmentPosition, u64)>,
+    },
+}
+
+impl PartitionPersistence {
+    /// # Errors
+    /// Returns an error if the partition WAL cannot be recovered.
+    pub async fn open(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_storage(directory, group, incarnation, DiskStorage).await
+    }
+}
+
+impl<S: DurableStorage> PartitionPersistence<S> {
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub async fn open_with_storage(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        Self::open_with_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            PARTITION_WAL_BYTES_MAX,
+            false,
+        )
+        .await
+    }
+
+    /// # Errors
+    /// Returns an error for invalid capacity or unverifiable durable history.
+    pub async fn open_with_capacity(
+        directory: &Path,
+        group: u64,
+        incarnation: u64,
+        storage: S,
+        capacity: u64,
+        preallocate_segments: bool,
+    ) -> io::Result<(Rc<Self>, Vec<Message<PrepareHeader>>)> {
+        let lease = if let Some(key) = storage.writer_identity(directory)? {
+            Some(WriterLease::acquire(key).await?)
+        } else {
+            None
+        };
+        let mut journal = PartitionPrepareJournal::open_with_storage_and_capacity(
+            directory,
+            group,
+            incarnation,
+            storage,
+            capacity,
+            preallocate_segments,
+        )
+        .await?;
+        let prepares = journal.take_recovered_prepares();
+        let mut accepted = AcceptedPrepares {
+            base: journal.checkpoint_op(),
+            checksums: VecDeque::with_capacity(prepares.len()),
+        };
+        for prepare in &prepares {
+            let header = prepare.header();
+            if header.op > journal.checkpoint_op() {
+                accepted.checksums.push_back(header.checksum);
+            }
+        }
+        let persistence = Rc::new(Self {
+            group,
+            instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed),
+            lease,
+            epoch: Cell::new(0),
+            accepted_head: Cell::new(journal.head()),
+            durable_head: Cell::new(journal.head()),
+            checkpoint: Cell::new(journal.checkpoint_op()),
+            checkpoint_checksum: Cell::new(journal.checkpoint_checksum()),
+            certified_log_view: Cell::new(journal.certified_log_view()),
+            requested_log_view: Cell::new(None),
+            checkpoint_requested: Cell::new(journal.checkpoint_op()),
+            checkpoint_running: Cell::new(false),
+            checkpoint_needed: Cell::new(false),
+            dirty_segments: RefCell::new(BTreeSet::new()),
+            dirty_offsets: std::array::from_fn(|_| RefCell::new(BTreeSet::new())),
+            purge_generation: Cell::new(journal.purge_marker().0),
+            purge_floor: Cell::new(journal.purge_marker().1),
+            capacity,
+            disk_bytes: Cell::new(journal.size_bytes()),
+            retained_bytes: Cell::new(journal.retained_bytes()),
+            segment_checkpoint: Cell::new(journal.segment_checkpoint()),
+            journal: RefCell::new(Some(journal)),
+            queue: RefCell::new(VecDeque::new()),
+            offset_files: RefCell::new(HashMap::new()),
+            retired_offset_files: RefCell::new(Vec::new()),
+            accepted: RefCell::new(accepted),
+            queued_bytes: Cell::new(0),
+            in_flight_bytes: Cell::new(0),
+            waiters: RefCell::new(Vec::new()),
+            running: Cell::new(false),
+            writer_active: Cell::new(false),
+            retired: Cell::new(false),
+            failure: RefCell::new(None),
+            notifier: RefCell::new(None),
+            completed_batches: Cell::new(0),
+            batched_prepares: Cell::new(0),
+            completed_checkpoints: Cell::new(0),
+            failed_writes: Cell::new(0),
+        });
+        Ok((persistence, prepares))
+    }
+
+    #[cfg(test)]
+    pub(crate) fn exhaust_capacity_for_test(&self) {
+        self.disk_bytes.set(self.capacity);
+        self.retained_bytes.set(self.capacity);
+    }
+
+    #[cfg(test)]
+    pub(crate) fn release_capacity_for_test(&self) {
+        self.disk_bytes.set(0);
+        self.retained_bytes.set(0);
+    }
+
+    pub const fn certified_log_view(&self) -> Option<u32> {
+        self.certified_log_view.get()
+    }
+
+    pub fn certify_log_view(&self, view: u32, op: u64, checksum: u128) -> bool {
+        if self.certified_log_view.get() == Some(view) {
+            return true;
+        }
+        if self.retired.get()
+            || self.failure.borrow().is_some()
+            || op > self.head()
+            || !(op == 0 && checksum == 0 || self.checksum(op) == Some(checksum))
+        {
+            return false;
+        }
+        let target = (view, op, checksum);
+        if self
+            .requested_log_view
+            .get()
+            .is_none_or(|(pending, _, _)| pending != view)
+        {
+            self.requested_log_view.set(Some(target));
+            self.queue.borrow_mut().push_back(Mutation::CertifyView {
+                epoch: self.epoch.get(),
+                view,
+                op,
+                checksum,
+            });
+        }
+        false
+    }
+
+    pub fn set_notifier(&self, notifier: PersistenceNotifier) {
+        *self.notifier.borrow_mut() = Some(notifier);
+    }
+
+    pub const fn accepts_completion(&self, completion: PersistenceCompletion) -> bool {
+        completion.instance == self.instance
+            && completion.epoch == self.epoch.get()
+            && !self.retired.get()
+    }
+
+    pub fn is_durable(&self, header: &PrepareHeader) -> bool {
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && header.op <= self.durable_head.get()
+            && self.checksum(header.op) == Some(header.checksum)
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        self.segment_checkpoint.get()
+    }
+
+    pub fn enable_segment_storage(&self, initial: SegmentPosition, max_size: u64) {
+        self.queue.borrow_mut().push_back(Mutation::EnableSegments {
+            epoch: self.epoch.get(),
+            initial,
+            max_size,
+        });
+    }
+
+    /// Verify the physical prefix before making its indexes and logical sizes visible.
+    ///
+    /// # Errors
+    /// Returns an error for a failed barrier or a body outside the durable segment range.
+    pub async fn validate_segment_prefix(
+        &self,
+        prepares: &[Frozen<4096>],
+        start_offset: u64,
+        mut position: u64,
+    ) -> io::Result<u64> {
+        self.drain_with_timeout().await?;
+        let journal = self.journal.borrow();
+        let journal = journal
+            .as_ref()
+            .ok_or_else(|| io::Error::other("segment writer has no journal"))?;
+        let initial = position;
+        for prepare in prepares {
+            let header = prepare_header(prepare)?;
+            let reference: SegmentReference = journal
+                .segment_reference(header)
+                .ok_or_else(|| io::Error::other("committed prepare has no durable segment body"))?;
+            if reference.start_offset != start_offset
+                || reference.position != position
+                || reference.length != (prepare.len() - size_of::<PrepareHeader>()) as u64
+            {
+                return Err(io::Error::other(
+                    "committed prepare differs from its segment position",
+                ));
+            }
+            position = position
+                .checked_add(reference.length)
+                .ok_or_else(|| io::Error::other("segment prefix overflow"))?;
+        }
+        Ok(position - initial)
+    }
+
+    pub const fn durable_op(&self) -> u64 {
+        self.durable_head.get()
+    }
+
+    pub fn is_durable_through(&self, op: u64) -> bool {
+        !self.retired.get() && self.failure.borrow().is_none() && op <= self.durable_head.get()
+    }
+
+    pub fn has_capacity(&self, frame_bytes: usize) -> bool {
+        let Ok(bytes) = journal::partition_journal::record_length(frame_bytes) else {
+            return false;
+        };
+        let bytes = bytes as u64;
+        !self.retired.get()
+            && self.failure.borrow().is_none()
+            && self
+                .retained_bytes
+                .get()
+                .saturating_add(self.queued_bytes.get())
+                .saturating_add(self.in_flight_bytes.get())
+                .saturating_add(bytes)
+                <= self.capacity
+    }
+
+    /// # Errors
+    /// Returns an error if persistence fails, capacity is exhausted, or history is invalid.
+    pub fn append(&self, prepare: Frozen<4096>, durable: bool) -> io::Result<()> {
+        let header = prepare_header(&prepare)?;
+        let bytes = journal::partition_journal::record_length(prepare.len())? as u64;
+        if self.accepted.borrow().checksum(header.op) == Some(header.checksum) {
+            return Ok(());
+        }
+        if !self.has_capacity(prepare.len()) {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "partition WAL capacity exhausted",
+            ));
+        }
+        if header.op != self.accepted_head.get().saturating_add(1) {
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "partition WAL submission is out of order",
+            ));
+        }
+        self.queued_bytes.set(self.queued_bytes.get() + bytes);
+        self.accepted
+            .borrow_mut()
+            .checksums
+            .push_back(header.checksum);
+        self.accepted_head.set(header.op);
+        self.queue.borrow_mut().push_back(Mutation::Append {
+            epoch: self.epoch.get(),
+            prepare,
+            durable,
+            bytes,
+        });
+        Ok(())
+    }
+
+    pub fn mark_segment_dirty(&self, start_offset: u64) {
+        self.dirty_segments.borrow_mut().insert(start_offset);
+    }
+
+    pub fn take_offset_file(&self, path: &str) -> Option<S::File> {
+        self.offset_files.borrow_mut().remove(path)
+    }
+
+    /// # Panics
+    /// Panics if the previous writer was not taken before replacement.
+    pub fn retain_offset_file(&self, path: String, file: S::File) {
+        assert!(self.offset_files.borrow_mut().insert(path, file).is_none());

Review Comment:
   fixed; displaced writers stay alive through the checkpoint.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {

Review Comment:
   external refs are supported; the caller writes their bodies first.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {
+            return Err(invalid(
+                "message offsets do not extend the physical segment tail",
+            ));
+        }
+        if self.tail.position.length >= self.max_size {
+            self.tail = self.allocate(SegmentPosition {
+                start_offset: batch.base_offset,
+                length: 0,
+                next_offset: batch.base_offset,
+            })?;
+        }
+        let reference = SegmentReference {
+            generation: self.tail.generation,
+            start_offset: self.tail.position.start_offset,
+            position: self.tail.position.length,
+            length: batch.batch_length,
+        };
+        self.tail.position.length = reference
+            .position
+            .checked_add(reference.length)
+            .ok_or_else(|| invalid("segment position exhausted"))?;
+        self.tail.position.next_offset = batch_next_offset(prepare)?;
+        Ok((Some(reference), Some(self.tail.position.next_offset)))
+    }
+
+    pub(super) fn reset_position(&mut self, position: SegmentPosition) -> io::Result<()> {
+        if !position.valid() {
+            return Err(invalid("invalid replacement segment boundary"));
+        }
+        self.tail = self.allocate(position)?;
+        self.checkpoint = self.tail;
+        Ok(())
+    }
+
+    fn allocate(&mut self, position: SegmentPosition) -> io::Result<SegmentCursor> {
+        let generation = self.next_generation;
+        self.next_generation = generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        Ok(SegmentCursor {
+            generation,
+            position,
+        })
+    }
+
+    pub(super) fn encode(self, bytes: &mut [u8]) {
+        let values = [
+            self.max_size,
+            self.next_generation,
+            self.tail.generation,
+            self.tail.position.start_offset,
+            self.tail.position.length,
+            self.tail.position.next_offset,
+            self.checkpoint.generation,
+            self.checkpoint.position.start_offset,
+            self.checkpoint.position.length,
+            self.checkpoint.position.next_offset,
+        ];
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip(values)
+        {
+            *field = value.to_le_bytes();
+        }
+    }
+
+    pub(super) fn decode(bytes: &[u8]) -> io::Result<Self> {
+        let mut values = [0; SEGMENT_STATE_BYTES / size_of::<u64>()];
+        for (value, field) in values
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *value = u64::from_le_bytes(*field);
+        }
+        let [
+            max_size,
+            next_generation,
+            tail_generation,
+            tail_start,
+            tail_length,
+            tail_next,
+            checkpoint_generation,
+            checkpoint_start,
+            checkpoint_length,
+            checkpoint_next,
+        ] = values;
+        let state = Self {
+            max_size,
+            next_generation,
+            tail: SegmentCursor {
+                generation: tail_generation,
+                position: SegmentPosition {
+                    start_offset: tail_start,
+                    length: tail_length,
+                    next_offset: tail_next,
+                },
+            },
+            checkpoint: SegmentCursor {
+                generation: checkpoint_generation,
+                position: SegmentPosition {
+                    start_offset: checkpoint_start,
+                    length: checkpoint_length,
+                    next_offset: checkpoint_next,
+                },
+            },
+        };
+        if max_size == 0
+            || tail_generation >= next_generation
+            || checkpoint_generation >= next_generation
+            || !state.tail.position.valid()
+            || !state.checkpoint.position.valid()

Review Comment:
   overflow already fails closed; a lower cap would just refuse sooner.



##########
core/journal/src/partition_journal/segments.rs:
##########
@@ -0,0 +1,663 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io;
+use std::path::{Path, PathBuf};
+
+use iggy_binary_protocol::batch::BatchHeader;
+use iggy_binary_protocol::{Operation, PrepareHeader};
+use server_common::iobuf::Frozen;
+
+use super::{JournalState, PartitionPrepareJournal, SegmentReference, StoredPrepare, invalid};
+use crate::durable_storage::{DurableFile, DurableStorage, OpenMode};
+
+pub(super) const SEGMENT_STATE_FLAG: usize = 99;
+pub(super) const SEGMENT_STATE_OFFSET: usize = 128;
+pub(super) const SEGMENT_STATE_BYTES: usize = 10 * size_of::<u64>();
+
+/// A whole-batch boundary. `next_offset` is the first offset after this prefix.
+/// Physical tails may exceed the checkpoint boundary but cannot be polled yet.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SegmentPosition {
+    pub start_offset: u64,
+    pub length: u64,
+    pub next_offset: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentCursor {
+    pub generation: u64,
+    pub position: SegmentPosition,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct SegmentState {
+    pub max_size: u64,
+    pub next_generation: u64,
+    pub tail: SegmentCursor,
+    pub checkpoint: SegmentCursor,
+}
+
+impl<S: DurableStorage> PartitionPrepareJournal<S> {
+    /// Enable segment body ownership after recovering the legacy committed view.
+    /// The initial boundary must describe durable materialized messages only.
+    ///
+    /// # Errors
+    /// Returns an error for inconsistent boundaries or a failed storage barrier.
+    pub async fn enable_segment_storage(
+        &mut self,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if let Some(segments) = self.state.segment_storage {
+            if segments.max_size != max_size {
+                return Err(invalid("segment size differs from the durable WAL layout"));
+            }
+            return Ok(());
+        }
+        if max_size == 0 || !initial.valid() {
+            return Err(invalid("invalid initial segment boundary"));
+        }
+        let generation = self
+            .entries
+            .values()
+            .filter_map(|entry| entry.reference)
+            .map(|reference| reference.generation)
+            .max()
+            .map_or(Some(0), |generation| generation.checked_add(1))
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        let state = JournalState {
+            segment_references: true,
+            segment_storage: Some(segments),
+            ..self.state
+        };
+        self.poisoned = true;
+        if initial.length > 0 {
+            self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+                .await?;
+            self.sync_segment_files().await?;
+        }
+        self.file.sync().await?;
+        // Upgrade before any uncommitted body reaches an offset-named file.
+        self.publish(state).await?;
+        self.state = state;
+        self.durable_head = state.head;
+        self.poisoned = false;
+        self.migrate_segment_prepares().await
+    }
+
+    pub const fn segment_checkpoint(&self) -> Option<SegmentPosition> {
+        match self.state.segment_storage {
+            Some(segments) => Some(segments.checkpoint.position),
+            None => None,
+        }
+    }
+
+    pub fn segment_reference(&self, header: &PrepareHeader) -> Option<SegmentReference> {
+        if !self.contains(header) {
+            return None;
+        }
+        self.entries
+            .get(&header.op)
+            .and_then(|entry| entry.reference)
+    }
+
+    /// Install a transferred checkpoint after all replacement segment files are durable.
+    ///
+    /// # Errors
+    /// Returns an error if the checkpoint contradicts the installed bytes or a barrier fails.
+    #[allow(clippy::too_many_lines)]
+    pub async fn reset_with_segment_checkpoint(
+        &mut self,
+        op: u64,
+        checksum: Option<u128>,
+        prepare: Option<Frozen<4096>>,
+        initial: SegmentPosition,
+        max_size: u64,
+    ) -> io::Result<()> {
+        self.ensure_healthy()?;
+        if !initial.valid() || max_size == 0 {
+            return Err(invalid("invalid installed segment boundary"));
+        }
+        if let Some(prepare) = &prepare {
+            let header = self.validate_checkpoint_prepare(prepare)?;
+            if header.op != op || Some(header.checksum) != checksum {
+                return Err(invalid("installed checkpoint prepare identity mismatch"));
+            }
+        }
+        let generation = self
+            .state
+            .segment_storage
+            .map_or(0, |segments| segments.next_generation);
+        let cursor = SegmentCursor {
+            generation,
+            position: initial,
+        };
+        let mut segments = SegmentState {
+            max_size,
+            next_generation: generation
+                .checked_add(1)
+                .ok_or_else(|| invalid("segment generation exhausted"))?,
+            tail: cursor,
+            checkpoint: cursor,
+        };
+        self.poisoned = true;
+        self.segment_files.clear();
+        self.open_segment_file(cursor, self.preallocate_segments.then_some(max_size))
+            .await?;
+        if self
+            .segment_files
+            .get(&(generation, initial.start_offset))
+            .ok_or_else(|| invalid("installed segment handle is absent"))?
+            .length()
+            .await?
+            != initial.length
+        {
+            return Err(invalid(
+                "installed segment size differs from its checkpoint",
+            ));
+        }
+        let checkpoint_prepare = if let Some(prepare) = prepare {
+            let header = self.validate_checkpoint_prepare(&prepare)?;
+            let reference = if header.operation == Operation::SendMessages {
+                let batch = decode_batch(prepare.as_slice())?;
+                if initial.length >= batch.batch_length
+                    && batch_next_offset(prepare.as_slice())? == initial.next_offset
+                {
+                    let reference = SegmentReference {
+                        generation,
+                        start_offset: initial.start_offset,
+                        position: initial.length - batch.batch_length,
+                        length: batch.batch_length,
+                    };
+                    let file = self
+                        .segment_files
+                        .get(&(generation, initial.start_offset))
+                        .ok_or_else(|| invalid("installed segment handle is absent"))?;
+                    if file
+                        .read(
+                            reference.position,
+                            prepare.len() - size_of::<PrepareHeader>(),
+                        )
+                        .await?
+                        != prepare.as_slice()[size_of::<PrepareHeader>()..]
+                    {
+                        return Err(invalid(
+                            "checkpoint prepare differs from installed segment bytes",
+                        ));
+                    }
+                    Some(reference)
+                } else if let Some(reference) = self
+                    .entries
+                    .get(&op)
+                    .filter(|entry| entry.checksum == header.checksum)
+                    .and_then(|entry| entry.reference)
+                {
+                    Some(reference)
+                } else {
+                    let retained = segments.allocate(SegmentPosition {
+                        start_offset: batch.base_offset,
+                        length: batch.batch_length,
+                        next_offset: batch_next_offset(prepare.as_slice())?,
+                    })?;
+                    let reference = SegmentReference {
+                        generation: retained.generation,
+                        start_offset: batch.base_offset,
+                        position: 0,
+                        length: batch.batch_length,
+                    };
+                    let mut file = self
+                        .storage
+                        .open(&reference.path(&self.directory), OpenMode::Create)
+                        .await?;
+                    file.write_frozen(0, prepare.slice(size_of::<PrepareHeader>()..))
+                        .await?;
+                    file.sync().await?;
+                    Some(reference)
+                }
+            } else {
+                None
+            };
+            Some((prepare, reference))
+        } else {
+            None
+        };
+        self.sync_segment_files().await?;
+        self.storage.sync_directory(&self.directory).await?;
+        self.state.segment_references = true;
+        self.state.segment_storage = Some(segments);
+        self.state.checkpoint = op;
+        self.state.anchor_known = checksum.is_some();
+        self.state.certified_log_view = None;
+        self.rewrite(op, checksum.unwrap_or(0), Some(0), checkpoint_prepare)
+            .await
+    }
+
+    pub(super) async fn migrate_segment_prepares(&mut self) -> io::Result<()> {
+        if self.state.segment_storage.is_some()
+            && self
+                .entries
+                .range(self.state.purge_floor.saturating_add(1)..)
+                .any(|(_, entry)| entry.reference.is_none())
+        {
+            self.rewrite(
+                self.state.checkpoint,
+                self.state.checkpoint_checksum,
+                None,
+                None,
+            )
+            .await?;
+        }
+        Ok(())
+    }
+
+    pub(super) async fn write_segment_bodies(
+        &mut self,
+        prepares: &[Frozen<4096>],
+        records: &[(u64, StoredPrepare, usize)],
+    ) -> io::Result<()> {
+        if self.state.segment_storage.is_none() {
+            return Ok(());
+        }
+        for (_, record, index) in records {
+            if let Some(reference) = record.reference {
+                self.write_segment_body(reference, &prepares[*index])
+                    .await?;
+            }
+        }
+        self.sync_segment_files().await
+    }
+
+    pub(super) async fn write_segment_body(
+        &mut self,
+        reference: SegmentReference,
+        prepare: &Frozen<4096>,
+    ) -> io::Result<()> {
+        let cursor = SegmentCursor {
+            generation: reference.generation,
+            position: SegmentPosition {
+                start_offset: reference.start_offset,
+                length: reference.position,
+                next_offset: reference.start_offset,
+            },
+        };
+        let preallocate_size = self
+            .state
+            .segment_storage
+            .filter(|_| self.preallocate_segments)
+            .map(|segments| segments.max_size);
+        self.open_segment_file(cursor, preallocate_size).await?;
+        self.segment_files
+            .get_mut(&(reference.generation, reference.start_offset))
+            .ok_or_else(|| invalid("segment writing handle is absent"))?
+            .write_frozen(
+                reference.position,
+                prepare.slice(size_of::<PrepareHeader>()..),
+            )
+            .await
+    }
+
+    pub(super) async fn sync_segment_files(&self) -> io::Result<()> {
+        for file in self.segment_files.values() {
+            // Keep the writing handle: reopening after an errseq writeback error
+            // could turn a failed body barrier into a successful acknowledgment.
+            file.sync().await?;
+        }
+        Ok(())
+    }
+
+    pub(super) fn retain_active_segment_file(&mut self) {
+        if let Some(segments) = self.state.segment_storage {
+            let active = (
+                segments.tail.generation,
+                segments.tail.position.start_offset,
+            );
+            self.segment_files.retain(|key, _| *key == active);
+        }
+    }
+
+    pub(super) fn retained_segment_paths(
+        &self,
+        entries: &BTreeMap<u64, StoredPrepare>,
+        segments: Option<SegmentState>,
+    ) -> BTreeSet<PathBuf> {
+        let mut paths = super::referenced_segments(entries, &self.directory);
+        if let Some(segments) = segments {
+            paths.insert(segments.tail.path(&self.directory));
+            paths.insert(segments.checkpoint.path(&self.directory));
+        }
+        paths
+    }
+
+    pub(super) fn segment_boundary(&self, through_op: u64) -> Option<SegmentCursor> {
+        let segments = self.state.segment_storage?;
+        self.entries
+            .range(..=through_op)
+            .rev()
+            .find_map(|(&op, entry)| {
+                let reference = entry.reference?;
+                let next_offset = entry.next_offset?;
+                (op > self.state.purge_floor
+                    && op > self.state.checkpoint
+                    && next_offset >= segments.checkpoint.position.next_offset)
+                    .then_some(SegmentCursor {
+                        generation: reference.generation,
+                        position: SegmentPosition {
+                            start_offset: reference.start_offset,
+                            length: reference.position + reference.length,
+                            next_offset,
+                        },
+                    })
+            })
+            .or(Some(segments.checkpoint))
+    }
+
+    pub(super) async fn recover_segment_files(&mut self) -> io::Result<()> {
+        let Some(segments) = self.state.segment_storage else {
+            return Ok(());
+        };
+        self.poisoned = true;
+        let parent = self.segment_directory()?.to_path_buf();
+        let cursor = segments.tail;
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        // Retention may remove a fully checkpointed sealed segment. Its private
+        // checkpoint prepare remains available without restoring polled data.
+        let restore = cursor.position.length < segments.max_size
+            || cursor.position.next_offset > segments.checkpoint.position.next_offset
+            || self.storage.exists(&public).await?;
+        if restore {
+            self.open_segment_file(cursor, None).await?;
+            let file = self
+                .segment_files
+                .get(&(cursor.generation, cursor.position.start_offset))
+                .ok_or_else(|| invalid("segment rollback handle is absent"))?;
+            if file.length().await? < cursor.position.length {
+                return Err(invalid("segment lost durably published bytes"));
+            }
+            file.truncate(cursor.position.length).await?;
+            if self.preallocate_segments {
+                file.preallocate(&public, segments.max_size);
+            }
+            file.sync().await?;
+            self.remove_segment_name(&public).await?;
+            self.storage
+                .hard_link(&cursor.path(&self.directory), &public)
+                .await?;
+        }
+        for entry in self.storage.entries(&parent).await? {
+            let Some(name) = entry.name.to_str() else {
+                continue;
+            };
+            let offset = name
+                .strip_suffix(".log")
+                .or_else(|| name.strip_suffix(".index"))
+                .and_then(|offset| offset.parse::<u64>().ok());
+            if !entry.directory
+                && offset.is_some_and(|offset| {
+                    offset > cursor.position.start_offset && offset >= cursor.position.next_offset
+                })
+            {
+                self.storage.remove_file(&parent.join(entry.name)).await?;
+            }
+        }
+        self.storage.sync_directory(&parent).await?;
+        self.retain_active_segment_file();
+        self.poisoned = false;
+        Ok(())
+    }
+
+    async fn open_segment_file(
+        &mut self,
+        cursor: SegmentCursor,
+        preallocate_size: Option<u64>,
+    ) -> io::Result<()> {
+        let key = (cursor.generation, cursor.position.start_offset);
+        if self.segment_files.contains_key(&key) {
+            return Ok(());
+        }
+        let parent = self.segment_directory()?.to_path_buf();
+        let retained = cursor.path(&self.directory);
+        let public = parent.join(format!("{:020}.log", cursor.position.start_offset));
+        let file = if self.storage.exists(&retained).await? {
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else if cursor.position.length > 0
+            || (self.storage.exists(&public).await?
+                && self
+                    .storage
+                    .open(&public, OpenMode::Read)
+                    .await?
+                    .length()
+                    .await?
+                    == 0)
+        {
+            self.storage.hard_link(&public, &retained).await?;
+            self.storage.open(&retained, OpenMode::ReadWrite).await?
+        } else {
+            let file = self.storage.open(&retained, OpenMode::Create).await?;
+            // Offset names can still point at a purged inode retained by older
+            // prepares. Unlink before reuse; never truncate that inode in place.
+            self.remove_segment_name(&public).await?;
+            self.storage.hard_link(&retained, &public).await?;
+            file
+        };
+        if let Some(size) = preallocate_size {
+            file.preallocate(&public, size);
+        }
+        self.storage.sync_directory(&self.directory).await?;
+        self.storage.sync_directory(&parent).await?;
+        self.segment_files.insert(key, file);
+        Ok(())
+    }
+
+    fn segment_directory(&self) -> io::Result<&Path> {
+        self.directory
+            .parent()
+            .ok_or_else(|| invalid("WAL has no segment directory"))
+    }
+
+    async fn remove_segment_name(&self, path: &Path) -> io::Result<()> {
+        match self.storage.remove_file(path).await {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error),
+        }
+    }
+}
+
+impl SegmentPosition {
+    const fn valid(self) -> bool {
+        self.next_offset >= self.start_offset
+            && ((self.length == 0) == (self.next_offset == self.start_offset))
+    }
+}
+
+impl SegmentCursor {
+    fn path(self, directory: &Path) -> PathBuf {
+        SegmentReference {
+            generation: self.generation,
+            start_offset: self.position.start_offset,
+            position: 0,
+            length: self.position.length,
+        }
+        .path(directory)
+    }
+}
+
+impl SegmentState {
+    pub(super) fn reserve(
+        &mut self,
+        header: &PrepareHeader,
+        prepare: &[u8],
+    ) -> io::Result<(Option<SegmentReference>, Option<u64>)> {
+        if header.operation != Operation::SendMessages {
+            return Ok((None, None));
+        }
+        let batch = decode_batch(prepare)?;
+        if batch.base_offset != self.tail.position.next_offset {
+            return Err(invalid(
+                "message offsets do not extend the physical segment tail",
+            ));
+        }
+        if self.tail.position.length >= self.max_size {
+            self.tail = self.allocate(SegmentPosition {
+                start_offset: batch.base_offset,
+                length: 0,
+                next_offset: batch.base_offset,
+            })?;
+        }
+        let reference = SegmentReference {
+            generation: self.tail.generation,
+            start_offset: self.tail.position.start_offset,
+            position: self.tail.position.length,
+            length: batch.batch_length,
+        };
+        self.tail.position.length = reference
+            .position
+            .checked_add(reference.length)
+            .ok_or_else(|| invalid("segment position exhausted"))?;
+        self.tail.position.next_offset = batch_next_offset(prepare)?;
+        Ok((Some(reference), Some(self.tail.position.next_offset)))
+    }
+
+    pub(super) fn reset_position(&mut self, position: SegmentPosition) -> io::Result<()> {
+        if !position.valid() {
+            return Err(invalid("invalid replacement segment boundary"));
+        }
+        self.tail = self.allocate(position)?;
+        self.checkpoint = self.tail;
+        Ok(())
+    }
+
+    fn allocate(&mut self, position: SegmentPosition) -> io::Result<SegmentCursor> {
+        let generation = self.next_generation;
+        self.next_generation = generation
+            .checked_add(1)
+            .ok_or_else(|| invalid("segment generation exhausted"))?;
+        Ok(SegmentCursor {
+            generation,
+            position,
+        })
+    }
+
+    pub(super) fn encode(self, bytes: &mut [u8]) {
+        let values = [
+            self.max_size,
+            self.next_generation,
+            self.tail.generation,
+            self.tail.position.start_offset,
+            self.tail.position.length,
+            self.tail.position.next_offset,
+            self.checkpoint.generation,
+            self.checkpoint.position.start_offset,
+            self.checkpoint.position.length,
+            self.checkpoint.position.next_offset,
+        ];
+        for (field, value) in bytes
+            .as_chunks_mut::<{ size_of::<u64>() }>()
+            .0
+            .iter_mut()
+            .zip(values)
+        {
+            *field = value.to_le_bytes();
+        }
+    }
+
+    pub(super) fn decode(bytes: &[u8]) -> io::Result<Self> {
+        let mut values = [0; SEGMENT_STATE_BYTES / size_of::<u64>()];
+        for (value, field) in values
+            .iter_mut()
+            .zip(bytes.as_chunks::<{ size_of::<u64>() }>().0)
+        {
+            *value = u64::from_le_bytes(*field);
+        }
+        let [
+            max_size,
+            next_generation,
+            tail_generation,
+            tail_start,
+            tail_length,
+            tail_next,
+            checkpoint_generation,
+            checkpoint_start,
+            checkpoint_length,
+            checkpoint_next,
+        ] = values;
+        let state = Self {
+            max_size,
+            next_generation,
+            tail: SegmentCursor {
+                generation: tail_generation,
+                position: SegmentPosition {
+                    start_offset: tail_start,
+                    length: tail_length,
+                    next_offset: tail_next,
+                },
+            },
+            checkpoint: SegmentCursor {
+                generation: checkpoint_generation,
+                position: SegmentPosition {
+                    start_offset: checkpoint_start,
+                    length: checkpoint_length,
+                    next_offset: checkpoint_next,
+                },
+            },
+        };

Review Comment:
   added malformed-layout decode and reopen cases with valid checksums.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4092:
URL: https://github.com/apache/iggy/pull/4092#discussion_r3983321741


##########
core/shard/src/router.rs:
##########
@@ -285,6 +286,15 @@ where
             Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
         M: RestorableMetadataStm,
     {

Review Comment:
   added drop counters for full and disconnected completion queues.



##########
core/shard/src/lib.rs:
##########
@@ -7381,6 +7416,24 @@ where
         // spreads over every group instead of replaying the same prefix.
         rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
 
+        let mut persistence_metrics = partitions::PersistenceMetrics::default();

Review Comment:
   let's measure wide-partition recovery before changing the sweep.



##########
core/server/src/consumer_group.rs:
##########
@@ -169,6 +169,9 @@ where
     let mut in_flight = Vec::new();
     let mut stale_clears = Vec::new();
     for (partition_id, ns, reply) in results {
+        if let Some(PartitionReadReply::Rejected(error)) = reply {

Review Comment:
   retry tests pass; rejected joins leave ownership unchanged.



##########
core/server/src/consumer_group.rs:
##########
@@ -117,7 +117,7 @@ async fn gather_in_flight<B, MJ, S, SB>(
     stream_id: &WireIdentifier,

Review Comment:
   documented recovery rejection and tested retry and ownership.



##########
core/partitions/src/state_transfer.rs:
##########
@@ -56,26 +60,9 @@ use std::path::{Path, PathBuf};
 use std::rc::Rc;
 use std::sync::atomic::Ordering;
 
-/// Framing marker for the consumer-offsets wire artifact, "ICO2". Bumped with
-/// the version when the dedup section was appended, so the magic alone tells
-/// the two layouts apart.
-pub(crate) const CONSUMER_OFFSETS_MAGIC: [u8; 4] = *b"ICO2";
-
-/// Version byte following the magic.
-///
-/// Any layout change bumps this, INCLUDING appended fields: the decoder
-/// deliberately fails closed on unknown versions and on trailing bytes,
-/// because a v2 field can change the meaning of fields v1 already read.
-pub(crate) const CONSUMER_OFFSETS_VERSION: u8 = 2;
-
-/// The previous framing, "ICO1" at version 1: the same layout without the
-/// dedup section. Still decoded so a rolling upgrade works in both orders --
-/// an upgraded replica rejoining behind the repair floor of an un-upgraded
-/// primary installs its artifact with an empty slice (dedup for that window
-/// degrades to at-least-once, exactly the pre-dedup behaviour) instead of
-/// refusing it and re-pulling forever.
-pub(crate) const CONSUMER_OFFSETS_MAGIC_V1: [u8; 4] = *b"ICO1";
-const CONSUMER_OFFSETS_VERSION_V1: u8 = 1;
+/// Current state-transfer offsets format, including the prepare-chain anchor.
+pub(crate) const CONSUMER_OFFSETS_MAGIC: [u8; 4] = *b"ICO1";

Review Comment:
   keeping ico1; this format hasn't shipped yet.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster): add per-topic durability and flatten server config [iggy]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5583683446

   ## [Codecov](https://app.codecov.io/gh/apache/iggy/pull/4092?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `96.55172%` with `1 line` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 85.53%. Comparing base ([`6c07954`](https://app.codecov.io/gh/apache/iggy/commit/6c07954a054ac2638cd4e7390e0549c91ae006fe?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`c8d1385`](https://app.codecov.io/gh/apache/iggy/commit/c8d1385e2259dff32664130be9387009ee2d5e12?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 1 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/iggy/pull/4092?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...oreign/node/src/wire/topic/create-topic.command.ts](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=foreign%2Fnode%2Fsrc%2Fwire%2Ftopic%2Fcreate-topic.command.ts&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Zm9yZWlnbi9ub2RlL3NyYy93aXJlL3RvcGljL2NyZWF0ZS10b3BpYy5jb21tYW5kLnRz) | 94.73% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master    #4092      +/-   ##
   ============================================
   - Coverage     85.98%   85.53%   -0.45%     
     Complexity     1431     1431              
   ============================================
     Files          1247     1245       -2     
     Lines        192967   191931    -1036     
     Branches     158323   157495     -828     
   ============================================
   - Hits         165915   164162    -1753     
   - Misses        22963    23690     +727     
   + Partials       4089     4079      -10     
   ```
   
   | [Components](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [Rust Core](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `86.85% <ø> (-0.04%)` | :arrow_down: |
   | [Java SDK](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `67.50% <ø> (-0.02%)` | :arrow_down: |
   | [C# SDK](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `77.06% <ø> (-0.02%)` | :arrow_down: |
   | [Python SDK](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `91.30% <ø> (-0.01%)` | :arrow_down: |
   | [PHP SDK](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `85.61% <ø> (-0.05%)` | :arrow_down: |
   | [Node SDK](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `89.95% <96.55%> (-6.29%)` | :arrow_down: |
   | [Go SDK](https://app.codecov.io/gh/apache/iggy/pull/4092/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `69.35% <ø> (-0.02%)` | :arrow_down: |
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/iggy/pull/4092?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [core/binary\_protocol/src/primitives/options.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fbinary_protocol%2Fsrc%2Fprimitives%2Foptions.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9iaW5hcnlfcHJvdG9jb2wvc3JjL3ByaW1pdGl2ZXMvb3B0aW9ucy5ycw==) | `94.21% <ø> (-0.12%)` | :arrow_down: |
   | [...ore/cli/src/commands/binary\_topics/create\_topic.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fcli%2Fsrc%2Fcommands%2Fbinary_topics%2Fcreate_topic.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jbGkvc3JjL2NvbW1hbmRzL2JpbmFyeV90b3BpY3MvY3JlYXRlX3RvcGljLnJz) | `92.68% <ø> (ø)` | |
   | [core/cli/src/main.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fcli%2Fsrc%2Fmain.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jbGkvc3JjL21haW4ucnM=) | `90.17% <ø> (ø)` | |
   | [core/common/src/traits/message\_client.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fcommon%2Fsrc%2Ftraits%2Fmessage_client.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb21tb24vc3JjL3RyYWl0cy9tZXNzYWdlX2NsaWVudC5ycw==) | `100.00% <ø> (ø)` | |
   | [core/common/src/types/options/mod.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fcommon%2Fsrc%2Ftypes%2Foptions%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb21tb24vc3JjL3R5cGVzL29wdGlvbnMvbW9kLnJz) | `87.10% <ø> (+0.43%)` | :arrow_up: |
   | [core/configs/src/common/defaults.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fdefaults.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vZGVmYXVsdHMucnM=) | `100.00% <ø> (ø)` | |
   | [core/configs/src/common/displays.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fdisplays.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vZGlzcGxheXMucnM=) | `100.00% <ø> (ø)` | |
   | [core/configs/src/common/server.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fserver.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vc2VydmVyLnJz) | `100.00% <ø> (ø)` | |
   | [core/configs/src/common/system.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fsystem.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vc3lzdGVtLnJz) | `100.00% <ø> (+4.44%)` | :arrow_up: |
   | [core/configs/src/common/validators.rs](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fvalidators.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vdmFsaWRhdG9ycy5ycw==) | `67.51% <ø> (+1.45%)` | :arrow_up: |
   | ... and [63 more](https://app.codecov.io/gh/apache/iggy/pull/4092?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | |
   
   ... and [52 files with indirect coverage changes](https://app.codecov.io/gh/apache/iggy/pull/4092/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   </details>
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(cluster)!: let topics require durable acks and flatten config [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on PR #4092:
URL: https://github.com/apache/iggy/pull/4092#issuecomment-5631328238

   sounds good, but lets do that in next PRs later today. we plan to merge this one today.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org